mirror of
https://github.com/nlohmann/json.git
synced 2026-10-01 22:45:17 +00:00
* Drop stale LCOV_EXCL_LINE from the json_pointer out_of_range.410 throw The comment said the size_type overflow check in array_index() is only triggered on special platforms like 32-bit, and the throw was excluded from coverage. On 64-bit platforms the check is true for SIZE_MAX itself, and unit-json_pointer.cpp has asserted that case four times since #5395, so the line is executed in the coverage job. Reword the comment and remove the exclusion marker so the coverage report notices if the tests stop reaching it. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Name all three C-array check aliases in the enum-macro NOLINTs NLOHMANN_JSON_SERIALIZE_ENUM(_STRICT) suppressed the c-array warning under modernize-avoid-c-arrays only, but clang-tidy emits the same diagnostic under the aliases cppcoreguidelines-avoid-c-arrays and hicpp-avoid-c-arrays too. Any user running those checks got a false positive at every macro expansion, and our own tests needed a local NOLINT at each call site to work around it. Name all three aliases in the four macro comments instead, and drop the now-redundant c-array names from the five test call-site NOLINTs. Comment-only change; behavior, the public API, and the ABI do not change. Ran make amalgamate. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Include doctest as a SYSTEM directory instead of disabling warnings for all tests test_main added -Wno-deprecated and -Wno-float-equal as PUBLIC compile options for every non-MSVC compiler, so they were applied to every translation unit, library headers included, and silenced the CI warnings meant to check the library's own -Wfloat-equal pragmas. The only code that actually needed the suppression was the vendored doctest.h, which was included as a normal (non-SYSTEM) directory. Include thirdparty/doctest as SYSTEM for test_main, matching what tests/abi/CMakeLists.txt already does, and drop the two suppressions from both targets. Verified locally that unit-comparison, unit-conversions and unit-constructor1 compile clean with -Werror -Weverything and doctest as -isystem, and that CMake still configures with JSON_BuildTests=ON. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove the no-op ci_clang_analyze target ci_clang_analyze configured the build with the real compiler and only then wrapped ninja with scan-build. scan-build intercepts compiles by overriding CC/CXX, but build.ninja already had the compiler path baked in from the configure step, so every run bypassed the analyzer: CI logs show "No bugs found" after a normal build, never an analysis. The job also used Debian's frozen clang-tools-14 rather than the image's own clang, and CLANG_ANALYZER_CHECKS still named three valist.* checkers that current clang merged into security.VAList. ci_clang_tidy already runs every clang-analyzer-* check (via .clang-tidy's "Checks: '*'") with warnings as errors, so nothing is lost by removing the dead job. Delete ci_clang_analyze, CLANG_ANALYZER_CHECKS and the SCAN_BUILD_TOOL lookup from cmake/ci.cmake, drop it from the ubuntu.yml ci_static_analysis_clang matrix, and drop the now-unused clang-tools apt package (iwyu stays for ci_single_binaries). Reword quality_assurance.md and assurance_case.md, which described the dead job as a working control, to say the Clang Static Analyzer checks run through clang-tidy. Verified that `cmake -DJSON_CI=ON` still configures cleanly and that ci_clang_analyze no longer appears in the generated build or in any CMake/workflow file. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Re-enable portability-template-virtual-member-function; remove redundant forwards .clang-tidy disabled three checks "to get the CI going" (#4489, 2024-11-13): portability-template-virtual-member-function, bugprone-use-after-move and its alias hicpp-invalid-access-moved. portability-template-virtual-member-function only flagged output_stream_adapter::write_character/write_characters; annotate both with NOLINT and re-enable the check. bugprone-use-after-move flagged several double forwards that have no effect at runtime: - from_json.hpp calls std::forward<BasicJsonType>(j).at(Idx) inside pack expansions; at() has no ref-qualified overloads and always returns an lvalue reference, so the forward is a no-op. Replace with plain j.at(Idx) in all four places. - the move constructor forwards the whole object to its base class and then reads other's members. That is item 9 of #5724 (together with its cppcheck suppressions) and is left to that change. - input_adapters.hpp forwards the container twice on purpose, so the begin/end iterator types match adapter_type; annotate with NOLINT and a comment instead of changing behavior. The check still flags the move constructor (see above) and two sites in at(KeyType&&) (both overloads, json.hpp, in the throw's string_t(std::forward<KeyType>(key)) after find(std::forward<KeyType>(key))). Open PR #5689 rewrites that hunk, so bugprone-use-after-move (and hicpp-invalid-access-moved) stay disabled for now, with a comment explaining why; re-enable them once #5689 and the #5724 move-constructor change have landed. Also resolve the portability-avoid-pragma-once TODO: single_include never has #pragma once (amalgamate.py strips it) and every supported compiler accepts it in include/, so keep it disabled with an explanatory comment instead of a TODO. Fix the stale "json.hpp, around line 1265" comment in unit-class_parser.cpp, which now points at the move constructor's actual line. Behavior, the public API and the ABI do not change. Verified with clang-tidy 22.1.8 that portability-template-virtual-member-function now reports nothing, that bugprone-use-after-move/ hicpp-invalid-access-moved report only the known at(KeyType&&) and move-constructor sites, and that unit-custom-base-class, unit-constructor1, unit-conversions, unit-element_access2, unit-class_parser and unit-diagnostic-positions (JSON_DIAGNOSTIC_POSITIONS=1) compile under ASan/UBSan and pass with the same assertion counts as before. Ran make amalgamate. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix stale and malformed NOLINT comments json_sax.hpp named "-warnings-as-errors" in the NOLINT list on the two JSON_ASSERT(false) lines; that is the suffix clang-tidy appends to a diagnostic tag under WarningsAsErrors, not a check name, and every other JSON_ASSERT(false) omits it. unit-capacity.cpp carried 30 "// NOLINT(misc-const-correctness)" comments on "json j = ...;" declarations that are all used with non-const members afterwards, so the check has nothing to report there. unit-constructor2.cpp used a blanket "// NOLINT: access after move is OK here" on a use-after-move that hides every check on the line; naming bugprone-use-after-move and hicpp-invalid-access-moved keeps the intent once those checks are re-enabled (#5724). Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 10 * Remove stale .clang-tidy entries -google-runtime-references disabled a check that neither clang-tidy 22.1.8 nor 23.1.2 lists under --list-checks -checks='*'; it was removed upstream. The commented-out HeaderFilterRegex line has been unused since the active HeaderFilterRegex was introduced in #2561 (2021). Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 11 * Remove the GCC C++20 -Wignored-attributes pragma in json.hpp The pragma (added in #5164) claimed to work around the C++ modules redefinition errors of #5103, but #5103 is about hard errors (e.g. "redefinition of std::__is_constant_evaluated()", conflicting std::integral_constant) that ignoring a warning cannot suppress; they are traced to GCC PR 124430 and reproduce with <map> or <string> instead of json.hpp too. A GCC 16.2 -std=gnu++20 -fmodules build following #5103's repro steps still fails with the pragma in place, and a build of all test TUs with GCC_CXXFLAGS (which enable -Wignored-attributes) and the pragma removed produces no such warning. The block only hid a warning class from GCC C++20 users while suggesting #5103 was handled. Overlaps #5610, whose hunks touch the closing half of this pragma to insert the json_literals.hpp include. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 9 * Fix stale doxygen comments hidden by the -Wdocumentation pragma macro_scope.hpp ignores -Wdocumentation and -Wdocumentation-unknown-command for the whole library, which also hides genuine documentation mistakes: - detail::unescape() documented "@return unescaped string" but returns void and unescapes its argument in place; reworded to "@param[in,out] s string to unescape in place" and dropped the bogus @return. - basic_json::get()'s copy-conversion overload wrote "converted to @tparam ValueType" inside @return, which Doxygen and Clang parse as a second, malformed @tparam; changed to "@a ValueType", matching the two other get() overloads a few lines above that already use it. This narrows the gap the -Wdocumentation pragma needs to cover; fully replacing the Doxygen-only commands it also hides (item 2c) is left for after #5267. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 2 * Fix -Wextra-semi-stmt at its actual source, not assert() clang_flags.cmake blamed the global -Wno-extra-semi-stmt on assert(), but assert() expands to an expression under glibc and libc++ and does not trigger this warning. unit-assert_macro.cpp overrides JSON_ASSERT with "{if (!(x)) ++assert_counter; }", a bare block followed by a semicolon at every JSON_ASSERT(...) call site in the library; that was the actual source of 151 of the 208 -Wextra-semi-stmt sites found in a Clang 22 -Weverything sweep of the test suite with the flag removed. Switched to the standard do/while(false) macro idiom, which does not expand to a statement-plus-semicolon, and corrected the comment to name the remaining source instead: vendored Doctest's CAPTURE(x) shim, which already ends in a semicolon. Verified with clang++ -Wextra-semi-stmt (plus the file's other CI ignores) that unit-assert_macro.cpp now compiles without any -Wextra-semi-stmt diagnostic. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 8 (step 1 of 2; step 2 covers the CAPTURE() call sites) * Drop the redundant semicolon from CAPTURE() call sites; remove -Wno-extra-semi-stmt doctest_compatibility.h defines CAPTURE(x) as DOCTEST_CAPTURE(x); (with a trailing semicolon baked into the macro), specifically so call sites do not need to add one themselves; most of the ~267 call sites already follow that convention. The remaining 64 call sites across 20 files wrote "CAPTURE(x);" anyway, turning into a statement plus an empty statement and triggering -Wextra-semi-stmt. Dropped the redundant semicolon at each of those sites. With item 6 having already made vendored Doctest a SYSTEM include, and this the last known source of -Wextra-semi-stmt findings, removed the flag from clang_flags.cmake entirely. Verified with clang++ -Wextra-semi-stmt (plus the file's other CI ignores) that all 20 touched files, plus a file with no CAPTURE() use (unit-json_pointer.cpp), compile without any -Wextra-semi-stmt diagnostic. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 8 (step 2 of 2) * Switch ci_static_analysis_clang off the frozen LLVM 22 dev image ubuntu.yml pinned the clang-tidy/clang-tidy-sanitizer/single-binaries job to silkeh/clang:dev, a tag last pushed 2026-02-18 that reports "clang version 22.0.0 (...+20251015...)", a pre-release snapshot from before the LLVM 22 release; the maintainer now updates dev-unstable, 22, and latest instead. Switched to silkeh/clang:22, matching the other clang jobs on :latest. Verified with clang-tidy 22.1.8 (the image's actual version) against this repository's .clang-tidy and library headers what the release image newly reports compared to :dev: - readability-redundant-typename fires at ~250 sites across the _cpp20-relevant conversion/to_chars headers; the library targets C++11 and keeps the typenames, so the check is disabled in .clang-tidy, matching how the file already handles checks that don't fit a C++11 codebase. - misc-anonymous-namespace-in-header fires on the two anonymous namespaces in from_json.hpp and to_json.hpp; added the alias to their existing NOLINT (cert-dcl59-cpp, fuchsia-header-anon-namespaces, google-build-namespaces). - bugprone-std-namespace-modification fires on every addition to namespace std: the std::hash, std::formatter and std::swap overloads in json.hpp, and the std::tuple_size/std::tuple_element specializations in iteration_proxy.hpp (this last file is not named in #5725's item 5, found by actually running clang-tidy 22.1.8 against the current tree). All six are legal, deliberate additions to namespace std (explicit/partial specializations of std types, or the pre-C++20 std::swap overload); annotated each with the check name next to its existing cert-dcl58-cpp NOLINT. - modernize-avoid-c-style-cast reported nothing new. Also added clang++-22/21, clang-tidy-22/21, g++-16 and gcov-16 to the find_program search lists in ci.cmake so a local "maximal warnings" configure prefers the current toolchain version over an older one on PATH. #5725 item 5 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate cmake/gcc_flags.cmake for GCC 16.2.0 GCC_CXXFLAGS was generated for GCC 15.1.0, but ci_test_gcc and ci_test_gcc_cxx{11..26} now run in gcc:latest, currently GCC 16.2.0, so the "maximal warnings" job was missing warnings introduced since 15.1.0 while carrying entries GCC 16 treats as duplicates or no-ops. Regenerated with https://github.com/nlohmann/gcc_flags (patched locally to not crash on an option whose "-x c++ <opt> -" probe fails before it reads stdin, e.g. -Wabi=; the tool otherwise raises BrokenPipeError instead of recording the option as an error) run against g++ 16.2.0 in the official gcc:16 Docker image, keeping the documented -Wno-* exclusions and the same alphabetical placement scheme as before. Also added three GCC 16 warnings the generator cannot discover on its own because it only probes value ranges/lists it finds in the -Q option name itself, not in the enum choices --help=warnings documents separately: - -Wbidi-chars=any, -Wleading-whitespace=spaces: manually verified these compile cleanly with g++ 16.2.0. - -Wstrict-flex-arrays: deliberately NOT added, unlike the other two. Without -fstrict-flex-arrays (which the library does not enable, as it would change codegen for flexible array members), GCC prints "'-Wstrict-flex-arrays' is ignored when '-fstrict-flex-arrays' is not present" on every translation unit, and under our -Werror that note itself aborts the build. This differs from the harmless no-op warnings already kept in the file (-Whsa, -Wsynth, -Wunreachable-code, -Wunsafe-loop-optimizations), which emit nothing; #5725 item 7 named -Wstrict-flex-arrays as one of the flags GCC 16 adds, but did not anticipate this failure mode. Verified: compiled the library header and a representative set of test translation units (including ones touched by items 1, 3, 8, 9, 10 of this issue) with the regenerated GCC_CXXFLAGS plus -Werror under g++ 16.2.0 at -std=c++11 through -std=c++26, with zero warnings; ran the full local test suite (129/129 passing, unrelated to this compiler) as a regression check. CI must still confirm the actual ci_test_gcc / ci_test_standards_gcc targets end to end, since this was verified with direct g++ invocations rather than through the CMake/ CXXFLAGS environment-variable plumbing in ci.cmake. #5725 item 7 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Avoid std::basic_string<CharType> for non-character output_adapter CharType output_adapter<CharType, StringType> defaulted StringType to std::basic_string<CharType>, and (with JSON_NO_IO undefined) always declared a std::basic_ostream<CharType>&-taking constructor. For CharType with no non-deprecated std::char_traits specialization (only std::uint8_t is ever used this way, by the binary writers), simply naming either type - as an unused default template argument, or as an unused, never-called constructor's parameter type - instantiates std::char_traits<CharType> merely to name it, which some standard libraries mark deprecated: with the library-wide -Wdocumentation pragma (item 2's other half, left for a later commit) temporarily removed, an Apple clang 21 / libc++ TU calling json::to_cbor(j, vec) with std::vector<std::uint8_t>& got one -Wdeprecated-declarations warning per binary writer at the old output_adapters.hpp:193. Replaced the eager std::basic_string<CharType> / std::basic_ostream <CharType> defaults with a bool-tagged partial specialization (not std::conditional, which requires naming both branches' types up front regardless of which is selected, reproducing the same warning) that only ever names std::basic_string<CharType> / std::basic_ostream <CharType> when CharType is actually one of char, wchar_t, char16_t, char32_t, or (with __cpp_lib_char8_t) char8_t. For any other CharType, output_adapter's StringType and ostream-constructor parameter fall back to two distinct empty placeholder types, kept distinct so the two constructor overloads do not collide into a single redeclaration. Public API / behavior: passing a std::basic_string<std::uint8_t>& or std::basic_ostream<std::uint8_t>& directly to a binary writer's output_adapter now fails to compile instead of compiling with a deprecation warning; this was neither documented nor tested. All documented uses (std::vector<CharType>, std::basic_ostream<CharType> and StringType for character CharType) are unaffected. Verified with Apple clang 21 / libc++, with the two -Wdocumentation* "ignored" pragma lines in macro_scope.hpp temporarily removed and -std=c++11/c++20 plus the project's -Weverything flag set: calling to_cbor/to_msgpack/to_ubjson/to_bjdata/to_bson/to_bon8 on a std::vector<std::uint8_t> now produces no char_traits<unsigned char> (or any other) deprecation warning, while the char-based string- and ostream-adapter paths, and a to_cbor/from_cbor round trip, still compile and run correctly; also verified with GCC 16.2.0. Ran the full local test suite, including the binary-format unit tests (unit-cbor, unit-msgpack, unit-ubjson, unit-bjdata, unit-bson, unit-bon8, unit-binary_writer_sinks, unit-binary_formats, unit-custom-binary-type): 129/129 passing. #5725 item 2 (step a) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove the library-wide -Wdocumentation pragma; fix what it hid macro_scope.hpp / macro_unscope.hpp pushed and popped a Clang diagnostic region over the entire library that ignored -Wdocumentation and -Wdocumentation-unknown-command. Removed both pragmas and fixed every finding a full -Wdocumentation (which implies -Wdocumentation-unknown-command and -Wdocumentation-deprecated-sync) build reports, so the library now compiles clean under Clang's documentation checks without a blanket suppression. Overlaps #5267, which is still open and edits a nearby doc block (json.hpp's get()/get_impl() @return, already fixed in the item 2 step (b) commit of this branch); this commit does not touch that block again. Unknown Doxygen alias commands (Doxyfile removed in #3071, so these were never rendered by anything) rewritten as plain prose, keeping the same information: - @requirement REQ-JSON-01 / REQ-JSON-02 (iter_impl.hpp, json_reverse_iterator.hpp): now "This class satisfies the following concept requirements (REQ-JSON-0N):". - @liveexample{prose,example-id} (three sites in json.hpp): kept the prose, dropped the command wrapper and the trailing example-id (docs/mkdocs/docs/examples/*.cpp still exist and are used directly by the rendered docs, not through this in-header alias) and unescaped the "\," commas that were only needed for the old alias's comma-separated argument syntax. - @complexity X (json.hpp x4, json_pointer.hpp x2, serializer.hpp x1): now "Complexity: X". Backslash sequences Clang's comment lexer tried to parse as commands, escaped to render as literal backslashes: - lexer.hpp get_codepoint(): two `\u` occurrences. - binary_reader.hpp get_bson_cstr() / get_bson_cstr_bulk(): two `\x00` occurrences. - serializer.hpp: three `\uXXXX` occurrences (constructor @param, append_codepoint_to_string_buffer() @brief, and the ensure_ascii member comment). One finding remained after all of the above: Clang reports "declaration is marked with '@deprecated' command but does not have a deprecation attribute" on the deprecated sax_parse(span_input_adapter&&, ...) overload, even though JSON_HEDLEY_DEPRECATED_FOR does expand to __attribute__((deprecated(...))) for Clang. Several isolated reproductions of this exact declaration shape - doc comment, template<>, two stacked __attribute__ macros, an overload set sharing the name - did not reproduce the warning, so this looks like a Clang comment/declaration-association quirk specific to this overload inside the much larger basic_json class template, not an actual documentation defect. Rather than keep the pragma library-wide for one Clang false positive, added a tightly scoped -Wdocumentation-deprecated-sync push/pop around just that overload. Verified with Apple clang 21 and the project's actual -Weverything flag set (cmake/clang_flags.cmake) on the full header at -std=c++11 and -std=c++20: zero -Wdocumentation* diagnostics. Also compiled clean with GCC 16.2.0 (the pragmas are already __clang__-gated, so this only confirms no unrelated breakage). Ran make check-amalgamation and the full local test suite: 129/129 passing. #5725 item 2 (step c) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Take the JSON value by const reference in the array and tuple from_json paths Review feedback on #5737 (gregmarr): once the no-op std::forward calls are gone, the forwarding references have no purpose. from_json_fn passes the value as const BasicJsonType&, so these functions were only ever instantiated with a const lvalue anyway. The std::array, std::pair and std::tuple overloads of from_json and their helpers now take const BasicJsonType& and pass j on unchanged. Because the deduced BasicJsonType is now the plain type, tuple_type and the static_assert name const BasicJsonType& explicitly, so the reference checks are unchanged: get<std::tuple<const std::string&>>() still works, and get<std::tuple<std::string&>>() still fails the same static_assert. from_json_tuple_get_impl keeps its forwarding reference, since tuple_type calls it through std::declval. Behavior, the public API and the ABI do not change. unit-conversions, unit-constructor1, unit-udt, unit-udt_macro, unit-regression1/2/3, unit-deserialization, unit-noexcept, unit-items, unit-allocator, unit-custom-object-type, unit-ordered_json2 and unit-brace-init-copy-semantics pass at C++11, C++17 and C++20 with unchanged assertion counts. Ran make amalgamate. Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
473 lines
16 KiB
C++
473 lines
16 KiB
C++
// __ _____ _____ _____
|
|
// __| | __| | | | JSON for Modern C++ (supporting code)
|
|
// | | |__ | | | | | | version 3.12.0
|
|
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
|
|
//
|
|
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// cmake/test.cmake selects the C++ standard versions with which to build a
|
|
// unit test based on the presence of JSON_HAS_CPP_<VERSION> macros.
|
|
// When using macros that are only defined for particular versions of the standard
|
|
// (e.g., JSON_HAS_FILESYSTEM for C++17 and up), please mention the corresponding
|
|
// version macro in a comment close by, like this:
|
|
// JSON_HAS_CPP_<VERSION> (do not remove; see note at top of file)
|
|
|
|
#include "doctest_compatibility.h"
|
|
|
|
#include <nlohmann/json.hpp>
|
|
using nlohmann::json;
|
|
|
|
#include <array> // array
|
|
#include <cstddef> // size_t
|
|
#include <cstdint> // uint8_t
|
|
#include <list>
|
|
#include <string> // string
|
|
#include <vector> // vector
|
|
|
|
#if defined(__cpp_lib_concepts) && defined(JSON_HAS_CPP_20)
|
|
#include <iterator>
|
|
#endif
|
|
|
|
namespace
|
|
{
|
|
TEST_CASE("Use arbitrary stdlib container")
|
|
{
|
|
std::string raw_data = "[1,2,3,4]";
|
|
std::list<char> data(raw_data.begin(), raw_data.end());
|
|
|
|
json as_json = json::parse(data.begin(), data.end());
|
|
CHECK(as_json.at(0) == 1);
|
|
CHECK(as_json.at(1) == 2);
|
|
CHECK(as_json.at(2) == 3);
|
|
CHECK(as_json.at(3) == 4);
|
|
}
|
|
|
|
struct MyContainer
|
|
{
|
|
const char* data;
|
|
};
|
|
|
|
const char* begin(const MyContainer& c)
|
|
{
|
|
return c.data;
|
|
}
|
|
|
|
const char* end(const MyContainer& c)
|
|
{
|
|
return c.data + strlen(c.data); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
|
|
}
|
|
|
|
TEST_CASE("Custom container non-member begin/end")
|
|
{
|
|
|
|
const MyContainer data{"[1,2,3,4]"};
|
|
json as_json = json::parse(data);
|
|
CHECK(as_json.at(0) == 1);
|
|
CHECK(as_json.at(1) == 2);
|
|
CHECK(as_json.at(2) == 3);
|
|
CHECK(as_json.at(3) == 4);
|
|
|
|
}
|
|
|
|
struct MyContainerNonConstADL
|
|
{
|
|
char* data;
|
|
std::size_t size;
|
|
};
|
|
|
|
char* begin(MyContainerNonConstADL& c)
|
|
{
|
|
return c.data;
|
|
}
|
|
|
|
char* end(MyContainerNonConstADL& c)
|
|
{
|
|
return c.data + c.size; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
|
|
}
|
|
|
|
TEST_CASE("Custom container non-member non-const begin/end")
|
|
{
|
|
// Container with lvalue-only non-const ADL begin/end (bug reproduction)
|
|
std::string raw_data = "[1,2,3,4]";
|
|
MyContainerNonConstADL data{&raw_data[0], raw_data.size()}; // NOLINT(readability-container-data-pointer)
|
|
const json as_json = json::parse(data);
|
|
CHECK(as_json.at(0) == 1);
|
|
CHECK(as_json.at(1) == 2);
|
|
CHECK(as_json.at(2) == 3);
|
|
CHECK(as_json.at(3) == 4);
|
|
|
|
// Same container with accept()
|
|
CHECK(json::accept(data));
|
|
}
|
|
|
|
TEST_CASE("Custom container non-member begin/end, rvalue")
|
|
{
|
|
// Regression check: rvalue container parsing should still work
|
|
const json as_json = json::parse(MyContainer{"[1,2,3,4]"});
|
|
CHECK(as_json.at(0) == 1);
|
|
CHECK(as_json.at(1) == 2);
|
|
CHECK(as_json.at(2) == 3);
|
|
CHECK(as_json.at(3) == 4);
|
|
}
|
|
|
|
TEST_CASE("Custom container member begin/end")
|
|
{
|
|
struct MyContainer2
|
|
{
|
|
const char* data;
|
|
|
|
const char* begin() const noexcept
|
|
{
|
|
return data;
|
|
}
|
|
|
|
const char* end() const noexcept
|
|
{
|
|
return data + strlen(data); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
|
|
}
|
|
};
|
|
|
|
const MyContainer2 data{"[1,2,3,4]"};
|
|
json as_json = json::parse(data);
|
|
CHECK(as_json.at(0) == 1);
|
|
CHECK(as_json.at(1) == 2);
|
|
CHECK(as_json.at(2) == 3);
|
|
CHECK(as_json.at(3) == 4);
|
|
}
|
|
|
|
TEST_CASE("Custom iterator")
|
|
{
|
|
const char* raw_data = "[1,2,3,4]";
|
|
|
|
struct MyIterator
|
|
{
|
|
using difference_type = std::size_t;
|
|
using value_type = char;
|
|
using pointer = const char*;
|
|
using reference = const char&;
|
|
using iterator_category = std::input_iterator_tag;
|
|
|
|
MyIterator& operator++()
|
|
{
|
|
++ptr; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
|
|
return *this;
|
|
}
|
|
|
|
reference operator*() const
|
|
{
|
|
return *ptr;
|
|
}
|
|
|
|
bool operator!=(const MyIterator& rhs) const
|
|
{
|
|
return ptr != rhs.ptr;
|
|
}
|
|
|
|
const char* ptr;
|
|
};
|
|
|
|
// avoid -Wunused-local-typedefs
|
|
CHECK(std::is_same<MyIterator::difference_type, std::size_t>::value);
|
|
CHECK(std::is_same<MyIterator::value_type, char>::value);
|
|
CHECK(std::is_same<MyIterator::pointer, const char*>::value);
|
|
CHECK(std::is_same<MyIterator::reference, const char&>::value);
|
|
CHECK(std::is_same<MyIterator::iterator_category, std::input_iterator_tag>::value);
|
|
|
|
const MyIterator begin{raw_data};
|
|
const MyIterator end{raw_data + strlen(raw_data)}; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
|
|
|
|
json as_json = json::parse(begin, end);
|
|
CHECK(as_json.at(0) == 1);
|
|
CHECK(as_json.at(1) == 2);
|
|
CHECK(as_json.at(2) == 3);
|
|
CHECK(as_json.at(3) == 4);
|
|
}
|
|
|
|
// Custom sentinel type for testing heterogeneous iterator+sentinel support
|
|
struct CustomSentinel
|
|
{
|
|
const char* end_ptr;
|
|
|
|
// only the iterator-first direction (it != sentinel) is ever evaluated by
|
|
// the library's parse loop; a reversed-order overload would go unused and
|
|
// trip -Wunneeded-internal-declaration under -Weverything
|
|
friend bool operator!=(const char* it, const CustomSentinel& sentinel)
|
|
{
|
|
return it != sentinel.end_ptr;
|
|
}
|
|
};
|
|
|
|
TEST_CASE("Parse with heterogeneous iterator and sentinel types")
|
|
{
|
|
const std::string json_str = R"({"key":"value"})";
|
|
const char* end_ptr = json_str.data() + json_str.size();
|
|
|
|
// Parse using pointer and sentinel (different types)
|
|
json j = json::parse(json_str.data(), CustomSentinel{end_ptr});
|
|
CHECK(j["key"] == "value");
|
|
|
|
// Accept using pointer and sentinel
|
|
CHECK(json::accept(json_str.data(), CustomSentinel{end_ptr}));
|
|
|
|
// Test that the same-type case still works
|
|
std::string raw_data = R"([1,2,3])";
|
|
std::list<char> data(raw_data.begin(), raw_data.end());
|
|
json j2 = json::parse(data.begin(), data.end());
|
|
CHECK(j2.at(0) == 1);
|
|
}
|
|
|
|
// A type whose data() hands out raw bytes but whose size() counts something
|
|
// else - here fixed-size records. Reading [data(), data() + size()) as bytes
|
|
// would silently truncate the input, so data() and size() alone must not be
|
|
// taken as evidence of contiguous byte storage.
|
|
struct record_buffer
|
|
{
|
|
using value_type = std::array<char, 4>;
|
|
|
|
std::string bytes;
|
|
|
|
const char* data() const noexcept
|
|
{
|
|
return bytes.data();
|
|
}
|
|
std::size_t size() const noexcept
|
|
{
|
|
return bytes.size() / sizeof(value_type);
|
|
}
|
|
const char* begin() const noexcept
|
|
{
|
|
return bytes.data();
|
|
}
|
|
const char* end() const noexcept
|
|
{
|
|
return bytes.data() + bytes.size();
|
|
}
|
|
};
|
|
|
|
TEST_CASE("Contiguous byte containers take the pointer adapter")
|
|
{
|
|
// Containers with contiguous single-byte storage are routed through the
|
|
// pointer-based adapter so the bulk fast paths apply in every standard, not
|
|
// only in C++20 where the library iterators model std::contiguous_iterator.
|
|
CHECK(nlohmann::detail::is_contiguous_byte_container<std::string>::value);
|
|
CHECK(nlohmann::detail::is_contiguous_byte_container<std::vector<char>>::value);
|
|
CHECK(nlohmann::detail::is_contiguous_byte_container<std::vector<std::uint8_t>>::value);
|
|
CHECK(nlohmann::detail::is_contiguous_byte_container<std::array<char, 4>>::value);
|
|
|
|
// input_adapter() takes its container by forwarding reference, so the trait
|
|
// is also asked about reference types
|
|
CHECK(nlohmann::detail::is_contiguous_byte_container<std::string&>::value);
|
|
CHECK(nlohmann::detail::is_contiguous_byte_container<const std::string&>::value);
|
|
|
|
// everything else keeps the iterator-based adapter
|
|
CHECK_FALSE(nlohmann::detail::is_contiguous_byte_container<std::list<char>>::value);
|
|
CHECK_FALSE(nlohmann::detail::is_contiguous_byte_container<std::vector<int>>::value);
|
|
CHECK_FALSE(nlohmann::detail::is_contiguous_byte_container<const char*>::value);
|
|
|
|
// including a type that has data() and size() but whose size() does not
|
|
// count the units data() points at: its value_type says so
|
|
CHECK_FALSE(nlohmann::detail::is_contiguous_byte_container<record_buffer>::value);
|
|
|
|
// and such a container still parses through its iterators, in full - taking
|
|
// it for a byte container would stop after data() + size() bytes
|
|
const record_buffer buffer{"[1,2,3,4,5]"};
|
|
CHECK(buffer.data() == buffer.bytes.data());
|
|
CHECK(buffer.size() * sizeof(record_buffer::value_type) < buffer.bytes.size());
|
|
CHECK(json::parse(buffer) == json({1, 2, 3, 4, 5}));
|
|
}
|
|
|
|
#if defined(__cpp_lib_concepts) && defined(JSON_HAS_CPP_20)
|
|
// JSON_HAS_CPP_20 (do not remove; see note at top of file)
|
|
TEST_CASE("Parse with std::counted_iterator and std::default_sentinel_t")
|
|
{
|
|
using iterator_type = std::string::const_iterator;
|
|
const std::string json_str = R"({"key":"value","array":[1,2,3]})";
|
|
const auto len = static_cast<std::iter_difference_t<iterator_type>>(json_str.size());
|
|
|
|
const std::counted_iterator<iterator_type> first(json_str.begin(), len);
|
|
const json j = json::parse(first, std::default_sentinel);
|
|
CHECK(j["key"] == "value");
|
|
CHECK(j["array"].size() == 3);
|
|
|
|
const std::counted_iterator<iterator_type> first2(json_str.begin(), len);
|
|
CHECK(json::accept(first2, std::default_sentinel));
|
|
}
|
|
|
|
TEST_CASE("std::counted_iterator reaches the contiguous fast paths")
|
|
{
|
|
// A sized sentinel makes the remaining element count computable in O(1), so
|
|
// std::counted_iterator over a contiguous iterator must reach the same bulk
|
|
// string/number scanners as a plain pointer - not just the byte-at-a-time
|
|
// fallback (see #5268 for the equivalent memcpy fast path).
|
|
#if JSON_HAS_RANGES
|
|
// JSON_HAS_RANGES is 0 on standard libraries with an incomplete <ranges>
|
|
// (libstdc++ < 11, libc++ < 16), where the adapter deliberately falls back
|
|
// to the byte-at-a-time scanner; everything below still has to work there.
|
|
using adapter_type = nlohmann::detail::iterator_input_adapter<std::counted_iterator<const char*>, std::default_sentinel_t>;
|
|
CHECK(adapter_type::supports_bulk_scan);
|
|
CHECK(adapter_type::supports_seek);
|
|
#endif
|
|
|
|
// exercise every fast path: long ASCII run, multibyte UTF-8, escapes, and
|
|
// integer/floating-point numbers
|
|
const std::string json_str =
|
|
R"({"ascii":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",)"
|
|
"\"utf8\":\"\xe4\xb8\xad\xe6\x96\x87\xf0\x9f\x98\x80\xc3\xa9\","
|
|
R"("escaped":"aéb\n\\","ints":[0,-1,18446744073709551615,-9223372036854775808],)"
|
|
R"("floats":[1.5,-2.25e3,0.30000000000000004]})";
|
|
const auto len = static_cast<std::iter_difference_t<const char*>>(json_str.size());
|
|
|
|
const std::counted_iterator<const char*> first(json_str.data(), len);
|
|
const json j = json::parse(first, std::default_sentinel);
|
|
|
|
// parsing through the pointer adapter must give exactly the same result
|
|
CHECK(j == json::parse(json_str));
|
|
|
|
#if !defined(JSON_NOEXCEPTION)
|
|
// Diagnostics that quote the offending token are reconstructed from the
|
|
// already-consumed input (supports_seek), a path a sized sentinel only
|
|
// reaches now; check a few that include the "last read" text. Parsing
|
|
// invalid input aborts when exceptions are off, hence the guard.
|
|
// Raw strings and explicit bytes: an escaped literal and two literals
|
|
// written next to each other both read as mistakes to static analysis.
|
|
const auto byte = [](int value)
|
|
{
|
|
return std::string(1, static_cast<char>(value));
|
|
};
|
|
const std::vector<std::string> diagnostic_docs =
|
|
{
|
|
"1\nx",
|
|
"truX",
|
|
"[tru]",
|
|
R"("abc)",
|
|
R"(["\ud834"])",
|
|
R"(["a)" + byte(0x01) + R"(b"])",
|
|
R"([")" + byte(0xC3) + byte(0x28) + R"("])",
|
|
"[1e]",
|
|
R"(["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaX)"
|
|
};
|
|
|
|
for (const auto& text : diagnostic_docs)
|
|
{
|
|
CAPTURE(text)
|
|
const std::counted_iterator<const char*> it(text.data(), static_cast<std::iter_difference_t<const char*>>(text.size()));
|
|
std::string counted_message;
|
|
std::string string_message;
|
|
try
|
|
{
|
|
const json counted_result = json::parse(it, std::default_sentinel);
|
|
static_cast<void>(counted_result);
|
|
}
|
|
catch (const json::parse_error& e)
|
|
{
|
|
counted_message = e.what();
|
|
}
|
|
try
|
|
{
|
|
const json string_result = json::parse(text);
|
|
static_cast<void>(string_result);
|
|
}
|
|
catch (const json::parse_error& e)
|
|
{
|
|
string_message = e.what();
|
|
}
|
|
CHECK_FALSE(counted_message.empty());
|
|
CHECK(counted_message == string_message);
|
|
}
|
|
|
|
// and errors must still be reported identically
|
|
const std::string bad = "[01\n]";
|
|
const std::counted_iterator<const char*> bad_first(bad.data(), static_cast<std::iter_difference_t<const char*>>(bad.size()));
|
|
std::string counted_what;
|
|
std::string string_what;
|
|
try
|
|
{
|
|
const json counted_result = json::parse(bad_first, std::default_sentinel);
|
|
static_cast<void>(counted_result);
|
|
}
|
|
catch (const json::parse_error& e)
|
|
{
|
|
counted_what = e.what();
|
|
}
|
|
try
|
|
{
|
|
const json string_result = json::parse(bad);
|
|
static_cast<void>(string_result);
|
|
}
|
|
catch (const json::parse_error& e)
|
|
{
|
|
string_what = e.what();
|
|
}
|
|
CHECK_FALSE(counted_what.empty());
|
|
CHECK(counted_what == string_what);
|
|
#endif
|
|
}
|
|
|
|
#if !defined(JSON_NOEXCEPTION)
|
|
// several cases below are truncated on purpose, and parsing invalid input
|
|
// aborts when exceptions are off
|
|
TEST_CASE("std::counted_iterator bulk scanning stops at the counted end")
|
|
{
|
|
// The count, not the size of the underlying buffer, is the end of the
|
|
// input: the bulk scanners must never look at the bytes behind it, even
|
|
// though they are readable. Each case is compared against parsing the
|
|
// equivalent prefix as a std::string.
|
|
const auto via_counted = [](const std::string & buf, std::size_t n) -> std::string
|
|
{
|
|
const std::counted_iterator<const char*> first(buf.data(), static_cast<std::iter_difference_t<const char*>>(n));
|
|
try
|
|
{
|
|
const json j = json::parse(first, std::default_sentinel);
|
|
return "OK|" + j.dump();
|
|
}
|
|
catch (const json::parse_error& e)
|
|
{
|
|
return {e.what()};
|
|
}
|
|
};
|
|
const auto via_prefix = [](const std::string & buf, std::size_t n) -> std::string
|
|
{
|
|
try
|
|
{
|
|
const json j = json::parse(buf.substr(0, n));
|
|
return "OK|" + j.dump();
|
|
}
|
|
catch (const json::parse_error& e)
|
|
{
|
|
return {e.what()};
|
|
}
|
|
};
|
|
|
|
struct testcase // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init)
|
|
{
|
|
const char* buffer;
|
|
std::size_t count;
|
|
};
|
|
const std::vector<testcase> cases =
|
|
{
|
|
{"[\"abc\"]____TRAILING____", 7}, // exact fit, tail hidden
|
|
{"[\"abcdefghijklmnop\"]____", 8}, // cut inside a string
|
|
{"[\"abc\"]____", 6}, // cut just before the closing quote
|
|
{"[12345]xxxxx", 4}, // cut inside a number
|
|
{"[123]999999", 5}, // number ends exactly at the count
|
|
{"[\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"]", 12}, // closing quote only behind the count
|
|
{"[\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"]", 19}, // cut inside an 8-byte SWAR stride
|
|
{"[\"\xe4\xb8\xad\xe6\x96\x87\"]", 5}, // cut inside a UTF-8 sequence
|
|
{"[\"\xe4\xb8\xad\xe6\x96\x87\"]____", 10}, // complete UTF-8, tail hidden
|
|
{"[1.25e3]TRAILINGDIGITS999", 7}, // number token reaches the count
|
|
};
|
|
|
|
for (const auto& tc : cases)
|
|
{
|
|
CAPTURE(tc.buffer)
|
|
CAPTURE(tc.count)
|
|
const std::string buffer = tc.buffer;
|
|
CHECK(via_counted(buffer, tc.count) == via_prefix(buffer, tc.count));
|
|
}
|
|
}
|
|
#endif
|
|
#endif
|
|
|
|
} // namespace
|