mirror of
https://github.com/nlohmann/json.git
synced 2026-10-08 15:37:13 +00:00
Merge branch 'develop' into fix/json_pointer_create_object_5357
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
132 files changed
+39854
-3884
No files matched your search
+41
-3
@@ -8,6 +8,7 @@ set(JSON_SIMDUTF_VERSION 9.1.0 CACHE STRING "The simdutf version used by JSON_Te
|
||||
|
||||
set(JSON_32bitTest AUTO CACHE STRING "Enable the 32bit unit test (ON/OFF/AUTO/ONLY).")
|
||||
set(JSON_TestStandards "" CACHE STRING "The list of standards to test explicitly.")
|
||||
set(JSON_TestShard "" CACHE STRING "Build only a part of the unit tests, given as <index>/<count> (e.g. 0/2), to split them across CI jobs with a time limit.")
|
||||
|
||||
# using an env var, since this will also affect targets executing cmake (such as "ci_test_compiler_default")
|
||||
if (NOT "" STREQUAL "$ENV{JSON_FORCED_GLOBAL_COMPILE_OPTIONS}")
|
||||
@@ -134,12 +135,17 @@ json_test_set_test_options(test-disabled_exceptions
|
||||
#$<$<CXX_COMPILER_ID:MSVC>:/EH>
|
||||
)
|
||||
|
||||
# raise timeout of expensive Unicode test
|
||||
json_test_set_test_options(test-unicode4 TEST_PROPERTIES TIMEOUT 3000)
|
||||
|
||||
# only the #972 regression test needs thirdparty/fifo_map on its include path
|
||||
json_test_set_test_options(test-regression1 LINK_LIBRARIES fifo_map_include)
|
||||
|
||||
# GCC's false -Warray-bounds error with JSON_DIAGNOSTICS only shows up when optimizing (#5742).
|
||||
# -O3 makes the optimizer-driven warnings of the ci_test_gcc flag set (-Winline,
|
||||
# -Wsuggest-attribute=...) fire on the library's inline functions; they are not
|
||||
# what this test checks, so turn them off for it.
|
||||
json_test_set_test_options(test-diagnostics-optimized
|
||||
COMPILE_OPTIONS $<$<CXX_COMPILER_ID:GNU>:-O3 -Werror=array-bounds -Wno-inline -Wno-suggest-attribute=pure -Wno-suggest-attribute=const>
|
||||
)
|
||||
|
||||
#############################################################################
|
||||
# add unit tests
|
||||
#############################################################################
|
||||
@@ -288,6 +294,33 @@ elseif(NOT json_32bit_test)
|
||||
list(FILTER files EXCLUDE REGEX src/unit-32bit.cpp)
|
||||
endif()
|
||||
|
||||
# with JSON_TestShard=<index>/<count>, keep every <count>-th unit test file,
|
||||
# starting at <index> (the glob is sorted, so the split is stable)
|
||||
set(test_shard_index 0)
|
||||
if(NOT "${JSON_TestShard}" STREQUAL "")
|
||||
if(NOT JSON_TestShard MATCHES "^([0-9]+)/([1-9][0-9]*)$")
|
||||
message(FATAL_ERROR "JSON_TestShard must be <index>/<count>, e.g. 0/2, not '${JSON_TestShard}'.")
|
||||
endif()
|
||||
set(test_shard_index ${CMAKE_MATCH_1})
|
||||
set(test_shard_count ${CMAKE_MATCH_2})
|
||||
if(NOT test_shard_index LESS test_shard_count)
|
||||
message(FATAL_ERROR "JSON_TestShard: the index must be less than the count, not '${JSON_TestShard}'.")
|
||||
endif()
|
||||
list(LENGTH files test_file_count)
|
||||
set(shard_files "")
|
||||
set(file_position 0)
|
||||
foreach(file ${files})
|
||||
math(EXPR file_shard "${file_position} % ${test_shard_count}")
|
||||
if(file_shard EQUAL test_shard_index)
|
||||
list(APPEND shard_files ${file})
|
||||
endif()
|
||||
math(EXPR file_position "${file_position} + 1")
|
||||
endforeach()
|
||||
set(files ${shard_files})
|
||||
list(LENGTH files shard_file_count)
|
||||
message(STATUS "Test shard ${JSON_TestShard}: ${shard_file_count} of ${test_file_count} unit test files")
|
||||
endif()
|
||||
|
||||
foreach(file ${files})
|
||||
json_test_add_test_for(${file} MAIN test_main CXX_STANDARDS ${test_cxx_standards} ${test_force})
|
||||
endforeach()
|
||||
@@ -305,6 +338,9 @@ if(json_32bit_test_only)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# the following variants of single test files are only built in the first shard
|
||||
if(test_shard_index EQUAL 0)
|
||||
|
||||
# test legacy comparison of discarded values
|
||||
json_test_set_test_options(test-comparison_legacy
|
||||
COMPILE_DEFINITIONS JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON=1
|
||||
@@ -332,6 +368,8 @@ json_test_add_test_for(src/unit-diagnostic-positions.cpp
|
||||
MAIN test_main CXX_STANDARDS ${test_cxx_standards} ${test_force}
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# *DO NOT* use json_test_set_test_options() below this line
|
||||
|
||||
#############################################################################
|
||||
|
||||
@@ -48,6 +48,10 @@ TEST_CASE("default namespace")
|
||||
expected += "_sbu8";
|
||||
#endif
|
||||
|
||||
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||
expected += "_ekmo";
|
||||
#endif
|
||||
|
||||
expected += "_v" STRINGIZE(NLOHMANN_JSON_VERSION_MAJOR);
|
||||
expected += "_" STRINGIZE(NLOHMANN_JSON_VERSION_MINOR);
|
||||
expected += "_" STRINGIZE(NLOHMANN_JSON_VERSION_PATCH) "::basic_json";
|
||||
|
||||
@@ -49,6 +49,10 @@ TEST_CASE("default namespace without version component")
|
||||
expected += "_sbu8";
|
||||
#endif
|
||||
|
||||
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||
expected += "_ekmo";
|
||||
#endif
|
||||
|
||||
expected += "::basic_json";
|
||||
|
||||
// fallback for Clang
|
||||
|
||||
+14
-1
@@ -3,6 +3,14 @@
|
||||
Each parser of the library (JSON, BJData, BON8, BSON, CBOR, MessagePack, and UBJSON) can be fuzz tested. Currently,
|
||||
[libFuzzer](https://llvm.org/docs/LibFuzzer.html) and [afl++](https://github.com/AFLplusplus/AFLplusplus) are supported.
|
||||
|
||||
## What the fuzzers check
|
||||
|
||||
Each fuzzer driver (`tests/src/fuzzer-parse_*.cpp`) parses its input twice: once with `allow_exceptions = false` and
|
||||
once with exceptions. Both calls must agree. Where parsing with exceptions fails, the call without exceptions must
|
||||
return a discarded value (or throw the same kind of non-parse error), and it must never throw a `parse_error`. Where
|
||||
parsing succeeds, both calls must return the same value. The drivers then serialize the value, parse the result back,
|
||||
and check that nothing was lost. The drivers check all of this with `assert`, so they refuse to build with `NDEBUG`.
|
||||
|
||||
## Corpus creation
|
||||
|
||||
For most effective fuzzing, a [corpus](https://llvm.org/docs/LibFuzzer.html#corpus) should be provided. A corpus is a
|
||||
@@ -54,6 +62,9 @@ Then pass the corpus directory as command-line argument (assuming it is located
|
||||
The fuzzer should be able to run indefinitely without crashing. In case of a crash, the tested input is dumped into
|
||||
a file starting with `crash-`.
|
||||
|
||||
To also detect memory leaks, build with AddressSanitizer (`FUZZER_ENGINE="-fsanitize=fuzzer,address"`): libFuzzer then
|
||||
runs LeakSanitizer by default (`-detect_leaks=1`). LeakSanitizer is not available with Apple Clang on macOS.
|
||||
|
||||
## afl++
|
||||
|
||||
To use afl++, you need to pass `-fsanitize=fuzzer` as `FUZZER_ENGINE`. It will be replaced by a `libAFLDriver.a` to
|
||||
@@ -76,7 +87,9 @@ directory `out`.
|
||||
|
||||
The library is further fuzz-tested 24/7 by Google's [OSS-Fuzz project](https://github.com/google/oss-fuzz). It uses
|
||||
the same `fuzzers` target as above and also relies on the `FUZZER_ENGINE` variable. See the used
|
||||
[build script](https://github.com/google/oss-fuzz/blob/master/projects/json/build.sh) for more information.
|
||||
[build script](https://github.com/google/oss-fuzz/blob/master/projects/json/build.sh) for more information. Its default
|
||||
`address` sanitizer includes LeakSanitizer, so OSS-Fuzz and the CIFuzz workflow (`.github/workflows/cifuzz.yml`) report
|
||||
memory leaks, too.
|
||||
|
||||
In case the build at OSS-Fuzz fails, an issue will be created automatically.
|
||||
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
This file implements a parser test suitable for fuzz testing. Given a byte
|
||||
array data, it performs the following steps:
|
||||
|
||||
- j0 = from_bjdata(data, allow_exceptions = false)
|
||||
- j1 = from_bjdata(data)
|
||||
- assert(j0 is discarded if parsing j1 fails, and j0 == j1 otherwise)
|
||||
- vec2 = to_bjdata(j1, use_size = false, use_type = false)
|
||||
- vec3 = to_bjdata(j1, use_size = true, use_type = false)
|
||||
- vec4 = to_bjdata(j1, use_size = true, use_type = true)
|
||||
@@ -59,6 +61,13 @@ drivers.
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
// compares dumps rather than values, because NaN != NaN; keep writes strings
|
||||
// byte for byte, so ill-formed UTF-8 that a binary reader accepts cannot throw
|
||||
static bool same_value(const json& lhs, const json& rhs)
|
||||
{
|
||||
return lhs.dump(-1, ' ', false, json::error_handler_t::keep) == rhs.dump(-1, ' ', false, json::error_handler_t::keep);
|
||||
}
|
||||
|
||||
// value-stable comparison for the round-trip checks below; see the note
|
||||
// above on why this compares dump()s rather than the json values directly
|
||||
static bool is_value_stable(const json& lhs, const json& rhs)
|
||||
@@ -69,11 +78,37 @@ static bool is_value_stable(const json& lhs, const json& rhs)
|
||||
// see http://llvm.org/docs/LibFuzzer.html
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
{
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
|
||||
// step 0: parse input without exceptions; a parse error must then be
|
||||
// reported as a discarded value, never thrown
|
||||
json j_noexcept;
|
||||
bool noexcept_threw = false;
|
||||
try
|
||||
{
|
||||
j_noexcept = json::from_bjdata(vec1, true, false);
|
||||
}
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
catch (const json::exception&)
|
||||
{
|
||||
// type and out-of-range errors are not parse errors and still throw
|
||||
noexcept_threw = true;
|
||||
}
|
||||
// whether step 1 succeeded; if not, the catch blocks below check that
|
||||
// step 0 failed, too
|
||||
bool parsed = false;
|
||||
|
||||
try
|
||||
{
|
||||
// step 1: parse input
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
json const j1 = json::from_bjdata(vec1);
|
||||
parsed = true;
|
||||
|
||||
// without exceptions, the same input must give the same value
|
||||
assert(!noexcept_threw && !j_noexcept.is_discarded() && same_value(j_noexcept, j1));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -107,14 +142,17 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
// parse errors are ok, because input may be random bytes
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::type_error&)
|
||||
{
|
||||
// type errors can occur during parsing, too
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::out_of_range&)
|
||||
{
|
||||
// out of range errors may happen if provided sizes are excessive
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
|
||||
// return 0 - non-zero return values are reserved for future use
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
This file implements a parser test suitable for fuzz testing. Given a byte
|
||||
array data, it performs the following steps:
|
||||
|
||||
- j0 = from_bon8(data, allow_exceptions = false)
|
||||
- j1 = from_bon8(data)
|
||||
- assert(j0 is discarded if parsing j1 fails, and j0 == j1 otherwise)
|
||||
- vec = to_bon8(j1)
|
||||
- j2 = from_bon8(vec)
|
||||
- assert(to_bon8(j2) == vec)
|
||||
@@ -34,6 +36,13 @@ drivers.
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
// compares dumps rather than values, because NaN != NaN; keep writes strings
|
||||
// byte for byte, so ill-formed UTF-8 that a binary reader accepts cannot throw
|
||||
static bool same_value(const json& lhs, const json& rhs)
|
||||
{
|
||||
return lhs.dump(-1, ' ', false, json::error_handler_t::keep) == rhs.dump(-1, ' ', false, json::error_handler_t::keep);
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
// the serialization of the value read from @a input, or the error message
|
||||
@@ -61,11 +70,37 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
assert(read_bon8(std::vector<uint8_t>(data, data + size)) == read_bon8(stream));
|
||||
}
|
||||
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
|
||||
// step 0: parse input without exceptions; a parse error must then be
|
||||
// reported as a discarded value, never thrown
|
||||
json j_noexcept;
|
||||
bool noexcept_threw = false;
|
||||
try
|
||||
{
|
||||
j_noexcept = json::from_bon8(vec1, true, false);
|
||||
}
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
catch (const json::exception&)
|
||||
{
|
||||
// type and out-of-range errors are not parse errors and still throw
|
||||
noexcept_threw = true;
|
||||
}
|
||||
// whether step 1 succeeded; if not, the catch blocks below check that
|
||||
// step 0 failed, too
|
||||
bool parsed = false;
|
||||
|
||||
try
|
||||
{
|
||||
// step 1: parse input
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
json const j1 = json::from_bon8(vec1);
|
||||
parsed = true;
|
||||
|
||||
// without exceptions, the same input must give the same value
|
||||
assert(!noexcept_threw && !j_noexcept.is_discarded() && same_value(j_noexcept, j1));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -87,14 +122,17 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
// parse errors are ok, because input may be random bytes
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::type_error&)
|
||||
{
|
||||
// type errors can occur during parsing, too
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::out_of_range&)
|
||||
{
|
||||
// out of range errors may happen if provided sizes are excessive
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
|
||||
// return 0 - non-zero return values are reserved for future use
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
This file implements a parser test suitable for fuzz testing. Given a byte
|
||||
array data, it performs the following steps:
|
||||
|
||||
- j0 = from_bson(data, allow_exceptions = false)
|
||||
- j1 = from_bson(data)
|
||||
- assert(j0 is discarded if parsing j1 fails, and j0 == j1 otherwise)
|
||||
- vec = to_bson(j1)
|
||||
- j2 = from_bson(vec)
|
||||
- assert(to_bson(j2) == vec)
|
||||
@@ -29,14 +31,47 @@ drivers.
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
// compares dumps rather than values, because NaN != NaN; keep writes strings
|
||||
// byte for byte, so ill-formed UTF-8 that a binary reader accepts cannot throw
|
||||
static bool same_value(const json& lhs, const json& rhs)
|
||||
{
|
||||
return lhs.dump(-1, ' ', false, json::error_handler_t::keep) == rhs.dump(-1, ' ', false, json::error_handler_t::keep);
|
||||
}
|
||||
|
||||
// see http://llvm.org/docs/LibFuzzer.html
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
{
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
|
||||
// step 0: parse input without exceptions; a parse error must then be
|
||||
// reported as a discarded value, never thrown
|
||||
json j_noexcept;
|
||||
bool noexcept_threw = false;
|
||||
try
|
||||
{
|
||||
j_noexcept = json::from_bson(vec1, true, false);
|
||||
}
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
catch (const json::exception&)
|
||||
{
|
||||
// type and out-of-range errors are not parse errors and still throw
|
||||
noexcept_threw = true;
|
||||
}
|
||||
// whether step 1 succeeded; if not, the catch blocks below check that
|
||||
// step 0 failed, too
|
||||
bool parsed = false;
|
||||
|
||||
try
|
||||
{
|
||||
// step 1: parse input
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
json const j1 = json::from_bson(vec1);
|
||||
parsed = true;
|
||||
|
||||
// without exceptions, the same input must give the same value
|
||||
assert(!noexcept_threw && !j_noexcept.is_discarded() && same_value(j_noexcept, j1));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -58,14 +93,17 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
// parse errors are ok, because input may be random bytes
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::type_error&)
|
||||
{
|
||||
// type errors can occur during parsing, too
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::out_of_range&)
|
||||
{
|
||||
// out of range errors can occur during parsing, too
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
|
||||
// return 0 - non-zero return values are reserved for future use
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
This file implements a parser test suitable for fuzz testing. Given a byte
|
||||
array data, it performs the following steps:
|
||||
|
||||
- j0 = from_cbor(data, allow_exceptions = false)
|
||||
- j1 = from_cbor(data)
|
||||
- assert(j0 is discarded if parsing j1 fails, and j0 == j1 otherwise)
|
||||
- vec = to_cbor(j1)
|
||||
- j2 = from_cbor(vec)
|
||||
- assert(to_cbor(j2) == vec)
|
||||
@@ -29,14 +31,47 @@ drivers.
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
// compares dumps rather than values, because NaN != NaN; keep writes strings
|
||||
// byte for byte, so ill-formed UTF-8 that a binary reader accepts cannot throw
|
||||
static bool same_value(const json& lhs, const json& rhs)
|
||||
{
|
||||
return lhs.dump(-1, ' ', false, json::error_handler_t::keep) == rhs.dump(-1, ' ', false, json::error_handler_t::keep);
|
||||
}
|
||||
|
||||
// see http://llvm.org/docs/LibFuzzer.html
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
{
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
|
||||
// step 0: parse input without exceptions; a parse error must then be
|
||||
// reported as a discarded value, never thrown
|
||||
json j_noexcept;
|
||||
bool noexcept_threw = false;
|
||||
try
|
||||
{
|
||||
j_noexcept = json::from_cbor(vec1, true, false);
|
||||
}
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
catch (const json::exception&)
|
||||
{
|
||||
// type and out-of-range errors are not parse errors and still throw
|
||||
noexcept_threw = true;
|
||||
}
|
||||
// whether step 1 succeeded; if not, the catch blocks below check that
|
||||
// step 0 failed, too
|
||||
bool parsed = false;
|
||||
|
||||
try
|
||||
{
|
||||
// step 1: parse input
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
json const j1 = json::from_cbor(vec1);
|
||||
parsed = true;
|
||||
|
||||
// without exceptions, the same input must give the same value
|
||||
assert(!noexcept_threw && !j_noexcept.is_discarded() && same_value(j_noexcept, j1));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -58,14 +93,17 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
// parse errors are ok, because input may be random bytes
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::type_error&)
|
||||
{
|
||||
// type errors can occur during parsing, too
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::out_of_range&)
|
||||
{
|
||||
// out of range errors can occur during parsing, too
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
|
||||
// return 0 - non-zero return values are reserved for future use
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
This file implements a parser test suitable for fuzz testing. Given a byte
|
||||
array data, it performs the following steps:
|
||||
|
||||
- j0 = parse(data, allow_exceptions = false)
|
||||
- j1 = parse(data)
|
||||
- assert(j0 is discarded if parsing j1 fails, and j0 == j1 otherwise)
|
||||
- s1 = serialize(j1)
|
||||
- j2 = parse(s1)
|
||||
- s2 = serialize(j2)
|
||||
@@ -30,13 +32,45 @@ drivers.
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
// compares dumps rather than values, because NaN != NaN; keep writes strings
|
||||
// byte for byte, so ill-formed UTF-8 that a binary reader accepts cannot throw
|
||||
static bool same_value(const json& lhs, const json& rhs)
|
||||
{
|
||||
return lhs.dump(-1, ' ', false, json::error_handler_t::keep) == rhs.dump(-1, ' ', false, json::error_handler_t::keep);
|
||||
}
|
||||
|
||||
// see http://llvm.org/docs/LibFuzzer.html
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
{
|
||||
// step 0: parse input without exceptions; a parse error must then be
|
||||
// reported as a discarded value, never thrown
|
||||
json j_noexcept;
|
||||
bool noexcept_threw = false;
|
||||
try
|
||||
{
|
||||
j_noexcept = json::parse(data, data + size, nullptr, false);
|
||||
}
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
catch (const json::exception&)
|
||||
{
|
||||
// type and out-of-range errors are not parse errors and still throw
|
||||
noexcept_threw = true;
|
||||
}
|
||||
// whether step 1 succeeded; if not, the catch blocks below check that
|
||||
// step 0 failed, too
|
||||
bool parsed = false;
|
||||
|
||||
try
|
||||
{
|
||||
// step 1: parse input
|
||||
json const j1 = json::parse(data, data + size);
|
||||
parsed = true;
|
||||
|
||||
// without exceptions, the same input must give the same value
|
||||
assert(!noexcept_threw && !j_noexcept.is_discarded() && same_value(j_noexcept, j1));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -63,10 +97,12 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
// parse errors are ok, because input may be random bytes
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::out_of_range&)
|
||||
{
|
||||
// out of range errors may happen if provided sizes are excessive
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
|
||||
// return 0 - non-zero return values are reserved for future use
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
This file implements a parser test suitable for fuzz testing. Given a byte
|
||||
array data, it performs the following steps:
|
||||
|
||||
- j0 = from_msgpack(data, allow_exceptions = false)
|
||||
- j1 = from_msgpack(data)
|
||||
- assert(j0 is discarded if parsing j1 fails, and j0 == j1 otherwise)
|
||||
- vec = to_msgpack(j1)
|
||||
- j2 = from_msgpack(vec)
|
||||
- assert(to_msgpack(j2) == vec)
|
||||
@@ -29,14 +31,47 @@ drivers.
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
// compares dumps rather than values, because NaN != NaN; keep writes strings
|
||||
// byte for byte, so ill-formed UTF-8 that a binary reader accepts cannot throw
|
||||
static bool same_value(const json& lhs, const json& rhs)
|
||||
{
|
||||
return lhs.dump(-1, ' ', false, json::error_handler_t::keep) == rhs.dump(-1, ' ', false, json::error_handler_t::keep);
|
||||
}
|
||||
|
||||
// see http://llvm.org/docs/LibFuzzer.html
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
{
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
|
||||
// step 0: parse input without exceptions; a parse error must then be
|
||||
// reported as a discarded value, never thrown
|
||||
json j_noexcept;
|
||||
bool noexcept_threw = false;
|
||||
try
|
||||
{
|
||||
j_noexcept = json::from_msgpack(vec1, true, false);
|
||||
}
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
catch (const json::exception&)
|
||||
{
|
||||
// type and out-of-range errors are not parse errors and still throw
|
||||
noexcept_threw = true;
|
||||
}
|
||||
// whether step 1 succeeded; if not, the catch blocks below check that
|
||||
// step 0 failed, too
|
||||
bool parsed = false;
|
||||
|
||||
try
|
||||
{
|
||||
// step 1: parse input
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
json const j1 = json::from_msgpack(vec1);
|
||||
parsed = true;
|
||||
|
||||
// without exceptions, the same input must give the same value
|
||||
assert(!noexcept_threw && !j_noexcept.is_discarded() && same_value(j_noexcept, j1));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -58,14 +93,17 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
// parse errors are ok, because input may be random bytes
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::type_error&)
|
||||
{
|
||||
// type errors can occur during parsing, too
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::out_of_range&)
|
||||
{
|
||||
// out of range errors may happen if provided sizes are excessive
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
|
||||
// return 0 - non-zero return values are reserved for future use
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
This file implements a parser test suitable for fuzz testing. Given a byte
|
||||
array data, it performs the following steps:
|
||||
|
||||
- j0 = from_ubjson(data, allow_exceptions = false)
|
||||
- j1 = from_ubjson(data)
|
||||
- assert(j0 is discarded if parsing j1 fails, and j0 == j1 otherwise)
|
||||
- vec2 = to_ubjson(j1, use_size = false, use_type = false)
|
||||
- vec3 = to_ubjson(j1, use_size = true, use_type = false)
|
||||
- vec4 = to_ubjson(j1, use_size = true, use_type = true)
|
||||
@@ -38,14 +40,47 @@ drivers.
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
// compares dumps rather than values, because NaN != NaN; keep writes strings
|
||||
// byte for byte, so ill-formed UTF-8 that a binary reader accepts cannot throw
|
||||
static bool same_value(const json& lhs, const json& rhs)
|
||||
{
|
||||
return lhs.dump(-1, ' ', false, json::error_handler_t::keep) == rhs.dump(-1, ' ', false, json::error_handler_t::keep);
|
||||
}
|
||||
|
||||
// see http://llvm.org/docs/LibFuzzer.html
|
||||
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
{
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
|
||||
// step 0: parse input without exceptions; a parse error must then be
|
||||
// reported as a discarded value, never thrown
|
||||
json j_noexcept;
|
||||
bool noexcept_threw = false;
|
||||
try
|
||||
{
|
||||
j_noexcept = json::from_ubjson(vec1, true, false);
|
||||
}
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
catch (const json::exception&)
|
||||
{
|
||||
// type and out-of-range errors are not parse errors and still throw
|
||||
noexcept_threw = true;
|
||||
}
|
||||
// whether step 1 succeeded; if not, the catch blocks below check that
|
||||
// step 0 failed, too
|
||||
bool parsed = false;
|
||||
|
||||
try
|
||||
{
|
||||
// step 1: parse input
|
||||
std::vector<uint8_t> const vec1(data, data + size);
|
||||
json const j1 = json::from_ubjson(vec1);
|
||||
parsed = true;
|
||||
|
||||
// without exceptions, the same input must give the same value
|
||||
assert(!noexcept_threw && !j_noexcept.is_discarded() && same_value(j_noexcept, j1));
|
||||
|
||||
try
|
||||
{
|
||||
@@ -77,14 +112,17 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||
catch (const json::parse_error&)
|
||||
{
|
||||
// parse errors are ok, because input may be random bytes
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::type_error&)
|
||||
{
|
||||
// type errors can occur during parsing, too
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
catch (const json::out_of_range&)
|
||||
{
|
||||
// out of range errors may happen if provided sizes are excessive
|
||||
assert(parsed || noexcept_threw || j_noexcept.is_discarded());
|
||||
}
|
||||
|
||||
// return 0 - non-zero return values are reserved for future use
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <array> // array
|
||||
#include <cstdint> // uint8_t
|
||||
#include <cstddef> // size_t
|
||||
#include <fstream> // ifstream, ios
|
||||
@@ -43,6 +44,33 @@ T next_integer_sample(T i, T last, T stride)
|
||||
return n < last ? n : last;
|
||||
}
|
||||
|
||||
// UTF-8 continuation bytes in [lo, hi] that stand in for all of them in the
|
||||
// ill-formed UTF-8 tests. Both the lexer's range checks and the serializer's
|
||||
// decoder (detail::decode) only distinguish the classes 0x80..0x8F, 0x90..0x9F,
|
||||
// and 0xA0..0xBF, so the first and last byte of each class within [lo, hi]
|
||||
// exercise every behavior while a test sweeps another byte position through
|
||||
// all 256 values (#5418). Define JSON_TEST_UTF8_EXHAUSTIVE to get every byte.
|
||||
inline std::vector<int> utf8_continuation_bytes(int lo, int hi)
|
||||
{
|
||||
std::vector<int> result;
|
||||
#ifdef JSON_TEST_UTF8_EXHAUSTIVE
|
||||
for (int byte = lo; byte <= hi; ++byte)
|
||||
{
|
||||
result.push_back(byte);
|
||||
}
|
||||
#else
|
||||
static const std::array<int, 6> class_ends = {{0x80, 0x8F, 0x90, 0x9F, 0xA0, 0xBF}};
|
||||
for (const int byte : class_ends)
|
||||
{
|
||||
if (lo <= byte && byte <= hi)
|
||||
{
|
||||
result.push_back(byte);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
|
||||
inline std::vector<std::uint8_t> read_binary_file(const std::string& filename)
|
||||
{
|
||||
std::ifstream file(filename, std::ios::binary);
|
||||
|
||||
+268
-24
@@ -12,6 +12,11 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <valarray>
|
||||
#if JSON_HAS_RANGES
|
||||
#include <ranges>
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
// special test case to check if memory is leaked if constructor throws
|
||||
@@ -48,14 +53,7 @@ TEST_CASE("bad_alloc")
|
||||
SECTION("bad_alloc")
|
||||
{
|
||||
// create JSON type using the throwing allocator
|
||||
using bad_json = nlohmann::basic_json<std::map,
|
||||
std::vector,
|
||||
std::string,
|
||||
bool,
|
||||
std::int64_t,
|
||||
std::uint64_t,
|
||||
double,
|
||||
bad_allocator>;
|
||||
using bad_json = nlohmann::json::with_allocator_t<bad_allocator>;
|
||||
|
||||
// creating an object should throw
|
||||
CHECK_THROWS_AS(bad_json(bad_json::value_t::object), std::bad_alloc&);
|
||||
@@ -129,14 +127,7 @@ void my_allocator_clean_up(T* p)
|
||||
TEST_CASE("controlled bad_alloc")
|
||||
{
|
||||
// create JSON type using the throwing allocator
|
||||
using my_json = nlohmann::basic_json<std::map,
|
||||
std::vector,
|
||||
std::string,
|
||||
bool,
|
||||
std::int64_t,
|
||||
std::uint64_t,
|
||||
double,
|
||||
my_allocator>;
|
||||
using my_json = nlohmann::json::with_allocator_t<my_allocator>;
|
||||
|
||||
SECTION("class json_value")
|
||||
{
|
||||
@@ -521,6 +512,10 @@ struct countdown_allocator : std::allocator<T>
|
||||
|
||||
TEST_CASE("converting a deeply nested value from another specialization fails cleanly (#5650)")
|
||||
{
|
||||
// MSVC 2015's debug STL constructs the containers' debug proxies through
|
||||
// the allocator in noexcept constructors, so a failing construction crashes
|
||||
// the program there instead of throwing std::bad_alloc. Nothing to check.
|
||||
#if !(defined(_MSC_VER) && _MSC_VER < 1910 && defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL > 0)
|
||||
using countdown_json = nlohmann::basic_json<std::map,
|
||||
std::vector,
|
||||
std::string,
|
||||
@@ -558,6 +553,7 @@ TEST_CASE("converting a deeply nested value from another specialization fails cl
|
||||
}
|
||||
}
|
||||
CHECK(failures > 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
namespace
|
||||
@@ -588,17 +584,265 @@ TEST_CASE("bad my_allocator::construct")
|
||||
{
|
||||
SECTION("my_allocator::construct doesn't forward")
|
||||
{
|
||||
using bad_alloc_json = nlohmann::basic_json<std::map,
|
||||
std::vector,
|
||||
std::string,
|
||||
bool,
|
||||
std::int64_t,
|
||||
std::uint64_t,
|
||||
double,
|
||||
allocator_no_forward>;
|
||||
using bad_alloc_json = nlohmann::json::with_allocator_t<allocator_no_forward>;
|
||||
|
||||
bad_alloc_json j;
|
||||
j["test"] = bad_alloc_json::array_t();
|
||||
j["test"].push_back("should not leak");
|
||||
}
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
std::size_t counting_allocator_allocations = 0;
|
||||
std::size_t counting_allocator_deallocations = 0;
|
||||
|
||||
template<class T>
|
||||
struct counting_allocator : std::allocator<T>
|
||||
{
|
||||
using std::allocator<T>::allocator;
|
||||
|
||||
T* allocate(std::size_t n)
|
||||
{
|
||||
++counting_allocator_allocations;
|
||||
return std::allocator<T>::allocate(n);
|
||||
}
|
||||
|
||||
void deallocate(T* p, std::size_t n)
|
||||
{
|
||||
++counting_allocator_deallocations;
|
||||
std::allocator<T>::deallocate(p, n);
|
||||
}
|
||||
|
||||
template <class U>
|
||||
struct rebind
|
||||
{
|
||||
using other = counting_allocator<U>;
|
||||
};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("destructor performs no allocation, only deallocation")
|
||||
{
|
||||
// see https://github.com/nlohmann/json/issues/4842 and
|
||||
// https://github.com/nlohmann/json/issues/5135: destroying nested
|
||||
// arrays/objects used to allocate a temporary stack (first with
|
||||
// std::allocator, later - after #4842 - with the provided allocator).
|
||||
// Since that stack could itself throw bad_alloc from inside the
|
||||
// noexcept destructor (#5135), destroy() no longer allocates anything:
|
||||
// it only ever frees what is already there.
|
||||
using counting_json = nlohmann::basic_json<std::map,
|
||||
std::vector,
|
||||
std::string,
|
||||
bool,
|
||||
std::int64_t,
|
||||
std::uint64_t,
|
||||
double,
|
||||
counting_allocator>;
|
||||
|
||||
SECTION("array")
|
||||
{
|
||||
auto* j = new counting_json({1, {2, {3, 4}}, 5}); // NOLINT(cppcoreguidelines-owning-memory)
|
||||
const auto allocations_before = counting_allocator_allocations;
|
||||
const auto deallocations_before = counting_allocator_deallocations;
|
||||
delete j; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
CHECK(counting_allocator_allocations == allocations_before);
|
||||
CHECK(counting_allocator_deallocations > deallocations_before);
|
||||
}
|
||||
|
||||
SECTION("object")
|
||||
{
|
||||
auto* j = new counting_json({{"a", {{"b", {1, 2}}}}, {"c", 3}}); // NOLINT(cppcoreguidelines-owning-memory)
|
||||
const auto allocations_before = counting_allocator_allocations;
|
||||
const auto deallocations_before = counting_allocator_deallocations;
|
||||
delete j; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
CHECK(counting_allocator_allocations == allocations_before);
|
||||
CHECK(counting_allocator_deallocations > deallocations_before);
|
||||
}
|
||||
|
||||
SECTION("mixed tree of empty/non-empty arrays and objects")
|
||||
{
|
||||
auto* j = new counting_json( // NOLINT(cppcoreguidelines-owning-memory)
|
||||
{
|
||||
{"empty_obj", counting_json::object()},
|
||||
{"empty_arr", counting_json::array()},
|
||||
{"nested", {{"a", counting_json::array({1, 2, counting_json::object()})}, {"b", 3}}},
|
||||
{"tail", counting_json::array({counting_json::array({1}), 2, counting_json::array({3})})}
|
||||
});
|
||||
const auto allocations_before = counting_allocator_allocations;
|
||||
const auto deallocations_before = counting_allocator_deallocations;
|
||||
delete j; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
CHECK(counting_allocator_allocations == allocations_before);
|
||||
CHECK(counting_allocator_deallocations > deallocations_before);
|
||||
}
|
||||
}
|
||||
|
||||
// the no-exceptions CI job skips every CHECK_THROWS_AS, which would leave
|
||||
// next_construct_fails set for the next allocation outside a check
|
||||
#if !defined(JSON_NOEXCEPTION)
|
||||
TEST_CASE("a failed allocation leaves the value unchanged")
|
||||
{
|
||||
// create JSON type using the throwing allocator
|
||||
using my_json = nlohmann::basic_json<std::map,
|
||||
std::vector,
|
||||
std::string,
|
||||
bool,
|
||||
std::int64_t,
|
||||
std::uint64_t,
|
||||
double,
|
||||
my_allocator>;
|
||||
|
||||
// Each of these creates a string, array, object, or binary value. The
|
||||
// value must be created before the type is changed: otherwise, a failed
|
||||
// creation left a value of the new type without anything behind it (an
|
||||
// assertion in its destructor, a null pointer everywhere else) or, when
|
||||
// an old value was destroyed first, with a pointer to that destroyed one.
|
||||
|
||||
SECTION("creating a binary value")
|
||||
{
|
||||
const std::vector<std::uint8_t> bytes = {1, 2, 3};
|
||||
my_json _;
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(_ = my_json::binary(bytes), std::bad_alloc&);
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(_ = my_json::binary(bytes, 42), std::bad_alloc&);
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(_ = my_json::binary(std::vector<std::uint8_t>(bytes)), std::bad_alloc&);
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(_ = my_json::binary(std::vector<std::uint8_t>(bytes), 42), std::bad_alloc&);
|
||||
next_construct_fails = false;
|
||||
}
|
||||
|
||||
SECTION("turning a null value into an array or object")
|
||||
{
|
||||
my_json j;
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j[0], std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j["key"], std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j[std::string_view("key")], std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
#endif
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j.push_back(my_json(1)), std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
|
||||
const my_json one = 1;
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j.push_back(one), std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j.push_back(my_json::object_t::value_type("key", 1)), std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j.emplace_back(1), std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j.emplace("key", 1), std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
|
||||
const my_json object = {{"key", 1}};
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(j.update(object), std::bad_alloc&);
|
||||
CHECK(j.is_null());
|
||||
|
||||
next_construct_fails = false;
|
||||
}
|
||||
|
||||
// With iterator debugging, VS 2015's containers construct a proxy with the
|
||||
// allocator in constructors that cannot report its failure, so a failing
|
||||
// allocator crashes this section there (SIGSEGV with VS 2015 Debug x86).
|
||||
#if !(defined(_MSC_VER) && _MSC_VER < 1910 && defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL > 0)
|
||||
SECTION("converting into an existing value")
|
||||
{
|
||||
// to_json replaces the value it is given; the old one must survive a
|
||||
// failed creation of the new one
|
||||
my_json j = "old";
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, std::string("new")), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, std::vector<int> {1, 2}), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, std::vector<bool> {true, false}), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, std::map<std::string, int> {{"a", 1}}), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, my_json::binary_t({1, 2})), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
// the overloads for lvalues of the value types, for the value types
|
||||
// themselves, and for the remaining compatible types
|
||||
const std::string string = "new";
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, string), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, "new"), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
// to_json only moves a binary value that it converted from another
|
||||
// container type, which my_json's std::vector<std::uint8_t> is not
|
||||
using binary_constructor = nlohmann::detail::external_constructor<nlohmann::detail::value_t::binary>;
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(binary_constructor::construct(j, my_json::binary_t({1, 2})), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
my_json::array_t array = {1, 2};
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, array), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, std::move(array)), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
my_json::object_t object = {{"a", 1}};
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, object), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, std::move(object)), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, std::valarray<int> {1, 2}), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||
const std::vector<int> numbers = {1, 2};
|
||||
next_construct_fails = true;
|
||||
CHECK_THROWS_AS(nlohmann::to_json(j, numbers | std::views::filter([](int /*unused*/)
|
||||
{
|
||||
return true;
|
||||
})), std::bad_alloc&);
|
||||
CHECK(j == "old");
|
||||
#endif
|
||||
|
||||
next_construct_fails = false;
|
||||
nlohmann::to_json(j, std::vector<int> {1, 2});
|
||||
CHECK(j == my_json({1, 2}));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -163,16 +163,7 @@ void int_to_string(alt_string& target, std::size_t value)
|
||||
target = std::to_string(value).c_str();
|
||||
}
|
||||
|
||||
using alt_json = nlohmann::basic_json <
|
||||
std::map,
|
||||
std::vector,
|
||||
alt_string,
|
||||
bool,
|
||||
std::int64_t,
|
||||
std::uint64_t,
|
||||
double,
|
||||
std::allocator,
|
||||
nlohmann::adl_serializer >;
|
||||
using alt_json = nlohmann::json::with_string_t<alt_string>;
|
||||
|
||||
bool operator<(const char* op1, const alt_string& op2) noexcept
|
||||
{
|
||||
|
||||
@@ -11,10 +11,15 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "make_test_data_available.hpp"
|
||||
|
||||
TEST_CASE("Binary Formats" * doctest::skip())
|
||||
TEST_CASE("Binary Formats")
|
||||
{
|
||||
SECTION("canada.json")
|
||||
{
|
||||
@@ -142,48 +147,6 @@ TEST_CASE("Binary Formats" * doctest::skip())
|
||||
CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(84.963));
|
||||
}
|
||||
|
||||
SECTION("jeopardy.json")
|
||||
{
|
||||
const auto* filename = TEST_DATA_DIRECTORY "/jeopardy/jeopardy.json";
|
||||
json j = json::parse(std::ifstream(filename));
|
||||
|
||||
const auto json_size = j.dump().size();
|
||||
const auto bjdata_1_size = json::to_bjdata(j).size();
|
||||
const auto bjdata_2_size = json::to_bjdata(j, true).size();
|
||||
const auto bjdata_3_size = json::to_bjdata(j, true, true).size();
|
||||
const auto bon8_size = json::to_bon8(j).size();
|
||||
const auto bson_size = json::to_bson({{"", j}}).size(); // wrap array in object for BSON
|
||||
const auto cbor_size = json::to_cbor(j).size();
|
||||
const auto msgpack_size = json::to_msgpack(j).size();
|
||||
const auto ubjson_1_size = json::to_ubjson(j).size();
|
||||
const auto ubjson_2_size = json::to_ubjson(j, true).size();
|
||||
const auto ubjson_3_size = json::to_ubjson(j, true, true).size();
|
||||
|
||||
CHECK(json_size == 52508728);
|
||||
CHECK(bjdata_1_size == 50710965);
|
||||
CHECK(bjdata_2_size == 51144830);
|
||||
CHECK(bjdata_3_size == 51144830);
|
||||
CHECK(bon8_size == 45942080);
|
||||
CHECK(bson_size == 56008520);
|
||||
CHECK(cbor_size == 46187320);
|
||||
CHECK(msgpack_size == 46158575);
|
||||
CHECK(ubjson_1_size == 50710965);
|
||||
CHECK(ubjson_2_size == 51144830);
|
||||
CHECK(ubjson_3_size == 49861422);
|
||||
|
||||
CHECK((100.0 * double(json_size) / double(json_size)) == Approx(100.0));
|
||||
CHECK((100.0 * double(bjdata_1_size) / double(json_size)) == Approx(96.576));
|
||||
CHECK((100.0 * double(bjdata_2_size) / double(json_size)) == Approx(97.402));
|
||||
CHECK((100.0 * double(bjdata_3_size) / double(json_size)) == Approx(97.402));
|
||||
CHECK((100.0 * double(bon8_size) / double(json_size)) == Approx(87.494));
|
||||
CHECK((100.0 * double(bson_size) / double(json_size)) == Approx(106.665));
|
||||
CHECK((100.0 * double(cbor_size) / double(json_size)) == Approx(87.961));
|
||||
CHECK((100.0 * double(msgpack_size) / double(json_size)) == Approx(87.906));
|
||||
CHECK((100.0 * double(ubjson_1_size) / double(json_size)) == Approx(96.576));
|
||||
CHECK((100.0 * double(ubjson_2_size) / double(json_size)) == Approx(97.402));
|
||||
CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(94.958));
|
||||
}
|
||||
|
||||
SECTION("sample.json")
|
||||
{
|
||||
const auto* filename = TEST_DATA_DIRECTORY "/json_testsuite/sample.json";
|
||||
@@ -224,3 +187,183 @@ TEST_CASE("Binary Formats" * doctest::skip())
|
||||
CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(89.450));
|
||||
}
|
||||
}
|
||||
|
||||
// jeopardy.json is 52 MB and produces ~500 MB of serialization output, so it
|
||||
// is kept apart from the cheap corpus files above (#5418)
|
||||
TEST_CASE("Binary Formats (jeopardy.json)" * doctest::skip())
|
||||
{
|
||||
const auto* filename = TEST_DATA_DIRECTORY "/jeopardy/jeopardy.json";
|
||||
json j = json::parse(std::ifstream(filename));
|
||||
|
||||
const auto json_size = j.dump().size();
|
||||
const auto bjdata_1_size = json::to_bjdata(j).size();
|
||||
const auto bjdata_2_size = json::to_bjdata(j, true).size();
|
||||
const auto bjdata_3_size = json::to_bjdata(j, true, true).size();
|
||||
const auto bon8_size = json::to_bon8(j).size();
|
||||
const auto bson_size = json::to_bson({{"", j}}).size(); // wrap array in object for BSON
|
||||
const auto cbor_size = json::to_cbor(j).size();
|
||||
const auto msgpack_size = json::to_msgpack(j).size();
|
||||
const auto ubjson_1_size = json::to_ubjson(j).size();
|
||||
const auto ubjson_2_size = json::to_ubjson(j, true).size();
|
||||
const auto ubjson_3_size = json::to_ubjson(j, true, true).size();
|
||||
|
||||
CHECK(json_size == 52508728);
|
||||
CHECK(bjdata_1_size == 50710965);
|
||||
CHECK(bjdata_2_size == 51144830);
|
||||
CHECK(bjdata_3_size == 51144830);
|
||||
CHECK(bon8_size == 45942080);
|
||||
CHECK(bson_size == 56008520);
|
||||
CHECK(cbor_size == 46187320);
|
||||
CHECK(msgpack_size == 46158575);
|
||||
CHECK(ubjson_1_size == 50710965);
|
||||
CHECK(ubjson_2_size == 51144830);
|
||||
CHECK(ubjson_3_size == 49861422);
|
||||
|
||||
CHECK((100.0 * double(json_size) / double(json_size)) == Approx(100.0));
|
||||
CHECK((100.0 * double(bjdata_1_size) / double(json_size)) == Approx(96.576));
|
||||
CHECK((100.0 * double(bjdata_2_size) / double(json_size)) == Approx(97.402));
|
||||
CHECK((100.0 * double(bjdata_3_size) / double(json_size)) == Approx(97.402));
|
||||
CHECK((100.0 * double(bon8_size) / double(json_size)) == Approx(87.494));
|
||||
CHECK((100.0 * double(bson_size) / double(json_size)) == Approx(106.665));
|
||||
CHECK((100.0 * double(cbor_size) / double(json_size)) == Approx(87.961));
|
||||
CHECK((100.0 * double(msgpack_size) / double(json_size)) == Approx(87.906));
|
||||
CHECK((100.0 * double(ubjson_1_size) / double(json_size)) == Approx(96.576));
|
||||
CHECK((100.0 * double(ubjson_2_size) / double(json_size)) == Approx(97.402));
|
||||
CHECK((100.0 * double(ubjson_3_size) / double(json_size)) == Approx(94.958));
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
// the binary formats as function pointers for "Binary formats with narrow number types";
|
||||
// named functions rather than lambdas, because clang 3.5 cannot convert a lambda
|
||||
// to a function pointer in the braced initializer of the format table
|
||||
using narrow_json = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int32_t, std::uint32_t, float>;
|
||||
using bytes = std::vector<std::uint8_t>;
|
||||
|
||||
bytes encode_cbor(const json& j)
|
||||
{
|
||||
return json::to_cbor(j);
|
||||
}
|
||||
narrow_json decode_cbor(const bytes& v, bool allow_exceptions)
|
||||
{
|
||||
return narrow_json::from_cbor(v, true, allow_exceptions);
|
||||
}
|
||||
|
||||
bytes encode_msgpack(const json& j)
|
||||
{
|
||||
return json::to_msgpack(j);
|
||||
}
|
||||
narrow_json decode_msgpack(const bytes& v, bool allow_exceptions)
|
||||
{
|
||||
return narrow_json::from_msgpack(v, true, allow_exceptions);
|
||||
}
|
||||
|
||||
bytes encode_ubjson(const json& j)
|
||||
{
|
||||
return json::to_ubjson(j);
|
||||
}
|
||||
narrow_json decode_ubjson(const bytes& v, bool allow_exceptions)
|
||||
{
|
||||
return narrow_json::from_ubjson(v, true, allow_exceptions);
|
||||
}
|
||||
|
||||
bytes encode_bjdata(const json& j)
|
||||
{
|
||||
return json::to_bjdata(j);
|
||||
}
|
||||
narrow_json decode_bjdata(const bytes& v, bool allow_exceptions)
|
||||
{
|
||||
return narrow_json::from_bjdata(v, true, allow_exceptions);
|
||||
}
|
||||
|
||||
// BSON can only store numbers as object members
|
||||
bytes encode_bson(const json& j)
|
||||
{
|
||||
return json::to_bson(json{{"a", j}});
|
||||
}
|
||||
narrow_json decode_bson(const bytes& v, bool allow_exceptions)
|
||||
{
|
||||
const auto result = narrow_json::from_bson(v, true, allow_exceptions);
|
||||
return result.is_discarded() ? result : result.at("a");
|
||||
}
|
||||
|
||||
bytes encode_bon8(const json& j)
|
||||
{
|
||||
return json::to_bon8(j);
|
||||
}
|
||||
narrow_json decode_bon8(const bytes& v, bool allow_exceptions)
|
||||
{
|
||||
return narrow_json::from_bon8(v, true, allow_exceptions);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Binary formats with narrow number types")
|
||||
{
|
||||
// Numbers that do not fit the number types are handled like the lexer
|
||||
// handles them in JSON text: an integer that fits neither integer type is
|
||||
// stored as a floating-point number, and a finite floating-point number
|
||||
// that overflows number_float_t is rejected with out_of_range.406.
|
||||
struct binary_format
|
||||
{
|
||||
const char* name;
|
||||
bytes (*encode)(const json&);
|
||||
narrow_json (*decode)(const bytes&, bool);
|
||||
};
|
||||
|
||||
const std::vector<binary_format> formats =
|
||||
{
|
||||
{"CBOR", encode_cbor, decode_cbor},
|
||||
{"MessagePack", encode_msgpack, decode_msgpack},
|
||||
{"UBJSON", encode_ubjson, decode_ubjson},
|
||||
{"BJData", encode_bjdata, decode_bjdata},
|
||||
{"BSON", encode_bson, decode_bson},
|
||||
{"BON8", encode_bon8, decode_bon8},
|
||||
};
|
||||
|
||||
for (const auto& format : formats)
|
||||
{
|
||||
const std::string name = format.name;
|
||||
INFO("format := ", name);
|
||||
const auto roundtrip = [&format](const json & j)
|
||||
{
|
||||
return format.decode(format.encode(j), true);
|
||||
};
|
||||
|
||||
// integers that fit keep their type
|
||||
CHECK(roundtrip(json(-5)).is_number_integer());
|
||||
CHECK(roundtrip(json(-5)).get<std::int32_t>() == -5);
|
||||
CHECK(roundtrip(json(3000000000u)).is_number_unsigned());
|
||||
CHECK(roundtrip(json(3000000000u)).get<std::uint32_t>() == 3000000000u);
|
||||
|
||||
// integers that fit neither integer type are stored as float
|
||||
CHECK(roundtrip(json(5000000000u)).is_number_float());
|
||||
CHECK(roundtrip(json(5000000000u)).get<float>() == 5000000000.0f);
|
||||
if (name != "BON8") // BON8 cannot encode integers above INT64_MAX
|
||||
{
|
||||
CHECK(roundtrip(json(10000000000000000000u)).is_number_float());
|
||||
CHECK(roundtrip(json(10000000000000000000u)).get<float>() == 10000000000000000000.0f);
|
||||
}
|
||||
CHECK(roundtrip(json(-3000000000LL)).is_number_float());
|
||||
CHECK(roundtrip(json(-3000000000LL)).get<float>() == -3000000000.0f);
|
||||
CHECK(roundtrip(json(-5000000000LL)).is_number_float());
|
||||
CHECK(roundtrip(json(-5000000000LL)).get<float>() == -5000000000.0f);
|
||||
|
||||
// floating-point numbers that fit
|
||||
CHECK(roundtrip(json(1.5)).get<float>() == 1.5f);
|
||||
const auto just_above_max = std::nextafter(static_cast<double>((std::numeric_limits<float>::max)()),
|
||||
std::numeric_limits<double>::infinity());
|
||||
CHECK(roundtrip(json(just_above_max)).get<float>() == (std::numeric_limits<float>::max)());
|
||||
|
||||
// infinity and NaN are passed on
|
||||
CHECK(std::isinf(roundtrip(json(std::numeric_limits<double>::infinity())).get<float>()));
|
||||
CHECK(std::isnan(roundtrip(json(std::numeric_limits<double>::quiet_NaN())).get<float>()));
|
||||
|
||||
// finite floating-point numbers that overflow number_float_t are rejected
|
||||
const std::string message = "[json.exception.out_of_range.406] syntax error while parsing " + name
|
||||
+ " value: number overflow";
|
||||
CHECK_THROWS_WITH_AS(roundtrip(json(1e300)), message.c_str(), narrow_json::out_of_range&);
|
||||
CHECK_THROWS_WITH_AS(roundtrip(json(-1e300)), message.c_str(), narrow_json::out_of_range&);
|
||||
CHECK(format.decode(format.encode(json(1e300)), false).is_discarded());
|
||||
}
|
||||
}
|
||||
+204
-7
@@ -9,8 +9,17 @@
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
#define JSON_TESTS_PRIVATE
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
using ordered_json = nlohmann::ordered_json;
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
@@ -106,10 +115,59 @@ TEST_CASE("BJData")
|
||||
{
|
||||
SECTION("discarded")
|
||||
{
|
||||
// discarded values are not serialized
|
||||
// a discarded value cannot be serialized to BJData
|
||||
json const j = json::value_t::discarded;
|
||||
const auto result = json::to_bjdata(j);
|
||||
CHECK(result.empty());
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j), "[json.exception.type_error.321] cannot serialize discarded value to BJData", json::type_error&);
|
||||
}
|
||||
|
||||
SECTION("discarded values nested in a container")
|
||||
{
|
||||
json const discarded = json::value_t::discarded;
|
||||
|
||||
SECTION("in an array")
|
||||
{
|
||||
json const j = {1, discarded, 2};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j), "[json.exception.type_error.321] (/1) cannot serialize discarded value to BJData", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j), "[json.exception.type_error.321] cannot serialize discarded value to BJData", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("as an object value")
|
||||
{
|
||||
json j;
|
||||
j["a"] = 1;
|
||||
j["b"] = discarded;
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j), "[json.exception.type_error.321] (/b) cannot serialize discarded value to BJData", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j), "[json.exception.type_error.321] cannot serialize discarded value to BJData", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("nested deeper (array in object in array)")
|
||||
{
|
||||
json inner_array = {1, discarded};
|
||||
json middle_object;
|
||||
middle_object["x"] = inner_array;
|
||||
json const j = {middle_object};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j), "[json.exception.type_error.321] (/0/x/1) cannot serialize discarded value to BJData", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j), "[json.exception.type_error.321] cannot serialize discarded value to BJData", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("optimized array of all-discarded elements")
|
||||
{
|
||||
json const j = {discarded, discarded};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j, true, true), "[json.exception.type_error.321] (/0) cannot serialize discarded value to BJData", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(j, true, true), "[json.exception.type_error.321] cannot serialize discarded value to BJData", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("null")
|
||||
@@ -1229,6 +1287,32 @@ TEST_CASE("BJData")
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vec2), "[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing BJData high-precision number: invalid number text: 1A", json::parse_error);
|
||||
std::vector<uint8_t> const vec3 = {'H', 'i', 2, '1', '.'};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vec3), "[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing BJData high-precision number: invalid number text: 1.", json::parse_error);
|
||||
// Reject NULs where they are read, including trailing NULs and payloads cut off after one.
|
||||
SECTION("NUL in high-precision number (issue #5753)")
|
||||
{
|
||||
for (const auto& vec : std::vector<std::vector<uint8_t>>
|
||||
{
|
||||
{'H', 'i', 3, '1', 0, 'x'},
|
||||
{'H', 'i', 2, '1', 0},
|
||||
{'H', 'i', 3, '1', 0}
|
||||
})
|
||||
{
|
||||
CAPTURE(vec)
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vec), "[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing BJData high-precision number: invalid number text; last byte: 0x00", json::parse_error);
|
||||
CHECK(json::from_bjdata(vec, true, false).is_discarded());
|
||||
CHECK(json::from_bjdata(vec, false, false).is_discarded());
|
||||
}
|
||||
|
||||
std::vector<uint8_t> const nested = {'[', 'H', 'i', 3, '1', 0, 'x', ']'};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(nested), "[json.exception.parse_error.115] parse error at byte 6: syntax error while parsing BJData high-precision number: invalid number text; last byte: 0x00", json::parse_error);
|
||||
CHECK(json::from_bjdata(nested, true, false).is_discarded());
|
||||
|
||||
std::vector<uint8_t> const valid = {'H', 'i', 1, '1'};
|
||||
const auto j = json::from_bjdata(valid);
|
||||
CHECK(j.is_number_unsigned());
|
||||
CHECK(j == json(1));
|
||||
}
|
||||
|
||||
std::vector<uint8_t> const vec_overflow = {'H', 'i', 5, '1', 'e', '4', '0', '0'};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vec_overflow), "[json.exception.out_of_range.406] number overflow parsing '1e400'", json::out_of_range);
|
||||
std::vector<uint8_t> const vec4 = {'H', 2, '1', '0'};
|
||||
@@ -2175,29 +2259,33 @@ TEST_CASE("BJData")
|
||||
|
||||
SECTION("start_array() in ndarray _ArraySize_")
|
||||
{
|
||||
// _ArrayType_ (2 events: key + string) is now emitted before
|
||||
// _ArraySize_ (see GitHub issue #5661), which shifts the events
|
||||
// below later by the same 2 events
|
||||
std::vector<uint8_t> const v = {'[', '$', 'i', '#', '[', '$', 'i', '#', 'i', 2, 2, 1, 1, 2};
|
||||
SaxCountdown scp(2);
|
||||
SaxCountdown scp(4);
|
||||
CHECK_FALSE(json::sax_parse(v, &scp, json::input_format_t::bjdata));
|
||||
}
|
||||
|
||||
SECTION("number_integer() in ndarray _ArraySize_")
|
||||
{
|
||||
std::vector<uint8_t> const v = {'[', '$', 'U', '#', '[', '$', 'i', '#', 'i', 2, 2, 1, 1, 2};
|
||||
SaxCountdown scp(3);
|
||||
SaxCountdown scp(5);
|
||||
CHECK_FALSE(json::sax_parse(v, &scp, json::input_format_t::bjdata));
|
||||
}
|
||||
|
||||
SECTION("key() in ndarray _ArrayType_")
|
||||
{
|
||||
// _ArrayType_ is emitted right after start_object(), before _ArraySize_
|
||||
std::vector<uint8_t> const v = {'[', '$', 'U', '#', '[', '$', 'U', '#', 'i', 2, 2, 2, 1, 2, 3, 4};
|
||||
SaxCountdown scp(6);
|
||||
SaxCountdown scp(1);
|
||||
CHECK_FALSE(json::sax_parse(v, &scp, json::input_format_t::bjdata));
|
||||
}
|
||||
|
||||
SECTION("string() in ndarray _ArrayType_")
|
||||
{
|
||||
std::vector<uint8_t> const v = {'[', '$', 'U', '#', '[', '$', 'U', '#', 'i', 2, 2, 2, 1, 2, 3, 4};
|
||||
SaxCountdown scp(7);
|
||||
SaxCountdown scp(2);
|
||||
CHECK_FALSE(json::sax_parse(v, &scp, json::input_format_t::bjdata));
|
||||
}
|
||||
|
||||
@@ -2800,6 +2888,22 @@ TEST_CASE("BJData")
|
||||
CHECK(out_single.at(0) == '{');
|
||||
CHECK(json::from_bjdata(out_single) == j_single);
|
||||
|
||||
// a double element that is finite and within the range of "single"
|
||||
// but is not exactly representable as a float, so narrowing it would
|
||||
// silently round it (0.1 is read back as 0.10000000149011612); this,
|
||||
// like the overflow case above, falls back to a plain object (see
|
||||
// GitHub issue #5661)
|
||||
json const j_single_rounded = json({{"_ArrayType_", "single"}, {"_ArraySize_", {2, 1}}, {"_ArrayData_", {1.5, 0.1}}});
|
||||
const auto out_single_rounded = json::to_bjdata(j_single_rounded);
|
||||
CHECK(out_single_rounded.at(0) == '{');
|
||||
CHECK(json::from_bjdata(out_single_rounded) == j_single_rounded);
|
||||
|
||||
// a double element that underflows to 0 when narrowed to "single"
|
||||
json const j_single_underflow = json({{"_ArrayType_", "single"}, {"_ArraySize_", {2, 1}}, {"_ArrayData_", {1.5, 1e-300}}});
|
||||
const auto out_single_underflow = json::to_bjdata(j_single_underflow);
|
||||
CHECK(out_single_underflow.at(0) == '{');
|
||||
CHECK(json::from_bjdata(out_single_underflow) == j_single_underflow);
|
||||
|
||||
// in-range boundary values still use the compact ndarray encoding
|
||||
json const j_uint8_ok = json({{"_ArrayType_", "uint8"}, {"_ArraySize_", {2, 1}}, {"_ArrayData_", {0, 255}}});
|
||||
CHECK(json::to_bjdata(j_uint8_ok) == std::vector<uint8_t>({'[', '$', 'U', '#', '[', 'i', 2, 'i', 1, ']', 0, 255}));
|
||||
@@ -2813,6 +2917,23 @@ TEST_CASE("BJData")
|
||||
CHECK(json::from_bjdata(out_single_ok) == json({{"_ArrayType_", "single"}, {"_ArraySize_", {2, 1}}, {"_ArrayData_", {1.5f, -1.5f}}}));
|
||||
}
|
||||
|
||||
SECTION("ndarray annotation keys are read back in the documented order")
|
||||
{
|
||||
// from_bjdata() must emit the annotation object's keys in the order
|
||||
// used throughout the documentation, _ArrayType_, _ArraySize_,
|
||||
// _ArrayData_: the type marker precedes the dimension vector on the
|
||||
// wire (see get_ubjson_size_type()), so it is known, and emitted,
|
||||
// before _ArraySize_. For a plain json this key order is invisible
|
||||
// (its comparison ignores it), but for an ordered_json it is not (see
|
||||
// GitHub issue #5661).
|
||||
const ordered_json o = ordered_json::parse(R"({"_ArrayType_":"uint8","_ArraySize_":[2,2],"_ArrayData_":[1,2,3,4]})");
|
||||
const auto packed = ordered_json::to_bjdata(o);
|
||||
CHECK(packed.at(0) == '[');
|
||||
const ordered_json o_back = ordered_json::from_bjdata(packed);
|
||||
CHECK(o_back == o);
|
||||
CHECK(o_back.dump() == o.dump());
|
||||
}
|
||||
|
||||
SECTION("ndarray that would not be read back as an annotated object stays as object")
|
||||
{
|
||||
// the reader only restores an annotated object from an ND-array
|
||||
@@ -4490,3 +4611,79 @@ TEST_CASE("BJData roundtrips" * doctest::skip())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5648 - from_bjdata(ptr, len) must read len bytes, not treat ptr as a C string")
|
||||
{
|
||||
// to_bjdata() encodes the integer 0 as the two bytes 'i' 0x00 (a BJData
|
||||
// type marker followed by the value byte 0x00), so the packed data
|
||||
// below contains a 0x00 byte before its end.
|
||||
const json j = {{"a", 0}};
|
||||
const std::vector<std::uint8_t> packed = json::to_bjdata(j);
|
||||
bool contains_nul = false;
|
||||
for (const auto byte : packed)
|
||||
{
|
||||
contains_nul |= (byte == 0x00);
|
||||
}
|
||||
REQUIRE(contains_nul);
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
// before the fix, from_bjdata had no (ptr, len) overload, so this call
|
||||
// bound to from_bjdata(InputType&&, bool strict) instead: ptr was read
|
||||
// as a NUL-terminated C string (stopping at the embedded 0x00 byte), and
|
||||
// len was silently converted to the strict flag. The deprecated
|
||||
// overload added for this issue forwards to from_bjdata(ptr, ptr + len,
|
||||
// ...) instead, like from_ubjson's deprecated (ptr, len) overload does.
|
||||
json result;
|
||||
CHECK_NOTHROW(result = json::from_bjdata(packed.data(), packed.size()));
|
||||
CHECK(result == j);
|
||||
|
||||
// len must not collapse into the strict flag either
|
||||
CHECK(json::from_bjdata(packed.data(), packed.size(), false) == j);
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_CASE("BJData large strings and binaries (chunked reader)")
|
||||
{
|
||||
// Strings share get_ubjson_string() -> get_string() -> get_bytes() with
|
||||
// plain UBJSON. Binary values are different: only a Draft 3 optimized
|
||||
// array (type marker 'B') is read back as a binary value, through
|
||||
// get_binary() -> get_bytes() (see parse_ubjson_internal()'s "If BJData
|
||||
// type marker is 'B'" branch); Draft 2 (the default) writes a binary
|
||||
// value as a plain array of uint8_t numbers instead (see the "round trip
|
||||
// of a binary value is value-stable, not byte-stable" test above), which
|
||||
// never reaches get_bytes(). Both reads happen in bounded chunks
|
||||
// (binary_reader.hpp, chunk_size == 4096); check lengths around and
|
||||
// beyond that size, for both vector (iterator) and pointer inputs.
|
||||
for (const std::size_t len :
|
||||
{
|
||||
std::size_t{0}, std::size_t{1}, std::size_t{4095}, std::size_t{4096},
|
||||
std::size_t{4097}, std::size_t{8192}, std::size_t{100000}
|
||||
})
|
||||
{
|
||||
CAPTURE(len)
|
||||
|
||||
// string
|
||||
const json j_string = std::string(len, 'x');
|
||||
const std::vector<std::uint8_t> v_string = json::to_bjdata(j_string);
|
||||
CHECK(json::from_bjdata(v_string) == j_string);
|
||||
// pointer input exercises the std::memcpy fast path
|
||||
CHECK(json::from_bjdata(reinterpret_cast<const char*>(v_string.data()),
|
||||
reinterpret_cast<const char*>(v_string.data()) + v_string.size()) == j_string);
|
||||
|
||||
// binary, forced into the Draft 3 optimized ('B' marker) encoding
|
||||
const json j_binary = json::binary(std::vector<std::uint8_t>(len, 0xCD));
|
||||
const std::vector<std::uint8_t> v_binary = json::to_bjdata(j_binary, true, true, json::bjdata_version_t::draft3);
|
||||
CHECK(json::from_bjdata(v_binary) == j_binary);
|
||||
CHECK(json::from_bjdata(reinterpret_cast<const char*>(v_binary.data()),
|
||||
reinterpret_cast<const char*>(v_binary.data()) + v_binary.size()) == j_binary);
|
||||
|
||||
// a truncated payload must still be reported as an error
|
||||
if (len > 16)
|
||||
{
|
||||
std::vector<std::uint8_t> truncated = v_string;
|
||||
truncated.resize(truncated.size() - 8);
|
||||
json _;
|
||||
CHECK_THROWS_AS(_ = json::from_bjdata(truncated), json::parse_error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,14 @@
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
#ifdef JSON_TEST_NO_GLOBAL_UDLS
|
||||
@@ -1014,6 +1022,36 @@ TEST_CASE("BON8 roundtrips" * doctest::skip())
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5648 - from_bon8(ptr, len) must read len bytes, not treat ptr as a C string")
|
||||
{
|
||||
// to_bon8() encodes the integer 40 as the two bytes 0xC2 0x00 (a BON8
|
||||
// lead byte followed by a continuation byte of 0x00), so the packed data
|
||||
// below contains a 0x00 byte before its end.
|
||||
const json j = {{"a", 40}, {"b", "x"}};
|
||||
const std::vector<std::uint8_t> packed = json::to_bon8(j);
|
||||
bool contains_nul = false;
|
||||
for (const auto byte : packed)
|
||||
{
|
||||
contains_nul |= (byte == 0x00);
|
||||
}
|
||||
REQUIRE(contains_nul);
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
// before the fix, from_bon8 had no (ptr, len) overload, so this call
|
||||
// bound to from_bon8(InputType&&, bool strict) instead: ptr was read as
|
||||
// a NUL-terminated C string (stopping at the embedded 0x00 byte), and
|
||||
// len was silently converted to the strict flag. The deprecated
|
||||
// overload added for this issue forwards to from_bon8(ptr, ptr + len,
|
||||
// ...) instead, like from_cbor's deprecated (ptr, len) overload does.
|
||||
json result;
|
||||
CHECK_NOTHROW(result = json::from_bon8(packed.data(), packed.size()));
|
||||
CHECK(result == j);
|
||||
|
||||
// len must not collapse into the strict flag either
|
||||
CHECK(json::from_bon8(packed.data(), packed.size(), false) == j);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
TEST_CASE("BON8 with std::byte")
|
||||
{
|
||||
|
||||
@@ -72,6 +72,28 @@ TEST_CASE("JSON_BRACE_INIT_COPY_SEMANTICS")
|
||||
CHECK(j7 == json::array({1, 2}));
|
||||
}
|
||||
|
||||
SECTION("single-element brace initialization copies a pair-shaped array value (#5662)")
|
||||
{
|
||||
// a JSON value that happens to be a 2-element array whose first
|
||||
// element is a string must still be copied, not turned into an
|
||||
// object; only a braced list written in the source, such as the
|
||||
// inner {"key", "value"} of {{"key", "value"}}, describes an object
|
||||
json const pair_shaped = json::array({"key", 42});
|
||||
|
||||
json const j1{pair_shaped};
|
||||
CHECK(j1.is_array());
|
||||
CHECK(j1 == pair_shaped);
|
||||
|
||||
json const j2 = {pair_shaped};
|
||||
CHECK(j2.is_array());
|
||||
CHECK(j2 == pair_shaped);
|
||||
|
||||
// the same holds for an rvalue of the same shape
|
||||
json const j3{json::array({"key", 42})};
|
||||
CHECK(j3.is_array());
|
||||
CHECK(j3 == pair_shaped);
|
||||
}
|
||||
|
||||
SECTION("what the macro does not change")
|
||||
{
|
||||
// lists with more than one element are unaffected
|
||||
|
||||
@@ -8,6 +8,14 @@
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
@@ -141,6 +149,54 @@ TEST_CASE("BSON")
|
||||
json const j = std::vector<int> {1, 2, 3, 4, 5, 6, 7};
|
||||
CHECK_THROWS_WITH_AS(json::to_bson(j), "[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array", json::type_error&);
|
||||
}
|
||||
|
||||
SECTION("discarded")
|
||||
{
|
||||
json const j = json::value_t::discarded;
|
||||
CHECK_THROWS_WITH_AS(json::to_bson(j), "[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is discarded", json::type_error&);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("discarded values nested in a container cannot be serialized to BSON")
|
||||
{
|
||||
json const discarded = json::value_t::discarded;
|
||||
|
||||
SECTION("as an object value")
|
||||
{
|
||||
json j;
|
||||
j["a"] = 1;
|
||||
j["b"] = discarded;
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_bson(j), "[json.exception.type_error.321] (/b) cannot serialize discarded value to BSON", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_bson(j), "[json.exception.type_error.321] cannot serialize discarded value to BSON", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("in an array that is an object value")
|
||||
{
|
||||
json j;
|
||||
j["a"] = json::array({1, discarded, 2});
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_bson(j), "[json.exception.type_error.321] (/a/1) cannot serialize discarded value to BSON", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_bson(j), "[json.exception.type_error.321] cannot serialize discarded value to BSON", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("nested deeper (array in object in object)")
|
||||
{
|
||||
json inner_array = {1, discarded};
|
||||
json middle_object;
|
||||
middle_object["x"] = inner_array;
|
||||
json j;
|
||||
j["outer"] = middle_object;
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_bson(j), "[json.exception.type_error.321] (/outer/x/1) cannot serialize discarded value to BSON", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_bson(j), "[json.exception.type_error.321] cannot serialize discarded value to BSON", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("keys containing code-point U+0000 cannot be serialized to BSON")
|
||||
@@ -1261,8 +1317,10 @@ TEST_CASE("BSON input that cannot be read is discarded by every overload")
|
||||
CHECK_THROWS_AS(_ = json::from_bson(input.begin(), input.end()), json::parse_error&);
|
||||
CHECK(json::from_bson(input, true, false).is_discarded());
|
||||
CHECK(json::from_bson(input.begin(), input.end(), true, false).is_discarded());
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
CHECK(json::from_bson(input.data(), input.size(), true, false).is_discarded());
|
||||
CHECK(json::from_bson({input.data(), input.size()}, true, false).is_discarded());
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_CASE("BSON SAX parsing stops at every event")
|
||||
@@ -1740,6 +1798,7 @@ TEST_CASE("BSON roundtrips" * doctest::skip())
|
||||
CHECK(j1 == j2);
|
||||
}
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
{
|
||||
INFO_WITH_TEMP(filename + ": uint8_t* and size");
|
||||
// parse JSON file
|
||||
@@ -1754,6 +1813,7 @@ TEST_CASE("BSON roundtrips" * doctest::skip())
|
||||
// compare parsed JSON values
|
||||
CHECK(j1 == j2);
|
||||
}
|
||||
#endif
|
||||
|
||||
{
|
||||
INFO_WITH_TEMP(filename + ": output to output adapters");
|
||||
@@ -1933,3 +1993,47 @@ TEST_CASE("Invalid document size handling")
|
||||
CHECK(json::from_bson(v, true, false).is_discarded());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("BSON large strings and binaries (chunked reader)")
|
||||
{
|
||||
// get_bson_string()/get_bson_binary() both read through get_string()/
|
||||
// get_binary(), which read in bounded chunks (binary_reader.hpp,
|
||||
// chunk_size == 4096); make sure roundtripping is correct for lengths
|
||||
// around and beyond that chunk size, for both vector (iterator) and
|
||||
// pointer inputs. BSON only accepts an object at the top level, so the
|
||||
// string/binary value is wrapped in one.
|
||||
for (const std::size_t len :
|
||||
{
|
||||
std::size_t{0}, std::size_t{1}, std::size_t{4095}, std::size_t{4096},
|
||||
std::size_t{4097}, std::size_t{8192}, std::size_t{100000}
|
||||
})
|
||||
{
|
||||
CAPTURE(len)
|
||||
|
||||
// string
|
||||
const json j_string = {{"k", std::string(len, 'x')}};
|
||||
const std::vector<std::uint8_t> v_string = json::to_bson(j_string);
|
||||
CHECK(json::from_bson(v_string) == j_string);
|
||||
// pointer input exercises the std::memcpy fast path
|
||||
CHECK(json::from_bson(reinterpret_cast<const char*>(v_string.data()),
|
||||
reinterpret_cast<const char*>(v_string.data()) + v_string.size()) == j_string);
|
||||
|
||||
// binary (BSON binary values always carry a subtype, so give one
|
||||
// explicitly; otherwise from_bson() would round-trip to subtype 0
|
||||
// rather than back to the original "no subtype" value)
|
||||
const json j_binary = {{"k", json::binary(std::vector<std::uint8_t>(len, 0xCD), std::uint8_t{0})}};
|
||||
const std::vector<std::uint8_t> v_binary = json::to_bson(j_binary);
|
||||
CHECK(json::from_bson(v_binary) == j_binary);
|
||||
CHECK(json::from_bson(reinterpret_cast<const char*>(v_binary.data()),
|
||||
reinterpret_cast<const char*>(v_binary.data()) + v_binary.size()) == j_binary);
|
||||
|
||||
// a truncated payload must still be reported as an error
|
||||
if (len > 16)
|
||||
{
|
||||
std::vector<std::uint8_t> truncated = v_string;
|
||||
truncated.resize(truncated.size() - 8);
|
||||
json _;
|
||||
CHECK_THROWS_AS(_ = json::from_bson(truncated), json::parse_error);
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
-33
@@ -8,6 +8,14 @@
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
@@ -30,10 +38,49 @@ TEST_CASE("CBOR")
|
||||
{
|
||||
SECTION("discarded")
|
||||
{
|
||||
// discarded values are not serialized
|
||||
// a discarded value cannot be serialized to CBOR
|
||||
json const j = json::value_t::discarded;
|
||||
const auto result = json::to_cbor(j);
|
||||
CHECK(result.empty());
|
||||
CHECK_THROWS_WITH_AS(json::to_cbor(j), "[json.exception.type_error.321] cannot serialize discarded value to CBOR", json::type_error&);
|
||||
}
|
||||
|
||||
SECTION("discarded values nested in a container")
|
||||
{
|
||||
json const discarded = json::value_t::discarded;
|
||||
|
||||
SECTION("in an array")
|
||||
{
|
||||
json const j = {1, discarded, 2};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_cbor(j), "[json.exception.type_error.321] (/1) cannot serialize discarded value to CBOR", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_cbor(j), "[json.exception.type_error.321] cannot serialize discarded value to CBOR", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("as an object value")
|
||||
{
|
||||
json j;
|
||||
j["a"] = 1;
|
||||
j["b"] = discarded;
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_cbor(j), "[json.exception.type_error.321] (/b) cannot serialize discarded value to CBOR", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_cbor(j), "[json.exception.type_error.321] cannot serialize discarded value to CBOR", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("nested deeper (array in object in array)")
|
||||
{
|
||||
json inner_array = {1, discarded};
|
||||
json middle_object;
|
||||
middle_object["x"] = inner_array;
|
||||
json const j = {middle_object};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_cbor(j), "[json.exception.type_error.321] (/0/x/1) cannot serialize discarded value to CBOR", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_cbor(j), "[json.exception.type_error.321] cannot serialize discarded value to CBOR", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("NaN")
|
||||
@@ -1652,7 +1699,7 @@ TEST_CASE("CBOR")
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xA1, 0x61, 0X61})), "[json.exception.parse_error.110] parse error at byte 4: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xBF, 0x61, 0X61})), "[json.exception.parse_error.110] parse error at byte 4: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x5F})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR binary: unexpected end of input", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x5F, 0x00})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR binary: expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x00", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x5F, 0x00})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR binary: expected length specification (0x40-0x5B); last byte: 0x00", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x41})), "[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing CBOR binary: unexpected end of input", json::parse_error&);
|
||||
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x18}), true, false).is_discarded());
|
||||
@@ -2215,8 +2262,10 @@ TEST_CASE("CBOR input that cannot be read is discarded by every overload")
|
||||
CHECK_THROWS_AS(_ = json::from_cbor(input.begin(), input.end()), json::parse_error&);
|
||||
CHECK(json::from_cbor(input, true, false).is_discarded());
|
||||
CHECK(json::from_cbor(input.begin(), input.end(), true, false).is_discarded());
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
CHECK(json::from_cbor(input.data(), input.size(), true, false).is_discarded());
|
||||
CHECK(json::from_cbor({input.data(), input.size()}, true, false).is_discarded());
|
||||
#endif
|
||||
|
||||
// a string that ends early, read through iterators that are not
|
||||
// contiguous and have to be copied from one element at a time
|
||||
@@ -2256,22 +2305,21 @@ TEST_CASE("CBOR indefinite-length strings do not recurse per chunk")
|
||||
{
|
||||
// Reading an indefinite-length string or byte array used to call itself
|
||||
// once per chunk, so a payload of repeated 0x7F (or 0x5F) bytes exhausted
|
||||
// the call stack before any of the input was rejected. The open levels are
|
||||
// counted now, and the levels below prove the reader still reads the same
|
||||
// values and reports the same errors at the same byte offsets.
|
||||
// the call stack before any of the input was rejected. Nested indefinite
|
||||
// chunks are now rejected at the second byte, without recursing.
|
||||
json _;
|
||||
|
||||
SECTION("many open levels are reported, not crashed on")
|
||||
SECTION("nested levels are rejected, not crashed on")
|
||||
{
|
||||
const std::vector<uint8_t> input(200000, 0x7F);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input), "[json.exception.parse_error.110] parse error at byte 200001: syntax error while parsing CBOR string: unexpected end of input", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: indefinite-length string is not allowed inside indefinite-length string; last byte: 0x7F", json::parse_error&);
|
||||
CHECK(json::from_cbor(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("many open levels are reported, not crashed on (binary)")
|
||||
SECTION("nested levels are rejected, not crashed on (binary)")
|
||||
{
|
||||
const std::vector<uint8_t> input(200000, 0x5F);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input), "[json.exception.parse_error.110] parse error at byte 200001: syntax error while parsing CBOR binary: unexpected end of input", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR binary: indefinite-length binary array is not allowed inside indefinite-length binary array; last byte: 0x5F", json::parse_error&);
|
||||
CHECK(json::from_cbor(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
@@ -2279,22 +2327,22 @@ TEST_CASE("CBOR indefinite-length strings do not recurse per chunk")
|
||||
{
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x7F, 0xFF})) == json(""));
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x7F, 0x61, 0x61, 0xFF})) == json("a"));
|
||||
// nested indefinite-length strings are concatenated across levels
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x7F, 0x7F, 0x61, 0x61, 0xFF, 0x61, 0x62, 0xFF})) == json("ab"));
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x7F, 0x7F, 0x7F, 0x61, 0x7A, 0xFF, 0xFF, 0xFF})) == json("z"));
|
||||
// empty and nonempty definite-length chunks concatenate in order
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x7F, 0x61, 'a', 0x60, 0x61, 'b', 0x61, 'c', 0xFF})) == json("abc"));
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0xA1, 0x7F, 0x61, 0x61, 0xFF, 0x01})) == json({{"a", 1}}));
|
||||
}
|
||||
|
||||
SECTION("chunks are still concatenated (binary)")
|
||||
{
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x5F, 0x41, 0x61, 0xFF})) == json::binary({0x61}));
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x5F, 0x5F, 0x41, 0x61, 0xFF, 0x41, 0x62, 0xFF})) == json::binary({0x61, 0x62}));
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x5F, 0xFF})) == json::binary({}));
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x5F, 0x41, 0x61, 0x40, 0x41, 0x62, 0x41, 0x63, 0xFF})) == json::binary({0x61, 0x62, 0x63}));
|
||||
}
|
||||
|
||||
SECTION("a chunk that is not a string is still rejected")
|
||||
{
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x7F, 0x7F, 0x00})), "[json.exception.parse_error.113] parse error at byte 3: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x00", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x5F, 0x5F, 0x00})), "[json.exception.parse_error.113] parse error at byte 3: syntax error while parsing CBOR binary: expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x00", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x7F, 0x00})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B); last byte: 0x00", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0x5F, 0x00})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR binary: expected length specification (0x40-0x5B); last byte: 0x00", json::parse_error&);
|
||||
}
|
||||
|
||||
SECTION("a break marker outside an indefinite-length string is not a string")
|
||||
@@ -2613,12 +2661,14 @@ TEST_CASE("CBOR roundtrips" * doctest::skip())
|
||||
CHECK(j1 == j2);
|
||||
}
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
{
|
||||
INFO_WITH_TEMP(filename + ": uint8_t* and size");
|
||||
json j2;
|
||||
CHECK_NOTHROW(j2 = json::from_cbor({packed.data(), packed.size()}));
|
||||
CHECK(j1 == j2);
|
||||
}
|
||||
#endif
|
||||
|
||||
{
|
||||
INFO_WITH_TEMP(filename + ": output to output adapters");
|
||||
@@ -2845,9 +2895,17 @@ TEST_CASE("examples from RFC 8949 Appendix A")
|
||||
{
|
||||
const auto packed = utils::read_binary_file(TEST_DATA_DIRECTORY "/binary_data/cbor_binary.cbor");
|
||||
json j;
|
||||
CHECK_NOTHROW(j = json::from_cbor(packed));
|
||||
// the fixture's tail contains nested indefinite-length byte strings.
|
||||
CHECK_THROWS_WITH_AS(j = json::from_cbor(packed), "[json.exception.parse_error.113] parse error at byte 513: syntax error while parsing CBOR binary: indefinite-length binary array is not allowed inside indefinite-length binary array; last byte: 0x5F", json::parse_error&);
|
||||
|
||||
const auto expected = utils::read_binary_file(TEST_DATA_DIRECTORY "/binary_data/cbor_binary.out");
|
||||
// keep the byte-for-byte decoding check for its valid prefix: the first
|
||||
// 512 encoded bytes contain 468 payload bytes in definite-length chunks.
|
||||
auto valid_prefix = packed;
|
||||
valid_prefix.resize(512);
|
||||
valid_prefix.push_back(0xFF);
|
||||
auto expected = utils::read_binary_file(TEST_DATA_DIRECTORY "/binary_data/cbor_binary.out");
|
||||
expected.resize(468);
|
||||
CHECK_NOTHROW(j = json::from_cbor(valid_prefix));
|
||||
CHECK(j == json::binary(expected));
|
||||
|
||||
// 0xd8
|
||||
@@ -3185,7 +3243,8 @@ TEST_CASE("Tagged values")
|
||||
// CBOR encodes negative integers as: result = -1 - n
|
||||
// For type 0x3B, n is an 8-byte uint64_t. Valid range for n with
|
||||
// the default int64_t is [0, INT64_MAX], producing results in [INT64_MIN, -1].
|
||||
// When n > INT64_MAX, the result exceeds int64_t range and is rejected.
|
||||
// When n > INT64_MAX, the result exceeds int64_t range and is stored
|
||||
// as a floating-point number, as the lexer does for JSON text.
|
||||
|
||||
SECTION("n = 0 is valid (result = -1)")
|
||||
{
|
||||
@@ -3206,33 +3265,34 @@ TEST_CASE("Tagged values")
|
||||
CHECK(result.get<int64_t>() == (std::numeric_limits<int64_t>::min)());
|
||||
}
|
||||
|
||||
SECTION("n = INT64_MAX + 1 is rejected (overflow)")
|
||||
SECTION("n = INT64_MAX + 1 is stored as float")
|
||||
{
|
||||
// n = INT64_MAX + 1 (0x8000000000000000)
|
||||
// result = -1 - n = -9223372036854775809, which exceeds int64_t range
|
||||
// result = -1 - n = -9223372036854775809, which exceeds int64_t range;
|
||||
// the nearest double is -9223372036854775808.0
|
||||
const std::vector<uint8_t> input = {0x3B, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
json _;
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input),
|
||||
"[json.exception.parse_error.112] parse error at byte 9: syntax error while parsing CBOR value: negative integer overflow",
|
||||
json::parse_error);
|
||||
const auto result = json::from_cbor(input);
|
||||
CHECK(result.is_number_float());
|
||||
CHECK(result.get<double>() == -9223372036854775808.0);
|
||||
CHECK(result == json::parse("-9223372036854775809"));
|
||||
}
|
||||
|
||||
SECTION("n = UINT64_MAX is rejected (overflow)")
|
||||
SECTION("n = UINT64_MAX is stored as float")
|
||||
{
|
||||
// n = UINT64_MAX (0xFFFFFFFFFFFFFFFF)
|
||||
// result = -1 - n = -18446744073709551616, which exceeds int64_t range
|
||||
const std::vector<uint8_t> input = {0x3B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
|
||||
json _;
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input),
|
||||
"[json.exception.parse_error.112] parse error at byte 9: syntax error while parsing CBOR value: negative integer overflow",
|
||||
json::parse_error);
|
||||
const auto result = json::from_cbor(input);
|
||||
CHECK(result.is_number_float());
|
||||
CHECK(result.get<double>() == -18446744073709551616.0);
|
||||
CHECK(result == json::parse("-18446744073709551616"));
|
||||
}
|
||||
|
||||
SECTION("overflow with allow_exceptions=false returns discarded")
|
||||
SECTION("overflow with allow_exceptions=false is not an error")
|
||||
{
|
||||
const std::vector<uint8_t> input = {0x3B, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
const auto result = json::from_cbor(input, true, false);
|
||||
CHECK(result.is_discarded());
|
||||
CHECK(result.is_number_float());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2317,6 +2317,58 @@ TEST_CASE("parser class")
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("comments before separators")
|
||||
{
|
||||
// The parser first checks for the expected ':' or ',' and only then
|
||||
// falls back to the full token switch, which skips comments. A comment
|
||||
// directly before a separator takes that fallback.
|
||||
json _;
|
||||
|
||||
SECTION("ignored")
|
||||
{
|
||||
const std::vector<std::pair<std::string, json>> inputs =
|
||||
{
|
||||
{"{\"a\" /* c */ : 1}", {{"a", 1}}},
|
||||
{"{\"a\" // c\n: 1}", {{"a", 1}}},
|
||||
{R"({"a": 1, "b" /* c */ : 2})", {{"a", 1}, {"b", 2}}},
|
||||
{R"({"a": 1 /* c */ , "b": 2})", {{"a", 1}, {"b", 2}}},
|
||||
{"{\"a\": 1 // c\n, \"b\": 2}", {{"a", 1}, {"b", 2}}},
|
||||
{"[1 /* c */ , 2]", {1, 2}},
|
||||
{"[1 // c\n, 2]", {1, 2}},
|
||||
{"{\"a\" /* c */ /* d */ : [1 // c\n , 2 /**/ ] /**/ , \"b\" : 3}", {{"a", {1, 2}}, {"b", 3}}}
|
||||
};
|
||||
for (const auto& input : inputs)
|
||||
{
|
||||
CAPTURE(input.first)
|
||||
CHECK(json::parse(input.first, nullptr, true, true) == input.second);
|
||||
CHECK(json::accept(input.first, true));
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ignored, with trailing commas")
|
||||
{
|
||||
CHECK(json::parse(std::string("[1 /* c */ , ]"), nullptr, true, true, true) == json({1}));
|
||||
CHECK(json::parse(std::string("{\"a\": 1 /* c */ , }"), nullptr, true, true, true) == json({{"a", 1}}));
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse(std::string("[1 /* c */ , ]"), nullptr, true, true),
|
||||
"[json.exception.parse_error.101] parse error at line 1, column 14: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal", json::parse_error);
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse(std::string("{\"a\": 1 /* c */ , }"), nullptr, true, true),
|
||||
"[json.exception.parse_error.101] parse error at line 1, column 19: syntax error while parsing object key - unexpected '}'; expected string literal", json::parse_error);
|
||||
}
|
||||
|
||||
SECTION("not ignored")
|
||||
{
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse(std::string("{\"a\" /* c */ : 1}")),
|
||||
"[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing object separator - invalid literal; last read: '\"a\" /'; expected ':'", json::parse_error);
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse(std::string("{\"a\": 1, \"b\" /* c */ : 2}")),
|
||||
"[json.exception.parse_error.101] parse error at line 1, column 14: syntax error while parsing object separator - invalid literal; last read: '\"b\" /'; expected ':'", json::parse_error);
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse(std::string("{\"a\": 1 /* c */ , \"b\": 2}")),
|
||||
"[json.exception.parse_error.101] parse error at line 1, column 9: syntax error while parsing object - invalid literal; last read: '1 /'; expected '}'", json::parse_error);
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse(std::string("[1 /* c */ , 2]")),
|
||||
"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing array - invalid literal; last read: '1 /'; expected ']'", json::parse_error);
|
||||
CHECK(!json::accept(std::string("[1 /* c */ , 2]")));
|
||||
}
|
||||
}
|
||||
|
||||
#if JSON_DIAGNOSTIC_POSITIONS
|
||||
// Macro for all test cases for start_pos and end_pos
|
||||
#define SETUP_TESTCASES() \
|
||||
|
||||
@@ -191,8 +191,10 @@ TEST_CASE("value conversion")
|
||||
{
|
||||
enum class bool_enum : bool { off, on };
|
||||
|
||||
CHECK(json(bool_enum::off).get<bool_enum>() == bool_enum::off);
|
||||
CHECK(json(bool_enum::on).get<bool_enum>() == bool_enum::on);
|
||||
// the extra parentheses keep doctest from printing the enum via its
|
||||
// underlying type, which MSVC 2015 reports as C4800
|
||||
CHECK((json(bool_enum::off).get<bool_enum>() == bool_enum::off));
|
||||
CHECK((json(bool_enum::on).get<bool_enum>() == bool_enum::on));
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -851,8 +853,11 @@ TEST_CASE("std::optional")
|
||||
CHECK_THROWS_WITH_AS(json(opt), "cannot serialize throwing_to_json_type", std::runtime_error&);
|
||||
|
||||
// the conversion is noexcept exactly when converting the contained value is
|
||||
// (except with MSVC 2017, where it is never noexcept, see to_json.hpp)
|
||||
#if !defined(_MSC_VER) || defined(__clang__) || _MSC_VER >= 1920
|
||||
static_assert(!std::is_nothrow_constructible<json, const std::optional<throwing_to_json_type>&>::value);
|
||||
static_assert(std::is_nothrow_constructible<json, const std::optional<int>&>::value);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -38,20 +38,7 @@ class json_metadata
|
||||
};
|
||||
|
||||
template<class T>
|
||||
using json_with_metadata =
|
||||
nlohmann::basic_json <
|
||||
std::map,
|
||||
std::vector,
|
||||
std::string,
|
||||
bool,
|
||||
std::int64_t,
|
||||
std::uint64_t,
|
||||
double,
|
||||
std::allocator,
|
||||
nlohmann::adl_serializer,
|
||||
std::vector<std::uint8_t>,
|
||||
json_metadata<T>
|
||||
>;
|
||||
using json_with_metadata = nlohmann::json::with_base_class_t<json_metadata<T>>;
|
||||
|
||||
TEST_CASE("JSON Node Metadata")
|
||||
{
|
||||
@@ -268,19 +255,7 @@ class visitor_adaptor
|
||||
void do_visit(const Ptr& ptr, const Fnc& fnc) const;
|
||||
};
|
||||
|
||||
using json_with_visitor_t = nlohmann::basic_json <
|
||||
std::map,
|
||||
std::vector,
|
||||
std::string,
|
||||
bool,
|
||||
std::int64_t,
|
||||
std::uint64_t,
|
||||
double,
|
||||
std::allocator,
|
||||
nlohmann::adl_serializer,
|
||||
std::vector<std::uint8_t>,
|
||||
visitor_adaptor
|
||||
>;
|
||||
using json_with_visitor_t = nlohmann::json::with_base_class_t<visitor_adaptor>;
|
||||
|
||||
template <class Fnc>
|
||||
void visitor_adaptor::visit(const Fnc& fnc) const
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
@@ -196,6 +198,198 @@ struct void_erase_map : std::map<Key, T, Compare, Allocator>
|
||||
|
||||
using void_erase_json = nlohmann::basic_json<void_erase_map>;
|
||||
|
||||
// wraps an iterator, but only offers the LegacyForwardIterator operations,
|
||||
// like the iterators of std::unordered_map and other hash maps
|
||||
template<class BaseIterator>
|
||||
class forward_only_iterator
|
||||
{
|
||||
BaseIterator m_it{};
|
||||
|
||||
public:
|
||||
using iterator_category = std::forward_iterator_tag;
|
||||
using value_type = typename std::iterator_traits<BaseIterator>::value_type;
|
||||
using difference_type = typename std::iterator_traits<BaseIterator>::difference_type;
|
||||
using pointer = typename std::iterator_traits<BaseIterator>::pointer;
|
||||
using reference = typename std::iterator_traits<BaseIterator>::reference;
|
||||
|
||||
forward_only_iterator() = default;
|
||||
explicit forward_only_iterator(BaseIterator it) : m_it(it) {}
|
||||
|
||||
BaseIterator base() const
|
||||
{
|
||||
return m_it;
|
||||
}
|
||||
|
||||
reference operator*() const
|
||||
{
|
||||
return *m_it;
|
||||
}
|
||||
pointer operator->() const
|
||||
{
|
||||
return &*m_it;
|
||||
}
|
||||
forward_only_iterator& operator++()
|
||||
{
|
||||
++m_it;
|
||||
return *this;
|
||||
}
|
||||
forward_only_iterator operator++(int)
|
||||
{
|
||||
auto result = *this;
|
||||
++m_it;
|
||||
return result;
|
||||
}
|
||||
|
||||
friend bool operator==(const forward_only_iterator& lhs, const forward_only_iterator& rhs)
|
||||
{
|
||||
return lhs.m_it == rhs.m_it;
|
||||
}
|
||||
friend bool operator!=(const forward_only_iterator& lhs, const forward_only_iterator& rhs)
|
||||
{
|
||||
return lhs.m_it != rhs.m_it;
|
||||
}
|
||||
};
|
||||
|
||||
// An ObjectType whose iterators are forward-only, as those of hash maps are;
|
||||
// it has no rbegin() and its iterators no operator--. A hash map is not used
|
||||
// directly for the same reason as in no_key_compare_map above.
|
||||
template<class Key, class T, class Compare, class Allocator>
|
||||
class forward_only_map
|
||||
{
|
||||
using map_t = std::map<Key, T, Compare, Allocator>;
|
||||
map_t data;
|
||||
|
||||
public:
|
||||
using key_type = typename map_t::key_type;
|
||||
using mapped_type = typename map_t::mapped_type;
|
||||
using value_type = typename map_t::value_type;
|
||||
using size_type = typename map_t::size_type;
|
||||
using allocator_type = typename map_t::allocator_type;
|
||||
using iterator = forward_only_iterator<typename map_t::iterator>;
|
||||
using const_iterator = forward_only_iterator<typename map_t::const_iterator>;
|
||||
|
||||
forward_only_map() noexcept(std::is_nothrow_default_constructible<map_t>::value) : data() {}
|
||||
|
||||
template<class InputIt>
|
||||
forward_only_map(InputIt first, InputIt last) : data(first, last) {}
|
||||
|
||||
iterator begin() noexcept
|
||||
{
|
||||
return iterator(data.begin());
|
||||
}
|
||||
iterator end() noexcept
|
||||
{
|
||||
return iterator(data.end());
|
||||
}
|
||||
const_iterator begin() const noexcept
|
||||
{
|
||||
return const_iterator(data.begin());
|
||||
}
|
||||
const_iterator end() const noexcept
|
||||
{
|
||||
return const_iterator(data.end());
|
||||
}
|
||||
const_iterator cbegin() const noexcept
|
||||
{
|
||||
return const_iterator(data.cbegin());
|
||||
}
|
||||
const_iterator cend() const noexcept
|
||||
{
|
||||
return const_iterator(data.cend());
|
||||
}
|
||||
|
||||
bool empty() const noexcept
|
||||
{
|
||||
return data.empty();
|
||||
}
|
||||
size_type size() const noexcept
|
||||
{
|
||||
return data.size();
|
||||
}
|
||||
size_type max_size() const noexcept
|
||||
{
|
||||
return data.max_size();
|
||||
}
|
||||
void clear() noexcept
|
||||
{
|
||||
data.clear();
|
||||
}
|
||||
|
||||
iterator find(const key_type& key)
|
||||
{
|
||||
return iterator(data.find(key));
|
||||
}
|
||||
const_iterator find(const key_type& key) const
|
||||
{
|
||||
return const_iterator(data.find(key));
|
||||
}
|
||||
size_type count(const key_type& key) const
|
||||
{
|
||||
return data.count(key);
|
||||
}
|
||||
|
||||
std::pair<iterator, bool> emplace(const key_type& key, const mapped_type& value)
|
||||
{
|
||||
const auto result = data.emplace(key, value);
|
||||
return {iterator(result.first), result.second};
|
||||
}
|
||||
|
||||
std::pair<iterator, bool> insert(const value_type& value)
|
||||
{
|
||||
const auto result = data.insert(value);
|
||||
return {iterator(result.first), result.second};
|
||||
}
|
||||
|
||||
template<class InputIt>
|
||||
void insert(InputIt first, InputIt last)
|
||||
{
|
||||
data.insert(first, last);
|
||||
}
|
||||
|
||||
mapped_type& operator[](const key_type& key)
|
||||
{
|
||||
return data[key];
|
||||
}
|
||||
|
||||
mapped_type& at(const key_type& key)
|
||||
{
|
||||
return data.at(key);
|
||||
}
|
||||
const mapped_type& at(const key_type& key) const
|
||||
{
|
||||
return data.at(key);
|
||||
}
|
||||
|
||||
iterator erase(iterator pos)
|
||||
{
|
||||
return iterator(data.erase(pos.base()));
|
||||
}
|
||||
iterator erase(iterator first, iterator last)
|
||||
{
|
||||
return iterator(data.erase(first.base(), last.base()));
|
||||
}
|
||||
size_type erase(const key_type& key)
|
||||
{
|
||||
return data.erase(key);
|
||||
}
|
||||
|
||||
void swap(forward_only_map& other) noexcept(noexcept(data.swap(other.data)))
|
||||
{
|
||||
data.swap(other.data);
|
||||
}
|
||||
|
||||
friend bool operator==(const forward_only_map& lhs, const forward_only_map& rhs)
|
||||
{
|
||||
return lhs.data == rhs.data;
|
||||
}
|
||||
friend bool operator<(const forward_only_map& lhs, const forward_only_map& rhs)
|
||||
{
|
||||
return lhs.data < rhs.data;
|
||||
}
|
||||
};
|
||||
|
||||
using forward_only_json = nlohmann::basic_json<forward_only_map>;
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("object type whose erase() returns void")
|
||||
@@ -322,3 +516,46 @@ TEST_CASE("object type without key_compare")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
TEST_CASE("object type with forward-only iterators")
|
||||
{
|
||||
CHECK(std::is_same<std::iterator_traits<forward_only_json::object_t::iterator>::iterator_category,
|
||||
std::forward_iterator_tag>::value);
|
||||
|
||||
SECTION("destroying nested objects and arrays")
|
||||
{
|
||||
forward_only_json j;
|
||||
j["a"] = 1;
|
||||
j["b"]["c"] = "x";
|
||||
j["b"]["d"] = forward_only_json::array();
|
||||
j["b"]["d"].push_back(forward_only_json::object());
|
||||
j["b"]["d"].push_back(true);
|
||||
j["b"]["e"]["f"]["g"] = nullptr;
|
||||
j["h"] = forward_only_json::object();
|
||||
j["i"]["j"] = 2;
|
||||
|
||||
CHECK(j.size() == 4);
|
||||
CHECK(j["b"].size() == 3);
|
||||
CHECK(j["b"]["d"].size() == 2);
|
||||
CHECK(j["b"]["e"]["f"]["g"].is_null());
|
||||
|
||||
CHECK(j.erase("b") == 1);
|
||||
CHECK(j.size() == 3);
|
||||
j = 42;
|
||||
CHECK(j == 42);
|
||||
}
|
||||
|
||||
SECTION("destroying a deeply nested object")
|
||||
{
|
||||
constexpr std::size_t depth = 100000;
|
||||
forward_only_json j;
|
||||
forward_only_json* cur = &j;
|
||||
for (std::size_t i = 0; i < depth; ++i)
|
||||
{
|
||||
(*cur)["s"] = i;
|
||||
cur = &(*cur)["o"];
|
||||
}
|
||||
CHECK(j["o"]["o"]["s"] == 2);
|
||||
// destroyed at the end of scope without recursing per level
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// This file tests the opt-in JSON_DELETE_DEPRECATED_FUNCTIONS, so it defines the
|
||||
// macro itself instead of relying on the build configuration.
|
||||
#ifdef JSON_DELETE_DEPRECATED_FUNCTIONS
|
||||
#undef JSON_DELETE_DEPRECATED_FUNCTIONS
|
||||
#endif
|
||||
#define JSON_DELETE_DEPRECATED_FUNCTIONS 1
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace
|
||||
{
|
||||
template<typename...>
|
||||
struct make_void
|
||||
{
|
||||
using type = void;
|
||||
};
|
||||
|
||||
template<typename... Ts>
|
||||
using void_t = typename make_void<Ts...>::type;
|
||||
|
||||
// A deleted function is still found by overload resolution, but naming it in an
|
||||
// unevaluated operand is ill-formed, so each of the following traits is false
|
||||
// exactly if the expression selects a deleted (or no) function.
|
||||
#define JSON_TEST_DETECT(name, expr) \
|
||||
template<typename J, typename = void> \
|
||||
struct name : std::false_type {}; \
|
||||
template<typename J> \
|
||||
struct name<J, void_t<decltype(expr)>> : std::true_type {}
|
||||
|
||||
using ptr_t = const std::uint8_t*;
|
||||
|
||||
JSON_TEST_DETECT(from_cbor_ptr_len, J::from_cbor(std::declval<ptr_t>(), std::declval<std::size_t>()));
|
||||
JSON_TEST_DETECT(from_msgpack_ptr_len, J::from_msgpack(std::declval<ptr_t>(), std::declval<std::size_t>()));
|
||||
JSON_TEST_DETECT(from_ubjson_ptr_len, J::from_ubjson(std::declval<ptr_t>(), std::declval<std::size_t>()));
|
||||
JSON_TEST_DETECT(from_bjdata_ptr_len, J::from_bjdata(std::declval<ptr_t>(), std::declval<std::size_t>()));
|
||||
JSON_TEST_DETECT(from_bon8_ptr_len, J::from_bon8(std::declval<ptr_t>(), std::declval<std::size_t>()));
|
||||
JSON_TEST_DETECT(from_bson_ptr_len, J::from_bson(std::declval<ptr_t>(), std::declval<std::size_t>()));
|
||||
|
||||
JSON_TEST_DETECT(from_cbor_ptr_ptr, J::from_cbor(std::declval<ptr_t>(), std::declval<ptr_t>()));
|
||||
JSON_TEST_DETECT(from_msgpack_ptr_ptr, J::from_msgpack(std::declval<ptr_t>(), std::declval<ptr_t>()));
|
||||
JSON_TEST_DETECT(from_ubjson_ptr_ptr, J::from_ubjson(std::declval<ptr_t>(), std::declval<ptr_t>()));
|
||||
JSON_TEST_DETECT(from_bjdata_ptr_ptr, J::from_bjdata(std::declval<ptr_t>(), std::declval<ptr_t>()));
|
||||
JSON_TEST_DETECT(from_bon8_ptr_ptr, J::from_bon8(std::declval<ptr_t>(), std::declval<ptr_t>()));
|
||||
JSON_TEST_DETECT(from_bson_ptr_ptr, J::from_bson(std::declval<ptr_t>(), std::declval<ptr_t>()));
|
||||
|
||||
JSON_TEST_DETECT(from_cbor_init_list, J::from_cbor({std::declval<ptr_t>(), std::declval<std::size_t>()}));
|
||||
JSON_TEST_DETECT(from_msgpack_init_list, J::from_msgpack({std::declval<ptr_t>(), std::declval<std::size_t>()}));
|
||||
JSON_TEST_DETECT(from_ubjson_init_list, J::from_ubjson({std::declval<ptr_t>(), std::declval<std::size_t>()}));
|
||||
JSON_TEST_DETECT(from_bson_init_list, J::from_bson({std::declval<ptr_t>(), std::declval<std::size_t>()}));
|
||||
|
||||
JSON_TEST_DETECT(parse_init_list, J::parse({std::declval<ptr_t>(), std::declval<std::size_t>()}));
|
||||
JSON_TEST_DETECT(accept_init_list, J::accept({std::declval<ptr_t>(), std::declval<std::size_t>()}));
|
||||
JSON_TEST_DETECT(sax_parse_init_list, J::sax_parse({std::declval<ptr_t>(), std::declval<std::size_t>()}, std::declval<nlohmann::json_sax<J>*>()));
|
||||
JSON_TEST_DETECT(parse_ptr_ptr, J::parse(std::declval<ptr_t>(), std::declval<ptr_t>()));
|
||||
|
||||
JSON_TEST_DETECT(iterator_wrapper, J::iterator_wrapper(std::declval<J&>()));
|
||||
JSON_TEST_DETECT(iterator_wrapper_const, J::iterator_wrapper(std::declval<const J&>()));
|
||||
JSON_TEST_DETECT(items, std::declval<J&>().items());
|
||||
|
||||
JSON_TEST_DETECT(json_ltlt_istream, std::declval<J&>() << std::declval<std::istream&>());
|
||||
JSON_TEST_DETECT(istream_gtgt_json, std::declval<std::istream&>() >> std::declval<J&>());
|
||||
JSON_TEST_DETECT(json_gtgt_ostream, std::declval<const J&>() >> std::declval<std::ostream&>());
|
||||
JSON_TEST_DETECT(ostream_ltlt_json, std::declval<std::ostream&>() << std::declval<const J&>());
|
||||
|
||||
JSON_TEST_DETECT(ptr_eq_ptr, std::declval<const typename J::json_pointer&>() == std::declval<const typename J::json_pointer&>());
|
||||
JSON_TEST_DETECT(ptr_ne_ptr, std::declval<const typename J::json_pointer&>() != std::declval<const typename J::json_pointer&>());
|
||||
JSON_TEST_DETECT(ptr_eq_string, std::declval<const typename J::json_pointer&>() == std::declval<const std::string&>());
|
||||
JSON_TEST_DETECT(string_eq_ptr, std::declval<const std::string&>() == std::declval<const typename J::json_pointer&>());
|
||||
JSON_TEST_DETECT(ptr_eq_c_string, std::declval<const typename J::json_pointer&>() == std::declval<const char*>());
|
||||
JSON_TEST_DETECT(c_string_eq_ptr, std::declval<const char*>() == std::declval<const typename J::json_pointer&>());
|
||||
JSON_TEST_DETECT(ptr_ne_string, std::declval<const typename J::json_pointer&>() != std::declval<const std::string&>());
|
||||
JSON_TEST_DETECT(string_ne_ptr, std::declval<const std::string&>() != std::declval<const typename J::json_pointer&>());
|
||||
JSON_TEST_DETECT(ptr_to_string, std::declval<const typename J::json_pointer&>().to_string());
|
||||
|
||||
// json_pointer with a basic_json type as template argument
|
||||
template<typename J>
|
||||
using legacy_ptr_t = const nlohmann::json_pointer<J>& ;
|
||||
JSON_TEST_DETECT(legacy_ptr_value, std::declval<const J&>().value(std::declval<legacy_ptr_t<J>>(), 0));
|
||||
JSON_TEST_DETECT(legacy_ptr_value_rvalue, std::declval<const J&>().value(std::declval<legacy_ptr_t<J>>(), std::string()));
|
||||
JSON_TEST_DETECT(legacy_ptr_contains, std::declval<const J&>().contains(std::declval<legacy_ptr_t<J>>()));
|
||||
JSON_TEST_DETECT(legacy_ptr_subscript, std::declval<J&>()[std::declval<legacy_ptr_t<J>>()]);
|
||||
JSON_TEST_DETECT(legacy_ptr_subscript_const, std::declval<const J&>()[std::declval<legacy_ptr_t<J>>()]);
|
||||
JSON_TEST_DETECT(legacy_ptr_at, std::declval<J&>().at(std::declval<legacy_ptr_t<J>>()));
|
||||
JSON_TEST_DETECT(legacy_ptr_at_const, std::declval<const J&>().at(std::declval<legacy_ptr_t<J>>()));
|
||||
JSON_TEST_DETECT(ptr_value, std::declval<const J&>().value(std::declval<const typename J::json_pointer&>(), 0));
|
||||
JSON_TEST_DETECT(ptr_at, std::declval<J&>().at(std::declval<const typename J::json_pointer&>()));
|
||||
|
||||
#undef JSON_TEST_DETECT
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("JSON_DELETE_DEPRECATED_FUNCTIONS")
|
||||
{
|
||||
// MSVC 2015 does not treat selecting a deleted function in decltype as a
|
||||
// substitution failure, so the traits cannot tell deleted functions apart
|
||||
// there; calling them still fails to compile
|
||||
#if !(defined(_MSC_VER) && _MSC_VER < 1910)
|
||||
SECTION("from_* with a pointer and a length")
|
||||
{
|
||||
// the overloads are deleted rather than removed, so the length cannot
|
||||
// silently bind to the strict parameter of from_*(InputType&&, bool)
|
||||
CHECK_FALSE(from_cbor_ptr_len<json>::value);
|
||||
CHECK_FALSE(from_msgpack_ptr_len<json>::value);
|
||||
CHECK_FALSE(from_ubjson_ptr_len<json>::value);
|
||||
CHECK_FALSE(from_bjdata_ptr_len<json>::value);
|
||||
CHECK_FALSE(from_bon8_ptr_len<json>::value);
|
||||
CHECK_FALSE(from_bson_ptr_len<json>::value);
|
||||
|
||||
// the replacement
|
||||
CHECK(from_cbor_ptr_ptr<json>::value);
|
||||
CHECK(from_msgpack_ptr_ptr<json>::value);
|
||||
CHECK(from_ubjson_ptr_ptr<json>::value);
|
||||
CHECK(from_bjdata_ptr_ptr<json>::value);
|
||||
CHECK(from_bon8_ptr_ptr<json>::value);
|
||||
CHECK(from_bson_ptr_ptr<json>::value);
|
||||
}
|
||||
|
||||
SECTION("initializer lists of a pointer and a length")
|
||||
{
|
||||
CHECK_FALSE(from_cbor_init_list<json>::value);
|
||||
CHECK_FALSE(from_msgpack_init_list<json>::value);
|
||||
CHECK_FALSE(from_ubjson_init_list<json>::value);
|
||||
CHECK_FALSE(from_bson_init_list<json>::value);
|
||||
CHECK_FALSE(parse_init_list<json>::value);
|
||||
CHECK_FALSE(accept_init_list<json>::value);
|
||||
CHECK_FALSE(sax_parse_init_list<json>::value);
|
||||
|
||||
// the replacement
|
||||
CHECK(parse_ptr_ptr<json>::value);
|
||||
}
|
||||
|
||||
SECTION("iterator_wrapper")
|
||||
{
|
||||
CHECK_FALSE(iterator_wrapper<json>::value);
|
||||
CHECK_FALSE(iterator_wrapper_const<json>::value);
|
||||
|
||||
// the replacement
|
||||
CHECK(items<json>::value);
|
||||
}
|
||||
|
||||
SECTION("stream operators with reversed operands")
|
||||
{
|
||||
CHECK_FALSE(json_ltlt_istream<json>::value);
|
||||
CHECK_FALSE(json_gtgt_ostream<json>::value);
|
||||
|
||||
// the replacement
|
||||
CHECK(istream_gtgt_json<json>::value);
|
||||
CHECK(ostream_ltlt_json<json>::value);
|
||||
}
|
||||
|
||||
SECTION("json_pointer")
|
||||
{
|
||||
// conversion to a string
|
||||
CHECK_FALSE(std::is_constructible<std::string, json::json_pointer>::value);
|
||||
CHECK_FALSE(std::is_convertible<json::json_pointer, std::string>::value);
|
||||
|
||||
// comparison with a string
|
||||
CHECK_FALSE(ptr_eq_string<json>::value);
|
||||
CHECK_FALSE(string_eq_ptr<json>::value);
|
||||
CHECK_FALSE(ptr_eq_c_string<json>::value);
|
||||
CHECK_FALSE(c_string_eq_ptr<json>::value);
|
||||
CHECK_FALSE(ptr_ne_string<json>::value);
|
||||
CHECK_FALSE(string_ne_ptr<json>::value);
|
||||
|
||||
// the replacement
|
||||
CHECK(ptr_to_string<json>::value);
|
||||
CHECK(ptr_eq_ptr<json>::value);
|
||||
CHECK(ptr_ne_ptr<json>::value);
|
||||
}
|
||||
|
||||
SECTION("json_pointer with a basic_json type as template argument")
|
||||
{
|
||||
CHECK_FALSE(legacy_ptr_value<json>::value);
|
||||
CHECK_FALSE(legacy_ptr_value_rvalue<json>::value);
|
||||
CHECK_FALSE(legacy_ptr_contains<json>::value);
|
||||
CHECK_FALSE(legacy_ptr_subscript<json>::value);
|
||||
CHECK_FALSE(legacy_ptr_subscript_const<json>::value);
|
||||
CHECK_FALSE(legacy_ptr_at<json>::value);
|
||||
CHECK_FALSE(legacy_ptr_at_const<json>::value);
|
||||
|
||||
// the replacement
|
||||
CHECK(ptr_value<json>::value);
|
||||
CHECK(ptr_at<json>::value);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
SECTION("the non-deprecated functions still work")
|
||||
{
|
||||
const json j = {{"a", {1, 2}}};
|
||||
const auto cbor = json::to_cbor(j);
|
||||
CHECK(json::from_cbor(cbor.data(), cbor.data() + cbor.size()) == j);
|
||||
|
||||
const json::json_pointer ptr("/a/1");
|
||||
CHECK(ptr == json::json_pointer("/a/1"));
|
||||
CHECK(ptr.to_string() == "/a/1");
|
||||
CHECK(j[ptr] == 2);
|
||||
CHECK(j.at(ptr) == 2);
|
||||
CHECK(j.value(ptr, 0) == 2);
|
||||
CHECK(j.contains(ptr));
|
||||
|
||||
std::ostringstream os;
|
||||
os << j;
|
||||
CHECK(os.str() == R"({"a":[1,2]})");
|
||||
std::istringstream is(os.str());
|
||||
json parsed;
|
||||
is >> parsed;
|
||||
CHECK(parsed == j);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,14 @@
|
||||
#define JSON_TEST_STRICT_NUL_HANDLING_ENABLED 1
|
||||
#endif
|
||||
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
#ifdef JSON_TEST_NO_GLOBAL_UDLS
|
||||
@@ -291,6 +299,7 @@ TEST_CASE("deserialization")
|
||||
}));
|
||||
}
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
SECTION("operator<<")
|
||||
{
|
||||
std::stringstream ss;
|
||||
@@ -299,6 +308,7 @@ TEST_CASE("deserialization")
|
||||
j << ss;
|
||||
CHECK(j == json({"foo", 1, 2, 3, false, {{"one", 1}}}));
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("operator>>")
|
||||
{
|
||||
@@ -423,6 +433,7 @@ TEST_CASE("deserialization")
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse(nullptr), "[json.exception.parse_error.101] parse error: attempting to parse an empty input; check that your input string or stream contains the expected JSON", json::parse_error&);
|
||||
}
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
SECTION("operator<<")
|
||||
{
|
||||
std::stringstream ss;
|
||||
@@ -430,6 +441,7 @@ TEST_CASE("deserialization")
|
||||
json j;
|
||||
CHECK_THROWS_WITH_AS(j << ss, "[json.exception.parse_error.101] parse error at line 1, column 29: syntax error while parsing array - unexpected end of input; expected ']'", json::parse_error&);
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("operator>>")
|
||||
{
|
||||
@@ -1148,9 +1160,9 @@ TEST_CASE("deserialization")
|
||||
{
|
||||
std::istringstream s(bom + "123 456");
|
||||
json j;
|
||||
j << s;
|
||||
s >> j;
|
||||
CHECK(j == 123);
|
||||
j << s;
|
||||
s >> j;
|
||||
CHECK(j == 456);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
// Regression test for https://github.com/nlohmann/json/issues/5742: with
|
||||
// JSON_DIAGNOSTICS, GCC (12 to at least 16) reported a false -Warray-bounds
|
||||
// error in the inlined set_parents() at -O3. The type of a new string was set
|
||||
// before the string was allocated, so GCC had to assume that operator new
|
||||
// could change it again and checked the object branch of set_parents()
|
||||
// against the string's allocation. Setting the type after creating the value
|
||||
// avoids this. The warning depends on GCC's inlining decisions, so the
|
||||
// sections cover two patterns that trigger it on different GCC versions
|
||||
// (#4819 and #5742).
|
||||
// On GCC, this file is compiled with -O3 -Werror=array-bounds (see
|
||||
// tests/CMakeLists.txt), so the test fails to build if the warning returns.
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
#ifdef JSON_DIAGNOSTICS
|
||||
#undef JSON_DIAGNOSTICS
|
||||
#endif
|
||||
|
||||
#define JSON_DIAGNOSTICS 1
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// the static table in to_json has an exit-time destructor
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
|
||||
namespace
|
||||
{
|
||||
enum class diag_color
|
||||
{
|
||||
red,
|
||||
green,
|
||||
blue
|
||||
};
|
||||
|
||||
void to_json(json& j, const diag_color& c)
|
||||
{
|
||||
static const std::pair<diag_color, json> m[] = // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
||||
{
|
||||
{diag_color::red, "r"},
|
||||
{diag_color::green, "g"},
|
||||
{diag_color::blue, "b"},
|
||||
};
|
||||
const auto* it = std::find_if(std::begin(m), std::end(m), [c](const std::pair<diag_color, json>& p)
|
||||
{
|
||||
return p.first == c;
|
||||
});
|
||||
j = ((it != std::end(m)) ? it : std::begin(m))->second; // like NLOHMANN_JSON_SERIALIZE_ENUM
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("diagnostics with optimization")
|
||||
{
|
||||
SECTION("issue #4819 - object in vector")
|
||||
{
|
||||
std::vector<json> jsons{};
|
||||
jsons.emplace_back(json({{"key", "value"}}));
|
||||
CHECK(jsons.back()["key"] == "value");
|
||||
}
|
||||
|
||||
SECTION("issue #5742 - string values from a static table")
|
||||
{
|
||||
json j = json::array();
|
||||
j.push_back(diag_color::red);
|
||||
j.push_back(diag_color::green);
|
||||
j.push_back(diag_color::blue);
|
||||
CHECK(j.dump() == R"(["r","g","b"])");
|
||||
CHECK_THROWS_WITH_AS(j[1].get<int>(), "[json.exception.type_error.302] (/1) type must be number, but is string", json::type_error);
|
||||
}
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
@@ -1551,6 +1551,10 @@ TEST_CASE_TEMPLATE("element access 2", Json, nlohmann::json, nlohmann::ordered_j
|
||||
// count(0) used to compile and then crash instead of failing to compile
|
||||
using nlohmann::detail::is_detected;
|
||||
|
||||
// MSVC 2015 does not treat selecting a deleted function in decltype as
|
||||
// a substitution failure, so it detects the deleted overloads as
|
||||
// callable; calling them still fails to compile
|
||||
#if !(defined(_MSC_VER) && _MSC_VER < 1910)
|
||||
CHECK_FALSE(is_detected<can_call_find_with_0, Json&>::value);
|
||||
CHECK_FALSE(is_detected<can_call_find_with_0, const Json&>::value);
|
||||
CHECK_FALSE(is_detected<can_call_count_with_0, Json&>::value);
|
||||
@@ -1562,6 +1566,7 @@ TEST_CASE_TEMPLATE("element access 2", Json, nlohmann::json, nlohmann::ordered_j
|
||||
|
||||
// another integral literal type must be rejected as well, not just int
|
||||
CHECK_FALSE(is_detected<can_call_contains_with_0L, Json&>::value);
|
||||
#endif
|
||||
|
||||
// the valid overloads must remain callable
|
||||
CHECK(is_detected<can_call_find, Json&, const char*>::value);
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// skip tests if JSON_DisableEnumSerialization=ON (#4384)
|
||||
#if defined(JSON_DISABLE_ENUM_SERIALIZATION) && (JSON_DISABLE_ENUM_SERIALIZATION == 1)
|
||||
#define SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||
#endif
|
||||
|
||||
// This file tests the opt-in JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS, so it defines
|
||||
// the macro itself rather than relying on a -D flag, and runs in every build.
|
||||
// The default behavior is tested in unit-enum_keyed_maps_default.cpp.
|
||||
#ifdef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||
#undef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||
#endif
|
||||
|
||||
#define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS 1
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
using nlohmann::ordered_json;
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#define STRINGIZE_EX(x) #x
|
||||
#define STRINGIZE(x) STRINGIZE_EX(x)
|
||||
|
||||
// NLOHMANN_JSON_SERIALIZE_ENUM uses a static std::pair
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
|
||||
namespace
|
||||
{
|
||||
// std::hash is only required for enums since C++14
|
||||
struct enum_hash
|
||||
{
|
||||
template<typename T>
|
||||
std::size_t operator()(T t) const noexcept
|
||||
{
|
||||
return static_cast<std::size_t>(t);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// the example from #4378
|
||||
enum TaskState // NOLINT(cert-int09-c,readability-enum-initial-value,cppcoreguidelines-use-enum-class)
|
||||
{
|
||||
TS_STOPPED,
|
||||
TS_RUNNING,
|
||||
TS_COMPLETED,
|
||||
TS_INVALID = -1,
|
||||
};
|
||||
|
||||
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM(TaskState,
|
||||
{
|
||||
{TS_INVALID, nullptr},
|
||||
{TS_STOPPED, "stopped"},
|
||||
{TS_RUNNING, "running"},
|
||||
{TS_COMPLETED, "completed"},
|
||||
})
|
||||
|
||||
enum class color {red, green, blue}; // blue is not mapped and falls back to "red"
|
||||
|
||||
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM(color,
|
||||
{
|
||||
{color::red, "red"},
|
||||
{color::green, "green"},
|
||||
})
|
||||
|
||||
enum class strict_color {red, green, blue}; // blue is not mapped
|
||||
|
||||
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM_STRICT(strict_color,
|
||||
{
|
||||
{strict_color::red, "red"},
|
||||
{strict_color::green, "green"},
|
||||
})
|
||||
|
||||
enum class digit {zero, one};
|
||||
|
||||
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM(digit,
|
||||
{
|
||||
{digit::zero, 0},
|
||||
{digit::one, 1},
|
||||
})
|
||||
|
||||
#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||
enum class plain {zero, one}; // serialized as integer
|
||||
#endif
|
||||
|
||||
TEST_CASE("JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS")
|
||||
{
|
||||
SECTION("the macro is part of the ABI tag")
|
||||
{
|
||||
const std::string ns = STRINGIZE(NLOHMANN_JSON_NAMESPACE);
|
||||
CHECK(ns.find("_ekmo") != std::string::npos);
|
||||
}
|
||||
|
||||
SECTION("std::map (#4378)")
|
||||
{
|
||||
using task_map = std::map<TaskState, std::string>;
|
||||
const task_map m = {{TS_STOPPED, "aa"}, {TS_COMPLETED, "bb"}};
|
||||
const json j = m;
|
||||
CHECK(j == json::parse(R"({"stopped":"aa","completed":"bb"})"));
|
||||
CHECK(j.get<task_map>() == m);
|
||||
|
||||
json j2;
|
||||
j2["x"] = m;
|
||||
CHECK(j2.dump() == R"({"x":{"completed":"bb","stopped":"aa"}})");
|
||||
}
|
||||
|
||||
SECTION("std::map with custom comparator")
|
||||
{
|
||||
using task_map = std::map<TaskState, int, std::greater<TaskState>>;
|
||||
const task_map m = {{TS_STOPPED, 1}, {TS_RUNNING, 2}};
|
||||
const json j = m;
|
||||
CHECK(j == json::parse(R"({"stopped":1,"running":2})"));
|
||||
CHECK(j.get<task_map>() == m);
|
||||
}
|
||||
|
||||
SECTION("std::unordered_map")
|
||||
{
|
||||
using task_map = std::unordered_map<TaskState, int, enum_hash>;
|
||||
const task_map m = {{TS_STOPPED, 1}, {TS_RUNNING, 2}};
|
||||
const json j = m;
|
||||
CHECK(j == json::parse(R"({"stopped":1,"running":2})"));
|
||||
CHECK(j.get<task_map>() == m);
|
||||
}
|
||||
|
||||
SECTION("nested maps")
|
||||
{
|
||||
using nested_map = std::map<color, std::map<TaskState, int>>;
|
||||
const nested_map m = {{color::green, {{TS_RUNNING, 1}}}, {color::red, {}}};
|
||||
const json j = m;
|
||||
CHECK(j == json::parse(R"({"green":{"running":1},"red":{}})"));
|
||||
CHECK(j.get<nested_map>() == m);
|
||||
}
|
||||
|
||||
SECTION("ordered_json keeps the order of the map")
|
||||
{
|
||||
using task_map = std::map<TaskState, int>;
|
||||
const task_map m = {{TS_STOPPED, 1}, {TS_RUNNING, 2}, {TS_COMPLETED, 3}};
|
||||
const ordered_json j = m;
|
||||
CHECK(j.dump() == R"({"stopped":1,"running":2,"completed":3})");
|
||||
CHECK(j.get<task_map>() == m);
|
||||
}
|
||||
|
||||
SECTION("empty map")
|
||||
{
|
||||
const json j = std::map<TaskState, int>();
|
||||
CHECK(j.is_object());
|
||||
CHECK(j.empty());
|
||||
}
|
||||
|
||||
SECTION("NLOHMANN_JSON_SERIALIZE_ENUM_STRICT")
|
||||
{
|
||||
using color_map = std::map<strict_color, int>;
|
||||
const color_map m = {{strict_color::red, 1}, {strict_color::green, 2}};
|
||||
const json j = m;
|
||||
CHECK(j == json::parse(R"({"red":1,"green":2})"));
|
||||
CHECK(j.get<color_map>() == m);
|
||||
|
||||
const color_map unmapped = {{strict_color::blue, 1}};
|
||||
json _;
|
||||
CHECK_THROWS_WITH_AS(_ = unmapped,
|
||||
"[json.exception.out_of_range.410] enum value out of range for strict_color", json::out_of_range&);
|
||||
}
|
||||
|
||||
SECTION("arrays of [key, value] pairs are still read")
|
||||
{
|
||||
using task_map = std::map<TaskState, int>;
|
||||
const task_map m = {{TS_STOPPED, 1}};
|
||||
CHECK(json::parse(R"([["stopped",1]])").get<task_map>() == m);
|
||||
}
|
||||
|
||||
SECTION("other containers are not affected")
|
||||
{
|
||||
const std::vector<std::pair<TaskState, int>> pairs = {{TS_STOPPED, 1}};
|
||||
const std::map<std::string, TaskState> string_keys = {{"a", TS_STOPPED}};
|
||||
const std::map<int, int> int_keys = {{1, 2}};
|
||||
CHECK(json(pairs) == json::parse(R"([["stopped",1]])"));
|
||||
CHECK(json(string_keys) == json::parse(R"({"a":"stopped"})"));
|
||||
CHECK(json(int_keys) == json::parse("[[1,2]]"));
|
||||
}
|
||||
|
||||
SECTION("maps with non-unique keys are still stored as arrays of pairs")
|
||||
{
|
||||
const std::multimap<TaskState, int> mm = {{TS_STOPPED, 1}, {TS_STOPPED, 2}};
|
||||
const std::unordered_multimap<TaskState, int, enum_hash> umm = {{TS_RUNNING, 3}, {TS_RUNNING, 3}};
|
||||
CHECK(json(mm) == json::parse(R"([["stopped",1],["stopped",2]])"));
|
||||
CHECK(json(umm) == json::parse(R"([["running",3],["running",3]])"));
|
||||
}
|
||||
|
||||
SECTION("keys that do not serialize to strings")
|
||||
{
|
||||
const std::map<TaskState, int> null_key = {{TS_INVALID, 1}};
|
||||
const std::map<digit, int> number_key = {{digit::zero, 1}};
|
||||
json j = "unchanged";
|
||||
|
||||
// mapped to null
|
||||
CHECK_THROWS_WITH_AS(j = null_key,
|
||||
"[json.exception.type_error.302] type must be string, but is null", json::type_error&);
|
||||
|
||||
// mapped to a number
|
||||
CHECK_THROWS_WITH_AS(j = number_key,
|
||||
"[json.exception.type_error.302] type must be string, but is number", json::type_error&);
|
||||
|
||||
#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||
// enum without NLOHMANN_JSON_SERIALIZE_ENUM
|
||||
const std::map<plain, int> plain_key = {{plain::zero, 1}};
|
||||
CHECK_THROWS_WITH_AS(j = plain_key,
|
||||
"[json.exception.type_error.302] type must be string, but is number", json::type_error&);
|
||||
#endif
|
||||
|
||||
CHECK(j == "unchanged");
|
||||
}
|
||||
|
||||
SECTION("keys that serialize to the same string")
|
||||
{
|
||||
const std::map<color, int> m = {{color::red, 1}, {color::blue, 2}};
|
||||
json j = "unchanged";
|
||||
|
||||
// color::blue is not mapped and falls back to "red"
|
||||
CHECK_THROWS_WITH_AS(j = m,
|
||||
"[json.exception.type_error.318] duplicate object key 'red'", json::type_error&);
|
||||
|
||||
CHECK(j == "unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
@@ -0,0 +1,144 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// This file tests maps with enum keys with the default setting of
|
||||
// JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS (or whatever a -D flag sets it to).
|
||||
// unit-enum_keyed_maps.cpp tests JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS=1.
|
||||
// These tests are not part of unit-conversions.cpp, because that object file
|
||||
// is already too big for the MinGW linker of some compilers.
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
// NLOHMANN_JSON_SERIALIZE_ENUM uses a static std::pair
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
|
||||
enum class cards {kreuz, pik, herz, karo};
|
||||
|
||||
// NOLINTNEXTLINE(misc-use-internal-linkage,misc-const-correctness,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM(cards,
|
||||
{
|
||||
{cards::kreuz, "kreuz"},
|
||||
{cards::pik, "pik"},
|
||||
{cards::herz, "herz"},
|
||||
{cards::karo, "karo"}
|
||||
})
|
||||
|
||||
enum TaskState // NOLINT(cert-int09-c,readability-enum-initial-value,cppcoreguidelines-use-enum-class)
|
||||
{
|
||||
TS_STOPPED,
|
||||
TS_RUNNING,
|
||||
TS_COMPLETED,
|
||||
TS_INVALID = -1,
|
||||
};
|
||||
|
||||
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM(TaskState,
|
||||
{
|
||||
{TS_INVALID, nullptr},
|
||||
{TS_STOPPED, "stopped"},
|
||||
{TS_RUNNING, "running"},
|
||||
{TS_COMPLETED, "completed"},
|
||||
})
|
||||
|
||||
enum class strict_cards {kreuz, pik, herz, karo, andere}; // andere not included in mapping
|
||||
|
||||
// NOLINTNEXTLINE(misc-use-internal-linkage,misc-const-correctness,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||
NLOHMANN_JSON_SERIALIZE_ENUM_STRICT(strict_cards,
|
||||
{
|
||||
{strict_cards::kreuz, "kreuz"},
|
||||
{strict_cards::pik, "pik"},
|
||||
{strict_cards::herz, "herz"},
|
||||
{strict_cards::karo, "karo"}
|
||||
})
|
||||
|
||||
namespace
|
||||
{
|
||||
// std::hash is only required for enums since C++14
|
||||
struct enum_hash
|
||||
{
|
||||
template<typename T>
|
||||
std::size_t operator()(T t) const noexcept
|
||||
{
|
||||
return static_cast<std::size_t>(t);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// see unit-enum_keyed_maps.cpp for JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS=1
|
||||
TEST_CASE("maps with enum keys")
|
||||
{
|
||||
using task_map = std::map<TaskState, std::string>;
|
||||
using task_umap = std::unordered_map<TaskState, std::string, enum_hash>;
|
||||
using task_gmap = std::map<TaskState, std::string, std::greater<TaskState>>;
|
||||
using nested_map = std::map<cards, std::map<TaskState, int>>;
|
||||
using strict_map = std::map<strict_cards, int>;
|
||||
using int_map = std::map<int, int>;
|
||||
using int_umap = std::unordered_map<int, int>;
|
||||
|
||||
const task_map m = {{TS_STOPPED, "aa"}, {TS_COMPLETED, "bb"}};
|
||||
|
||||
#if !JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||
SECTION("stored as array of pairs")
|
||||
{
|
||||
CHECK(json(m) == json::parse(R"([["stopped","aa"],["completed","bb"]])"));
|
||||
CHECK(json(task_umap {{TS_RUNNING, "cc"}}) == json::parse(R"([["running","cc"]])"));
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("read from array of pairs")
|
||||
{
|
||||
CHECK(json::parse(R"([["stopped","aa"],["completed","bb"]])").get<task_map>() == m);
|
||||
}
|
||||
|
||||
SECTION("read from object (#4378)")
|
||||
{
|
||||
const json j = json::parse(R"({"stopped":"aa","completed":"bb"})");
|
||||
CHECK(j.get<task_map>() == m);
|
||||
CHECK(j.get<task_umap>() == task_umap(m.begin(), m.end()));
|
||||
CHECK(j.get<task_gmap>() == task_gmap(m.begin(), m.end()));
|
||||
CHECK(json::parse(R"({"kreuz":{"stopped":1}})").get<nested_map>() == nested_map {{cards::kreuz, {{TS_STOPPED, 1}}}});
|
||||
CHECK(nlohmann::ordered_json::parse(R"({"stopped":"aa","completed":"bb"})").get<task_map>() == m);
|
||||
|
||||
// object keys go through the enum's from_json
|
||||
strict_map sm;
|
||||
CHECK_THROWS_WITH_AS(json::parse(R"({"what?":1})").get_to(sm),
|
||||
"[json.exception.out_of_range.410] enum value out of range for strict_cards: \"what?\"", json::out_of_range&);
|
||||
}
|
||||
|
||||
SECTION("objects are only read for enum keys")
|
||||
{
|
||||
// built rather than parsed, so that the messages do not gain a byte
|
||||
// range with JSON_DIAGNOSTIC_POSITIONS
|
||||
const json j = {{"1", 2}};
|
||||
int_map im;
|
||||
int_umap ium;
|
||||
CHECK_THROWS_WITH_AS(j.get_to(im),
|
||||
"[json.exception.type_error.302] type must be array, but is object", json::type_error&);
|
||||
CHECK_THROWS_WITH_AS(j.get_to(ium),
|
||||
"[json.exception.type_error.302] type must be array, but is object", json::type_error&);
|
||||
}
|
||||
|
||||
SECTION("other types are rejected")
|
||||
{
|
||||
task_map tm;
|
||||
CHECK_THROWS_WITH_AS(json("stopped").get_to(tm),
|
||||
"[json.exception.type_error.302] type must be array, but is string", json::type_error&);
|
||||
}
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
+39
-8
@@ -12,8 +12,10 @@
|
||||
using json = nlohmann::json;
|
||||
using ordered_json = nlohmann::ordered_json;
|
||||
|
||||
#include <limits>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace
|
||||
{
|
||||
@@ -91,6 +93,9 @@ TEST_CASE("hash<nlohmann::json>")
|
||||
// Collect hashes for different JSON values and make sure that they are distinct
|
||||
// We cannot compare against fixed values, because the implementation of
|
||||
// std::hash may differ between compilers.
|
||||
//
|
||||
// numbers that compare equal under operator== (0 == 0U == 0.0) must hash
|
||||
// equally, so they are only inserted once below and checked separately.
|
||||
|
||||
std::set<std::size_t> hashes;
|
||||
|
||||
@@ -107,10 +112,7 @@ TEST_CASE("hash<nlohmann::json>")
|
||||
|
||||
// number
|
||||
hashes.insert(std::hash<json> {}(json(0)));
|
||||
hashes.insert(std::hash<json> {}(json(static_cast<unsigned>(0))));
|
||||
|
||||
hashes.insert(std::hash<json> {}(json(-1)));
|
||||
hashes.insert(std::hash<json> {}(json(0.0)));
|
||||
hashes.insert(std::hash<json> {}(json(42.23)));
|
||||
|
||||
// array
|
||||
@@ -132,7 +134,36 @@ TEST_CASE("hash<nlohmann::json>")
|
||||
// discarded
|
||||
hashes.insert(std::hash<json> {}(json(json::value_t::discarded)));
|
||||
|
||||
CHECK(hashes.size() == 21);
|
||||
CHECK(hashes.size() == 19);
|
||||
|
||||
// numbers that compare equal under operator== must hash equally,
|
||||
// regardless of which of number_integer, number_unsigned, or
|
||||
// number_float actually holds the value
|
||||
CHECK(json(0) == json(static_cast<unsigned>(0)));
|
||||
CHECK(json(0) == json(0.0));
|
||||
CHECK(std::hash<json> {}(json(0)) == std::hash<json> {}(json(static_cast<unsigned>(0))));
|
||||
CHECK(std::hash<json> {}(json(0)) == std::hash<json> {}(json(0.0)));
|
||||
CHECK(std::hash<json> {}(json(-1)) == std::hash<json> {}(json(-1.0)));
|
||||
|
||||
// a std::unordered_set relies on this same consistency between == and hash
|
||||
const std::unordered_set<json> numbers {json(0), json(static_cast<unsigned>(0)), json(0.0)};
|
||||
CHECK(numbers.size() == 1);
|
||||
|
||||
// -0.0 compares equal to 0 and 0.0
|
||||
CHECK(json(-0.0) == json(0));
|
||||
CHECK(std::hash<json> {}(json(-0.0)) == std::hash<json> {}(json(0)));
|
||||
CHECK(std::hash<json> {}(json(-0.0)) == std::hash<json> {}(json(0.0)));
|
||||
|
||||
// the ends of the integer ranges, which equal floats exactly
|
||||
const auto int_min = (std::numeric_limits<json::number_integer_t>::min)();
|
||||
const auto int_max = (std::numeric_limits<json::number_integer_t>::max)();
|
||||
const auto two_63 = json::number_unsigned_t(1) << 63U;
|
||||
CHECK(json(int_min) == json(-9223372036854775808.0));
|
||||
CHECK(std::hash<json> {}(json(int_min)) == std::hash<json> {}(json(-9223372036854775808.0)));
|
||||
CHECK(json(two_63) == json(9223372036854775808.0));
|
||||
CHECK(std::hash<json> {}(json(two_63)) == std::hash<json> {}(json(9223372036854775808.0)));
|
||||
CHECK(json(json::number_unsigned_t(int_max)) == json(int_max));
|
||||
CHECK(std::hash<json> {}(json(json::number_unsigned_t(int_max))) == std::hash<json> {}(json(int_max)));
|
||||
}
|
||||
|
||||
TEST_CASE("hash<nlohmann::ordered_json>")
|
||||
@@ -156,10 +187,7 @@ TEST_CASE("hash<nlohmann::ordered_json>")
|
||||
|
||||
// number
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(0)));
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(static_cast<unsigned>(0))));
|
||||
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(-1)));
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(0.0)));
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(42.23)));
|
||||
|
||||
// array
|
||||
@@ -181,7 +209,10 @@ TEST_CASE("hash<nlohmann::ordered_json>")
|
||||
// discarded
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(ordered_json::value_t::discarded)));
|
||||
|
||||
CHECK(hashes.size() == 21);
|
||||
CHECK(hashes.size() == 19);
|
||||
|
||||
CHECK(std::hash<ordered_json> {}(ordered_json(0)) == std::hash<ordered_json> {}(ordered_json(static_cast<unsigned>(0))));
|
||||
CHECK(std::hash<ordered_json> {}(ordered_json(0)) == std::hash<ordered_json> {}(ordered_json(0.0)));
|
||||
}
|
||||
|
||||
TEST_CASE("hash of deeply nested values")
|
||||
|
||||
@@ -8,6 +8,14 @@
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
@@ -19,6 +27,7 @@ DOCTEST_GCC_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wrange-loop-construct")
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
TEST_CASE("iterator_wrapper")
|
||||
{
|
||||
SECTION("object")
|
||||
@@ -715,6 +724,7 @@ TEST_CASE("iterator_wrapper")
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST_CASE("items()")
|
||||
{
|
||||
|
||||
@@ -9,6 +9,14 @@
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
#define JSON_TESTS_PRIVATE
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
#ifdef JSON_TEST_NO_GLOBAL_UDLS
|
||||
@@ -630,7 +638,9 @@ TEST_CASE("JSON pointers")
|
||||
std::stringstream ss;
|
||||
ss << ptr;
|
||||
CHECK(ptr.to_string() == ptr_str);
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
CHECK(std::string(ptr) == ptr_str);
|
||||
#endif
|
||||
CHECK(ss.str() == ptr_str);
|
||||
}
|
||||
}
|
||||
@@ -810,8 +820,6 @@ TEST_CASE("JSON pointers")
|
||||
|
||||
SECTION("equality comparison")
|
||||
{
|
||||
const char* ptr_cpstring = "/foo/bar";
|
||||
const char ptr_castring[] = "/foo/bar"; // NOLINT(misc-const-correctness,hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
|
||||
std::string ptr_string{"/foo/bar"};
|
||||
auto ptr1 = json::json_pointer(ptr_string);
|
||||
auto ptr2 = json::json_pointer(ptr_string);
|
||||
@@ -821,6 +829,12 @@ TEST_CASE("JSON pointers")
|
||||
|
||||
CHECK(ptr1 == ptr2);
|
||||
|
||||
CHECK_FALSE(ptr1 != ptr2);
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
const char* ptr_cpstring = "/foo/bar";
|
||||
const char ptr_castring[] = "/foo/bar"; // NOLINT(misc-const-correctness,hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
|
||||
|
||||
CHECK(ptr1 == "/foo/bar");
|
||||
CHECK(ptr1 == ptr_cpstring);
|
||||
CHECK(ptr1 == ptr_castring);
|
||||
@@ -831,8 +845,6 @@ TEST_CASE("JSON pointers")
|
||||
CHECK(ptr_castring == ptr1);
|
||||
CHECK(ptr_string == ptr1);
|
||||
|
||||
CHECK_FALSE(ptr1 != ptr2);
|
||||
|
||||
CHECK_FALSE(ptr1 != "/foo/bar");
|
||||
CHECK_FALSE(ptr1 != ptr_cpstring);
|
||||
CHECK_FALSE(ptr1 != ptr_castring);
|
||||
@@ -854,6 +866,7 @@ TEST_CASE("JSON pointers")
|
||||
CHECK_THROWS_WITH_AS("/~~" == ptr1,
|
||||
"[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'", json::parse_error&);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("less-than comparison")
|
||||
@@ -905,6 +918,7 @@ TEST_CASE("JSON pointers")
|
||||
json_ptr_j ptr_j{ptr_string};
|
||||
json_ptr_oj ptr_oj{ptr_string};
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
CHECK(j.contains(ptr));
|
||||
CHECK(j.contains(ptr_j));
|
||||
CHECK(j.contains(ptr_oj));
|
||||
@@ -917,6 +931,7 @@ TEST_CASE("JSON pointers")
|
||||
|
||||
CHECK(j.value(ptr, "x") == j.value(ptr_j, "x"));
|
||||
CHECK(j.value(ptr, "x") == j.value(ptr_oj, "x"));
|
||||
#endif
|
||||
|
||||
CHECK(ptr == ptr_j);
|
||||
CHECK(ptr == ptr_oj);
|
||||
|
||||
@@ -13,6 +13,7 @@ using nlohmann::json;
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
TEST_CASE("tests on very large JSONs")
|
||||
@@ -354,3 +355,199 @@ TEST_CASE("tests on deeply nested JSONs")
|
||||
}
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
json nested_array(const std::size_t depth, json leaf)
|
||||
{
|
||||
json j = std::move(leaf);
|
||||
for (std::size_t i = 0; i < depth; ++i)
|
||||
{
|
||||
json a = json::array();
|
||||
a.push_back(std::move(j));
|
||||
j = std::move(a);
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
json nested_object(const std::size_t depth, json leaf)
|
||||
{
|
||||
json j = std::move(leaf);
|
||||
for (std::size_t i = 0; i < depth; ++i)
|
||||
{
|
||||
json o = json::object();
|
||||
o["k"] = std::move(j);
|
||||
j = std::move(o);
|
||||
}
|
||||
return j;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("issue #5392 - binary writers on deeply nested values")
|
||||
{
|
||||
// 200 is past the point where the writers stop recursing, and still
|
||||
// shallow enough that from_* and operator== (which still recurse) are fine.
|
||||
const json deep_array = nested_array(200, json(0));
|
||||
const json deep_object = nested_object(200, json("x"));
|
||||
const json empty_array = nested_array(200, json::array());
|
||||
const json empty_object = nested_object(200, json::object());
|
||||
const json mixed = nested_object(80, nested_array(80, json(true)));
|
||||
|
||||
SECTION("roundtrip past the recursion bound")
|
||||
{
|
||||
CHECK(json::from_cbor(json::to_cbor(deep_array)) == deep_array);
|
||||
CHECK(json::from_msgpack(json::to_msgpack(deep_array)) == deep_array);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(deep_array)) == deep_array);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(deep_array, true, false)) == deep_array);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(deep_array, true, true)) == deep_array);
|
||||
CHECK(json::from_bjdata(json::to_bjdata(deep_array)) == deep_array);
|
||||
|
||||
CHECK(json::from_cbor(json::to_cbor(deep_object)) == deep_object);
|
||||
CHECK(json::from_msgpack(json::to_msgpack(deep_object)) == deep_object);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(deep_object)) == deep_object);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(deep_object, true, true)) == deep_object);
|
||||
CHECK(json::from_bjdata(json::to_bjdata(deep_object)) == deep_object);
|
||||
|
||||
CHECK(json::from_cbor(json::to_cbor(empty_array)) == empty_array);
|
||||
CHECK(json::from_msgpack(json::to_msgpack(empty_array)) == empty_array);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(empty_array)) == empty_array);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(empty_array, true, true)) == empty_array);
|
||||
|
||||
CHECK(json::from_cbor(json::to_cbor(empty_object)) == empty_object);
|
||||
CHECK(json::from_msgpack(json::to_msgpack(empty_object)) == empty_object);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(empty_object)) == empty_object);
|
||||
|
||||
CHECK(json::from_cbor(json::to_cbor(mixed)) == mixed);
|
||||
CHECK(json::from_msgpack(json::to_msgpack(mixed)) == mixed);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(mixed)) == mixed);
|
||||
CHECK(json::from_bjdata(json::to_bjdata(mixed)) == mixed);
|
||||
}
|
||||
|
||||
SECTION("the two ways of writing a value meet at the bound")
|
||||
{
|
||||
for (std::size_t depth = 120; depth <= 140; ++depth)
|
||||
{
|
||||
CAPTURE(depth);
|
||||
|
||||
const json array = nested_array(depth, json(7));
|
||||
CHECK(json::from_cbor(json::to_cbor(array)) == array);
|
||||
CHECK(json::from_msgpack(json::to_msgpack(array)) == array);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(array, true, true)) == array);
|
||||
|
||||
const json object = nested_object(depth, json(7));
|
||||
CHECK(json::from_cbor(json::to_cbor(object)) == object);
|
||||
CHECK(json::from_msgpack(json::to_msgpack(object)) == object);
|
||||
CHECK(json::from_bjdata(json::to_bjdata(object)) == object);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("a BJData ndarray below the bound is still an ndarray")
|
||||
{
|
||||
const json ndarray = json({{"_ArrayType_", "uint8"}, {"_ArraySize_", {2, 3}}, {"_ArrayData_", {1, 2, 3, 4, 5, 6}}});
|
||||
const json invalid = json({{"_ArrayType_", "nope"}, {"_ArraySize_", {1}}, {"_ArrayData_", {1}}});
|
||||
|
||||
const json deep_ndarray = nested_array(140, ndarray);
|
||||
const json deep_invalid = nested_array(140, invalid);
|
||||
|
||||
CHECK(json::from_bjdata(json::to_bjdata(deep_ndarray)) == deep_ndarray);
|
||||
CHECK(json::from_bjdata(json::to_bjdata(deep_invalid)) == deep_invalid);
|
||||
CHECK(json::from_bjdata(json::to_bjdata(ndarray)) == ndarray);
|
||||
}
|
||||
|
||||
SECTION("byte-exact across the switch-over")
|
||||
{
|
||||
// nested one-element arrays around the recursion bound: the exact
|
||||
// bytes a writer produces do not depend on whether it stayed on the
|
||||
// call stack or moved to the heap one partway through
|
||||
for (const std::size_t depth :
|
||||
{
|
||||
nlohmann::detail::recursion_depth_limit() - 1, nlohmann::detail::recursion_depth_limit(),
|
||||
nlohmann::detail::recursion_depth_limit() + 1, nlohmann::detail::recursion_depth_limit() + 2
|
||||
})
|
||||
{
|
||||
CAPTURE(depth);
|
||||
const json array = nested_array(depth, json(0));
|
||||
|
||||
std::vector<std::uint8_t> expected_cbor(depth, 0x81);
|
||||
expected_cbor.push_back(0x00);
|
||||
CHECK(json::to_cbor(array) == expected_cbor);
|
||||
|
||||
std::vector<std::uint8_t> expected_msgpack(depth, 0x91);
|
||||
expected_msgpack.push_back(0x00);
|
||||
CHECK(json::to_msgpack(array) == expected_msgpack);
|
||||
|
||||
std::string expected_ubjson(depth, '[');
|
||||
expected_ubjson += "i";
|
||||
expected_ubjson += '\0';
|
||||
expected_ubjson.append(depth, ']');
|
||||
const auto packed_ubjson = json::to_ubjson(array);
|
||||
CHECK(std::string(packed_ubjson.begin(), packed_ubjson.end()) == expected_ubjson);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("a deep object, and a BJData ndarray, past the recursion bound")
|
||||
{
|
||||
const std::size_t depth = nlohmann::detail::recursion_depth_limit() + 50;
|
||||
|
||||
const json object = nested_object(depth, json(42));
|
||||
CHECK(json::from_cbor(json::to_cbor(object)) == object);
|
||||
CHECK(json::from_msgpack(json::to_msgpack(object)) == object);
|
||||
CHECK(json::from_ubjson(json::to_ubjson(object, true, true)) == object);
|
||||
CHECK(json::from_bjdata(json::to_bjdata(object)) == object);
|
||||
|
||||
const json ndarray = json({{"_ArrayType_", "uint8"}, {"_ArraySize_", {2, 3}}, {"_ArrayData_", {1, 2, 3, 4, 5, 6}}});
|
||||
const json deep_ndarray = nested_array(depth, ndarray);
|
||||
CHECK(json::from_bjdata(json::to_bjdata(deep_ndarray)) == deep_ndarray);
|
||||
}
|
||||
|
||||
SECTION("a discarded value past the recursion bound still throws type_error.321")
|
||||
{
|
||||
const std::size_t depth = nlohmann::detail::recursion_depth_limit() + 50;
|
||||
const json discarded_leaf(json::value_t::discarded);
|
||||
const json deep_discarded = nested_array(depth, discarded_leaf);
|
||||
|
||||
CHECK_THROWS_WITH_AS(json::to_cbor(deep_discarded), "[json.exception.type_error.321] cannot serialize discarded value to CBOR", json::type_error);
|
||||
CHECK_THROWS_WITH_AS(json::to_msgpack(deep_discarded), "[json.exception.type_error.321] cannot serialize discarded value to MessagePack", json::type_error);
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(deep_discarded), "[json.exception.type_error.321] cannot serialize discarded value to UBJSON", json::type_error);
|
||||
CHECK_THROWS_WITH_AS(json::to_bjdata(deep_discarded), "[json.exception.type_error.321] cannot serialize discarded value to BJData", json::type_error);
|
||||
}
|
||||
|
||||
SECTION("does not overflow the C++ stack")
|
||||
{
|
||||
const std::size_t depth = 100000;
|
||||
const json j = json::parse(std::string(depth, '[') + "0" + std::string(depth, ']'));
|
||||
|
||||
std::vector<std::uint8_t> packed;
|
||||
CHECK_NOTHROW(packed = json::to_cbor(j));
|
||||
CHECK(json::from_cbor(packed) == j);
|
||||
|
||||
CHECK_NOTHROW(packed = json::to_msgpack(j));
|
||||
CHECK(json::from_msgpack(packed) == j);
|
||||
|
||||
CHECK_NOTHROW(packed = json::to_ubjson(j));
|
||||
CHECK(json::from_ubjson(packed) == j);
|
||||
|
||||
CHECK_NOTHROW(packed = json::to_ubjson(j, true, false));
|
||||
CHECK(json::from_ubjson(packed) == j);
|
||||
|
||||
CHECK_NOTHROW(packed = json::to_bjdata(j));
|
||||
CHECK(json::from_bjdata(packed) == j);
|
||||
}
|
||||
|
||||
SECTION("regression test for https://issues.oss-fuzz.com/issues/566583014")
|
||||
{
|
||||
// 200000 nested one-element CBOR arrays, the innermost holding null;
|
||||
// round-tripping this used to recurse once per level on the way back
|
||||
// out through to_cbor(), deep enough to overflow the stack
|
||||
std::vector<std::uint8_t> v(200000, 0x81);
|
||||
v.push_back(0xf6);
|
||||
const json j = json::from_cbor(v);
|
||||
CHECK(json::to_cbor(j) == v);
|
||||
|
||||
// the MessagePack analogue: fixarray of 1 nesting down to nil
|
||||
std::vector<std::uint8_t> v_msgpack(200000, 0x91);
|
||||
v_msgpack.push_back(0xc0);
|
||||
const json j_msgpack = json::from_msgpack(v_msgpack);
|
||||
CHECK(json::to_msgpack(j_msgpack) == v_msgpack);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
// This file contains the C++17-only part of unit-msgpack.cpp (std::byte
|
||||
// input). It is kept in a separate translation unit so the (much larger)
|
||||
// unit-msgpack.cpp does not need to be compiled and run a second time just
|
||||
// for this one test case (#5418).
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#include <cstddef>
|
||||
#include <vector>
|
||||
|
||||
// Test suite for verifying MessagePack handling with std::byte input
|
||||
TEST_CASE("MessagePack with std::byte")
|
||||
{
|
||||
|
||||
SECTION("std::byte compatibility")
|
||||
{
|
||||
SECTION("vector roundtrip")
|
||||
{
|
||||
json original =
|
||||
{
|
||||
{"name", "test"},
|
||||
{"value", 42},
|
||||
{"array", {1, 2, 3}}
|
||||
};
|
||||
|
||||
std::vector<uint8_t> temp = json::to_msgpack(original);
|
||||
// Convert the uint8_t vector to std::byte vector
|
||||
std::vector<std::byte> msgpack_data(temp.size());
|
||||
for (size_t i = 0; i < temp.size(); ++i)
|
||||
{
|
||||
msgpack_data[i] = std::byte(temp[i]);
|
||||
}
|
||||
// Deserialize from std::byte vector back to JSON
|
||||
json from_bytes;
|
||||
CHECK_NOTHROW(from_bytes = json::from_msgpack(msgpack_data));
|
||||
|
||||
CHECK(from_bytes == original);
|
||||
}
|
||||
|
||||
SECTION("empty vector")
|
||||
{
|
||||
const std::vector<std::byte> empty_data;
|
||||
CHECK_THROWS_WITH_AS([&]()
|
||||
{
|
||||
[[maybe_unused]] auto result = json::from_msgpack(empty_data);
|
||||
return true;
|
||||
}
|
||||
(),
|
||||
"[json.exception.parse_error.110] parse error at byte 1: syntax error while parsing MessagePack value: unexpected end of input",
|
||||
json::parse_error&);
|
||||
}
|
||||
|
||||
SECTION("comparison with workaround")
|
||||
{
|
||||
json original =
|
||||
{
|
||||
{"string", "hello"},
|
||||
{"integer", 42},
|
||||
{"float", 3.14},
|
||||
{"boolean", true},
|
||||
{"null", nullptr},
|
||||
{"array", {1, 2, 3}},
|
||||
{"object", {{"key", "value"}}}
|
||||
};
|
||||
|
||||
std::vector<uint8_t> temp = json::to_msgpack(original);
|
||||
|
||||
std::vector<std::byte> msgpack_data(temp.size());
|
||||
for (size_t i = 0; i < temp.size(); ++i)
|
||||
{
|
||||
msgpack_data[i] = std::byte(temp[i]);
|
||||
}
|
||||
// Attempt direct deserialization using std::byte input
|
||||
const json direct_result = json::from_msgpack(msgpack_data);
|
||||
|
||||
// Test the workaround approach: reinterpret as unsigned char* and use iterator range
|
||||
const auto* const char_start = reinterpret_cast<unsigned char const*>(msgpack_data.data());
|
||||
const auto* const char_end = char_start + msgpack_data.size();
|
||||
json workaround_result = json::from_msgpack(char_start, char_end);
|
||||
|
||||
// Verify that the final deserialized JSON matches the original JSON
|
||||
CHECK(direct_result == workaround_result);
|
||||
CHECK(direct_result == original);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
+94
-82
@@ -8,6 +8,14 @@
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
#ifdef JSON_TEST_NO_GLOBAL_UDLS
|
||||
@@ -33,10 +41,49 @@ TEST_CASE("MessagePack")
|
||||
{
|
||||
SECTION("discarded")
|
||||
{
|
||||
// discarded values are not serialized
|
||||
// a discarded value cannot be serialized to MessagePack
|
||||
json const j = json::value_t::discarded;
|
||||
const auto result = json::to_msgpack(j);
|
||||
CHECK(result.empty());
|
||||
CHECK_THROWS_WITH_AS(json::to_msgpack(j), "[json.exception.type_error.321] cannot serialize discarded value to MessagePack", json::type_error&);
|
||||
}
|
||||
|
||||
SECTION("discarded values nested in a container")
|
||||
{
|
||||
json const discarded = json::value_t::discarded;
|
||||
|
||||
SECTION("in an array")
|
||||
{
|
||||
json const j = {1, discarded, 2};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_msgpack(j), "[json.exception.type_error.321] (/1) cannot serialize discarded value to MessagePack", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_msgpack(j), "[json.exception.type_error.321] cannot serialize discarded value to MessagePack", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("as an object value")
|
||||
{
|
||||
json j;
|
||||
j["a"] = 1;
|
||||
j["b"] = discarded;
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_msgpack(j), "[json.exception.type_error.321] (/b) cannot serialize discarded value to MessagePack", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_msgpack(j), "[json.exception.type_error.321] cannot serialize discarded value to MessagePack", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("nested deeper (array in object in array)")
|
||||
{
|
||||
json inner_array = {1, discarded};
|
||||
json middle_object;
|
||||
middle_object["x"] = inner_array;
|
||||
json const j = {middle_object};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_msgpack(j), "[json.exception.type_error.321] (/0/x/1) cannot serialize discarded value to MessagePack", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_msgpack(j), "[json.exception.type_error.321] cannot serialize discarded value to MessagePack", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("null")
|
||||
@@ -1795,8 +1842,10 @@ TEST_CASE("MessagePack input that cannot be read is discarded by every overload"
|
||||
CHECK_THROWS_AS(_ = json::from_msgpack(input.begin(), input.end()), json::parse_error&);
|
||||
CHECK(json::from_msgpack(input, true, false).is_discarded());
|
||||
CHECK(json::from_msgpack(input.begin(), input.end(), true, false).is_discarded());
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
CHECK(json::from_msgpack(input.data(), input.size(), true, false).is_discarded());
|
||||
CHECK(json::from_msgpack({input.data(), input.size()}, true, false).is_discarded());
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_CASE("MessagePack SAX parsing stops at every event")
|
||||
@@ -2099,12 +2148,14 @@ TEST_CASE("MessagePack roundtrips" * doctest::skip())
|
||||
CHECK(j1 == j2);
|
||||
}
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
{
|
||||
INFO_WITH_TEMP(filename + ": uint8_t* and size");
|
||||
json j2;
|
||||
CHECK_NOTHROW(j2 = json::from_msgpack({packed.data(), packed.size()}));
|
||||
CHECK(j1 == j2);
|
||||
}
|
||||
#endif
|
||||
|
||||
{
|
||||
INFO_WITH_TEMP(filename + ": output to output adapters");
|
||||
@@ -2122,85 +2173,6 @@ TEST_CASE("MessagePack roundtrips" * doctest::skip())
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
// Test suite for verifying MessagePack handling with std::byte input
|
||||
TEST_CASE("MessagePack with std::byte")
|
||||
{
|
||||
|
||||
SECTION("std::byte compatibility")
|
||||
{
|
||||
SECTION("vector roundtrip")
|
||||
{
|
||||
json original =
|
||||
{
|
||||
{"name", "test"},
|
||||
{"value", 42},
|
||||
{"array", {1, 2, 3}}
|
||||
};
|
||||
|
||||
std::vector<uint8_t> temp = json::to_msgpack(original);
|
||||
// Convert the uint8_t vector to std::byte vector
|
||||
std::vector<std::byte> msgpack_data(temp.size());
|
||||
for (size_t i = 0; i < temp.size(); ++i)
|
||||
{
|
||||
msgpack_data[i] = std::byte(temp[i]);
|
||||
}
|
||||
// Deserialize from std::byte vector back to JSON
|
||||
json from_bytes;
|
||||
CHECK_NOTHROW(from_bytes = json::from_msgpack(msgpack_data));
|
||||
|
||||
CHECK(from_bytes == original);
|
||||
}
|
||||
|
||||
SECTION("empty vector")
|
||||
{
|
||||
const std::vector<std::byte> empty_data;
|
||||
CHECK_THROWS_WITH_AS([&]()
|
||||
{
|
||||
[[maybe_unused]] auto result = json::from_msgpack(empty_data);
|
||||
return true;
|
||||
}
|
||||
(),
|
||||
"[json.exception.parse_error.110] parse error at byte 1: syntax error while parsing MessagePack value: unexpected end of input",
|
||||
json::parse_error&);
|
||||
}
|
||||
|
||||
SECTION("comparison with workaround")
|
||||
{
|
||||
json original =
|
||||
{
|
||||
{"string", "hello"},
|
||||
{"integer", 42},
|
||||
{"float", 3.14},
|
||||
{"boolean", true},
|
||||
{"null", nullptr},
|
||||
{"array", {1, 2, 3}},
|
||||
{"object", {{"key", "value"}}}
|
||||
};
|
||||
|
||||
std::vector<uint8_t> temp = json::to_msgpack(original);
|
||||
|
||||
std::vector<std::byte> msgpack_data(temp.size());
|
||||
for (size_t i = 0; i < temp.size(); ++i)
|
||||
{
|
||||
msgpack_data[i] = std::byte(temp[i]);
|
||||
}
|
||||
// Attempt direct deserialization using std::byte input
|
||||
const json direct_result = json::from_msgpack(msgpack_data);
|
||||
|
||||
// Test the workaround approach: reinterpret as unsigned char* and use iterator range
|
||||
const auto* const char_start = reinterpret_cast<unsigned char const*>(msgpack_data.data());
|
||||
const auto* const char_end = char_start + msgpack_data.size();
|
||||
json workaround_result = json::from_msgpack(char_start, char_end);
|
||||
|
||||
// Verify that the final deserialized JSON matches the original JSON
|
||||
CHECK(direct_result == workaround_result);
|
||||
CHECK(direct_result == original);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// the fake sizes below do not fit into a 32-bit std::size_t
|
||||
// with clang and libstdc++ 10, the std::filesystem::path conversion that
|
||||
// C++17 builds consider for every string type is ambiguous for a class
|
||||
@@ -2510,3 +2482,43 @@ TEST_CASE("MessagePack numbers use the active union member (see #5644)")
|
||||
CHECK(json::from_msgpack(result) == j);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("MessagePack large strings and binaries (chunked reader)")
|
||||
{
|
||||
// get_msgpack_string()/get_msgpack_binary() both read through get_binary(),
|
||||
// which reads in bounded chunks (binary_reader.hpp, chunk_size == 4096);
|
||||
// make sure roundtripping is correct for lengths around and beyond that
|
||||
// chunk size, for both vector (iterator) and pointer inputs.
|
||||
for (const std::size_t len :
|
||||
{
|
||||
std::size_t{0}, std::size_t{1}, std::size_t{4095}, std::size_t{4096},
|
||||
std::size_t{4097}, std::size_t{8192}, std::size_t{100000}
|
||||
})
|
||||
{
|
||||
CAPTURE(len)
|
||||
|
||||
// string
|
||||
const json j_string = std::string(len, 'x');
|
||||
const std::vector<std::uint8_t> v_string = json::to_msgpack(j_string);
|
||||
CHECK(json::from_msgpack(v_string) == j_string);
|
||||
// pointer input exercises the std::memcpy fast path
|
||||
CHECK(json::from_msgpack(reinterpret_cast<const char*>(v_string.data()),
|
||||
reinterpret_cast<const char*>(v_string.data()) + v_string.size()) == j_string);
|
||||
|
||||
// binary
|
||||
const json j_binary = json::binary(std::vector<std::uint8_t>(len, 0xCD));
|
||||
const std::vector<std::uint8_t> v_binary = json::to_msgpack(j_binary);
|
||||
CHECK(json::from_msgpack(v_binary) == j_binary);
|
||||
CHECK(json::from_msgpack(reinterpret_cast<const char*>(v_binary.data()),
|
||||
reinterpret_cast<const char*>(v_binary.data()) + v_binary.size()) == j_binary);
|
||||
|
||||
// a truncated payload must still be reported as an error
|
||||
if (len > 16)
|
||||
{
|
||||
std::vector<std::uint8_t> truncated = v_string;
|
||||
truncated.resize(truncated.size() - 8);
|
||||
json _;
|
||||
CHECK_THROWS_AS(_ = json::from_msgpack(truncated), json::parse_error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,9 @@ using ordered_json = nlohmann::ordered_json;
|
||||
#endif
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <list>
|
||||
#include <new>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
@@ -107,6 +109,84 @@ DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
|
||||
using float_json = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, float>;
|
||||
|
||||
#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
|
||||
namespace
|
||||
{
|
||||
// An allocator whose allocate() can be told to fail on demand, so tests can
|
||||
// check that ~basic_json() tolerates - in fact, after #5135, never even
|
||||
// triggers - an allocation failure. This replaces an earlier version of
|
||||
// this test that overrode the process-wide ::operator new/::operator
|
||||
// delete, which affected every allocation in the whole unit-regression2
|
||||
// binary rather than just the values under test.
|
||||
std::size_t failing_allocator_allocations = 0;
|
||||
std::size_t failing_allocator_deallocations = 0;
|
||||
bool fail_next_allocation = false;
|
||||
|
||||
template<class T>
|
||||
struct failing_allocator : std::allocator<T>
|
||||
{
|
||||
using std::allocator<T>::allocator;
|
||||
|
||||
failing_allocator() noexcept = default;
|
||||
template<class U>
|
||||
failing_allocator(const failing_allocator<U>& /*unused*/) noexcept {} // NOLINT(google-explicit-constructor)
|
||||
|
||||
T* allocate(std::size_t n)
|
||||
{
|
||||
if (fail_next_allocation)
|
||||
{
|
||||
fail_next_allocation = false;
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
++failing_allocator_allocations;
|
||||
return std::allocator<T>::allocate(n);
|
||||
}
|
||||
|
||||
void deallocate(T* p, std::size_t n)
|
||||
{
|
||||
++failing_allocator_deallocations;
|
||||
std::allocator<T>::deallocate(p, n);
|
||||
}
|
||||
|
||||
template<class U>
|
||||
struct rebind
|
||||
{
|
||||
using other = failing_allocator<U>;
|
||||
};
|
||||
};
|
||||
|
||||
using failing_json = nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, failing_allocator>;
|
||||
using failing_ordered_json = nlohmann::basic_json<nlohmann::ordered_map, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, failing_allocator>;
|
||||
|
||||
// builds `depth` levels of nesting around a scalar, iteratively (never
|
||||
// recursing: each wrap only moves the previous, already-built value, which
|
||||
// is O(1)), each level an array or an object depending on `nest_objects`
|
||||
template<class BasicJsonType>
|
||||
BasicJsonType make_deep_nest(std::size_t depth, bool nest_objects)
|
||||
{
|
||||
BasicJsonType v = 0;
|
||||
for (std::size_t i = 0; i < depth; ++i)
|
||||
{
|
||||
if (nest_objects)
|
||||
{
|
||||
BasicJsonType wrapper = BasicJsonType::object();
|
||||
wrapper["x"] = std::move(v);
|
||||
v = std::move(wrapper);
|
||||
}
|
||||
else
|
||||
{
|
||||
BasicJsonType wrapper = BasicJsonType::array();
|
||||
wrapper.push_back(std::move(v));
|
||||
v = std::move(wrapper);
|
||||
}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #1647
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
@@ -569,7 +649,7 @@ TEST_CASE("regression tests 2")
|
||||
SECTION("issue #2067 - cannot serialize binary data to text JSON")
|
||||
{
|
||||
const std::array<unsigned char, 23> data = {{0x81, 0xA4, 0x64, 0x61, 0x74, 0x61, 0xC4, 0x0F, 0x33, 0x30, 0x30, 0x32, 0x33, 0x34, 0x30, 0x31, 0x30, 0x37, 0x30, 0x35, 0x30, 0x31, 0x30}};
|
||||
const json j = json::from_msgpack(data.data(), data.size());
|
||||
const json j = json::from_msgpack(data.begin(), data.end());
|
||||
// dump() is nodiscard; this only checks that dumping does not throw
|
||||
CHECK_NOTHROW(
|
||||
utils::ignore_return_value(
|
||||
@@ -808,6 +888,15 @@ TEST_CASE("regression tests 2")
|
||||
CHECK(j == k);
|
||||
}
|
||||
|
||||
SECTION("issue #4552 - UTF-8 invalid characters are not always ignored when dumping with error_handler_t::ignore")
|
||||
{
|
||||
json node;
|
||||
node["test"] = "test\334\005";
|
||||
CHECK(node.dump(-1, ' ', false, json::error_handler_t::ignore) == "{\"test\":\"test\\u0005\"}");
|
||||
CHECK(node.dump(-1, ' ', false, json::error_handler_t::keep) == "{\"test\":\"test\334\\u0005\"}");
|
||||
CHECK(node.dump(-1, ' ', true, json::error_handler_t::keep) == "{\"test\":\"test\334\\u0005\"}");
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
SECTION("issue #5066 - MSVC converts json to std::variant<json> via the conversion operator")
|
||||
{
|
||||
@@ -940,4 +1029,211 @@ TEST_CASE("regression test - excessive binary container size honors allow_except
|
||||
CHECK(json::from_cbor(std::vector<std::uint8_t> {0x9b, 0, 0, 0, 0, 0, 0, 0, 0x02}, true, false).is_discarded());
|
||||
}
|
||||
|
||||
#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
|
||||
TEST_CASE("regression test #5135 - destructor never allocates, even under memory pressure")
|
||||
{
|
||||
// Before the fix, ~basic_json() flattened a nested array/object into a
|
||||
// heap-allocated std::vector to avoid recursing; that allocation could
|
||||
// itself throw bad_alloc, which escapes a noexcept destructor and
|
||||
// terminates the program. destroy() no longer allocates anything, so
|
||||
// none of the sections below ever observe fail_next_allocation being
|
||||
// consumed: CHECK(fail_next_allocation) confirms it was never touched.
|
||||
|
||||
SECTION("the original report: a small, mixed array/object nest")
|
||||
{
|
||||
failing_allocator_allocations = 0;
|
||||
failing_allocator_deallocations = 0;
|
||||
{
|
||||
const failing_json j = failing_json::array(
|
||||
{
|
||||
failing_json::array({1, 2}),
|
||||
failing_json::object({{"key", failing_json::array({3})}})
|
||||
});
|
||||
fail_next_allocation = true;
|
||||
} // j is destroyed here, with every further allocation set to fail
|
||||
|
||||
CHECK(fail_next_allocation);
|
||||
fail_next_allocation = false;
|
||||
CHECK(failing_allocator_deallocations > 0);
|
||||
}
|
||||
|
||||
SECTION("100000-deep nested array")
|
||||
{
|
||||
std::size_t allocations_before = 0;
|
||||
{
|
||||
const auto j = make_deep_nest<failing_json>(100000, false);
|
||||
allocations_before = failing_allocator_allocations;
|
||||
fail_next_allocation = true;
|
||||
}
|
||||
|
||||
CHECK(fail_next_allocation);
|
||||
fail_next_allocation = false;
|
||||
CHECK(failing_allocator_allocations == allocations_before);
|
||||
}
|
||||
|
||||
SECTION("100000-deep nested object")
|
||||
{
|
||||
std::size_t allocations_before = 0;
|
||||
{
|
||||
const auto j = make_deep_nest<failing_json>(100000, true);
|
||||
allocations_before = failing_allocator_allocations;
|
||||
fail_next_allocation = true;
|
||||
}
|
||||
|
||||
CHECK(fail_next_allocation);
|
||||
fail_next_allocation = false;
|
||||
CHECK(failing_allocator_allocations == allocations_before);
|
||||
}
|
||||
|
||||
SECTION("100000-deep nested ordered_json")
|
||||
{
|
||||
std::size_t allocations_before = 0;
|
||||
{
|
||||
const auto j = make_deep_nest<failing_ordered_json>(100000, true);
|
||||
allocations_before = failing_allocator_allocations;
|
||||
fail_next_allocation = true;
|
||||
}
|
||||
|
||||
CHECK(fail_next_allocation);
|
||||
fail_next_allocation = false;
|
||||
CHECK(failing_allocator_allocations == allocations_before);
|
||||
}
|
||||
|
||||
SECTION("wide and deep: 1000 arrays of 1000 elements, each a small nested object")
|
||||
{
|
||||
std::size_t allocations_before = 0;
|
||||
{
|
||||
failing_json wide = failing_json::array();
|
||||
for (std::size_t i = 0; i < 1000; ++i)
|
||||
{
|
||||
failing_json inner = failing_json::array();
|
||||
for (std::size_t k = 0; k < 1000; ++k)
|
||||
{
|
||||
inner.push_back(failing_json::object({{"a", 1}, {"b", failing_json::array({1, 2, 3})}}));
|
||||
}
|
||||
wide.push_back(std::move(inner));
|
||||
}
|
||||
|
||||
allocations_before = failing_allocator_allocations;
|
||||
fail_next_allocation = true;
|
||||
}
|
||||
|
||||
CHECK(fail_next_allocation);
|
||||
fail_next_allocation = false;
|
||||
CHECK(failing_allocator_allocations == allocations_before);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
// a single-element chain of `depth` arrays, built iteratively (never
|
||||
// recursing: each wrap only moves the previous, already-built value)
|
||||
template<class BasicJsonType>
|
||||
BasicJsonType make_single_chain(std::size_t depth)
|
||||
{
|
||||
BasicJsonType v = 1;
|
||||
for (std::size_t i = 0; i < depth; ++i)
|
||||
{
|
||||
BasicJsonType wrapper = BasicJsonType::array();
|
||||
wrapper.push_back(std::move(v));
|
||||
v = std::move(wrapper);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// copies value first, to make sure nothing was corrupted by building it,
|
||||
// then lets both the copy and the original destruct via normal scope exit
|
||||
template<class BasicJsonType>
|
||||
void check_destroy_edge_case(const BasicJsonType& value)
|
||||
{
|
||||
const BasicJsonType copy = value; // NOLINT(performance-unnecessary-copy-initialization): the copy is the point
|
||||
CHECK(copy == value);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE_TEMPLATE("regression test #5135 - destroy() edge cases", BasicJsonType, json, ordered_json)
|
||||
{
|
||||
using binary_t = typename BasicJsonType::binary_t;
|
||||
|
||||
SECTION("mix of empty objects, empty arrays, non-empty containers, and scalars")
|
||||
{
|
||||
BasicJsonType root = BasicJsonType::array();
|
||||
root.push_back(BasicJsonType::object());
|
||||
root.push_back(BasicJsonType::array());
|
||||
root.push_back(BasicJsonType::object({{"k", 1}}));
|
||||
root.push_back(BasicJsonType::array({1, 2, 3}));
|
||||
root.push_back(nullptr);
|
||||
root.push_back(true);
|
||||
root.push_back(42);
|
||||
root.push_back(3.14);
|
||||
root.push_back("a string");
|
||||
root.push_back(BasicJsonType(binary_t({1, 2, 3})));
|
||||
check_destroy_edge_case(root);
|
||||
}
|
||||
|
||||
SECTION("container child in first position only")
|
||||
{
|
||||
BasicJsonType root = BasicJsonType::array({BasicJsonType::array({1, 2}), 3, 4, 5});
|
||||
check_destroy_edge_case(root);
|
||||
}
|
||||
|
||||
SECTION("container child in last position only")
|
||||
{
|
||||
BasicJsonType root = BasicJsonType::array({1, 2, 3, BasicJsonType::array({4, 5})});
|
||||
check_destroy_edge_case(root);
|
||||
}
|
||||
|
||||
SECTION("container children in first and last position")
|
||||
{
|
||||
BasicJsonType root = BasicJsonType::array({BasicJsonType::array({1}), 2, 3, BasicJsonType::array({4})});
|
||||
check_destroy_edge_case(root);
|
||||
}
|
||||
|
||||
SECTION("single-element chain, 1000 levels deep")
|
||||
{
|
||||
auto root = make_single_chain<BasicJsonType>(1000);
|
||||
check_destroy_edge_case(root);
|
||||
}
|
||||
|
||||
SECTION("top-level empty array")
|
||||
{
|
||||
BasicJsonType root = BasicJsonType::array();
|
||||
check_destroy_edge_case(root);
|
||||
}
|
||||
|
||||
SECTION("top-level empty object")
|
||||
{
|
||||
BasicJsonType root = BasicJsonType::object();
|
||||
check_destroy_edge_case(root);
|
||||
}
|
||||
|
||||
SECTION("object whose last child is a non-empty array whose last child is an empty object")
|
||||
{
|
||||
BasicJsonType inner_array = BasicJsonType::array({1, 2, BasicJsonType::object()});
|
||||
BasicJsonType root = BasicJsonType::object({{"a", 1}, {"b", inner_array}});
|
||||
check_destroy_edge_case(root);
|
||||
}
|
||||
|
||||
SECTION("destruction via erase() on a deeply nested child")
|
||||
{
|
||||
BasicJsonType root = BasicJsonType::array();
|
||||
root.push_back(make_single_chain<BasicJsonType>(500));
|
||||
root.push_back(BasicJsonType::object({{"k", BasicJsonType::array({1, 2, 3})}}));
|
||||
// erase() must destroy the removed subtree without recursing or
|
||||
// allocating beyond what erase() itself needs
|
||||
root.erase(0);
|
||||
CAPTURE(root.size())
|
||||
CHECK(root.size() == 1);
|
||||
}
|
||||
|
||||
SECTION("destruction via assignment on a deep tree")
|
||||
{
|
||||
auto root = make_single_chain<BasicJsonType>(2000);
|
||||
// assigning a new value destroys the old one in place
|
||||
root = nullptr;
|
||||
CHECK(root.is_null());
|
||||
}
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
@@ -22,6 +22,14 @@
|
||||
// scoped enum, so get<std::byte>() (needed below to get<std::vector<std::byte>>()
|
||||
// from a plain JSON array, not just from an already-binary value) relies on
|
||||
// enum serialization being enabled
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#if defined(JSON_DISABLE_ENUM_SERIALIZATION) && (JSON_DISABLE_ENUM_SERIALIZATION == 1)
|
||||
#define SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||
#endif
|
||||
@@ -533,7 +541,7 @@ TEST_CASE("regression tests 3")
|
||||
}
|
||||
#endif
|
||||
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||
#if JSON_HAS_RANGE_VIEW_CONVERSION
|
||||
SECTION("issue #4916 - constructing array from C++20 ranges view does not work")
|
||||
{
|
||||
std::vector<int> nums{1, 2, 37, 42, 21};
|
||||
@@ -548,7 +556,7 @@ TEST_CASE("regression tests 3")
|
||||
#endif
|
||||
|
||||
// owning_view is not available in libstdc++ < 12
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__) && !(defined(__GLIBCXX__) && _GLIBCXX_RELEASE < 12)
|
||||
#if JSON_HAS_RANGE_VIEW_CONVERSION && !(defined(__GLIBCXX__) && _GLIBCXX_RELEASE < 12)
|
||||
SECTION("issue #4916 - constructing array from prvalue C++20 ranges view (owning_view)")
|
||||
{
|
||||
json const j(std::vector<int> {1, 2, 37, 42, 21} | std::views::filter([](int i)
|
||||
@@ -560,7 +568,7 @@ TEST_CASE("regression tests 3")
|
||||
}
|
||||
#endif
|
||||
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||
#if JSON_HAS_RANGE_VIEW_CONVERSION
|
||||
SECTION("issue #4916 - constructing array from C++20 transform view (prvalue elements)")
|
||||
{
|
||||
std::vector<int> nums{1, 2, 3};
|
||||
@@ -862,6 +870,50 @@ TEST_CASE("issue #5338 - truncated CBOR tagged binary subtype is rejected")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5676 - SAX parsing of CBOR tags")
|
||||
{
|
||||
const json expected = json::binary({1, 2, 3}, 42);
|
||||
const auto cbor = json::to_cbor(expected);
|
||||
|
||||
nlohmann::detail::json_sax_acceptor<json> acceptor;
|
||||
CHECK_FALSE(json::sax_parse(cbor, &acceptor, json::input_format_t::cbor));
|
||||
CHECK_FALSE(json::sax_parse(cbor, &acceptor, json::input_format_t::cbor,
|
||||
true, false, false, json::cbor_tag_handler_t::error));
|
||||
|
||||
CHECK(json::sax_parse(cbor, &acceptor, json::input_format_t::cbor,
|
||||
true, false, false, json::cbor_tag_handler_t::ignore));
|
||||
|
||||
json parsed;
|
||||
nlohmann::detail::json_sax_dom_parser<json, nlohmann::detail::string_input_adapter_type> sax(parsed);
|
||||
CHECK(json::sax_parse(cbor, &sax, json::input_format_t::cbor,
|
||||
true, false, false, json::cbor_tag_handler_t::store));
|
||||
CHECK(parsed == expected);
|
||||
|
||||
json iterator_parsed;
|
||||
nlohmann::detail::json_sax_dom_parser<json, nlohmann::detail::string_input_adapter_type> iterator_sax(iterator_parsed);
|
||||
CHECK(json::sax_parse(cbor.begin(), cbor.end(), &iterator_sax, json::input_format_t::cbor,
|
||||
true, false, false, json::cbor_tag_handler_t::store));
|
||||
CHECK(iterator_parsed == expected);
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
json span_parsed;
|
||||
nlohmann::detail::json_sax_dom_parser<json, nlohmann::detail::string_input_adapter_type> span_sax(span_parsed);
|
||||
CHECK(json::sax_parse(nlohmann::detail::span_input_adapter(cbor.data(), cbor.size()), &span_sax,
|
||||
json::input_format_t::cbor, true, false, false, json::cbor_tag_handler_t::store));
|
||||
CHECK(span_parsed == expected);
|
||||
#endif
|
||||
|
||||
const std::string text = "null";
|
||||
CHECK(json::sax_parse(text, &acceptor, json::input_format_t::json,
|
||||
true, false, false, json::cbor_tag_handler_t::store));
|
||||
CHECK(json::sax_parse(text.begin(), text.end(), &acceptor, json::input_format_t::json,
|
||||
true, false, false, json::cbor_tag_handler_t::store));
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
CHECK(json::sax_parse(nlohmann::detail::span_input_adapter(text.data(), text.size()), &acceptor,
|
||||
json::input_format_t::json, true, false, false, json::cbor_tag_handler_t::store));
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5402 - update(merge_objects=true) overwrites a primitive with an object")
|
||||
{
|
||||
json t = {{"k", 1}};
|
||||
@@ -920,4 +972,12 @@ TEST_CASE("regression test #5476 - array type without reserve()")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5317 - nested indefinite-length CBOR string chunks are rejected")
|
||||
{
|
||||
json _;
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<std::uint8_t>({0x7F, 0x7F, 0x61, 0x61, 0xFF, 0xFF})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: indefinite-length string is not allowed inside indefinite-length string; last byte: 0x7F", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<std::uint8_t>({0x5F, 0x5F, 0x41, 0x61, 0xFF, 0xFF})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR binary: indefinite-length binary array is not allowed inside indefinite-length binary array; last byte: 0x5F", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<std::uint8_t>({0xA1, 0x7F, 0x7F, 0xFF, 0xFF, 0x01})), "[json.exception.parse_error.113] parse error at byte 3: syntax error while parsing CBOR string: indefinite-length string is not allowed inside indefinite-length string; last byte: 0x7F", json::parse_error&);
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
@@ -8,6 +8,14 @@
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
@@ -48,6 +56,7 @@ TEST_CASE("serialization")
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
SECTION("operator>>")
|
||||
{
|
||||
SECTION("no given width")
|
||||
@@ -79,6 +88,7 @@ TEST_CASE("serialization")
|
||||
"[\n\t\"foo\",\n\t1,\n\t2,\n\t3,\n\tfalse,\n\t{\n\t\t\"one\": 1\n\t}\n]");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("dump")
|
||||
{
|
||||
@@ -92,6 +102,8 @@ TEST_CASE("serialization")
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::ignore) == "\"äü\"");
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::replace) == "\"ä\xEF\xBF\xBDü\"");
|
||||
CHECK(j.dump(-1, ' ', true, json::error_handler_t::replace) == "\"\\u00e4\\ufffd\\u00fc\"");
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::keep) == "\"ä\xA9ü\"");
|
||||
CHECK(j.dump(-1, ' ', true, json::error_handler_t::keep) == "\"\\u00e4\xA9\\u00fc\"");
|
||||
}
|
||||
|
||||
SECTION("invalid character (regression guard for shared UTF-8 decoder, see #5529)")
|
||||
@@ -114,6 +126,8 @@ TEST_CASE("serialization")
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::ignore) == "\"123\"");
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::replace) == "\"123\xEF\xBF\xBD\"");
|
||||
CHECK(j.dump(-1, ' ', true, json::error_handler_t::replace) == "\"123\\ufffd\"");
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::keep) == "\"123\xC2\"");
|
||||
CHECK(j.dump(-1, ' ', true, json::error_handler_t::keep) == "\"123\xC2\"");
|
||||
}
|
||||
|
||||
SECTION("unexpected character")
|
||||
@@ -126,6 +140,39 @@ TEST_CASE("serialization")
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::ignore) == "\"123456\"");
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::replace) == "\"123\xEF\xBF\xBD\x34\x35\x36\"");
|
||||
CHECK(j.dump(-1, ' ', true, json::error_handler_t::replace) == "\"123\\ufffd456\"");
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::keep) == "\"123\xF1\xB0\x34\x35\x36\"");
|
||||
CHECK(j.dump(-1, ' ', true, json::error_handler_t::keep) == "\"123\xF1\xB0\x34\x35\x36\"");
|
||||
}
|
||||
|
||||
SECTION("keep: valid characters are still escaped")
|
||||
{
|
||||
// an invalid byte followed by characters that must be escaped
|
||||
const json j = "\xC2\"\\\n\xFF\x05";
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::keep) == "\"\xC2\\\"\\\\\\n\xFF\\u0005\"");
|
||||
CHECK(j.dump(-1, ' ', true, json::error_handler_t::keep) == "\"\xC2\\\"\\\\\\n\xFF\\u0005\"");
|
||||
}
|
||||
|
||||
SECTION("keep: truncated multibyte sequences")
|
||||
{
|
||||
CHECK(json("\xF0\x9F\x98").dump(-1, ' ', false, json::error_handler_t::keep) == "\"\xF0\x9F\x98\"");
|
||||
CHECK(json("\xF0\x9F\x98").dump(-1, ' ', true, json::error_handler_t::keep) == "\"\xF0\x9F\x98\"");
|
||||
CHECK(json("\xF0\x9F\x98" "a").dump(-1, ' ', false, json::error_handler_t::keep) == "\"\xF0\x9F\x98" "a\"");
|
||||
CHECK(json("\xF0\x9F\x98" "a").dump(-1, ' ', true, json::error_handler_t::keep) == "\"\xF0\x9F\x98" "a\"");
|
||||
}
|
||||
|
||||
SECTION("keep: long string with many invalid bytes")
|
||||
{
|
||||
// exceeds the internal string buffer several times
|
||||
std::string input;
|
||||
std::string expected = "\"";
|
||||
for (int i = 0; i < 2000; ++i)
|
||||
{
|
||||
input += "\xFF\xE2\x82\n\xC3\xA4";
|
||||
expected += "\xFF\xE2\x82\\n\xC3\xA4";
|
||||
}
|
||||
expected += "\"";
|
||||
const json j = input;
|
||||
CHECK(j.dump(-1, ' ', false, json::error_handler_t::keep) == expected);
|
||||
}
|
||||
|
||||
SECTION("U+FFFD Substitution of Maximal Subparts")
|
||||
@@ -799,3 +846,185 @@ TEST_CASE("serializer buffers are flushed mid-string and mid-binary")
|
||||
CHECK(j.dump(2) == "{\n \"bytes\": [" + expected_pretty_bytes + "],\n \"subtype\": null\n}");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("serialization boundary values for the write buffer")
|
||||
{
|
||||
// write_buffer is a std::array<char, 1024> (write_buffer_size). put_string()
|
||||
// guards it with two checks, and each must be exercised exactly on and one
|
||||
// past its own boundary: a heap overflow in a different manual buffer path
|
||||
// (the dump(1100) indent buffer) once survived 100% line coverage because
|
||||
// every test that touched it only ever grew the buffer by a single step,
|
||||
// never landing on the exact edge of the comparison that protects it.
|
||||
//
|
||||
// - straight-through: put_string() bypasses write_buffer entirely and
|
||||
// writes directly to the output adapter once `length >= write_buffer.size()`.
|
||||
// - flush-then-copy: otherwise, if `write_buffer_pos + length > write_buffer.size()`,
|
||||
// put_string() flushes what is pending and then memcpy's the new run into
|
||||
// the freshly emptied buffer.
|
||||
|
||||
SECTION("top-level string exercises the straight-through guard (length >= 1024)")
|
||||
{
|
||||
// dump() of a bare string writes the opening quote with put_char()
|
||||
// (write_buffer_pos: 0 -> 1), then the body with put_string(). With
|
||||
// write_buffer_pos == 1, `1 + length > 1024` and `length >= 1024` flip
|
||||
// together at length 1024, so 1023/1024/1025 cover "just under",
|
||||
// "exactly at" and "just over" the guard in one move: 1023 is copied
|
||||
// into the buffer (filling it exactly), 1024 and 1025 bypass it.
|
||||
for (const std::size_t len :
|
||||
{
|
||||
std::size_t{1023}, std::size_t{1024}, std::size_t{1025}
|
||||
})
|
||||
{
|
||||
CAPTURE(len)
|
||||
const std::string body(len, 'a');
|
||||
const json j = body;
|
||||
const std::string expected = '"' + body + '"';
|
||||
|
||||
CHECK(j.dump() == expected);
|
||||
|
||||
std::ostringstream o;
|
||||
o << j;
|
||||
CHECK(o.str() == expected);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("string nested in an array exercises the flush-then-copy guard")
|
||||
{
|
||||
// json::array({body}) writes '[' then '"' before the body, so
|
||||
// write_buffer_pos == 2 when put_string() is entered for it. The
|
||||
// body's last byte then lands at logical offset 2 + len: len == 1022
|
||||
// lands exactly on offset 1024 (2 + 1022 == write_buffer.size(), so the
|
||||
// strict "> " guard does not fire and the body fits snugly), while
|
||||
// len == 1023 lands one past it at offset 1025 (2 + 1023 > 1024),
|
||||
// which must flush what's pending before copying the body in.
|
||||
for (const std::size_t len :
|
||||
{
|
||||
std::size_t{1022}, std::size_t{1023}
|
||||
})
|
||||
{
|
||||
CAPTURE(len)
|
||||
const std::string body(len, 'a');
|
||||
const json j = json::array({body});
|
||||
const std::string expected = "[\"" + body + "\"]";
|
||||
|
||||
CHECK(j.dump() == expected);
|
||||
|
||||
std::ostringstream o;
|
||||
o << j;
|
||||
CHECK(o.str() == expected);
|
||||
|
||||
CHECK(json::parse(j.dump()) == j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("serialization boundary values for the string buffer")
|
||||
{
|
||||
// string_buffer is a std::array<char, 512>. dump_escaped_impl() flushes it
|
||||
// mid-string once fewer than 13 bytes remain (`string_buffer.size() - bytes
|
||||
// < 13`), 13 being one more than the most a single code point can ever
|
||||
// write at once (a surrogate pair: two back-to-back "\uXXXX" escapes, 12
|
||||
// bytes). Every write into string_buffer that this check protects happens
|
||||
// in steps of 2 (a simple "\\x" escape) or 6 (one "\uXXXX" unit), so
|
||||
// `bytes` only ever takes even values at the point the check runs - the
|
||||
// tightest values actually reachable are therefore 498 (512 - 498 == 14,
|
||||
// one simple escape away from the threshold) and 500 (512 - 500 == 12,
|
||||
// where the flush fires immediately and resets bytes to 0).
|
||||
|
||||
SECTION("a run of 2-byte escapes lands bytes on, and one step past, the flush threshold")
|
||||
{
|
||||
for (const int count :
|
||||
{
|
||||
249, 250, 251
|
||||
})
|
||||
{
|
||||
CAPTURE(count)
|
||||
const json j = std::string(static_cast<std::size_t>(count), '\n');
|
||||
std::string expected = "\"";
|
||||
for (int i = 0; i < count; ++i)
|
||||
{
|
||||
expected += "\\n";
|
||||
}
|
||||
expected += '"';
|
||||
CHECK(j.dump() == expected);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("an ASCII prefix leaves the tightest reachable margin before a 12-byte surrogate pair")
|
||||
{
|
||||
// U+1F600 (the "\xF0\x9F\x98\x80" UTF-8 bytes) is dumped under
|
||||
// ensure_ascii as the 12-byte surrogate pair "\ud83d\ude00"; that
|
||||
// write happens in a single step with no intermediate flush check, so
|
||||
// it is the write most exposed by an off-by-one in the "< 13" guard.
|
||||
// A prefix of 249 newlines leaves exactly 14 bytes of headroom
|
||||
// (512 - 498), the smallest margin the guard ever actually allows
|
||||
// into a new code point; 250 newlines instead trigger the guard's own
|
||||
// flush first, so the emoji starts from a freshly emptied (512-byte)
|
||||
// buffer, and 251 repeats that with one more escape already past the
|
||||
// reset. Together they cover the margin the guard allows landing on,
|
||||
// one step before, and one step after - all must still produce the
|
||||
// identical, correct escapes.
|
||||
for (const int prefix_count :
|
||||
{
|
||||
249, 250, 251
|
||||
})
|
||||
{
|
||||
CAPTURE(prefix_count)
|
||||
const std::string prefix(static_cast<std::size_t>(prefix_count), '\n');
|
||||
const std::string emoji = "\xF0\x9F\x98\x80";
|
||||
const json j = prefix + emoji;
|
||||
|
||||
std::string expected_prefix;
|
||||
for (int i = 0; i < prefix_count; ++i)
|
||||
{
|
||||
expected_prefix += "\\n";
|
||||
}
|
||||
|
||||
// newline escaping does not depend on ensure_ascii: only the
|
||||
// emoji differs (raw UTF-8 bytes vs. a \u-escaped surrogate pair)
|
||||
std::string expected_raw = "\"";
|
||||
expected_raw += expected_prefix;
|
||||
expected_raw += emoji;
|
||||
expected_raw += '"';
|
||||
std::string expected_ascii = "\"";
|
||||
expected_ascii += expected_prefix;
|
||||
expected_ascii += R"(\ud83d\ude00")";
|
||||
CHECK(j.dump(-1, ' ', false) == expected_raw);
|
||||
CHECK(j.dump(-1, ' ', true) == expected_ascii);
|
||||
CHECK(json::parse(j.dump(-1, ' ', true)) == j);
|
||||
CHECK(json::parse(j.dump(-1, ' ', false)) == j);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("SWAR bulk-copy stride: k plain bytes followed by a byte handled individually")
|
||||
{
|
||||
// string_bulk_run()/find_ascii_copyable_run() (string_scan.hpp) scan 8
|
||||
// bytes at a time and fall back to a byte-at-a-time tail scan for
|
||||
// what is left over. k from 0 to 17 spans zero, one and two full
|
||||
// 8-byte strides plus a 1-byte tail, so every possible stopping point
|
||||
// within and right after the SIMD stride is covered.
|
||||
for (std::size_t k = 0; k <= 17; ++k)
|
||||
{
|
||||
CAPTURE(k)
|
||||
const std::string prefix(k, 'a');
|
||||
|
||||
// (a) the run is stopped by a quote that must itself be escaped
|
||||
{
|
||||
const json j = prefix + "\"";
|
||||
CHECK(j.dump() == '"' + prefix + "\\\"" + '"');
|
||||
}
|
||||
|
||||
// (b) the run is stopped by a control character
|
||||
{
|
||||
const json j = prefix + "\x01";
|
||||
CHECK(j.dump() == '"' + prefix + "\\u0001" + '"');
|
||||
}
|
||||
|
||||
// (c) the run is stopped by a non-ASCII byte under ensure_ascii
|
||||
{
|
||||
const json j = prefix + "\xC3\xA9"; // prefix + 'é'
|
||||
CHECK(j.dump(-1, ' ', true) == '"' + prefix + "\\u00e9" + '"');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+137
-5
@@ -8,6 +8,14 @@
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// capture whether JSON_DELETE_DEPRECATED_FUNCTIONS was enabled on the command
|
||||
// line *before* including json.hpp, since the library #undefs it once the header
|
||||
// has been fully processed (see include/nlohmann/detail/macro_unscope.hpp); the
|
||||
// tests of deprecated functions are skipped if these functions are deleted
|
||||
#if defined(JSON_DELETE_DEPRECATED_FUNCTIONS) && (JSON_DELETE_DEPRECATED_FUNCTIONS == 1)
|
||||
#define JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
#endif
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
@@ -27,10 +35,59 @@ TEST_CASE("UBJSON")
|
||||
{
|
||||
SECTION("discarded")
|
||||
{
|
||||
// discarded values are not serialized
|
||||
// a discarded value cannot be serialized to UBJSON
|
||||
json const j = json::value_t::discarded;
|
||||
const auto result = json::to_ubjson(j);
|
||||
CHECK(result.empty());
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j), "[json.exception.type_error.321] cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
}
|
||||
|
||||
SECTION("discarded values nested in a container")
|
||||
{
|
||||
json const discarded = json::value_t::discarded;
|
||||
|
||||
SECTION("in an array")
|
||||
{
|
||||
json const j = {1, discarded, 2};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j), "[json.exception.type_error.321] (/1) cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j), "[json.exception.type_error.321] cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("as an object value")
|
||||
{
|
||||
json j;
|
||||
j["a"] = 1;
|
||||
j["b"] = discarded;
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j), "[json.exception.type_error.321] (/b) cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j), "[json.exception.type_error.321] cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("nested deeper (array in object in array)")
|
||||
{
|
||||
json inner_array = {1, discarded};
|
||||
json middle_object;
|
||||
middle_object["x"] = inner_array;
|
||||
json const j = {middle_object};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j), "[json.exception.type_error.321] (/0/x/1) cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j), "[json.exception.type_error.321] cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("optimized array of all-discarded elements")
|
||||
{
|
||||
json const j = {discarded, discarded};
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j, true, true), "[json.exception.type_error.321] (/0) cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j, true, true), "[json.exception.type_error.321] cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("null")
|
||||
@@ -745,6 +802,32 @@ TEST_CASE("UBJSON")
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_ubjson(vec2), "[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A", json::parse_error);
|
||||
std::vector<uint8_t> const vec3 = {'H', 'i', 2, '1', '.'};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_ubjson(vec3), "[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1.", json::parse_error);
|
||||
// Reject NULs where they are read, including trailing NULs and payloads cut off after one.
|
||||
SECTION("NUL in high-precision number (issue #5753)")
|
||||
{
|
||||
for (const auto& vec : std::vector<std::vector<uint8_t>>
|
||||
{
|
||||
{'H', 'i', 3, '1', 0, 'x'},
|
||||
{'H', 'i', 2, '1', 0},
|
||||
{'H', 'i', 3, '1', 0}
|
||||
})
|
||||
{
|
||||
CAPTURE(vec)
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_ubjson(vec), "[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text; last byte: 0x00", json::parse_error);
|
||||
CHECK(json::from_ubjson(vec, true, false).is_discarded());
|
||||
CHECK(json::from_ubjson(vec, false, false).is_discarded());
|
||||
}
|
||||
|
||||
std::vector<uint8_t> const nested = {'[', 'H', 'i', 3, '1', 0, 'x', ']'};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_ubjson(nested), "[json.exception.parse_error.115] parse error at byte 6: syntax error while parsing UBJSON high-precision number: invalid number text; last byte: 0x00", json::parse_error);
|
||||
CHECK(json::from_ubjson(nested, true, false).is_discarded());
|
||||
|
||||
std::vector<uint8_t> const valid = {'H', 'i', 1, '1'};
|
||||
const auto j = json::from_ubjson(valid);
|
||||
CHECK(j.is_number_unsigned());
|
||||
CHECK(j == json(1));
|
||||
}
|
||||
|
||||
std::vector<uint8_t> const vec_overflow = {'H', 'i', 5, '1', 'e', '4', '0', '0'};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_ubjson(vec_overflow), "[json.exception.out_of_range.406] number overflow parsing '1e400'", json::out_of_range&);
|
||||
std::vector<uint8_t> const vec4 = {'H', 2, '1', '0'};
|
||||
@@ -2091,9 +2174,14 @@ TEST_CASE("UBJSON")
|
||||
|
||||
SECTION("discarded")
|
||||
{
|
||||
// a discarded value cannot be serialized to UBJSON, even as part
|
||||
// of an optimized array of a single (here: valueless) type
|
||||
json const j = {json::value_t::discarded, json::value_t::discarded};
|
||||
std::vector<uint8_t> expected = {'[', '$', 'N', '#', 'i', 2};
|
||||
CHECK(json::to_ubjson(j, true, true) == expected);
|
||||
#if JSON_DIAGNOSTICS
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j, true, true), "[json.exception.type_error.321] (/0) cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#else
|
||||
CHECK_THROWS_WITH_AS(json::to_ubjson(j, true, true), "[json.exception.type_error.321] cannot serialize discarded value to UBJSON", json::type_error&);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2212,8 +2300,10 @@ TEST_CASE("UBJSON input that cannot be read is discarded by every overload")
|
||||
CHECK_THROWS_AS(_ = json::from_ubjson(input.begin(), input.end()), json::parse_error&);
|
||||
CHECK(json::from_ubjson(input, true, false).is_discarded());
|
||||
CHECK(json::from_ubjson(input.begin(), input.end(), true, false).is_discarded());
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
CHECK(json::from_ubjson(input.data(), input.size(), true, false).is_discarded());
|
||||
CHECK(json::from_ubjson({input.data(), input.size()}, true, false).is_discarded());
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_CASE("UBJSON SAX parsing stops at every event")
|
||||
@@ -2961,12 +3051,14 @@ TEST_CASE("UBJSON roundtrips" * doctest::skip())
|
||||
CHECK(j1 == j2);
|
||||
}
|
||||
|
||||
#ifndef JSON_TEST_DEPRECATED_FUNCTIONS_DELETED
|
||||
{
|
||||
INFO_WITH_TEMP(filename + ": uint8_t* and size");
|
||||
json j2;
|
||||
CHECK_NOTHROW(j2 = json::from_ubjson({packed.data(), packed.size()}));
|
||||
CHECK(j1 == j2);
|
||||
}
|
||||
#endif
|
||||
|
||||
{
|
||||
INFO_WITH_TEMP(filename + ": output to output adapters");
|
||||
@@ -3216,3 +3308,43 @@ TEST_CASE("UBJSON and BJData integer markers at every range edge")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("UBJSON large strings (chunked reader)")
|
||||
{
|
||||
// get_ubjson_string() reads through get_string(), which reads in bounded
|
||||
// chunks (binary_reader.hpp, chunk_size == 4096); make sure roundtripping
|
||||
// is correct for lengths around and beyond that chunk size, for both
|
||||
// vector (iterator) and pointer inputs.
|
||||
//
|
||||
// A binary value is not included here: plain UBJSON (unlike BJData, see
|
||||
// the "BJData large strings and binaries" test) has no reader-side binary
|
||||
// type, so even the optimized uint8_t-array encoding of a binary value is
|
||||
// read back element-by-element as a JSON array of numbers rather than
|
||||
// through get_binary() - it never reaches the chunked path this test is
|
||||
// about (see the "roundtrip only works to an array of numbers" case
|
||||
// above).
|
||||
for (const std::size_t len :
|
||||
{
|
||||
std::size_t{0}, std::size_t{1}, std::size_t{4095}, std::size_t{4096},
|
||||
std::size_t{4097}, std::size_t{8192}, std::size_t{100000}
|
||||
})
|
||||
{
|
||||
CAPTURE(len)
|
||||
|
||||
const json j_string = std::string(len, 'x');
|
||||
const std::vector<std::uint8_t> v_string = json::to_ubjson(j_string);
|
||||
CHECK(json::from_ubjson(v_string) == j_string);
|
||||
// pointer input exercises the std::memcpy fast path
|
||||
CHECK(json::from_ubjson(reinterpret_cast<const char*>(v_string.data()),
|
||||
reinterpret_cast<const char*>(v_string.data()) + v_string.size()) == j_string);
|
||||
|
||||
// a truncated payload must still be reported as an error
|
||||
if (len > 16)
|
||||
{
|
||||
std::vector<std::uint8_t> truncated = v_string;
|
||||
truncated.resize(truncated.size() - 8);
|
||||
json _;
|
||||
CHECK_THROWS_AS(_ = json::from_ubjson(truncated), json::parse_error);
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
-3
@@ -23,6 +23,7 @@ using nlohmann::json;
|
||||
using namespace nlohmann::literals; // NOLINT(google-build-using-namespace)
|
||||
#endif
|
||||
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
@@ -684,8 +685,7 @@ static std::ostream& operator<<(std::ostream& os, small_pod l)
|
||||
TEST_CASE("custom serializer for pods" * doctest::test_suite("udt"))
|
||||
{
|
||||
using custom_json =
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator, pod_serializer>;
|
||||
nlohmann::json::with_json_serializer_t<pod_serializer>;
|
||||
|
||||
auto p = udt::small_pod{42, '/', 42};
|
||||
custom_json const j = p;
|
||||
@@ -703,7 +703,7 @@ TEST_CASE("custom serializer for pods" * doctest::test_suite("udt"))
|
||||
template <typename T, typename>
|
||||
struct another_adl_serializer;
|
||||
|
||||
using custom_json = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, double, std::allocator, another_adl_serializer>;
|
||||
using custom_json = nlohmann::json::with_json_serializer_t<another_adl_serializer>;
|
||||
|
||||
template <typename T, typename>
|
||||
struct another_adl_serializer
|
||||
@@ -734,6 +734,80 @@ TEST_CASE("custom serializer that does adl by default" * doctest::test_suite("ud
|
||||
CHECK(me == cj.get<udt::person>());
|
||||
}
|
||||
|
||||
TEST_CASE("with_*_t aliases" * doctest::test_suite("udt"))
|
||||
{
|
||||
// a custom base class used to check with_base_class_t
|
||||
struct custom_base_class {};
|
||||
|
||||
CHECK(std::is_same<json::with_object_t<std::deque>,
|
||||
nlohmann::basic_json<std::deque, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_array_t<std::deque>,
|
||||
nlohmann::basic_json<std::map, std::deque, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_string_t<std::wstring>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::wstring, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_boolean_t<int>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, int,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_integers_t<std::int32_t, std::uint32_t>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
std::int32_t, std::uint32_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_float_t<float>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, float, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_allocator_t<std::allocator>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_json_serializer_t<nlohmann::adl_serializer>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_binary_t<std::vector<char>>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<char>>>::value);
|
||||
|
||||
CHECK(std::is_same<json::with_base_class_t<custom_base_class>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>, custom_base_class>>::value);
|
||||
|
||||
// with_string_t on ordered_json must keep ordered_map as the object type
|
||||
CHECK(std::is_same<nlohmann::ordered_json::with_string_t<std::wstring>,
|
||||
nlohmann::basic_json<nlohmann::ordered_map, std::vector, std::wstring, bool,
|
||||
std::int64_t, std::uint64_t, double, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
|
||||
// the aliases are members of the resulting type, so they can be chained
|
||||
CHECK(std::is_same<json::with_integers_t<int, unsigned int>::with_float_t<float>,
|
||||
nlohmann::basic_json<std::map, std::vector, std::string, bool,
|
||||
int, unsigned int, float, std::allocator,
|
||||
nlohmann::adl_serializer, std::vector<std::uint8_t>>>::value);
|
||||
CHECK(std::is_same<json::with_float_t<float>::with_integers_t<int, unsigned int>,
|
||||
json::with_integers_t<int, unsigned int>::with_float_t<float>>::value);
|
||||
|
||||
// replacing the object type of json with ordered_map yields ordered_json
|
||||
CHECK(std::is_same<json::with_object_t<nlohmann::ordered_map>, nlohmann::ordered_json>::value);
|
||||
CHECK(std::is_same<nlohmann::ordered_json::with_object_t<std::map>, json>::value);
|
||||
}
|
||||
|
||||
TEST_CASE("different basic_json types conversions")
|
||||
{
|
||||
SECTION("null")
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,623 +0,0 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// for some reason including this after the json header leads to linker errors with VS 2017...
|
||||
#include <locale>
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include "make_test_data_available.hpp"
|
||||
#include "test_utils.hpp"
|
||||
|
||||
TEST_CASE("Unicode (1/5)" * doctest::skip())
|
||||
{
|
||||
SECTION("\\uxxxx sequences")
|
||||
{
|
||||
// create an escaped string from a code point
|
||||
const auto codepoint_to_unicode = [](std::size_t cp)
|
||||
{
|
||||
// code points are represented as a six-character sequence: a
|
||||
// reverse solidus, followed by the lowercase letter u, followed
|
||||
// by four hexadecimal digits that encode the character's code
|
||||
// point
|
||||
std::stringstream ss;
|
||||
ss << "\\u" << std::setw(4) << std::setfill('0') << std::hex << cp;
|
||||
return ss.str();
|
||||
};
|
||||
|
||||
SECTION("correct sequences")
|
||||
{
|
||||
// generate all UTF-8 code points; in total, 1112064 code points are
|
||||
// generated: 0x1FFFFF code points - 2048 invalid values between
|
||||
// 0xD800 and 0xDFFF.
|
||||
for (std::size_t cp = 0; cp <= 0x10FFFFu; ++cp)
|
||||
{
|
||||
// string to store the code point as in \uxxxx format
|
||||
std::string json_text = "\"";
|
||||
|
||||
// decide whether to use one or two \uxxxx sequences
|
||||
if (cp < 0x10000u)
|
||||
{
|
||||
// The Unicode standard permanently reserves these code point
|
||||
// values for UTF-16 encoding of the high and low surrogates, and
|
||||
// they will never be assigned a character, so there should be no
|
||||
// reason to encode them. The official Unicode standard says that
|
||||
// no UTF forms, including UTF-16, can encode these code points.
|
||||
if (cp >= 0xD800u && cp <= 0xDFFFu)
|
||||
{
|
||||
// if we would not skip these code points, we would get a
|
||||
// "missing low surrogate" exception
|
||||
continue;
|
||||
}
|
||||
|
||||
// code points in the Basic Multilingual Plane can be
|
||||
// represented with one \uxxxx sequence
|
||||
json_text += codepoint_to_unicode(cp);
|
||||
}
|
||||
else
|
||||
{
|
||||
// To escape an extended character that is not in the Basic
|
||||
// Multilingual Plane, the character is represented as a
|
||||
// 12-character sequence, encoding the UTF-16 surrogate pair
|
||||
const auto codepoint1 = 0xd800u + (((cp - 0x10000u) >> 10) & 0x3ffu);
|
||||
const auto codepoint2 = 0xdc00u + ((cp - 0x10000u) & 0x3ffu);
|
||||
json_text += codepoint_to_unicode(codepoint1) + codepoint_to_unicode(codepoint2);
|
||||
}
|
||||
|
||||
json_text += "\"";
|
||||
CAPTURE(json_text)
|
||||
json _;
|
||||
CHECK_NOTHROW(_ = json::parse(json_text));
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("incorrect sequences")
|
||||
{
|
||||
SECTION("incorrect surrogate values")
|
||||
{
|
||||
json _;
|
||||
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uDC00\\uDC00\""), "[json.exception.parse_error.101] parse error at line 1, column 7: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '\"\\uDC00'", json::parse_error&);
|
||||
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD7FF\\uDC00\""), "[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '\"\\uD7FF\\uDC00'", json::parse_error&);
|
||||
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800]\""), "[json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF; last read: '\"\\uD800]'", json::parse_error&);
|
||||
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800\\v\""), "[json.exception.parse_error.101] parse error at line 1, column 9: syntax error while parsing value - invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF; last read: '\"\\uD800\\v'", json::parse_error&);
|
||||
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800\\u123\""), "[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: '\\u' must be followed by 4 hex digits; last read: '\"\\uD800\\u123\"'", json::parse_error&);
|
||||
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800\\uDBFF\""), "[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF; last read: '\"\\uD800\\uDBFF'", json::parse_error&);
|
||||
|
||||
CHECK_THROWS_WITH_AS(_ = json::parse("\"\\uD800\\uE000\""), "[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF; last read: '\"\\uD800\\uE000'", json::parse_error&);
|
||||
}
|
||||
}
|
||||
|
||||
#if 0 // NOLINT(readability-avoid-unconditional-preprocessor-if)
|
||||
SECTION("incorrect sequences")
|
||||
{
|
||||
SECTION("high surrogate without low surrogate")
|
||||
{
|
||||
// D800..DBFF are high surrogates and must be followed by low
|
||||
// surrogates DC00..DFFF; here, nothing follows
|
||||
for (std::size_t cp = 0xD800u; cp <= 0xDBFFu; ++cp)
|
||||
{
|
||||
std::string json_text = "\"" + codepoint_to_unicode(cp) + "\"";
|
||||
CAPTURE(json_text)
|
||||
CHECK_THROWS_AS(json::parse(json_text), json::parse_error&);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("high surrogate with wrong low surrogate")
|
||||
{
|
||||
// D800..DBFF are high surrogates and must be followed by low
|
||||
// surrogates DC00..DFFF; here a different sequence follows
|
||||
for (std::size_t cp1 = 0xD800u; cp1 <= 0xDBFFu; ++cp1)
|
||||
{
|
||||
for (std::size_t cp2 = 0x0000u; cp2 <= 0xFFFFu; ++cp2)
|
||||
{
|
||||
if (0xDC00u <= cp2 && cp2 <= 0xDFFFu)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
std::string json_text = "\"" + codepoint_to_unicode(cp1) + codepoint_to_unicode(cp2) + "\"";
|
||||
CAPTURE(json_text)
|
||||
CHECK_THROWS_AS(json::parse(json_text), json::parse_error&);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("low surrogate without high surrogate")
|
||||
{
|
||||
// low surrogates DC00..DFFF must follow high surrogates; here,
|
||||
// they occur alone
|
||||
for (std::size_t cp = 0xDC00u; cp <= 0xDFFFu; ++cp)
|
||||
{
|
||||
std::string json_text = "\"" + codepoint_to_unicode(cp) + "\"";
|
||||
CAPTURE(json_text)
|
||||
CHECK_THROWS_AS(json::parse(json_text), json::parse_error&);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
SECTION("read all unicode characters")
|
||||
{
|
||||
// read a file with all Unicode characters stored as single-character
|
||||
// strings in a JSON array
|
||||
std::ifstream f(TEST_DATA_DIRECTORY "/json_nlohmann_tests/all_unicode.json");
|
||||
json j;
|
||||
CHECK_NOTHROW(f >> j);
|
||||
|
||||
// the array has 1112064 + 1 elements (a terminating "null" value)
|
||||
// Note: 1112064 = 0x1FFFFF code points - 2048 invalid values between
|
||||
// 0xD800 and 0xDFFF.
|
||||
CHECK(j.size() == 1112065);
|
||||
|
||||
SECTION("check JSON Pointers")
|
||||
{
|
||||
for (const auto& s : j)
|
||||
{
|
||||
// skip non-string JSON values
|
||||
if (!s.is_string())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
auto ptr = s.get<std::string>();
|
||||
|
||||
// tilde must be followed by 0 or 1
|
||||
if (ptr == "~")
|
||||
{
|
||||
ptr += "0";
|
||||
}
|
||||
|
||||
// JSON Pointers must begin with "/"
|
||||
ptr.insert(0, "/");
|
||||
|
||||
CHECK_NOTHROW(json::json_pointer("/" + ptr));
|
||||
|
||||
// check escape/unescape roundtrip
|
||||
auto escaped = nlohmann::detail::escape(ptr);
|
||||
nlohmann::detail::unescape(escaped);
|
||||
CHECK(escaped == ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ignore byte-order-mark")
|
||||
{
|
||||
SECTION("in a stream")
|
||||
{
|
||||
// read a file with a UTF-8 BOM
|
||||
std::ifstream f(TEST_DATA_DIRECTORY "/json_nlohmann_tests/bom.json");
|
||||
json j;
|
||||
CHECK_NOTHROW(f >> j);
|
||||
}
|
||||
|
||||
SECTION("with an iterator")
|
||||
{
|
||||
std::string i = "\xef\xbb\xbf{\n \"foo\": true\n}";
|
||||
json _;
|
||||
CHECK_NOTHROW(_ = json::parse(i.begin(), i.end()));
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("error for incomplete/wrong BOM")
|
||||
{
|
||||
json _;
|
||||
CHECK_THROWS_AS(_ = json::parse("\xef\xbb"), json::parse_error&);
|
||||
CHECK_THROWS_AS(_ = json::parse("\xef\xbb\xbb"), json::parse_error&);
|
||||
}
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
void roundtrip(bool success_expected, const std::string& s);
|
||||
|
||||
void roundtrip(bool success_expected, const std::string& s)
|
||||
{
|
||||
CAPTURE(s)
|
||||
json _;
|
||||
|
||||
// create JSON string value
|
||||
const json j = s;
|
||||
// create JSON text
|
||||
const std::string ps = std::string("\"") + s + "\"";
|
||||
|
||||
if (success_expected)
|
||||
{
|
||||
// serialization succeeds
|
||||
// dump() is nodiscard; this only checks that dumping does not throw
|
||||
CHECK_NOTHROW(utils::ignore_return_value(j.dump()));
|
||||
|
||||
// exclude parse test for U+0000
|
||||
if (s[0] != '\0')
|
||||
{
|
||||
// parsing JSON text succeeds
|
||||
CHECK_NOTHROW(_ = json::parse(ps));
|
||||
}
|
||||
|
||||
// roundtrip succeeds
|
||||
CHECK_NOTHROW(_ = json::parse(j.dump()));
|
||||
|
||||
// after roundtrip, the same string is stored
|
||||
const json jr = json::parse(j.dump());
|
||||
CHECK(jr.get<std::string>() == s);
|
||||
}
|
||||
else
|
||||
{
|
||||
// serialization fails
|
||||
// dump() is nodiscard; the exception is thrown by dump() itself before it would return
|
||||
CHECK_THROWS_AS(utils::ignore_return_value(j.dump()), json::type_error&);
|
||||
|
||||
// parsing JSON text fails
|
||||
CHECK_THROWS_AS(_ = json::parse(ps), json::parse_error&);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Markus Kuhn's UTF-8 decoder capability and stress test")
|
||||
{
|
||||
// Markus Kuhn <http://www.cl.cam.ac.uk/~mgk25/> - 2015-08-28 - CC BY 4.0
|
||||
// http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
|
||||
|
||||
SECTION("1 Some correct UTF-8 text")
|
||||
{
|
||||
roundtrip(true, "κόσμε");
|
||||
}
|
||||
|
||||
SECTION("2 Boundary condition test cases")
|
||||
{
|
||||
SECTION("2.1 First possible sequence of a certain length")
|
||||
{
|
||||
// 2.1.1 1 byte (U-00000000)
|
||||
roundtrip(true, std::string("\0", 1));
|
||||
// 2.1.2 2 bytes (U-00000080)
|
||||
roundtrip(true, "\xc2\x80");
|
||||
// 2.1.3 3 bytes (U-00000800)
|
||||
roundtrip(true, "\xe0\xa0\x80");
|
||||
// 2.1.4 4 bytes (U-00010000)
|
||||
roundtrip(true, "\xf0\x90\x80\x80");
|
||||
|
||||
// 2.1.5 5 bytes (U-00200000)
|
||||
roundtrip(false, "\xF8\x88\x80\x80\x80");
|
||||
// 2.1.6 6 bytes (U-04000000)
|
||||
roundtrip(false, "\xFC\x84\x80\x80\x80\x80");
|
||||
}
|
||||
|
||||
SECTION("2.2 Last possible sequence of a certain length")
|
||||
{
|
||||
// 2.2.1 1 byte (U-0000007F)
|
||||
roundtrip(true, "\x7f");
|
||||
// 2.2.2 2 bytes (U-000007FF)
|
||||
roundtrip(true, "\xdf\xbf");
|
||||
// 2.2.3 3 bytes (U-0000FFFF)
|
||||
roundtrip(true, "\xef\xbf\xbf");
|
||||
|
||||
// 2.2.4 4 bytes (U-001FFFFF)
|
||||
roundtrip(false, "\xF7\xBF\xBF\xBF");
|
||||
// 2.2.5 5 bytes (U-03FFFFFF)
|
||||
roundtrip(false, "\xFB\xBF\xBF\xBF\xBF");
|
||||
// 2.2.6 6 bytes (U-7FFFFFFF)
|
||||
roundtrip(false, "\xFD\xBF\xBF\xBF\xBF\xBF");
|
||||
}
|
||||
|
||||
SECTION("2.3 Other boundary conditions")
|
||||
{
|
||||
// 2.3.1 U-0000D7FF = ed 9f bf
|
||||
roundtrip(true, "\xed\x9f\xbf");
|
||||
// 2.3.2 U-0000E000 = ee 80 80
|
||||
roundtrip(true, "\xee\x80\x80");
|
||||
// 2.3.3 U-0000FFFD = ef bf bd
|
||||
roundtrip(true, "\xef\xbf\xbd");
|
||||
// 2.3.4 U-0010FFFF = f4 8f bf bf
|
||||
roundtrip(true, "\xf4\x8f\xbf\xbf");
|
||||
|
||||
// 2.3.5 U-00110000 = f4 90 80 80
|
||||
roundtrip(false, "\xf4\x90\x80\x80");
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("3 Malformed sequences")
|
||||
{
|
||||
SECTION("3.1 Unexpected continuation bytes")
|
||||
{
|
||||
// Each unexpected continuation byte should be separately signalled as a
|
||||
// malformed sequence of its own.
|
||||
|
||||
// 3.1.1 First continuation byte 0x80
|
||||
roundtrip(false, "\x80");
|
||||
// 3.1.2 Last continuation byte 0xbf
|
||||
roundtrip(false, "\xbf");
|
||||
|
||||
// 3.1.3 2 continuation bytes
|
||||
roundtrip(false, "\x80\xbf");
|
||||
// 3.1.4 3 continuation bytes
|
||||
roundtrip(false, "\x80\xbf\x80");
|
||||
// 3.1.5 4 continuation bytes
|
||||
roundtrip(false, "\x80\xbf\x80\xbf");
|
||||
// 3.1.6 5 continuation bytes
|
||||
roundtrip(false, "\x80\xbf\x80\xbf\x80");
|
||||
// 3.1.7 6 continuation bytes
|
||||
roundtrip(false, "\x80\xbf\x80\xbf\x80\xbf");
|
||||
// 3.1.8 7 continuation bytes
|
||||
roundtrip(false, "\x80\xbf\x80\xbf\x80\xbf\x80");
|
||||
|
||||
// 3.1.9 Sequence of all 64 possible continuation bytes (0x80-0xbf)
|
||||
roundtrip(false, "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf");
|
||||
}
|
||||
|
||||
SECTION("3.2 Lonely start characters")
|
||||
{
|
||||
// 3.2.1 All 32 first bytes of 2-byte sequences (0xc0-0xdf)
|
||||
roundtrip(false, "\xc0 \xc1 \xc2 \xc3 \xc4 \xc5 \xc6 \xc7 \xc8 \xc9 \xca \xcb \xcc \xcd \xce \xcf \xd0 \xd1 \xd2 \xd3 \xd4 \xd5 \xd6 \xd7 \xd8 \xd9 \xda \xdb \xdc \xdd \xde \xdf");
|
||||
// 3.2.2 All 16 first bytes of 3-byte sequences (0xe0-0xef)
|
||||
roundtrip(false, "\xe0 \xe1 \xe2 \xe3 \xe4 \xe5 \xe6 \xe7 \xe8 \xe9 \xea \xeb \xec \xed \xee \xef");
|
||||
// 3.2.3 All 8 first bytes of 4-byte sequences (0xf0-0xf7)
|
||||
roundtrip(false, "\xf0 \xf1 \xf2 \xf3 \xf4 \xf5 \xf6 \xf7");
|
||||
// 3.2.4 All 4 first bytes of 5-byte sequences (0xf8-0xfb)
|
||||
roundtrip(false, "\xf8 \xf9 \xfa \xfb");
|
||||
// 3.2.5 All 2 first bytes of 6-byte sequences (0xfc-0xfd)
|
||||
roundtrip(false, "\xfc \xfd");
|
||||
}
|
||||
|
||||
SECTION("3.3 Sequences with last continuation byte missing")
|
||||
{
|
||||
// All bytes of an incomplete sequence should be signalled as a single
|
||||
// malformed sequence, i.e., you should see only a single replacement
|
||||
// character in each of the next 10 tests. (Characters as in section 2)
|
||||
|
||||
// 3.3.1 2-byte sequence with last byte missing (U+0000)
|
||||
roundtrip(false, "\xc0");
|
||||
// 3.3.2 3-byte sequence with last byte missing (U+0000)
|
||||
roundtrip(false, "\xe0\x80");
|
||||
// 3.3.3 4-byte sequence with last byte missing (U+0000)
|
||||
roundtrip(false, "\xf0\x80\x80");
|
||||
// 3.3.4 5-byte sequence with last byte missing (U+0000)
|
||||
roundtrip(false, "\xf8\x80\x80\x80");
|
||||
// 3.3.5 6-byte sequence with last byte missing (U+0000)
|
||||
roundtrip(false, "\xfc\x80\x80\x80\x80");
|
||||
// 3.3.6 2-byte sequence with last byte missing (U-000007FF)
|
||||
roundtrip(false, "\xdf");
|
||||
// 3.3.7 3-byte sequence with last byte missing (U-0000FFFF)
|
||||
roundtrip(false, "\xef\xbf");
|
||||
// 3.3.8 4-byte sequence with last byte missing (U-001FFFFF)
|
||||
roundtrip(false, "\xf7\xbf\xbf");
|
||||
// 3.3.9 5-byte sequence with last byte missing (U-03FFFFFF)
|
||||
roundtrip(false, "\xfb\xbf\xbf\xbf");
|
||||
// 3.3.10 6-byte sequence with last byte missing (U-7FFFFFFF)
|
||||
roundtrip(false, "\xfd\xbf\xbf\xbf\xbf");
|
||||
}
|
||||
|
||||
SECTION("3.4 Concatenation of incomplete sequences")
|
||||
{
|
||||
// All the 10 sequences of 3.3 concatenated, you should see 10 malformed
|
||||
// sequences being signalled:
|
||||
roundtrip(false, "\xc0\xe0\x80\xf0\x80\x80\xf8\x80\x80\x80\xfc\x80\x80\x80\x80\xdf\xef\xbf\xf7\xbf\xbf\xfb\xbf\xbf\xbf\xfd\xbf\xbf\xbf\xbf");
|
||||
}
|
||||
|
||||
SECTION("3.5 Impossible bytes")
|
||||
{
|
||||
// The following two bytes cannot appear in a correct UTF-8 string
|
||||
|
||||
// 3.5.1 fe
|
||||
roundtrip(false, "\xfe");
|
||||
// 3.5.2 ff
|
||||
roundtrip(false, "\xff");
|
||||
// 3.5.3 fe fe ff ff
|
||||
roundtrip(false, "\xfe\xfe\xff\xff");
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("4 Overlong sequences")
|
||||
{
|
||||
// The following sequences are not malformed according to the letter of
|
||||
// the Unicode 2.0 standard. However, they are longer then necessary and
|
||||
// a correct UTF-8 encoder is not allowed to produce them. A "safe UTF-8
|
||||
// decoder" should reject them just like malformed sequences for two
|
||||
// reasons: (1) It helps to debug applications if overlong sequences are
|
||||
// not treated as valid representations of characters, because this helps
|
||||
// to spot problems more quickly. (2) Overlong sequences provide
|
||||
// alternative representations of characters, that could maliciously be
|
||||
// used to bypass filters that check only for ASCII characters. For
|
||||
// instance, a 2-byte encoded line feed (LF) would not be caught by a
|
||||
// line counter that counts only 0x0a bytes, but it would still be
|
||||
// processed as a line feed by an unsafe UTF-8 decoder later in the
|
||||
// pipeline. From a security point of view, ASCII compatibility of UTF-8
|
||||
// sequences means also, that ASCII characters are *only* allowed to be
|
||||
// represented by ASCII bytes in the range 0x00-0x7f. To ensure this
|
||||
// aspect of ASCII compatibility, use only "safe UTF-8 decoders" that
|
||||
// reject overlong UTF-8 sequences for which a shorter encoding exists.
|
||||
|
||||
SECTION("4.1 Examples of an overlong ASCII character")
|
||||
{
|
||||
// With a safe UTF-8 decoder, all the following five overlong
|
||||
// representations of the ASCII character slash ("/") should be rejected
|
||||
// like a malformed UTF-8 sequence, for instance by substituting it with
|
||||
// a replacement character. If you see a slash below, you do not have a
|
||||
// safe UTF-8 decoder!
|
||||
|
||||
// 4.1.1 U+002F = c0 af
|
||||
roundtrip(false, "\xc0\xaf");
|
||||
// 4.1.2 U+002F = e0 80 af
|
||||
roundtrip(false, "\xe0\x80\xaf");
|
||||
// 4.1.3 U+002F = f0 80 80 af
|
||||
roundtrip(false, "\xf0\x80\x80\xaf");
|
||||
// 4.1.4 U+002F = f8 80 80 80 af
|
||||
roundtrip(false, "\xf8\x80\x80\x80\xaf");
|
||||
// 4.1.5 U+002F = fc 80 80 80 80 af
|
||||
roundtrip(false, "\xfc\x80\x80\x80\x80\xaf");
|
||||
}
|
||||
|
||||
SECTION("4.2 Maximum overlong sequences")
|
||||
{
|
||||
// Below you see the highest Unicode value that is still resulting in an
|
||||
// overlong sequence if represented with the given number of bytes. This
|
||||
// is a boundary test for safe UTF-8 decoders. All five characters should
|
||||
// be rejected like malformed UTF-8 sequences.
|
||||
|
||||
// 4.2.1 U-0000007F = c1 bf
|
||||
roundtrip(false, "\xc1\xbf");
|
||||
// 4.2.2 U-000007FF = e0 9f bf
|
||||
roundtrip(false, "\xe0\x9f\xbf");
|
||||
// 4.2.3 U-0000FFFF = f0 8f bf bf
|
||||
roundtrip(false, "\xf0\x8f\xbf\xbf");
|
||||
// 4.2.4 U-001FFFFF = f8 87 bf bf bf
|
||||
roundtrip(false, "\xf8\x87\xbf\xbf\xbf");
|
||||
// 4.2.5 U-03FFFFFF = fc 83 bf bf bf bf
|
||||
roundtrip(false, "\xfc\x83\xbf\xbf\xbf\xbf");
|
||||
}
|
||||
|
||||
SECTION("4.3 Overlong representation of the NUL character")
|
||||
{
|
||||
// The following five sequences should also be rejected like malformed
|
||||
// UTF-8 sequences and should not be treated like the ASCII NUL
|
||||
// character.
|
||||
|
||||
// 4.3.1 U+0000 = c0 80
|
||||
roundtrip(false, "\xc0\x80");
|
||||
// 4.3.2 U+0000 = e0 80 80
|
||||
roundtrip(false, "\xe0\x80\x80");
|
||||
// 4.3.3 U+0000 = f0 80 80 80
|
||||
roundtrip(false, "\xf0\x80\x80\x80");
|
||||
// 4.3.4 U+0000 = f8 80 80 80 80
|
||||
roundtrip(false, "\xf8\x80\x80\x80\x80");
|
||||
// 4.3.5 U+0000 = fc 80 80 80 80 80
|
||||
roundtrip(false, "\xfc\x80\x80\x80\x80\x80");
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("5 Illegal code positions")
|
||||
{
|
||||
// The following UTF-8 sequences should be rejected like malformed
|
||||
// sequences, because they never represent valid ISO 10646 characters and
|
||||
// a UTF-8 decoder that accepts them might introduce security problems
|
||||
// comparable to overlong UTF-8 sequences.
|
||||
|
||||
SECTION("5.1 Single UTF-16 surrogates")
|
||||
{
|
||||
// 5.1.1 U+D800 = ed a0 80
|
||||
roundtrip(false, "\xed\xa0\x80");
|
||||
// 5.1.2 U+DB7F = ed ad bf
|
||||
roundtrip(false, "\xed\xad\xbf");
|
||||
// 5.1.3 U+DB80 = ed ae 80
|
||||
roundtrip(false, "\xed\xae\x80");
|
||||
// 5.1.4 U+DBFF = ed af bf
|
||||
roundtrip(false, "\xed\xaf\xbf");
|
||||
// 5.1.5 U+DC00 = ed b0 80
|
||||
roundtrip(false, "\xed\xb0\x80");
|
||||
// 5.1.6 U+DF80 = ed be 80
|
||||
roundtrip(false, "\xed\xbe\x80");
|
||||
// 5.1.7 U+DFFF = ed bf bf
|
||||
roundtrip(false, "\xed\xbf\xbf");
|
||||
}
|
||||
|
||||
SECTION("5.2 Paired UTF-16 surrogates")
|
||||
{
|
||||
// 5.2.1 U+D800 U+DC00 = ed a0 80 ed b0 80
|
||||
roundtrip(false, "\xed\xa0\x80\xed\xb0\x80");
|
||||
// 5.2.2 U+D800 U+DFFF = ed a0 80 ed bf bf
|
||||
roundtrip(false, "\xed\xa0\x80\xed\xbf\xbf");
|
||||
// 5.2.3 U+DB7F U+DC00 = ed ad bf ed b0 80
|
||||
roundtrip(false, "\xed\xad\xbf\xed\xb0\x80");
|
||||
// 5.2.4 U+DB7F U+DFFF = ed ad bf ed bf bf
|
||||
roundtrip(false, "\xed\xad\xbf\xed\xbf\xbf");
|
||||
// 5.2.5 U+DB80 U+DC00 = ed ae 80 ed b0 80
|
||||
roundtrip(false, "\xed\xae\x80\xed\xb0\x80");
|
||||
// 5.2.6 U+DB80 U+DFFF = ed ae 80 ed bf bf
|
||||
roundtrip(false, "\xed\xae\x80\xed\xbf\xbf");
|
||||
// 5.2.7 U+DBFF U+DC00 = ed af bf ed b0 80
|
||||
roundtrip(false, "\xed\xaf\xbf\xed\xb0\x80");
|
||||
// 5.2.8 U+DBFF U+DFFF = ed af bf ed bf bf
|
||||
roundtrip(false, "\xed\xaf\xbf\xed\xbf\xbf");
|
||||
}
|
||||
|
||||
SECTION("5.3 Noncharacter code positions")
|
||||
{
|
||||
// The following "noncharacters" are "reserved for internal use" by
|
||||
// applications, and according to older versions of the Unicode Standard
|
||||
// "should never be interchanged". Unicode Corrigendum #9 dropped the
|
||||
// latter restriction. Nevertheless, their presence in incoming UTF-8 data
|
||||
// can remain a potential security risk, depending on what use is made of
|
||||
// these codes subsequently. Examples of such internal use:
|
||||
//
|
||||
// - Some file APIs with 16-bit characters may use the integer value -1
|
||||
// = U+FFFF to signal an end-of-file (EOF) or error condition.
|
||||
//
|
||||
// - In some UTF-16 receivers, code point U+FFFE might trigger a
|
||||
// byte-swap operation (to convert between UTF-16LE and UTF-16BE).
|
||||
//
|
||||
// With such internal use of noncharacters, it may be desirable and safer
|
||||
// to block those code points in UTF-8 decoders, as they should never
|
||||
// occur legitimately in incoming UTF-8 data, and could trigger unsafe
|
||||
// behaviour in subsequent processing.
|
||||
|
||||
// Particularly problematic noncharacters in 16-bit applications:
|
||||
|
||||
// 5.3.1 U+FFFE = ef bf be
|
||||
roundtrip(true, "\xef\xbf\xbe");
|
||||
// 5.3.2 U+FFFF = ef bf bf
|
||||
roundtrip(true, "\xef\xbf\xbf");
|
||||
|
||||
// 5.3.3 U+FDD0 .. U+FDEF
|
||||
roundtrip(true, "\xEF\xB7\x90");
|
||||
roundtrip(true, "\xEF\xB7\x91");
|
||||
roundtrip(true, "\xEF\xB7\x92");
|
||||
roundtrip(true, "\xEF\xB7\x93");
|
||||
roundtrip(true, "\xEF\xB7\x94");
|
||||
roundtrip(true, "\xEF\xB7\x95");
|
||||
roundtrip(true, "\xEF\xB7\x96");
|
||||
roundtrip(true, "\xEF\xB7\x97");
|
||||
roundtrip(true, "\xEF\xB7\x98");
|
||||
roundtrip(true, "\xEF\xB7\x99");
|
||||
roundtrip(true, "\xEF\xB7\x9A");
|
||||
roundtrip(true, "\xEF\xB7\x9B");
|
||||
roundtrip(true, "\xEF\xB7\x9C");
|
||||
roundtrip(true, "\xEF\xB7\x9D");
|
||||
roundtrip(true, "\xEF\xB7\x9E");
|
||||
roundtrip(true, "\xEF\xB7\x9F");
|
||||
roundtrip(true, "\xEF\xB7\xA0");
|
||||
roundtrip(true, "\xEF\xB7\xA1");
|
||||
roundtrip(true, "\xEF\xB7\xA2");
|
||||
roundtrip(true, "\xEF\xB7\xA3");
|
||||
roundtrip(true, "\xEF\xB7\xA4");
|
||||
roundtrip(true, "\xEF\xB7\xA5");
|
||||
roundtrip(true, "\xEF\xB7\xA6");
|
||||
roundtrip(true, "\xEF\xB7\xA7");
|
||||
roundtrip(true, "\xEF\xB7\xA8");
|
||||
roundtrip(true, "\xEF\xB7\xA9");
|
||||
roundtrip(true, "\xEF\xB7\xAA");
|
||||
roundtrip(true, "\xEF\xB7\xAB");
|
||||
roundtrip(true, "\xEF\xB7\xAC");
|
||||
roundtrip(true, "\xEF\xB7\xAD");
|
||||
roundtrip(true, "\xEF\xB7\xAE");
|
||||
roundtrip(true, "\xEF\xB7\xAF");
|
||||
|
||||
// 5.3.4 U+nFFFE U+nFFFF (for n = 1..10)
|
||||
roundtrip(true, "\xF0\x9F\xBF\xBF");
|
||||
roundtrip(true, "\xF0\xAF\xBF\xBF");
|
||||
roundtrip(true, "\xF0\xBF\xBF\xBF");
|
||||
roundtrip(true, "\xF1\x8F\xBF\xBF");
|
||||
roundtrip(true, "\xF1\x9F\xBF\xBF");
|
||||
roundtrip(true, "\xF1\xAF\xBF\xBF");
|
||||
roundtrip(true, "\xF1\xBF\xBF\xBF");
|
||||
roundtrip(true, "\xF2\x8F\xBF\xBF");
|
||||
roundtrip(true, "\xF2\x9F\xBF\xBF");
|
||||
roundtrip(true, "\xF2\xAF\xBF\xBF");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,612 +0,0 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// for some reason including this after the json header leads to linker errors with VS 2017...
|
||||
#include <locale>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include "make_test_data_available.hpp"
|
||||
#include "test_utils.hpp"
|
||||
|
||||
// this test suite uses static variables with non-trivial destructors
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
|
||||
namespace
|
||||
{
|
||||
extern size_t calls;
|
||||
size_t calls = 0;
|
||||
|
||||
void check_utf8dump(bool success_expected, int byte1, int byte2, int byte3, int byte4);
|
||||
|
||||
void check_utf8dump(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1)
|
||||
{
|
||||
static std::string json_string;
|
||||
json_string.clear();
|
||||
|
||||
CAPTURE(byte1)
|
||||
CAPTURE(byte2)
|
||||
CAPTURE(byte3)
|
||||
CAPTURE(byte4)
|
||||
|
||||
json_string += std::string(1, static_cast<char>(byte1));
|
||||
|
||||
if (byte2 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte2));
|
||||
}
|
||||
|
||||
if (byte3 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte3));
|
||||
}
|
||||
|
||||
if (byte4 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte4));
|
||||
}
|
||||
|
||||
CAPTURE(json_string)
|
||||
|
||||
// store the string in a JSON value
|
||||
static json j;
|
||||
static json j2;
|
||||
j = json_string;
|
||||
j2 = "abc" + json_string + "xyz";
|
||||
|
||||
static std::string s_ignored;
|
||||
static std::string s_ignored2;
|
||||
static std::string s_ignored_ascii;
|
||||
static std::string s_ignored2_ascii;
|
||||
static std::string s_replaced;
|
||||
static std::string s_replaced2;
|
||||
static std::string s_replaced_ascii;
|
||||
static std::string s_replaced2_ascii;
|
||||
|
||||
// dumping with ignore/replace must not throw in any case
|
||||
s_ignored = j.dump(-1, ' ', false, json::error_handler_t::ignore);
|
||||
s_ignored2 = j2.dump(-1, ' ', false, json::error_handler_t::ignore);
|
||||
s_ignored_ascii = j.dump(-1, ' ', true, json::error_handler_t::ignore);
|
||||
s_ignored2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::ignore);
|
||||
s_replaced = j.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
s_replaced2 = j2.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
s_replaced_ascii = j.dump(-1, ' ', true, json::error_handler_t::replace);
|
||||
s_replaced2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::replace);
|
||||
|
||||
if (success_expected)
|
||||
{
|
||||
static std::string s_strict;
|
||||
// strict mode must not throw if success is expected
|
||||
s_strict = j.dump();
|
||||
// all dumps should agree on the string
|
||||
CHECK(s_strict == s_ignored);
|
||||
CHECK(s_strict == s_replaced);
|
||||
}
|
||||
else
|
||||
{
|
||||
// strict mode must throw if success is not expected
|
||||
// dump() is nodiscard; the exception is thrown by dump() itself before it would return
|
||||
CHECK_THROWS_AS(utils::ignore_return_value(j.dump()), json::type_error&);
|
||||
// ignore and replace must create different dumps
|
||||
CHECK(s_ignored != s_replaced);
|
||||
|
||||
// check that replace string contains a replacement character
|
||||
CHECK(s_replaced.find("\xEF\xBF\xBD") != std::string::npos);
|
||||
}
|
||||
|
||||
// check that prefix and suffix are preserved
|
||||
CHECK(s_ignored2.substr(1, 3) == "abc");
|
||||
CHECK(s_ignored2.substr(s_ignored2.size() - 4, 3) == "xyz");
|
||||
CHECK(s_ignored2_ascii.substr(1, 3) == "abc");
|
||||
CHECK(s_ignored2_ascii.substr(s_ignored2_ascii.size() - 4, 3) == "xyz");
|
||||
CHECK(s_replaced2.substr(1, 3) == "abc");
|
||||
CHECK(s_replaced2.substr(s_replaced2.size() - 4, 3) == "xyz");
|
||||
CHECK(s_replaced2_ascii.substr(1, 3) == "abc");
|
||||
CHECK(s_replaced2_ascii.substr(s_replaced2_ascii.size() - 4, 3) == "xyz");
|
||||
}
|
||||
|
||||
void check_utf8string(bool success_expected, int byte1, int byte2, int byte3, int byte4);
|
||||
|
||||
// create and check a JSON string with up to four UTF-8 bytes
|
||||
void check_utf8string(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1)
|
||||
{
|
||||
if (++calls % 100000 == 0)
|
||||
{
|
||||
std::cout << calls << " of 455355 UTF-8 strings checked" << std::endl; // NOLINT(performance-avoid-endl)
|
||||
}
|
||||
|
||||
static std::string json_string;
|
||||
json_string = "\"";
|
||||
|
||||
CAPTURE(byte1)
|
||||
json_string += std::string(1, static_cast<char>(byte1));
|
||||
|
||||
if (byte2 != -1)
|
||||
{
|
||||
CAPTURE(byte2)
|
||||
json_string += std::string(1, static_cast<char>(byte2));
|
||||
}
|
||||
|
||||
if (byte3 != -1)
|
||||
{
|
||||
CAPTURE(byte3)
|
||||
json_string += std::string(1, static_cast<char>(byte3));
|
||||
}
|
||||
|
||||
if (byte4 != -1)
|
||||
{
|
||||
CAPTURE(byte4)
|
||||
json_string += std::string(1, static_cast<char>(byte4));
|
||||
}
|
||||
|
||||
json_string += "\"";
|
||||
|
||||
CAPTURE(json_string)
|
||||
|
||||
json _;
|
||||
if (success_expected)
|
||||
{
|
||||
CHECK_NOTHROW(_ = json::parse(json_string));
|
||||
}
|
||||
else
|
||||
{
|
||||
CHECK_THROWS_AS(_ = json::parse(json_string), json::parse_error&);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Unicode (2/5)" * doctest::skip())
|
||||
{
|
||||
SECTION("RFC 3629")
|
||||
{
|
||||
/*
|
||||
RFC 3629 describes in Sect. 4 the syntax of UTF-8 byte sequences as
|
||||
follows:
|
||||
|
||||
A UTF-8 string is a sequence of octets representing a sequence of UCS
|
||||
characters. An octet sequence is valid UTF-8 only if it matches the
|
||||
following syntax, which is derived from the rules for encoding UTF-8
|
||||
and is expressed in the ABNF of [RFC2234].
|
||||
|
||||
UTF8-octets = *( UTF8-char )
|
||||
UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
|
||||
UTF8-1 = %x00-7F
|
||||
UTF8-2 = %xC2-DF UTF8-tail
|
||||
UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
|
||||
%xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
|
||||
UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
|
||||
%xF4 %x80-8F 2( UTF8-tail )
|
||||
UTF8-tail = %x80-BF
|
||||
*/
|
||||
|
||||
SECTION("ill-formed first byte")
|
||||
{
|
||||
for (int byte1 = 0x80; byte1 <= 0xC1; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
|
||||
for (int byte1 = 0xF5; byte1 <= 0xFF; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("UTF8-1 (x00-x7F)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0x00; byte1 <= 0x7F; ++byte1)
|
||||
{
|
||||
// unescaped control characters are parse errors in JSON
|
||||
if (0x00 <= byte1 && byte1 <= 0x1F)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
continue;
|
||||
}
|
||||
|
||||
// a single quote is a parse error in JSON
|
||||
if (byte1 == 0x22)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
continue;
|
||||
}
|
||||
|
||||
// a single backslash is a parse error in JSON
|
||||
if (byte1 == 0x5C)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
continue;
|
||||
}
|
||||
|
||||
// all other characters are OK
|
||||
check_utf8string(true, byte1);
|
||||
check_utf8dump(true, byte1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("UTF8-2 (xC2-xDF UTF8-tail)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0xC2; byte1 <= 0xDF; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
check_utf8string(true, byte1, byte2);
|
||||
check_utf8dump(true, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing second byte")
|
||||
{
|
||||
for (int byte1 = 0xC2; byte1 <= 0xDF; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong second byte")
|
||||
{
|
||||
for (int byte1 = 0xC2; byte1 <= 0xDF; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2)
|
||||
{
|
||||
// skip correct second byte
|
||||
if (0x80 <= byte2 && byte2 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
check_utf8string(false, byte1, byte2);
|
||||
check_utf8dump(false, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("UTF8-3 (xE0 xA0-BF UTF8-tail)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0xA0; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(true, byte1, byte2, byte3);
|
||||
check_utf8dump(true, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing second byte")
|
||||
{
|
||||
for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing third byte")
|
||||
{
|
||||
for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0xA0; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2);
|
||||
check_utf8dump(false, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong second byte")
|
||||
{
|
||||
for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2)
|
||||
{
|
||||
// skip correct second byte
|
||||
if (0xA0 <= byte2 && byte2 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong third byte")
|
||||
{
|
||||
for (int byte1 = 0xE0; byte1 <= 0xE0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0xA0; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3)
|
||||
{
|
||||
// skip correct third byte
|
||||
if (0x80 <= byte3 && byte3 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("UTF8-3 (xE1-xEC UTF8-tail UTF8-tail)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(true, byte1, byte2, byte3);
|
||||
check_utf8dump(true, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing second byte")
|
||||
{
|
||||
for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing third byte")
|
||||
{
|
||||
for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2);
|
||||
check_utf8dump(false, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong second byte")
|
||||
{
|
||||
for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2)
|
||||
{
|
||||
// skip correct second byte
|
||||
if (0x80 <= byte2 && byte2 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong third byte")
|
||||
{
|
||||
for (int byte1 = 0xE1; byte1 <= 0xEC; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3)
|
||||
{
|
||||
// skip correct third byte
|
||||
if (0x80 <= byte3 && byte3 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("UTF8-3 (xED x80-9F UTF8-tail)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0xED; byte1 <= 0xED; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0x9F; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(true, byte1, byte2, byte3);
|
||||
check_utf8dump(true, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing second byte")
|
||||
{
|
||||
for (int byte1 = 0xED; byte1 <= 0xED; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing third byte")
|
||||
{
|
||||
for (int byte1 = 0xED; byte1 <= 0xED; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0x9F; ++byte2)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2);
|
||||
check_utf8dump(false, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong second byte")
|
||||
{
|
||||
for (int byte1 = 0xED; byte1 <= 0xED; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2)
|
||||
{
|
||||
// skip correct second byte
|
||||
if (0x80 <= byte2 && byte2 <= 0x9F)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong third byte")
|
||||
{
|
||||
for (int byte1 = 0xED; byte1 <= 0xED; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0x9F; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3)
|
||||
{
|
||||
// skip correct third byte
|
||||
if (0x80 <= byte3 && byte3 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("UTF8-3 (xEE-xEF UTF8-tail UTF8-tail)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(true, byte1, byte2, byte3);
|
||||
check_utf8dump(true, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing second byte")
|
||||
{
|
||||
for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing third byte")
|
||||
{
|
||||
for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2);
|
||||
check_utf8dump(false, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong second byte")
|
||||
{
|
||||
for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2)
|
||||
{
|
||||
// skip correct second byte
|
||||
if (0x80 <= byte2 && byte2 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong third byte")
|
||||
{
|
||||
for (int byte1 = 0xEE; byte1 <= 0xEF; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3)
|
||||
{
|
||||
// skip correct third byte
|
||||
if (0x80 <= byte3 && byte3 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
@@ -1,326 +0,0 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// for some reason including this after the json header leads to linker errors with VS 2017...
|
||||
#include <locale>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include "make_test_data_available.hpp"
|
||||
#include "test_utils.hpp"
|
||||
|
||||
// this test suite uses static variables with non-trivial destructors
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
|
||||
namespace
|
||||
{
|
||||
extern size_t calls;
|
||||
size_t calls = 0;
|
||||
|
||||
void check_utf8dump(bool success_expected, int byte1, int byte2, int byte3, int byte4);
|
||||
|
||||
void check_utf8dump(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1)
|
||||
{
|
||||
static std::string json_string;
|
||||
json_string.clear();
|
||||
|
||||
CAPTURE(byte1)
|
||||
CAPTURE(byte2)
|
||||
CAPTURE(byte3)
|
||||
CAPTURE(byte4)
|
||||
|
||||
json_string += std::string(1, static_cast<char>(byte1));
|
||||
|
||||
if (byte2 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte2));
|
||||
}
|
||||
|
||||
if (byte3 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte3));
|
||||
}
|
||||
|
||||
if (byte4 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte4));
|
||||
}
|
||||
|
||||
CAPTURE(json_string)
|
||||
|
||||
// store the string in a JSON value
|
||||
static json j;
|
||||
static json j2;
|
||||
j = json_string;
|
||||
j2 = "abc" + json_string + "xyz";
|
||||
|
||||
static std::string s_ignored;
|
||||
static std::string s_ignored2;
|
||||
static std::string s_ignored_ascii;
|
||||
static std::string s_ignored2_ascii;
|
||||
static std::string s_replaced;
|
||||
static std::string s_replaced2;
|
||||
static std::string s_replaced_ascii;
|
||||
static std::string s_replaced2_ascii;
|
||||
|
||||
// dumping with ignore/replace must not throw in any case
|
||||
s_ignored = j.dump(-1, ' ', false, json::error_handler_t::ignore);
|
||||
s_ignored2 = j2.dump(-1, ' ', false, json::error_handler_t::ignore);
|
||||
s_ignored_ascii = j.dump(-1, ' ', true, json::error_handler_t::ignore);
|
||||
s_ignored2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::ignore);
|
||||
s_replaced = j.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
s_replaced2 = j2.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
s_replaced_ascii = j.dump(-1, ' ', true, json::error_handler_t::replace);
|
||||
s_replaced2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::replace);
|
||||
|
||||
if (success_expected)
|
||||
{
|
||||
static std::string s_strict;
|
||||
// strict mode must not throw if success is expected
|
||||
s_strict = j.dump();
|
||||
// all dumps should agree on the string
|
||||
CHECK(s_strict == s_ignored);
|
||||
CHECK(s_strict == s_replaced);
|
||||
}
|
||||
else
|
||||
{
|
||||
// strict mode must throw if success is not expected
|
||||
// dump() is nodiscard; the exception is thrown by dump() itself before it would return
|
||||
CHECK_THROWS_AS(utils::ignore_return_value(j.dump()), json::type_error&);
|
||||
// ignore and replace must create different dumps
|
||||
CHECK(s_ignored != s_replaced);
|
||||
|
||||
// check that replace string contains a replacement character
|
||||
CHECK(s_replaced.find("\xEF\xBF\xBD") != std::string::npos);
|
||||
}
|
||||
|
||||
// check that prefix and suffix are preserved
|
||||
CHECK(s_ignored2.substr(1, 3) == "abc");
|
||||
CHECK(s_ignored2.substr(s_ignored2.size() - 4, 3) == "xyz");
|
||||
CHECK(s_ignored2_ascii.substr(1, 3) == "abc");
|
||||
CHECK(s_ignored2_ascii.substr(s_ignored2_ascii.size() - 4, 3) == "xyz");
|
||||
CHECK(s_replaced2.substr(1, 3) == "abc");
|
||||
CHECK(s_replaced2.substr(s_replaced2.size() - 4, 3) == "xyz");
|
||||
CHECK(s_replaced2_ascii.substr(1, 3) == "abc");
|
||||
CHECK(s_replaced2_ascii.substr(s_replaced2_ascii.size() - 4, 3) == "xyz");
|
||||
}
|
||||
|
||||
void check_utf8string(bool success_expected, int byte1, int byte2, int byte3, int byte4);
|
||||
|
||||
// create and check a JSON string with up to four UTF-8 bytes
|
||||
void check_utf8string(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1)
|
||||
{
|
||||
if (++calls % 100000 == 0)
|
||||
{
|
||||
std::cout << calls << " of 1641521 UTF-8 strings checked" << std::endl; // NOLINT(performance-avoid-endl)
|
||||
}
|
||||
|
||||
static std::string json_string;
|
||||
json_string = "\"";
|
||||
|
||||
CAPTURE(byte1)
|
||||
json_string += std::string(1, static_cast<char>(byte1));
|
||||
|
||||
if (byte2 != -1)
|
||||
{
|
||||
CAPTURE(byte2)
|
||||
json_string += std::string(1, static_cast<char>(byte2));
|
||||
}
|
||||
|
||||
if (byte3 != -1)
|
||||
{
|
||||
CAPTURE(byte3)
|
||||
json_string += std::string(1, static_cast<char>(byte3));
|
||||
}
|
||||
|
||||
if (byte4 != -1)
|
||||
{
|
||||
CAPTURE(byte4)
|
||||
json_string += std::string(1, static_cast<char>(byte4));
|
||||
}
|
||||
|
||||
json_string += "\"";
|
||||
|
||||
CAPTURE(json_string)
|
||||
|
||||
json _;
|
||||
if (success_expected)
|
||||
{
|
||||
CHECK_NOTHROW(_ = json::parse(json_string));
|
||||
}
|
||||
else
|
||||
{
|
||||
CHECK_THROWS_AS(_ = json::parse(json_string), json::parse_error&);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Unicode (3/5)" * doctest::skip())
|
||||
{
|
||||
SECTION("RFC 3629")
|
||||
{
|
||||
/*
|
||||
RFC 3629 describes in Sect. 4 the syntax of UTF-8 byte sequences as
|
||||
follows:
|
||||
|
||||
A UTF-8 string is a sequence of octets representing a sequence of UCS
|
||||
characters. An octet sequence is valid UTF-8 only if it matches the
|
||||
following syntax, which is derived from the rules for encoding UTF-8
|
||||
and is expressed in the ABNF of [RFC2234].
|
||||
|
||||
UTF8-octets = *( UTF8-char )
|
||||
UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
|
||||
UTF8-1 = %x00-7F
|
||||
UTF8-2 = %xC2-DF UTF8-tail
|
||||
UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
|
||||
%xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
|
||||
UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
|
||||
%xF4 %x80-8F 2( UTF8-tail )
|
||||
UTF8-tail = %x80-BF
|
||||
*/
|
||||
|
||||
SECTION("UTF8-4 (xF0 x90-BF UTF8-tail UTF8-tail)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(true, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(true, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing second byte")
|
||||
{
|
||||
for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing third byte")
|
||||
{
|
||||
for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2);
|
||||
check_utf8dump(false, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing fourth byte")
|
||||
{
|
||||
for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong second byte")
|
||||
{
|
||||
for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2)
|
||||
{
|
||||
// skip correct second byte
|
||||
if (0x90 <= byte2 && byte2 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong third byte")
|
||||
{
|
||||
for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3)
|
||||
{
|
||||
// skip correct third byte
|
||||
if (0x80 <= byte3 && byte3 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong fourth byte")
|
||||
{
|
||||
for (int byte1 = 0xF0; byte1 <= 0xF0; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x90; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x00; byte4 <= 0xFF; ++byte4)
|
||||
{
|
||||
// skip correct fourth byte
|
||||
if (0x80 <= byte4 && byte4 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
@@ -1,326 +0,0 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// for some reason including this after the json header leads to linker errors with VS 2017...
|
||||
#include <locale>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include "make_test_data_available.hpp"
|
||||
#include "test_utils.hpp"
|
||||
|
||||
// this test suite uses static variables with non-trivial destructors
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
|
||||
namespace
|
||||
{
|
||||
extern size_t calls;
|
||||
size_t calls = 0;
|
||||
|
||||
void check_utf8dump(bool success_expected, int byte1, int byte2, int byte3, int byte4);
|
||||
|
||||
void check_utf8dump(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1)
|
||||
{
|
||||
static std::string json_string;
|
||||
json_string.clear();
|
||||
|
||||
CAPTURE(byte1)
|
||||
CAPTURE(byte2)
|
||||
CAPTURE(byte3)
|
||||
CAPTURE(byte4)
|
||||
|
||||
json_string += std::string(1, static_cast<char>(byte1));
|
||||
|
||||
if (byte2 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte2));
|
||||
}
|
||||
|
||||
if (byte3 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte3));
|
||||
}
|
||||
|
||||
if (byte4 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte4));
|
||||
}
|
||||
|
||||
CAPTURE(json_string)
|
||||
|
||||
// store the string in a JSON value
|
||||
static json j;
|
||||
static json j2;
|
||||
j = json_string;
|
||||
j2 = "abc" + json_string + "xyz";
|
||||
|
||||
static std::string s_ignored;
|
||||
static std::string s_ignored2;
|
||||
static std::string s_ignored_ascii;
|
||||
static std::string s_ignored2_ascii;
|
||||
static std::string s_replaced;
|
||||
static std::string s_replaced2;
|
||||
static std::string s_replaced_ascii;
|
||||
static std::string s_replaced2_ascii;
|
||||
|
||||
// dumping with ignore/replace must not throw in any case
|
||||
s_ignored = j.dump(-1, ' ', false, json::error_handler_t::ignore);
|
||||
s_ignored2 = j2.dump(-1, ' ', false, json::error_handler_t::ignore);
|
||||
s_ignored_ascii = j.dump(-1, ' ', true, json::error_handler_t::ignore);
|
||||
s_ignored2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::ignore);
|
||||
s_replaced = j.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
s_replaced2 = j2.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
s_replaced_ascii = j.dump(-1, ' ', true, json::error_handler_t::replace);
|
||||
s_replaced2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::replace);
|
||||
|
||||
if (success_expected)
|
||||
{
|
||||
static std::string s_strict;
|
||||
// strict mode must not throw if success is expected
|
||||
s_strict = j.dump();
|
||||
// all dumps should agree on the string
|
||||
CHECK(s_strict == s_ignored);
|
||||
CHECK(s_strict == s_replaced);
|
||||
}
|
||||
else
|
||||
{
|
||||
// strict mode must throw if success is not expected
|
||||
// dump() is nodiscard; the exception is thrown by dump() itself before it would return
|
||||
CHECK_THROWS_AS(utils::ignore_return_value(j.dump()), json::type_error&);
|
||||
// ignore and replace must create different dumps
|
||||
CHECK(s_ignored != s_replaced);
|
||||
|
||||
// check that replace string contains a replacement character
|
||||
CHECK(s_replaced.find("\xEF\xBF\xBD") != std::string::npos);
|
||||
}
|
||||
|
||||
// check that prefix and suffix are preserved
|
||||
CHECK(s_ignored2.substr(1, 3) == "abc");
|
||||
CHECK(s_ignored2.substr(s_ignored2.size() - 4, 3) == "xyz");
|
||||
CHECK(s_ignored2_ascii.substr(1, 3) == "abc");
|
||||
CHECK(s_ignored2_ascii.substr(s_ignored2_ascii.size() - 4, 3) == "xyz");
|
||||
CHECK(s_replaced2.substr(1, 3) == "abc");
|
||||
CHECK(s_replaced2.substr(s_replaced2.size() - 4, 3) == "xyz");
|
||||
CHECK(s_replaced2_ascii.substr(1, 3) == "abc");
|
||||
CHECK(s_replaced2_ascii.substr(s_replaced2_ascii.size() - 4, 3) == "xyz");
|
||||
}
|
||||
|
||||
void check_utf8string(bool success_expected, int byte1, int byte2, int byte3, int byte4);
|
||||
|
||||
// create and check a JSON string with up to four UTF-8 bytes
|
||||
void check_utf8string(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1)
|
||||
{
|
||||
if (++calls % 100000 == 0)
|
||||
{
|
||||
std::cout << calls << " of 5517507 UTF-8 strings checked" << std::endl; // NOLINT(performance-avoid-endl)
|
||||
}
|
||||
|
||||
static std::string json_string;
|
||||
json_string = "\"";
|
||||
|
||||
CAPTURE(byte1)
|
||||
json_string += std::string(1, static_cast<char>(byte1));
|
||||
|
||||
if (byte2 != -1)
|
||||
{
|
||||
CAPTURE(byte2)
|
||||
json_string += std::string(1, static_cast<char>(byte2));
|
||||
}
|
||||
|
||||
if (byte3 != -1)
|
||||
{
|
||||
CAPTURE(byte3)
|
||||
json_string += std::string(1, static_cast<char>(byte3));
|
||||
}
|
||||
|
||||
if (byte4 != -1)
|
||||
{
|
||||
CAPTURE(byte4)
|
||||
json_string += std::string(1, static_cast<char>(byte4));
|
||||
}
|
||||
|
||||
json_string += "\"";
|
||||
|
||||
CAPTURE(json_string)
|
||||
|
||||
json _;
|
||||
if (success_expected)
|
||||
{
|
||||
CHECK_NOTHROW(_ = json::parse(json_string));
|
||||
}
|
||||
else
|
||||
{
|
||||
CHECK_THROWS_AS(_ = json::parse(json_string), json::parse_error&);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Unicode (4/5)" * doctest::skip())
|
||||
{
|
||||
SECTION("RFC 3629")
|
||||
{
|
||||
/*
|
||||
RFC 3629 describes in Sect. 4 the syntax of UTF-8 byte sequences as
|
||||
follows:
|
||||
|
||||
A UTF-8 string is a sequence of octets representing a sequence of UCS
|
||||
characters. An octet sequence is valid UTF-8 only if it matches the
|
||||
following syntax, which is derived from the rules for encoding UTF-8
|
||||
and is expressed in the ABNF of [RFC2234].
|
||||
|
||||
UTF8-octets = *( UTF8-char )
|
||||
UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
|
||||
UTF8-1 = %x00-7F
|
||||
UTF8-2 = %xC2-DF UTF8-tail
|
||||
UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
|
||||
%xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
|
||||
UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
|
||||
%xF4 %x80-8F 2( UTF8-tail )
|
||||
UTF8-tail = %x80-BF
|
||||
*/
|
||||
|
||||
SECTION("UTF8-4 (xF1-F3 UTF8-tail UTF8-tail UTF8-tail)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(true, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(true, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing second byte")
|
||||
{
|
||||
for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing third byte")
|
||||
{
|
||||
for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2);
|
||||
check_utf8dump(false, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing fourth byte")
|
||||
{
|
||||
for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong second byte")
|
||||
{
|
||||
for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2)
|
||||
{
|
||||
// skip correct second byte
|
||||
if (0x80 <= byte2 && byte2 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong third byte")
|
||||
{
|
||||
for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3)
|
||||
{
|
||||
// skip correct third byte
|
||||
if (0x80 <= byte3 && byte3 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong fourth byte")
|
||||
{
|
||||
for (int byte1 = 0xF1; byte1 <= 0xF3; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0xBF; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x00; byte4 <= 0xFF; ++byte4)
|
||||
{
|
||||
// skip correct fourth byte
|
||||
if (0x80 <= byte4 && byte4 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
@@ -1,326 +0,0 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | 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
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// for some reason including this after the json header leads to linker errors with VS 2017...
|
||||
#include <locale>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using nlohmann::json;
|
||||
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include "make_test_data_available.hpp"
|
||||
#include "test_utils.hpp"
|
||||
|
||||
// this test suite uses static variables with non-trivial destructors
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
|
||||
namespace
|
||||
{
|
||||
extern size_t calls;
|
||||
size_t calls = 0;
|
||||
|
||||
void check_utf8dump(bool success_expected, int byte1, int byte2, int byte3, int byte4);
|
||||
|
||||
void check_utf8dump(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1)
|
||||
{
|
||||
static std::string json_string;
|
||||
json_string.clear();
|
||||
|
||||
CAPTURE(byte1)
|
||||
CAPTURE(byte2)
|
||||
CAPTURE(byte3)
|
||||
CAPTURE(byte4)
|
||||
|
||||
json_string += std::string(1, static_cast<char>(byte1));
|
||||
|
||||
if (byte2 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte2));
|
||||
}
|
||||
|
||||
if (byte3 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte3));
|
||||
}
|
||||
|
||||
if (byte4 != -1)
|
||||
{
|
||||
json_string += std::string(1, static_cast<char>(byte4));
|
||||
}
|
||||
|
||||
CAPTURE(json_string)
|
||||
|
||||
// store the string in a JSON value
|
||||
static json j;
|
||||
static json j2;
|
||||
j = json_string;
|
||||
j2 = "abc" + json_string + "xyz";
|
||||
|
||||
static std::string s_ignored;
|
||||
static std::string s_ignored2;
|
||||
static std::string s_ignored_ascii;
|
||||
static std::string s_ignored2_ascii;
|
||||
static std::string s_replaced;
|
||||
static std::string s_replaced2;
|
||||
static std::string s_replaced_ascii;
|
||||
static std::string s_replaced2_ascii;
|
||||
|
||||
// dumping with ignore/replace must not throw in any case
|
||||
s_ignored = j.dump(-1, ' ', false, json::error_handler_t::ignore);
|
||||
s_ignored2 = j2.dump(-1, ' ', false, json::error_handler_t::ignore);
|
||||
s_ignored_ascii = j.dump(-1, ' ', true, json::error_handler_t::ignore);
|
||||
s_ignored2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::ignore);
|
||||
s_replaced = j.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
s_replaced2 = j2.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
s_replaced_ascii = j.dump(-1, ' ', true, json::error_handler_t::replace);
|
||||
s_replaced2_ascii = j2.dump(-1, ' ', true, json::error_handler_t::replace);
|
||||
|
||||
if (success_expected)
|
||||
{
|
||||
static std::string s_strict;
|
||||
// strict mode must not throw if success is expected
|
||||
s_strict = j.dump();
|
||||
// all dumps should agree on the string
|
||||
CHECK(s_strict == s_ignored);
|
||||
CHECK(s_strict == s_replaced);
|
||||
}
|
||||
else
|
||||
{
|
||||
// strict mode must throw if success is not expected
|
||||
// dump() is nodiscard; the exception is thrown by dump() itself before it would return
|
||||
CHECK_THROWS_AS(utils::ignore_return_value(j.dump()), json::type_error&);
|
||||
// ignore and replace must create different dumps
|
||||
CHECK(s_ignored != s_replaced);
|
||||
|
||||
// check that replace string contains a replacement character
|
||||
CHECK(s_replaced.find("\xEF\xBF\xBD") != std::string::npos);
|
||||
}
|
||||
|
||||
// check that prefix and suffix are preserved
|
||||
CHECK(s_ignored2.substr(1, 3) == "abc");
|
||||
CHECK(s_ignored2.substr(s_ignored2.size() - 4, 3) == "xyz");
|
||||
CHECK(s_ignored2_ascii.substr(1, 3) == "abc");
|
||||
CHECK(s_ignored2_ascii.substr(s_ignored2_ascii.size() - 4, 3) == "xyz");
|
||||
CHECK(s_replaced2.substr(1, 3) == "abc");
|
||||
CHECK(s_replaced2.substr(s_replaced2.size() - 4, 3) == "xyz");
|
||||
CHECK(s_replaced2_ascii.substr(1, 3) == "abc");
|
||||
CHECK(s_replaced2_ascii.substr(s_replaced2_ascii.size() - 4, 3) == "xyz");
|
||||
}
|
||||
|
||||
void check_utf8string(bool success_expected, int byte1, int byte2, int byte3, int byte4);
|
||||
|
||||
// create and check a JSON string with up to four UTF-8 bytes
|
||||
void check_utf8string(bool success_expected, int byte1, int byte2 = -1, int byte3 = -1, int byte4 = -1)
|
||||
{
|
||||
if (++calls % 100000 == 0)
|
||||
{
|
||||
std::cout << calls << " of 1246225 UTF-8 strings checked" << std::endl; // NOLINT(performance-avoid-endl)
|
||||
}
|
||||
|
||||
static std::string json_string;
|
||||
json_string = "\"";
|
||||
|
||||
CAPTURE(byte1)
|
||||
json_string += std::string(1, static_cast<char>(byte1));
|
||||
|
||||
if (byte2 != -1)
|
||||
{
|
||||
CAPTURE(byte2)
|
||||
json_string += std::string(1, static_cast<char>(byte2));
|
||||
}
|
||||
|
||||
if (byte3 != -1)
|
||||
{
|
||||
CAPTURE(byte3)
|
||||
json_string += std::string(1, static_cast<char>(byte3));
|
||||
}
|
||||
|
||||
if (byte4 != -1)
|
||||
{
|
||||
CAPTURE(byte4)
|
||||
json_string += std::string(1, static_cast<char>(byte4));
|
||||
}
|
||||
|
||||
json_string += "\"";
|
||||
|
||||
CAPTURE(json_string)
|
||||
|
||||
json _;
|
||||
if (success_expected)
|
||||
{
|
||||
CHECK_NOTHROW(_ = json::parse(json_string));
|
||||
}
|
||||
else
|
||||
{
|
||||
CHECK_THROWS_AS(_ = json::parse(json_string), json::parse_error&);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Unicode (5/5)" * doctest::skip())
|
||||
{
|
||||
SECTION("RFC 3629")
|
||||
{
|
||||
/*
|
||||
RFC 3629 describes in Sect. 4 the syntax of UTF-8 byte sequences as
|
||||
follows:
|
||||
|
||||
A UTF-8 string is a sequence of octets representing a sequence of UCS
|
||||
characters. An octet sequence is valid UTF-8 only if it matches the
|
||||
following syntax, which is derived from the rules for encoding UTF-8
|
||||
and is expressed in the ABNF of [RFC2234].
|
||||
|
||||
UTF8-octets = *( UTF8-char )
|
||||
UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
|
||||
UTF8-1 = %x00-7F
|
||||
UTF8-2 = %xC2-DF UTF8-tail
|
||||
UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
|
||||
%xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
|
||||
UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
|
||||
%xF4 %x80-8F 2( UTF8-tail )
|
||||
UTF8-tail = %x80-BF
|
||||
*/
|
||||
|
||||
SECTION("UTF8-4 (xF4 x80-8F UTF8-tail UTF8-tail)")
|
||||
{
|
||||
SECTION("well-formed")
|
||||
{
|
||||
for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(true, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(true, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing second byte")
|
||||
{
|
||||
for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1)
|
||||
{
|
||||
check_utf8string(false, byte1);
|
||||
check_utf8dump(false, byte1);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing third byte")
|
||||
{
|
||||
for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2);
|
||||
check_utf8dump(false, byte1, byte2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: missing fourth byte")
|
||||
{
|
||||
for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3);
|
||||
check_utf8dump(false, byte1, byte2, byte3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong second byte")
|
||||
{
|
||||
for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x00; byte2 <= 0xFF; ++byte2)
|
||||
{
|
||||
// skip correct second byte
|
||||
if (0x80 <= byte2 && byte2 <= 0x8F)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong third byte")
|
||||
{
|
||||
for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x00; byte3 <= 0xFF; ++byte3)
|
||||
{
|
||||
// skip correct third byte
|
||||
if (0x80 <= byte3 && byte3 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int byte4 = 0x80; byte4 <= 0xBF; ++byte4)
|
||||
{
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ill-formed: wrong fourth byte")
|
||||
{
|
||||
for (int byte1 = 0xF4; byte1 <= 0xF4; ++byte1)
|
||||
{
|
||||
for (int byte2 = 0x80; byte2 <= 0x8F; ++byte2)
|
||||
{
|
||||
for (int byte3 = 0x80; byte3 <= 0xBF; ++byte3)
|
||||
{
|
||||
for (int byte4 = 0x00; byte4 <= 0xFF; ++byte4)
|
||||
{
|
||||
// skip correct fourth byte
|
||||
if (0x80 <= byte4 && byte4 <= 0xBF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
check_utf8string(false, byte1, byte2, byte3, byte4);
|
||||
check_utf8dump(false, byte1, byte2, byte3, byte4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
Reference in new issue
Block a user