mirror of
https://github.com/nlohmann/json.git
synced 2026-09-07 16:57:59 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf6c1f39d2 | ||
|
|
1cba195509 | ||
|
|
1df654d19d | ||
|
|
90bd0f7fec | ||
|
|
3d89ac50a0 | ||
|
|
ee69490b28 | ||
|
|
3970ecccd1 | ||
|
|
00e5d21041 | ||
|
|
755c547003 |
@@ -108,7 +108,9 @@ The tests are located in [`tests/src/unit-*.cpp`](https://github.com/nlohmann/js
|
||||
are structured along the features of the library or the nature of the tests. Usually, it should be clear from the
|
||||
context which existing file needs to be extended, and only very few cases require creating new test files.
|
||||
|
||||
When fixing a bug, edit `unit-regression2.cpp` and add a section referencing the fixed issue.
|
||||
When fixing a bug, edit `unit-regression3.cpp` and add a section referencing the fixed issue.
|
||||
`unit-regression2.cpp` holds the older tests; the two files exist because a single one grew large enough for the
|
||||
MinGW linker to fail relocating it, so please keep adding to the smaller file rather than growing one of them.
|
||||
|
||||
#### Exceptions
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ jobs:
|
||||
container: ubuntu:focal
|
||||
strategy:
|
||||
matrix:
|
||||
target: [ci_cmake_flags, ci_test_diagnostics, ci_test_diagnostic_positions, ci_test_noexceptions, ci_test_noimplicitconversions, ci_test_legacycomparison, ci_test_noglobaludls, ci_test_disableenumserialization, ci_test_skiplibraryversioncheck]
|
||||
target: [ci_cmake_flags, ci_test_diagnostics, ci_test_diagnostic_positions, ci_test_noexceptions, ci_test_noimplicitconversions, ci_test_legacycomparison, ci_test_noglobaludls]
|
||||
steps:
|
||||
- name: Install build-essential
|
||||
run: apt-get update ; apt-get install -y build-essential unzip wget git libssl-dev
|
||||
|
||||
@@ -242,40 +242,6 @@ add_custom_target(ci_test_noglobaludls
|
||||
COMMENT "Compile and test with global UDLs disabled"
|
||||
)
|
||||
|
||||
###############################################################################
|
||||
# Disable enum serialization.
|
||||
###############################################################################
|
||||
|
||||
add_custom_target(ci_test_disableenumserialization
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DCMAKE_BUILD_TYPE=Debug -GNinja
|
||||
-DJSON_BuildTests=ON -DJSON_FastTests=ON -DJSON_DisableEnumSerialization=ON
|
||||
-S${PROJECT_SOURCE_DIR} -B${PROJECT_BINARY_DIR}/build_disableenumserialization
|
||||
COMMAND ${CMAKE_COMMAND} --build ${PROJECT_BINARY_DIR}/build_disableenumserialization
|
||||
COMMAND cd ${PROJECT_BINARY_DIR}/build_disableenumserialization && ${CMAKE_CTEST_COMMAND} --parallel ${N} --output-on-failure
|
||||
COMMENT "Compile and test with enum serialization disabled"
|
||||
)
|
||||
|
||||
###############################################################################
|
||||
# Skip the multiple-inclusion library version check.
|
||||
###############################################################################
|
||||
|
||||
# tests/src/skip_library_version_check.cpp deliberately simulates a scenario
|
||||
# (mixing two differently-versioned inclusions of the library in one
|
||||
# translation unit) that unavoidably triggers the compiler's own "macro
|
||||
# redefined" warning, so -- unlike the ci_test_* targets above -- it is
|
||||
# compiled directly here, with a modest warning set, instead of being folded
|
||||
# into the library's own -Weverything/-Werror unit test matrix.
|
||||
add_custom_target(ci_test_skiplibraryversioncheck
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/skip_library_version_check
|
||||
COMMAND ${CMAKE_CXX_COMPILER} -std=c++11 -Wall -Wextra
|
||||
-I${PROJECT_SOURCE_DIR}/include
|
||||
${PROJECT_SOURCE_DIR}/tests/src/skip_library_version_check.cpp
|
||||
-o ${PROJECT_BINARY_DIR}/skip_library_version_check/skip_library_version_check
|
||||
COMMAND ${PROJECT_BINARY_DIR}/skip_library_version_check/skip_library_version_check
|
||||
COMMENT "Compile and run a translation unit simulating a mismatched library version, with JSON_SKIP_LIBRARY_VERSION_CHECK defined"
|
||||
)
|
||||
|
||||
###############################################################################
|
||||
# Coverage.
|
||||
###############################################################################
|
||||
|
||||
@@ -69,6 +69,12 @@ The library uses the following mapping from JSON values types to UBJSON types ac
|
||||
Note that `use_size = true` alone may result in larger representations - the benefit of this parameter is that the
|
||||
receiving side is immediately informed on the number of elements of the container.
|
||||
|
||||
An array whose type marker is `Z` (null), `T` (true) or `F` (false) stores no payload at all, because the marker
|
||||
already is the value. Its declared count is therefore the only thing that decides how much memory the receiving side
|
||||
allocates, and a handful of bytes can describe billions of elements. `from_ubjson` rejects such an array with
|
||||
[`out_of_range.408`](../../home/exceptions.md#jsonexceptionout_of_range408) when the count exceeds 1,048,576, and
|
||||
`to_ubjson` writes longer arrays of these types without the annotation, so any value it produces can be read back.
|
||||
|
||||
!!! info "Binary values"
|
||||
|
||||
If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the UBJSON
|
||||
|
||||
@@ -868,6 +868,12 @@ The size of an array or object in a [binary format](../features/binary_formats/i
|
||||
the size following `#` for [UBJSON](../features/binary_formats/ubjson.md)/[BJData](../features/binary_formats/bjdata.md),
|
||||
or the encoded length for [CBOR](../features/binary_formats/cbor.md).
|
||||
|
||||
The exception is also thrown for a [UBJSON](../features/binary_formats/ubjson.md) array of a type that is encoded by its
|
||||
marker alone (`Z`, `T` or `F`) whose declared count exceeds 1,048,576. Such an array has no payload, so its count alone
|
||||
decides how much memory is allocated, and a handful of bytes would otherwise describe billions of values.
|
||||
[`to_ubjson`](../api/basic_json/to_ubjson.md) writes longer arrays of these types without the size and type annotation,
|
||||
so any value it produces can still be read back.
|
||||
|
||||
!!! failure "Example messages"
|
||||
|
||||
```
|
||||
@@ -879,6 +885,9 @@ or the encoded length for [CBOR](../features/binary_formats/cbor.md).
|
||||
```
|
||||
[json.exception.out_of_range.408] syntax error while parsing CBOR size: excessive map size
|
||||
```
|
||||
```
|
||||
[json.exception.out_of_range.408] syntax error while parsing UBJSON size: excessive array size
|
||||
```
|
||||
|
||||
### json.exception.out_of_range.409
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -826,7 +826,17 @@ class binary_writer
|
||||
|
||||
std::vector<CharType> bjdx = {'[', '{', 'S', 'H', 'T', 'F', 'N', 'Z'}; // excluded markers in bjdata optimized type
|
||||
|
||||
if (same_prefix && !(use_bjdata && std::find(bjdx.begin(), bjdx.end(), first_prefix) != bjdx.end()))
|
||||
// an optimized array of a valueless type carries no payload, so a
|
||||
// reader has nothing but the declared count to bound the allocation
|
||||
// by and refuses an excessive one. Write the unoptimized form for
|
||||
// those, at one byte per element, so the result can be read back.
|
||||
// Objects are not affected: every element is preceded by its key.
|
||||
const bool valueless_type = (first_prefix == 'Z' || first_prefix == 'T' || first_prefix == 'F');
|
||||
const bool excessive_valueless = valueless_type
|
||||
&& j.m_data.m_value.array->size() > detail::max_valueless_container_size;
|
||||
|
||||
if (same_prefix && !excessive_valueless
|
||||
&& !(use_bjdata && std::find(bjdx.begin(), bjdx.end(), first_prefix) != bjdx.end()))
|
||||
{
|
||||
prefix_required = false;
|
||||
oa->write_character(to_char_type('$'));
|
||||
|
||||
+70
-28
@@ -4473,8 +4473,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::forward<InputType>(i));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in CBOR format (iterator pair, or iterator+sentinel pair for C++20 ranges support)
|
||||
@@ -4490,8 +4493,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::move(first), std::move(last));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
@@ -4516,8 +4522,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
auto ia = i.get();
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
// NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::cbor).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in MessagePack format
|
||||
@@ -4531,8 +4540,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::forward<InputType>(i));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in MessagePack format (iterator pair, or iterator+sentinel pair for C++20 ranges support)
|
||||
@@ -4547,8 +4559,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::move(first), std::move(last));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
@@ -4571,8 +4586,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
auto ia = i.get();
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
// NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::msgpack).sax_parse(input_format_t::msgpack, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in UBJSON format
|
||||
@@ -4586,8 +4604,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::forward<InputType>(i));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in UBJSON format (iterator pair, or iterator+sentinel pair for C++20 ranges support)
|
||||
@@ -4602,8 +4623,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::move(first), std::move(last));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
@@ -4626,8 +4650,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
auto ia = i.get();
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
// NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::ubjson).sax_parse(input_format_t::ubjson, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in BJData format
|
||||
@@ -4641,8 +4668,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::forward<InputType>(i));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata).sax_parse(input_format_t::bjdata, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata).sax_parse(input_format_t::bjdata, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in BJData format (iterator pair, or iterator+sentinel pair for C++20 ranges support)
|
||||
@@ -4657,8 +4687,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::move(first), std::move(last));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata).sax_parse(input_format_t::bjdata, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::bjdata).sax_parse(input_format_t::bjdata, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in BSON format
|
||||
@@ -4672,8 +4705,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::forward<InputType>(i));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// @brief create a JSON value from an input in BSON format (iterator pair, or iterator+sentinel pair for C++20 ranges support)
|
||||
@@ -4688,8 +4724,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
basic_json result;
|
||||
auto ia = detail::input_adapter(std::move(first), std::move(last));
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
@@ -4712,8 +4751,11 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
auto ia = i.get();
|
||||
detail::json_sax_dom_parser<basic_json, decltype(ia)> sdp(result, allow_exceptions);
|
||||
// NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg)
|
||||
const bool res = binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict); // cppcheck-suppress[accessMoved]
|
||||
return res ? result : basic_json(value_t::discarded);
|
||||
if (!binary_reader<decltype(ia)>(std::move(ia), input_format_t::bson).sax_parse(input_format_t::bson, &sdp, strict)) // cppcheck-suppress[accessMoved]
|
||||
{
|
||||
result = value_t::discarded;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/// @}
|
||||
|
||||
|
||||
+700
-400
File diff suppressed because it is too large
Load Diff
@@ -1,61 +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
|
||||
|
||||
// Standalone compile-and-run check for the JSON_SKIP_LIBRARY_VERSION_CHECK
|
||||
// configuration macro, which (per #5423) was never exercised anywhere in the
|
||||
// test matrix.
|
||||
//
|
||||
// include/nlohmann/detail/abi_macros.hpp normally emits a #warning if
|
||||
// NLOHMANN_JSON_VERSION_MAJOR/MINOR/PATCH are already defined (as they would
|
||||
// be by an earlier inclusion of a different version of the library) with
|
||||
// values that mismatch the version about to be defined -- unless
|
||||
// JSON_SKIP_LIBRARY_VERSION_CHECK is defined, in which case the check (and
|
||||
// that #warning) is skipped.
|
||||
//
|
||||
// This file deliberately is not named tests/src/unit-*.cpp: it is compiled
|
||||
// directly (with a modest, non-strict warning set) by the dedicated
|
||||
// ci_test_skiplibraryversioncheck target in cmake/ci.cmake, rather than being
|
||||
// folded into the library's own -Weverything/-Werror unit test matrix. That
|
||||
// is because the scenario simulated here -- mixing two different, already
|
||||
// differently-versioned inclusions of the library in one translation unit --
|
||||
// unavoidably also triggers the *compiler's own* "macro redefined" warning,
|
||||
// independent of (and unaffected by) JSON_SKIP_LIBRARY_VERSION_CHECK, which
|
||||
// only ever silences the library's own #warning. Building this file under
|
||||
// -Weverything -Werror would therefore fail for a reason unrelated to the
|
||||
// macro under test.
|
||||
#define NLOHMANN_JSON_VERSION_MAJOR 0
|
||||
#define NLOHMANN_JSON_VERSION_MINOR 0
|
||||
#define NLOHMANN_JSON_VERSION_PATCH 0
|
||||
|
||||
#define JSON_SKIP_LIBRARY_VERSION_CHECK 1
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
int main()
|
||||
{
|
||||
// reaching this point at all already proves that the mismatched,
|
||||
// pre-defined version macros above did not stop compilation -- which is
|
||||
// exactly what JSON_SKIP_LIBRARY_VERSION_CHECK is for. The library must
|
||||
// also still be fully usable.
|
||||
const nlohmann::json j = {{"a", 1}, {"b", {1, 2, 3}}};
|
||||
if (j.dump() != "{\"a\":1,\"b\":[1,2,3]}")
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
// include/nlohmann/detail/abi_macros.hpp unconditionally (re)defines the
|
||||
// version macros to the library's real, current version right after the
|
||||
// (here, skipped) mismatch check, regardless of the deliberately wrong
|
||||
// stand-in values defined above.
|
||||
if (NLOHMANN_JSON_VERSION_MAJOR == 0 && NLOHMANN_JSON_VERSION_MINOR == 0 && NLOHMANN_JSON_VERSION_PATCH == 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -3288,8 +3288,10 @@ TEST_CASE("BJData")
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vR1), "[json.exception.parse_error.113] parse error at byte 6: syntax error while parsing BJData size: ndarray dimensional vector is not allowed", json::parse_error&);
|
||||
CHECK(json::from_bjdata(vR1, true, false).is_discarded());
|
||||
|
||||
// a dimension vector that opens another one is rejected where the
|
||||
// nested '[' is read, rather than after it has been descended into
|
||||
std::vector<uint8_t> const vR2 = {'[', '$', 'i', '#', '[', '#', '[', 'i', 1, ']', ']', 1};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vR2), "[json.exception.parse_error.113] parse error at byte 11: syntax error while parsing BJData size: expected length type specification (U, i, u, I, m, l, M, L) after '#'; last byte: 0x5D", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vR2), "[json.exception.parse_error.113] parse error at byte 7: syntax error while parsing BJData size: ndarray dimensional vector is not allowed", json::parse_error&);
|
||||
CHECK(json::from_bjdata(vR2, true, false).is_discarded());
|
||||
|
||||
std::vector<uint8_t> const vR3 = {'[', '#', '[', 'i', '2', 'i', 2, ']'};
|
||||
@@ -3297,7 +3299,7 @@ TEST_CASE("BJData")
|
||||
CHECK(json::from_bjdata(vR3, true, false).is_discarded());
|
||||
|
||||
std::vector<uint8_t> const vR4 = {'[', '$', 'i', '#', '[', '$', 'i', '#', '[', 'i', 1, ']', 1};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vR4), "[json.exception.parse_error.110] parse error at byte 14: syntax error while parsing BJData number: unexpected end of input", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vR4), "[json.exception.parse_error.113] parse error at byte 9: syntax error while parsing BJData size: ndarray dimensional vector is not allowed", json::parse_error&);
|
||||
CHECK(json::from_bjdata(vR4, true, false).is_discarded());
|
||||
|
||||
std::vector<uint8_t> const vR5 = {'[', '$', 'i', '#', '[', '[', '[', ']', ']', ']'};
|
||||
@@ -3305,12 +3307,25 @@ TEST_CASE("BJData")
|
||||
CHECK(json::from_bjdata(vR5, true, false).is_discarded());
|
||||
|
||||
std::vector<uint8_t> const vR6 = {'[', '$', 'i', '#', '[', '$', 'i', '#', '[', 'i', '2', 'i', 2, ']'};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vR6), "[json.exception.parse_error.112] parse error at byte 14: syntax error while parsing BJData size: ndarray can not be recursive", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vR6), "[json.exception.parse_error.113] parse error at byte 9: syntax error while parsing BJData size: ndarray dimensional vector is not allowed", json::parse_error&);
|
||||
CHECK(json::from_bjdata(vR6, true, false).is_discarded());
|
||||
|
||||
std::vector<uint8_t> const vH = {'[', 'H', '[', '#', '[', '$', 'i', '#', '[', 'i', '2', 'i', 2, ']'};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vH), "[json.exception.parse_error.113] parse error at byte 3: syntax error while parsing BJData size: ndarray dimensional vector is not allowed", json::parse_error&);
|
||||
CHECK(json::from_bjdata(vH, true, false).is_discarded());
|
||||
|
||||
// Every "#[" of this chain used to open another dimension vector
|
||||
// and cost several stack frames before anything was rejected, so a
|
||||
// long enough chain crashed the process (see #5104). The nested
|
||||
// vector is refused where it is read, so the length is irrelevant.
|
||||
std::vector<uint8_t> vRdeep = {'['};
|
||||
for (std::size_t i = 0; i < 100000; ++i)
|
||||
{
|
||||
vRdeep.push_back('#');
|
||||
vRdeep.push_back('[');
|
||||
}
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_bjdata(vRdeep), "[json.exception.parse_error.113] parse error at byte 5: syntax error while parsing BJData size: ndarray dimensional vector is not allowed", json::parse_error&);
|
||||
CHECK(json::from_bjdata(vRdeep, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("objects")
|
||||
|
||||
@@ -1011,6 +1011,91 @@ TEST_CASE("BSON document size mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("BSON nesting does not consume the call stack")
|
||||
{
|
||||
// An embedded document or array used to be read by calling back into the
|
||||
// document reader, so the native call stack grew with the nesting depth of
|
||||
// the input (#5104). The open documents are kept on a heap stack now.
|
||||
//
|
||||
// Deeply nested values must not be compared, copied or dumped here: those
|
||||
// operations are still recursive and would reintroduce the crash.
|
||||
|
||||
// A document nested deeply enough to have crashed. The bytes are built
|
||||
// here rather than with to_bson(), because the writer still recurses once
|
||||
// per level and would overflow the stack before the reader is ever
|
||||
// reached. Every level is
|
||||
// <int32 size> 0x03 'a' 0x00 <inner document> 0x00
|
||||
// so a level is eight bytes larger than the one it holds, and the sizes
|
||||
// can be filled in from the outside in.
|
||||
const std::size_t depth = 30000;
|
||||
std::vector<uint8_t> input;
|
||||
input.reserve(5 + (8 * depth));
|
||||
for (std::size_t i = 0; i < depth; ++i)
|
||||
{
|
||||
const std::uint32_t size = static_cast<std::uint32_t>(5 + (8 * (depth - i)));
|
||||
input.push_back(static_cast<uint8_t>(size & 0xFF));
|
||||
input.push_back(static_cast<uint8_t>((size >> 8) & 0xFF));
|
||||
input.push_back(static_cast<uint8_t>((size >> 16) & 0xFF));
|
||||
input.push_back(static_cast<uint8_t>((size >> 24) & 0xFF));
|
||||
input.push_back(0x03); // embedded document
|
||||
input.push_back('a');
|
||||
input.push_back(0x00);
|
||||
}
|
||||
// the innermost document is empty, then one terminator closes each level
|
||||
input.insert(input.end(), {0x05, 0x00, 0x00, 0x00, 0x00});
|
||||
input.insert(input.end(), depth, 0x00);
|
||||
|
||||
SECTION("a well-formed deep document is read through the SAX interface")
|
||||
{
|
||||
SaxCountdown accept_all(1000000);
|
||||
CHECK(json::sax_parse(input, &accept_all, json::input_format_t::bson));
|
||||
}
|
||||
|
||||
SECTION("a well-formed deep document is read into a value")
|
||||
{
|
||||
json j = json::from_bson(input);
|
||||
|
||||
// walked rather than compared: comparing, copying or dumping a value
|
||||
// this deep is still recursive
|
||||
std::size_t measured = 0;
|
||||
const json* q = &j;
|
||||
while (q->is_object() && !q->empty())
|
||||
{
|
||||
q = &q->begin().value();
|
||||
++measured;
|
||||
}
|
||||
CHECK(measured == depth);
|
||||
}
|
||||
|
||||
SECTION("embedded documents and arrays are still read the same way")
|
||||
{
|
||||
const json values = {{"a", {{"b", {{"c", 1}}}}}};
|
||||
CHECK(json::from_bson(json::to_bson(values)) == values);
|
||||
|
||||
const json array = {{"a", {1, 2, 3}}};
|
||||
CHECK(json::from_bson(json::to_bson(array)) == array);
|
||||
|
||||
const json mixed = {{"a", {json{{"x", 1}}, json{{"y", 2}}}}};
|
||||
CHECK(json::from_bson(json::to_bson(mixed)) == mixed);
|
||||
|
||||
CHECK(json::from_bson(json::to_bson(json::object())) == json::object());
|
||||
}
|
||||
|
||||
SECTION("a size that does not match is still reported per document")
|
||||
{
|
||||
// the embedded document claims one byte too many
|
||||
std::vector<uint8_t> const bad =
|
||||
{
|
||||
0x15, 0x00, 0x00, 0x00, 0x03, 'a', 0x00,
|
||||
0x0D, 0x00, 0x00, 0x00, 0x08, 'b', 0x00, 0x01, 0x00,
|
||||
0x00
|
||||
};
|
||||
json _;
|
||||
CHECK_THROWS_AS(_ = json::from_bson(bad), json::parse_error&);
|
||||
CHECK(json::from_bson(bad, true, false).is_discarded());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("BSON numerical data")
|
||||
{
|
||||
SECTION("number")
|
||||
|
||||
@@ -42,39 +42,6 @@ TEST_CASE("byte_container_with_subtype")
|
||||
CHECK(container.subtype() == static_cast<subtype_type>(-1));
|
||||
}
|
||||
|
||||
SECTION("move semantics")
|
||||
{
|
||||
// the rvalue-reference constructor (without a subtype) must actually move
|
||||
// the passed-in container rather than copy it; comparing the buffer address
|
||||
// before and after is a stronger check than just observing the source is
|
||||
// empty afterward, since a copy-then-clear could also leave it empty
|
||||
{
|
||||
std::vector<std::uint8_t> bytes = {{0xCA, 0xFE, 0xBA, 0xBE}};
|
||||
const auto* const data_ptr = bytes.data();
|
||||
|
||||
nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>> container(std::move(bytes));
|
||||
|
||||
CHECK(container.size() == 4);
|
||||
CHECK(container.data() == data_ptr);
|
||||
CHECK(!container.has_subtype());
|
||||
CHECK(bytes.empty()); // NOLINT(bugprone-use-after-move,clang-analyzer-cplusplus.Move,hicpp-invalid-access-moved)
|
||||
}
|
||||
|
||||
// same check for the rvalue-reference constructor that also takes a subtype
|
||||
{
|
||||
std::vector<std::uint8_t> bytes = {{0xCA, 0xFE, 0xBA, 0xBE}};
|
||||
const auto* const data_ptr = bytes.data();
|
||||
|
||||
nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>> container(std::move(bytes), 42);
|
||||
|
||||
CHECK(container.size() == 4);
|
||||
CHECK(container.data() == data_ptr);
|
||||
CHECK(container.has_subtype());
|
||||
CHECK(container.subtype() == 42);
|
||||
CHECK(bytes.empty()); // NOLINT(bugprone-use-after-move,clang-analyzer-cplusplus.Move,hicpp-invalid-access-moved)
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("comparisons")
|
||||
{
|
||||
std::vector<std::uint8_t> const bytes = {{0xCA, 0xFE, 0xBA, 0xBE}};
|
||||
|
||||
@@ -2035,6 +2035,145 @@ TEST_CASE("CBOR definite length equal to the indefinite-length sentinel")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("CBOR nesting does not consume the call stack")
|
||||
{
|
||||
// Containers used to be read by calling back into the value reader once
|
||||
// per element, and a tag by calling it for the tagged value, so the native
|
||||
// call stack grew with the nesting depth of the input. Each of the three
|
||||
// costs a single byte to encode -- 0x9F, 0x81 and 0xC2 -- so a payload of
|
||||
// repeated bytes crashed the process (#5104). The containers are kept on a
|
||||
// heap stack now, and a tag is read in a loop.
|
||||
//
|
||||
// Deeply nested values must not be compared, copied or dumped here: those
|
||||
// operations are still recursive and would reintroduce the crash.
|
||||
json _;
|
||||
|
||||
SECTION("indefinite-length containers")
|
||||
{
|
||||
const std::vector<uint8_t> input(500000, 0x9F);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input), "[json.exception.parse_error.110] parse error at byte 500001: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&);
|
||||
CHECK(json::from_cbor(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("definite-length containers")
|
||||
{
|
||||
const std::vector<uint8_t> input(500000, 0x81);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input), "[json.exception.parse_error.110] parse error at byte 500001: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&);
|
||||
CHECK(json::from_cbor(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("tags")
|
||||
{
|
||||
// a tag is not a value of its own, so a chain of them used to recurse
|
||||
const std::vector<uint8_t> input(500000, 0xC2);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(input, true, true, json::cbor_tag_handler_t::ignore), "[json.exception.parse_error.110] parse error at byte 500001: syntax error while parsing CBOR value: unexpected end of input", json::parse_error&);
|
||||
CHECK(json::from_cbor(input, true, false, json::cbor_tag_handler_t::ignore).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("a well-formed deep value is read through the SAX interface")
|
||||
{
|
||||
std::vector<uint8_t> input(200000, 0x9F);
|
||||
input.insert(input.end(), 200000, 0xFF);
|
||||
|
||||
SaxCountdown accept_all(1000000);
|
||||
CHECK(json::sax_parse(input, &accept_all, json::input_format_t::cbor));
|
||||
}
|
||||
|
||||
SECTION("a well-formed deep value is read into a value")
|
||||
{
|
||||
const std::size_t depth = 10000;
|
||||
std::vector<uint8_t> input(depth, 0x81);
|
||||
input.push_back(0x00);
|
||||
|
||||
json j = json::from_cbor(input);
|
||||
|
||||
std::size_t measured = 0;
|
||||
const json* p = &j;
|
||||
while (p->is_array() && !p->empty())
|
||||
{
|
||||
p = &p->front();
|
||||
++measured;
|
||||
}
|
||||
CHECK(measured == depth);
|
||||
CHECK(p->is_number());
|
||||
}
|
||||
|
||||
SECTION("containers are still read the same way")
|
||||
{
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x80})) == json::array());
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0xA0})) == json::object());
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x9F, 0xFF})) == json::array());
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0xBF, 0xFF})) == json::object());
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x9F, 0x01, 0x02, 0xFF})) == json({1, 2}));
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0xBF, 0x61, 'a', 0x01, 0xFF})) == json({{"a", 1}}));
|
||||
// definite and indefinite forms nested inside each other
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x9F, 0x82, 0x01, 0x02, 0xA1, 0x61, 'k', 0xBF, 0xFF, 0xFF})) == json({{1, 2}, {{"k", json::object()}}}));
|
||||
}
|
||||
|
||||
SECTION("tagged values are still read the same way")
|
||||
{
|
||||
const auto ignore = json::cbor_tag_handler_t::ignore;
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0xC2, 0x01}), true, true, ignore) == json(1));
|
||||
// a chain of tags resolves to the value that follows it
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0xC2, 0xC2, 0xC2, 0x01}), true, true, ignore) == json(1));
|
||||
// a tag inside a container, and one in front of a container
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0x82, 0xC2, 0x01, 0x02}), true, true, ignore) == json({1, 2}));
|
||||
CHECK(json::from_cbor(std::vector<uint8_t>({0xC2, 0x82, 0x01, 0x02}), true, true, ignore) == json({1, 2}));
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
json _;
|
||||
|
||||
SECTION("many open levels are reported, 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(json::from_cbor(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("many open levels are reported, 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(json::from_cbor(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("chunks are still concatenated")
|
||||
{
|
||||
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"));
|
||||
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}));
|
||||
}
|
||||
|
||||
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&);
|
||||
}
|
||||
|
||||
SECTION("a break marker outside an indefinite-length string is not a string")
|
||||
{
|
||||
// 0xFF only closes a string that was opened; on its own it is not one
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_cbor(std::vector<uint8_t>({0xA1, 0xFF, 0x01})), "[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF", json::parse_error&);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("CBOR roundtrips" * doctest::skip())
|
||||
{
|
||||
SECTION("input from flynn")
|
||||
|
||||
@@ -1761,40 +1761,6 @@ TEST_CASE("std::filesystem::path")
|
||||
}
|
||||
#endif
|
||||
|
||||
// the ADL to_json overload for std::u8string only exists under the same guard
|
||||
// as std::filesystem::path support (it is otherwise only reached indirectly,
|
||||
// via std::filesystem::path::u8string()) -- mirror both #if conditions from
|
||||
// include/nlohmann/detail/conversions/to_json.hpp exactly
|
||||
#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
|
||||
#if defined(__cpp_lib_char8_t)
|
||||
TEST_CASE("std::u8string")
|
||||
{
|
||||
SECTION("ascii")
|
||||
{
|
||||
const std::u8string s = u8"Path";
|
||||
json const j = s;
|
||||
|
||||
CHECK(j.template get<std::string>() == "Path");
|
||||
}
|
||||
|
||||
SECTION("utf-8")
|
||||
{
|
||||
// use \u universal-character-names (rather than raw \x byte escapes
|
||||
// or literal non-ASCII source bytes) to compose the multi-byte UTF-8
|
||||
// encoding -- MSVC treats \x escapes used that way inside a u8
|
||||
// literal as a nonstandard extension (warning C5321), which some of
|
||||
// our CI configs promote to an error; \u is portable and produces
|
||||
// the exact same encoded bytes without depending on the source
|
||||
// file's encoding
|
||||
const std::u8string s = u8"P\u011B\u0161ina";
|
||||
json const j = s;
|
||||
|
||||
CHECK(j.template get<std::string>() == "P\xc4\x9b\xc5\xa1ina");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
TEST_CASE("std::optional")
|
||||
{
|
||||
SECTION("null")
|
||||
|
||||
@@ -672,102 +672,6 @@ TEST_CASE("JSON patch")
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("patch_inplace")
|
||||
{
|
||||
SECTION("happy path: patch_inplace mirrors patch() on success")
|
||||
{
|
||||
// mirrors "A.5. Replacing a Value" above, but applies the patch with
|
||||
// patch_inplace() to a mutable copy instead of using patch()'s
|
||||
// returned copy
|
||||
json doc = R"(
|
||||
{
|
||||
"baz": "qux",
|
||||
"foo": "bar"
|
||||
}
|
||||
)"_json;
|
||||
|
||||
json const patch = R"(
|
||||
[
|
||||
{ "op": "replace", "path": "/baz", "value": "boo" }
|
||||
]
|
||||
)"_json;
|
||||
|
||||
json const expected = R"(
|
||||
{
|
||||
"baz": "boo",
|
||||
"foo": "bar"
|
||||
}
|
||||
)"_json;
|
||||
|
||||
doc.patch_inplace(patch);
|
||||
CHECK(doc == expected);
|
||||
}
|
||||
|
||||
// this test relies on the "test" operation actually throwing so the
|
||||
// partial-application state can be observed right after the throw
|
||||
// point; under JSON_NOEXCEPTION, JSON_THROW() calls std::abort()
|
||||
// instead (there is no C++ exception to throw), and doctest's
|
||||
// CHECK_THROWS_AS() is compiled out to a no-op that never even
|
||||
// invokes the given expression (see doctest's "--no-throw" test
|
||||
// filter, which ci_test_noexceptions passes) -- so patch()/
|
||||
// patch_inplace() would never be called at all and the follow-up
|
||||
// state assertions below would fail against the untouched original
|
||||
#if !defined(JSON_NOEXCEPTION)
|
||||
SECTION("distinguishing contract vs patch(): partial application on failure")
|
||||
{
|
||||
// Unlike patch(), which is all-or-nothing because it applies the
|
||||
// patch to an internal copy that is simply discarded when an
|
||||
// exception is thrown (leaving the original untouched no matter
|
||||
// what), patch_inplace() mutates the document it is called on
|
||||
// directly and immediately, operation by operation. So if a JSON
|
||||
// Patch fails partway through, whatever operations already
|
||||
// succeeded remain applied -- the document is left in a partially
|
||||
// patched state. This is empirically verified current behavior,
|
||||
// not just documented intent, and is pinned here as such.
|
||||
json const original = R"(
|
||||
{
|
||||
"baz": "qux",
|
||||
"foo": "bar"
|
||||
}
|
||||
)"_json;
|
||||
|
||||
// the first operation ("replace") succeeds; the second ("test")
|
||||
// fails because the value at "/baz" no longer (and never did)
|
||||
// equal "not boo"
|
||||
json const patch = R"(
|
||||
[
|
||||
{ "op": "replace", "path": "/baz", "value": "boo" },
|
||||
{ "op": "test", "path": "/baz", "value": "not boo" }
|
||||
]
|
||||
)"_json;
|
||||
|
||||
// patch() never modifies the object it is called on -- it always
|
||||
// operates on (and returns) a separate copy, so the original is
|
||||
// left completely untouched, regardless of success or failure.
|
||||
// copy_for_patch is intentionally a real copy, not a reference
|
||||
// to `original`: the whole point of this check is to catch a
|
||||
// hypothetical future regression where patch() *does* mutate its
|
||||
// receiver. Using a reference here would make the assertion
|
||||
// below compare `original` to itself -- trivially true even if
|
||||
// such a bug existed -- which is exactly what a static analyzer
|
||||
// can't see when it suggests "this copy is never modified, use
|
||||
// a reference instead".
|
||||
json copy_for_patch = original; // NOLINT(performance-unnecessary-copy-initialization)
|
||||
CHECK_THROWS_AS(copy_for_patch.patch(patch), json::other_error&);
|
||||
CHECK(copy_for_patch == original);
|
||||
|
||||
// patch_inplace(), in contrast, already applied the successful
|
||||
// "replace" operation to the document before the "test" operation
|
||||
// threw -- that change is not rolled back
|
||||
json doc = original;
|
||||
CHECK_THROWS_AS(doc.patch_inplace(patch), json::other_error&);
|
||||
CHECK(doc != original);
|
||||
CHECK(doc.at("baz") == "boo");
|
||||
CHECK(doc.at("foo") == "bar");
|
||||
}
|
||||
#endif // !defined(JSON_NOEXCEPTION)
|
||||
}
|
||||
|
||||
SECTION("errors")
|
||||
{
|
||||
SECTION("unknown operation")
|
||||
|
||||
@@ -1598,6 +1598,67 @@ TEST_CASE("MessagePack")
|
||||
}
|
||||
|
||||
// use this testcase outside [hide] to run it with Valgrind
|
||||
TEST_CASE("MessagePack nesting does not consume the call stack")
|
||||
{
|
||||
// Reading a container used to call back into the value reader once per
|
||||
// element, so the native call stack grew with the nesting depth of the
|
||||
// input: one frame per byte for repeated 0x91 (a one-element array), which
|
||||
// crashes the process long before the input is exhausted (#5104). The
|
||||
// containers are kept on a heap stack now.
|
||||
//
|
||||
// Note that deeply nested values must not be compared, copied or dumped
|
||||
// here: those operations are still recursive, and would reintroduce the
|
||||
// very crash this checks for. Depth is measured by descending instead.
|
||||
|
||||
SECTION("an unterminated chain is reported, not crashed on")
|
||||
{
|
||||
json _;
|
||||
const std::vector<uint8_t> input(300000, 0x91);
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_msgpack(input), "[json.exception.parse_error.110] parse error at byte 300001: syntax error while parsing MessagePack value: unexpected end of input", json::parse_error&);
|
||||
CHECK(json::from_msgpack(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("a well-formed deep value is read through the SAX interface")
|
||||
{
|
||||
std::vector<uint8_t> input(300000, 0x91);
|
||||
input.push_back(0x01); // innermost value
|
||||
|
||||
SaxCountdown accept_all(600001);
|
||||
CHECK(json::sax_parse(input, &accept_all, json::input_format_t::msgpack));
|
||||
}
|
||||
|
||||
SECTION("a well-formed deep value is read into a value")
|
||||
{
|
||||
const std::size_t depth = 10000;
|
||||
std::vector<uint8_t> input(depth, 0x91);
|
||||
input.push_back(0x01);
|
||||
|
||||
json j = json::from_msgpack(input);
|
||||
|
||||
std::size_t measured = 0;
|
||||
const json* p = &j;
|
||||
while (p->is_array() && !p->empty())
|
||||
{
|
||||
p = &p->front();
|
||||
++measured;
|
||||
}
|
||||
CHECK(measured == depth);
|
||||
CHECK(p->is_number());
|
||||
}
|
||||
|
||||
SECTION("containers are still read the same way")
|
||||
{
|
||||
CHECK(json::from_msgpack(std::vector<uint8_t>({0x90})) == json::array());
|
||||
CHECK(json::from_msgpack(std::vector<uint8_t>({0x80})) == json::object());
|
||||
CHECK(json::from_msgpack(std::vector<uint8_t>({0x92, 0x90, 0x80})) == json({json::array(), json::object()}));
|
||||
CHECK(json::from_msgpack(std::vector<uint8_t>({0x91, 0x91, 0x91, 0x90})) == json({{{json::array()}}}));
|
||||
CHECK(json::from_msgpack(std::vector<uint8_t>({0x81, 0xA1, 'a', 0x81, 0xA1, 'b', 0x92, 0x01, 0x02})) == json({{"a", {{"b", {1, 2}}}}}));
|
||||
// array 16 and map 32, i.e. the counted forms
|
||||
CHECK(json::from_msgpack(std::vector<uint8_t>({0xDC, 0x00, 0x02, 0x01, 0x02})) == json({1, 2}));
|
||||
CHECK(json::from_msgpack(std::vector<uint8_t>({0xDF, 0x00, 0x00, 0x00, 0x01, 0xA1, 'k', 0xC3})) == json({{"k", true}}));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("single MessagePack roundtrip")
|
||||
{
|
||||
SECTION("sample.json")
|
||||
|
||||
@@ -70,7 +70,7 @@ TEST_CASE("check_for_mem_leak_on_adl_to_json-2")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("check_for_mem_leak_on_adl_to_json-3")
|
||||
TEST_CASE("check_for_mem_leak_on_adl_to_json-2")
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -1,91 +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
|
||||
|
||||
// This translation unit is a dedicated, small compile-and-run check for two
|
||||
// configuration macros that (per #5423) were never exercised anywhere in the
|
||||
// test matrix:
|
||||
// - JSON_NO_IO, which removes the library's <istream>/<ostream> support
|
||||
// (operator<<, operator>>, and the stream-based overloads of dump()/parse())
|
||||
// - the JSON_THROW_USER / JSON_TRY_USER / JSON_CATCH_USER trio, which lets a
|
||||
// user replace the library's internal exception handling
|
||||
//
|
||||
// Both macros are about excluding/replacing a facility the library would
|
||||
// otherwise pull in on its own, and defining one has no bearing on the other,
|
||||
// so -- to keep the test matrix small -- they are exercised together in a
|
||||
// single dedicated file instead of two.
|
||||
//
|
||||
// JSON_NO_IO requires this file itself to never rely on <iostream>/<sstream>;
|
||||
// only string-based parsing/dumping is used below.
|
||||
#define JSON_NO_IO 1
|
||||
|
||||
// The user-supplied exception macros below are a *conforming* replacement:
|
||||
// they simply forward to the real throw/try/catch keywords (via a counter so
|
||||
// the test can assert each macro was actually invoked, not just defined), so
|
||||
// every exception-related behavior the library relies on internally --
|
||||
// including rethrowing std::out_of_range as json::out_of_range in at() --
|
||||
// keeps working exactly as it would with the library's own default macros.
|
||||
static int json_throw_user_call_count = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
#define JSON_THROW_USER(exception) do { ++json_throw_user_call_count; throw exception; } while (false) // NOLINT(cppcoreguidelines-macro-usage)
|
||||
#define JSON_TRY_USER try // NOLINT(cppcoreguidelines-macro-usage)
|
||||
#define JSON_CATCH_USER(exception) catch (exception) // NOLINT(cppcoreguidelines-macro-usage)
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
using json = nlohmann::json;
|
||||
|
||||
TEST_CASE("JSON_NO_IO")
|
||||
{
|
||||
// everything that does not touch <istream>/<ostream> must keep working:
|
||||
// parsing from and dumping to std::string
|
||||
const json j = json::parse("{\"a\":[1,2,3],\"b\":true}");
|
||||
CHECK(j.dump() == "{\"a\":[1,2,3],\"b\":true}");
|
||||
CHECK(j.at("a").size() == 3);
|
||||
CHECK(j.at("b").get<bool>() == true);
|
||||
}
|
||||
|
||||
// this test relies on CHECK_THROWS_AS() actually invoking the guarded
|
||||
// expression so json_throw_user_call_count gets bumped and can be observed
|
||||
// afterwards; doctest's "--no-throw" test filter (which ci_test_noexceptions
|
||||
// passes, together with a global -DJSON_NOEXCEPTION added to CMAKE_CXX_FLAGS
|
||||
// for every translation unit in that build, this file included) compiles
|
||||
// CHECK_THROWS_AS() out to a no-op that never even invokes the given
|
||||
// expression -- so json::parse()/at() below would never be called at all and
|
||||
// the call-count assertions would fail even though our JSON_THROW_USER
|
||||
// override (which always really throws, regardless of JSON_NOEXCEPTION) would
|
||||
// have worked fine on its own
|
||||
#if !defined(JSON_NOEXCEPTION)
|
||||
TEST_CASE("JSON_THROW_USER, JSON_TRY_USER, JSON_CATCH_USER")
|
||||
{
|
||||
json_throw_user_call_count = 0;
|
||||
|
||||
// json::parse() is [[nodiscard]] (JSON_HEDLEY_WARN_UNUSED_RESULT); under
|
||||
// GCC in C++11 mode that expands to __attribute__((warn_unused_result)),
|
||||
// which -- unlike a [[nodiscard]] attribute proper -- GCC does not
|
||||
// consider satisfied by doctest's CHECK_THROWS_AS() wrapping the
|
||||
// expression in a (void) cast, so the discarded return value would still
|
||||
// be flagged under -Werror=unused-result; assign it to discard it instead,
|
||||
// matching the established `json _ = json::parse(...)` pattern used
|
||||
// elsewhere in the test suite (see unit-class_parser.cpp)
|
||||
json _; // NOLINT(readability-identifier-naming)
|
||||
|
||||
// a parse error goes through JSON_THROW directly, i.e., through our
|
||||
// JSON_THROW_USER override
|
||||
CHECK_THROWS_AS(_ = json::parse("this is not JSON"), json::parse_error&);
|
||||
CHECK(json_throw_user_call_count > 0);
|
||||
|
||||
// at() on an out-of-range array index internally catches std::out_of_range
|
||||
// (JSON_TRY_USER/JSON_CATCH_USER) and rethrows it as json::out_of_range
|
||||
// (JSON_THROW_USER again), so this exercises all three macros together
|
||||
const int count_before = json_throw_user_call_count;
|
||||
const json arr = json::array({1, 2, 3});
|
||||
CHECK_THROWS_AS(arr.at(10), json::out_of_range&);
|
||||
CHECK(json_throw_user_call_count > count_before);
|
||||
}
|
||||
#endif
|
||||
@@ -18,14 +18,6 @@
|
||||
// for some reason including this after the json header leads to linker errors with VS 2017...
|
||||
#include <locale>
|
||||
|
||||
// skip tests if JSON_DisableEnumSerialization=ON (#4384): std::byte is a
|
||||
// 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
|
||||
#if defined(JSON_DISABLE_ENUM_SERIALIZATION) && (JSON_DISABLE_ENUM_SERIALIZATION == 1)
|
||||
#define SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||
#endif
|
||||
|
||||
#define JSON_TESTS_PRIVATE
|
||||
#include <nlohmann/json.hpp>
|
||||
using json = nlohmann::json;
|
||||
@@ -247,209 +239,6 @@ class my_allocator : public std::allocator<T>
|
||||
};
|
||||
};
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3077
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
class FooAlloc
|
||||
{};
|
||||
|
||||
class Foo
|
||||
{
|
||||
public:
|
||||
explicit Foo(const FooAlloc& /* unused */ = FooAlloc()) {}
|
||||
|
||||
bool value = false;
|
||||
};
|
||||
|
||||
class FooBar
|
||||
{
|
||||
public:
|
||||
Foo foo{}; // NOLINT(readability-redundant-member-init)
|
||||
};
|
||||
|
||||
inline void from_json(const nlohmann::json& j, FooBar& fb) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
j.at("value").get_to(fb.foo.value);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3171
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct for_3171_base // NOLINT(cppcoreguidelines-special-member-functions)
|
||||
{
|
||||
for_3171_base(const std::string& /*unused*/ = {}) {}
|
||||
virtual ~for_3171_base();
|
||||
|
||||
for_3171_base(const for_3171_base& other) // NOLINT(hicpp-use-equals-default,modernize-use-equals-default)
|
||||
: str(other.str)
|
||||
{}
|
||||
|
||||
for_3171_base& operator=(const for_3171_base& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
str = other.str;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
for_3171_base(for_3171_base&& other) noexcept
|
||||
: str(std::move(other.str))
|
||||
{}
|
||||
|
||||
for_3171_base& operator=(for_3171_base&& other) noexcept
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
str = std::move(other.str);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
virtual void _from_json(const json& j)
|
||||
{
|
||||
j.at("str").get_to(str);
|
||||
}
|
||||
|
||||
std::string str{}; // NOLINT(readability-redundant-member-init)
|
||||
};
|
||||
|
||||
for_3171_base::~for_3171_base() = default;
|
||||
|
||||
struct for_3171_derived : public for_3171_base
|
||||
{
|
||||
for_3171_derived() = default;
|
||||
~for_3171_derived() override;
|
||||
explicit for_3171_derived(const std::string& /*unused*/) { }
|
||||
|
||||
for_3171_derived(const for_3171_derived& other) // NOLINT(hicpp-use-equals-default,modernize-use-equals-default)
|
||||
: for_3171_base(other)
|
||||
{}
|
||||
|
||||
for_3171_derived& operator=(const for_3171_derived& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
for_3171_base::operator=(other); // Call base class assignment operator
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
for_3171_derived(for_3171_derived&& other) noexcept
|
||||
: for_3171_base(std::move(other))
|
||||
{}
|
||||
|
||||
for_3171_derived& operator=(for_3171_derived&& other) noexcept
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
for_3171_base::operator=(std::move(other)); // Call base class move assignment operator
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
|
||||
for_3171_derived::~for_3171_derived() = default;
|
||||
|
||||
inline void from_json(const json& j, for_3171_base& tb) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
tb._from_json(j);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3312
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifdef JSON_HAS_CPP_20
|
||||
struct for_3312
|
||||
{
|
||||
std::string name;
|
||||
};
|
||||
|
||||
inline void from_json(const json& j, for_3312& obj) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
j.at("name").get_to(obj.name);
|
||||
}
|
||||
#endif
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3204
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct for_3204_foo
|
||||
{
|
||||
for_3204_foo() = default;
|
||||
explicit for_3204_foo(std::string /*unused*/) {} // NOLINT(performance-unnecessary-value-param)
|
||||
};
|
||||
|
||||
struct for_3204_bar
|
||||
{
|
||||
enum constructed_from_t // NOLINT(cppcoreguidelines-use-enum-class)
|
||||
{
|
||||
constructed_from_none = 0,
|
||||
constructed_from_foo = 1,
|
||||
constructed_from_json = 2
|
||||
};
|
||||
|
||||
explicit for_3204_bar(std::function<void(for_3204_foo)> /*unused*/) noexcept // NOLINT(performance-unnecessary-value-param)
|
||||
: constructed_from(constructed_from_foo) {}
|
||||
explicit for_3204_bar(std::function<void(json)> /*unused*/) noexcept // NOLINT(performance-unnecessary-value-param)
|
||||
: constructed_from(constructed_from_json) {}
|
||||
|
||||
constructed_from_t constructed_from = constructed_from_none;
|
||||
};
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3333
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct for_3333 final
|
||||
{
|
||||
for_3333(int x_ = 0, int y_ = 0) : x(x_), y(y_) {}
|
||||
|
||||
template <class T>
|
||||
for_3333(const T& /*unused*/)
|
||||
{
|
||||
CHECK(false);
|
||||
}
|
||||
|
||||
int x = 0;
|
||||
int y = 0;
|
||||
};
|
||||
|
||||
template <>
|
||||
inline for_3333::for_3333(const json& j)
|
||||
: for_3333(j.value("x", 0), j.value("y", 0))
|
||||
{}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3810
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct Example_3810
|
||||
{
|
||||
int bla{};
|
||||
|
||||
Example_3810() = default;
|
||||
};
|
||||
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Example_3810, bla) // NOLINT(misc-use-internal-linkage)
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #4740
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
struct Example_4740
|
||||
{
|
||||
std::optional<std::string> host = std::nullopt;
|
||||
std::optional<int> port = std::nullopt;
|
||||
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Example_4740, host, port)
|
||||
};
|
||||
#endif
|
||||
|
||||
TEST_CASE("regression tests 2")
|
||||
{
|
||||
SECTION("issue #1001 - Fix memory leak during parser callback")
|
||||
@@ -967,613 +756,6 @@ TEST_CASE("regression tests 2")
|
||||
CHECK(j == k);
|
||||
}
|
||||
|
||||
#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
|
||||
// JSON_HAS_CPP_17 (do not remove; see note at top of file)
|
||||
SECTION("issue #3070 - Version 3.10.3 breaks backward-compatibility with 3.10.2 ")
|
||||
{
|
||||
nlohmann::detail::std_fs::path text_path("/tmp/text.txt");
|
||||
const json j(text_path);
|
||||
|
||||
const auto j_path = j.get<nlohmann::detail::std_fs::path>();
|
||||
CHECK(j_path == text_path);
|
||||
|
||||
#if DOCTEST_CLANG || DOCTEST_GCC >= DOCTEST_COMPILER(8, 4, 0)
|
||||
// only known to work on Clang and GCC >=8.4
|
||||
CHECK_THROWS_WITH_AS(nlohmann::detail::std_fs::path(json(1)), "[json.exception.type_error.302] type must be string, but is number", json::type_error);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("issue #3077 - explicit constructor with default does not compile")
|
||||
{
|
||||
json j;
|
||||
j[0]["value"] = true;
|
||||
std::vector<FooBar> foo;
|
||||
j.get_to(foo);
|
||||
}
|
||||
|
||||
SECTION("issue #3108 - ordered_json doesn't support range based erase")
|
||||
{
|
||||
ordered_json j = {1, 2, 2, 4};
|
||||
|
||||
auto last = std::unique(j.begin(), j.end());
|
||||
j.erase(last, j.end());
|
||||
|
||||
CHECK(j.dump() == "[1,2,4]");
|
||||
|
||||
j.erase(std::remove_if(j.begin(), j.end(), [](const ordered_json & val)
|
||||
{
|
||||
return val == 2;
|
||||
}), j.end());
|
||||
|
||||
CHECK(j.dump() == "[1,4]");
|
||||
}
|
||||
|
||||
SECTION("issue #3343 - json and ordered_json are not interchangeable")
|
||||
{
|
||||
json::object_t jobj({ { "product", "one" } });
|
||||
ordered_json::object_t ojobj({{"product", "one"}});
|
||||
|
||||
auto jit = jobj.begin();
|
||||
auto ojit = ojobj.begin();
|
||||
|
||||
CHECK(jit->first == ojit->first);
|
||||
CHECK(jit->second.get<std::string>() == ojit->second.get<std::string>());
|
||||
}
|
||||
|
||||
SECTION("issue #3171 - if class is_constructible from std::string wrong from_json overload is being selected, compilation failed")
|
||||
{
|
||||
const json j{{ "str", "value"}};
|
||||
|
||||
// failed with: error: no match for ‘operator=’ (operand types are ‘for_3171_derived’ and ‘const nlohmann::basic_json<>::string_t’
|
||||
// {aka ‘const std::__cxx11::basic_string<char>’})
|
||||
// s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
|
||||
auto td = j.get<for_3171_derived>();
|
||||
|
||||
CHECK(td.str == "value");
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_20
|
||||
SECTION("issue #3312 - Parse to custom class from unordered_json breaks on G++11.2.0 with C++20")
|
||||
{
|
||||
// see test for #3171
|
||||
const ordered_json j = {{"name", "class"}};
|
||||
for_3312 obj{};
|
||||
|
||||
j.get_to(obj);
|
||||
|
||||
CHECK(obj.name == "class");
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(JSON_HAS_CPP_17) && JSON_USE_IMPLICIT_CONVERSIONS
|
||||
SECTION("issue #3428 - Error occurred when converting nlohmann::json to std::any")
|
||||
{
|
||||
const json j;
|
||||
const std::any a1 = j;
|
||||
std::any&& a2 = j;
|
||||
|
||||
CHECK(a1.type() == typeid(j));
|
||||
CHECK(a2.type() == typeid(j));
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("issue #3204 - ambiguous regression")
|
||||
{
|
||||
const for_3204_bar bar_from_foo([](for_3204_foo) noexcept {}); // NOLINT(performance-unnecessary-value-param)
|
||||
const for_3204_bar bar_from_json([](json) noexcept {}); // NOLINT(performance-unnecessary-value-param)
|
||||
|
||||
CHECK(bar_from_foo.constructed_from == for_3204_bar::constructed_from_foo);
|
||||
CHECK(bar_from_json.constructed_from == for_3204_bar::constructed_from_json);
|
||||
}
|
||||
|
||||
SECTION("issue #3333 - Ambiguous conversion from nlohmann::basic_json<> to custom class")
|
||||
{
|
||||
const json j
|
||||
{
|
||||
{"x", 1},
|
||||
{"y", 2}
|
||||
};
|
||||
const for_3333 p = j;
|
||||
|
||||
CHECK(p.x == 1);
|
||||
CHECK(p.y == 2);
|
||||
}
|
||||
|
||||
SECTION("issue #3810 - ordered_json doesn't support construction from C array of custom type")
|
||||
{
|
||||
Example_3810 states[45]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
||||
|
||||
// fix "not used" warning
|
||||
states[0].bla = 1;
|
||||
|
||||
const auto* const expected = R"([{"bla":1},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0}])";
|
||||
|
||||
// This works:
|
||||
nlohmann::json j;
|
||||
j["test"] = states;
|
||||
CHECK(j["test"].dump() == expected);
|
||||
|
||||
// This doesn't compile:
|
||||
nlohmann::ordered_json oj;
|
||||
oj["test"] = states;
|
||||
CHECK(oj["test"].dump() == expected);
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
SECTION("issue #4740 - build issue with std::optional")
|
||||
{
|
||||
const auto t1 = Example_4740();
|
||||
const auto j1 = nlohmann::json(t1);
|
||||
CHECK(j1.dump() == "{\"host\":null,\"port\":null}");
|
||||
const auto t2 = j1.get<Example_4740>();
|
||||
CHECK(!t2.host.has_value());
|
||||
CHECK(!t2.port.has_value());
|
||||
|
||||
// improve coverage
|
||||
auto t3 = Example_4740();
|
||||
t3.port = 80;
|
||||
t3.host = "example.com";
|
||||
const auto j2 = nlohmann::json(t3);
|
||||
CHECK(j2.dump() == "{\"host\":\"example.com\",\"port\":80}");
|
||||
const auto t4 = j2.get<Example_4740>();
|
||||
CHECK(t4.host.has_value());
|
||||
CHECK(t4.port.has_value());
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !defined(_MSVC_LANG)
|
||||
// MSVC returns garbage on invalid enum values, so this test is excluded
|
||||
// there.
|
||||
SECTION("issue #4762 - json exception 302 with unhelpful explanation : type must be number, but is number")
|
||||
{
|
||||
// In #4762, the main issue was that a json object with an invalid type
|
||||
// returned "number" as type_name(), because this was the default case.
|
||||
// This test makes sure we now return "invalid" instead.
|
||||
json j;
|
||||
j.m_data.m_type = static_cast<json::value_t>(100); // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange)
|
||||
CHECK(j.type_name() == "invalid");
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
SECTION("issue #4804: from_cbor incompatible with std::vector<std::byte> as binary_t")
|
||||
{
|
||||
const std::vector<std::uint8_t> data = {0x80};
|
||||
const auto decoded = json_4804::from_cbor(data);
|
||||
CHECK((decoded == json_4804::array()));
|
||||
}
|
||||
|
||||
#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||
SECTION("discussion #4209 - custom BinaryType direct assignment and round-tripping")
|
||||
{
|
||||
// Test that assigning a custom BinaryType directly creates a binary value, not an array
|
||||
const std::vector<std::byte> original{std::byte{1}, std::byte{2}, std::byte{3}};
|
||||
const json_4804 j = original;
|
||||
CHECK(j.is_binary());
|
||||
CHECK(!j.is_array());
|
||||
|
||||
// Test round-tripping: extracting the binary value back as the custom container type
|
||||
const auto extracted = j.get<std::vector<std::byte>>();
|
||||
CHECK(extracted == original);
|
||||
|
||||
// Test that the default json alias behavior is unchanged: std::vector<uint8_t> -> array
|
||||
const json default_json = std::vector<std::uint8_t> {1, 2, 3};
|
||||
CHECK(default_json.is_array());
|
||||
CHECK(!default_json.is_binary());
|
||||
}
|
||||
|
||||
SECTION("discussion #4209 - custom BinaryType extraction from parsed array")
|
||||
{
|
||||
// Test that extracting a custom BinaryType from a parsed JSON array still works
|
||||
// (not just from a binary-typed node)
|
||||
const auto j = json_4804::parse("[1,2,3]");
|
||||
CHECK(j.is_array());
|
||||
CHECK(!j.is_binary());
|
||||
|
||||
// Extracting as custom BinaryType should work from arrays
|
||||
const auto extracted = j.get<std::vector<std::byte>>();
|
||||
CHECK(extracted.size() == 3);
|
||||
CHECK(extracted[0] == std::byte{1});
|
||||
CHECK(extracted[1] == std::byte{2});
|
||||
CHECK(extracted[2] == std::byte{3});
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("issue #5046 - implicit conversion of return json to std::optional no longer implicit")
|
||||
{
|
||||
const json jval{};
|
||||
auto GetValue = [](const json & valRoot) -> std::optional<json>
|
||||
{
|
||||
if (valRoot.contains("default"))
|
||||
{
|
||||
return valRoot.at("default");
|
||||
}
|
||||
return std::nullopt;
|
||||
};
|
||||
auto result = GetValue(jval);
|
||||
CHECK(!result.has_value());
|
||||
}
|
||||
#endif
|
||||
|
||||
#if JSON_HAS_RANGES == 1
|
||||
SECTION("issue #4440 - assert when using std::views::filter and GCC 10")
|
||||
{
|
||||
auto noOpFilter = std::views::filter([](auto&&) noexcept
|
||||
{
|
||||
return true;
|
||||
});
|
||||
json j = {1, 2, 3};
|
||||
auto filtered = j | noOpFilter;
|
||||
CHECK(*filtered.begin() == 1);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||
SECTION("issue #4916 - constructing array from C++20 ranges view does not work")
|
||||
{
|
||||
std::vector<int> nums{1, 2, 37, 42, 21};
|
||||
auto filteredNums = nums | std::views::filter([](int i)
|
||||
{
|
||||
return i > 10;
|
||||
});
|
||||
json const j(filteredNums);
|
||||
CHECK(j.type() == json::value_t::array);
|
||||
CHECK(j == json({37, 42, 21}));
|
||||
}
|
||||
#endif
|
||||
|
||||
// owning_view is not available in libstdc++ < 12
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__) && !(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)
|
||||
{
|
||||
return i > 10;
|
||||
}));
|
||||
CHECK(j.type() == json::value_t::array);
|
||||
CHECK(j == json({37, 42, 21}));
|
||||
}
|
||||
#endif
|
||||
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||
SECTION("issue #4916 - constructing array from C++20 transform view (prvalue elements)")
|
||||
{
|
||||
std::vector<int> nums{1, 2, 3};
|
||||
auto t = nums | std::views::transform([](int i) noexcept
|
||||
{
|
||||
return i * 2;
|
||||
});
|
||||
json const j(t);
|
||||
CHECK(j.type() == json::value_t::array);
|
||||
CHECK(j == json({2, 4, 6}));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_CASE_TEMPLATE("issue #4798 - nlohmann::json::to_msgpack() encode float NaN as double", T, double, float) // NOLINT(readability-math-missing-parentheses, bugprone-throwing-static-initialization)
|
||||
{
|
||||
// With issue #4798, we encode NaN, infinity, and -infinity as float instead
|
||||
// of double to allow for smaller encodings.
|
||||
const json jx = std::numeric_limits<T>::quiet_NaN();
|
||||
const json jy = std::numeric_limits<T>::infinity();
|
||||
const json jz = -std::numeric_limits<T>::infinity();
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// MessagePack
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// expected MessagePack values
|
||||
const std::vector<std::uint8_t> msgpack_x = {{0xCA, 0x7F, 0xC0, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> msgpack_y = {{0xCA, 0x7F, 0x80, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> msgpack_z = {{0xCA, 0xFF, 0x80, 0x00, 0x00}};
|
||||
|
||||
CHECK(json::to_msgpack(jx) == msgpack_x);
|
||||
CHECK(json::to_msgpack(jy) == msgpack_y);
|
||||
CHECK(json::to_msgpack(jz) == msgpack_z);
|
||||
|
||||
CHECK(std::isnan(json::from_msgpack(msgpack_x).get<T>()));
|
||||
CHECK(json::from_msgpack(msgpack_y).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_msgpack(msgpack_z).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
|
||||
// Make sure the other MessagePakc encodings for NaN, infinity, and
|
||||
// -infinity are still supported.
|
||||
const std::vector<std::uint8_t> msgpack_x_2 = {{0xCB, 0x7F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> msgpack_y_2 = {{0xCB, 0x7F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> msgpack_z_2 = {{0xCB, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
CHECK(std::isnan(json::from_msgpack(msgpack_x_2).get<T>()));
|
||||
CHECK(json::from_msgpack(msgpack_y_2).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_msgpack(msgpack_z_2).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// CBOR
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// expected CBOR values
|
||||
const std::vector<std::uint8_t> cbor_x = {{0xF9, 0x7E, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_y = {{0xF9, 0x7C, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_z = {{0xF9, 0xfC, 0x00}};
|
||||
|
||||
CHECK(json::to_cbor(jx) == cbor_x);
|
||||
CHECK(json::to_cbor(jy) == cbor_y);
|
||||
CHECK(json::to_cbor(jz) == cbor_z);
|
||||
|
||||
CHECK(std::isnan(json::from_cbor(cbor_x).get<T>()));
|
||||
CHECK(json::from_cbor(cbor_y).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_cbor(cbor_z).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
|
||||
// Make sure the other CBOR encodings for NaN, infinity, and -infinity are
|
||||
// still supported.
|
||||
const std::vector<std::uint8_t> cbor_x_2 = {{0xFA, 0x7F, 0xC0, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_y_2 = {{0xFA, 0x7F, 0x80, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_z_2 = {{0xFA, 0xFF, 0x80, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_x_3 = {{0xFB, 0x7F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_y_3 = {{0xFB, 0x7F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_z_3 = {{0xFB, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
CHECK(std::isnan(json::from_cbor(cbor_x_2).get<T>()));
|
||||
CHECK(json::from_cbor(cbor_y_2).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_cbor(cbor_z_2).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
CHECK(std::isnan(json::from_cbor(cbor_x_3).get<T>()));
|
||||
CHECK(json::from_cbor(cbor_y_3).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_cbor(cbor_z_3).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
}
|
||||
|
||||
TEST_CASE("regression test #5074 - portable workaround for single-element brace init")
|
||||
{
|
||||
json const j_obj = {{"key", "value"}};
|
||||
|
||||
json const j = json::array({j_obj});
|
||||
CHECK(j.is_array());
|
||||
CHECK(j.size() == 1);
|
||||
CHECK(j[0] == j_obj);
|
||||
}
|
||||
|
||||
#if defined(JSON_BRACE_INIT_COPY_SEMANTICS) && (JSON_BRACE_INIT_COPY_SEMANTICS == 1)
|
||||
TEST_CASE("regression test #5074 - single-element brace init with JSON_BRACE_INIT_COPY_SEMANTICS")
|
||||
{
|
||||
// with JSON_BRACE_INIT_COPY_SEMANTICS: single-element brace init copies/moves
|
||||
json const j_obj = {{"key", "value"}, {"num", 42}};
|
||||
json const j_arr = {1, 2, 3};
|
||||
|
||||
// object: brace init copies instead of wrapping
|
||||
json const j1{j_obj};
|
||||
CHECK(j1.is_object());
|
||||
CHECK(j1 == j_obj);
|
||||
|
||||
// array: brace init copies instead of wrapping
|
||||
json const j2{j_arr};
|
||||
CHECK(j2.is_array());
|
||||
CHECK(j2.size() == 3);
|
||||
CHECK(j2 == j_arr);
|
||||
|
||||
// primitives still work as initializer lists
|
||||
json const j3{true};
|
||||
CHECK(j3.is_boolean());
|
||||
|
||||
json const j4{42};
|
||||
CHECK(j4.is_number_integer());
|
||||
}
|
||||
#endif
|
||||
|
||||
struct Example_5122
|
||||
{
|
||||
float b = 2;
|
||||
nlohmann::ordered_map<std::string, std::string> c{}; // NOLINT(readability-redundant-member-init): needed for GCC -Weffc++
|
||||
int a = 1;
|
||||
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Example_5122, b, c, a)
|
||||
};
|
||||
|
||||
TEST_CASE("regression test #5122 - from_json into types holding nlohmann::ordered_map")
|
||||
{
|
||||
Example_5122 src;
|
||||
src.c.emplace("first", "1");
|
||||
src.c.emplace("second", "2");
|
||||
|
||||
ordered_json const j = src;
|
||||
Example_5122 const dst = j.get<Example_5122>();
|
||||
|
||||
CHECK(dst.b == src.b);
|
||||
CHECK(dst.a == src.a);
|
||||
REQUIRE(dst.c.size() == src.c.size());
|
||||
auto src_it = src.c.begin();
|
||||
auto dst_it = dst.c.begin();
|
||||
for (; src_it != src.c.end(); ++src_it, ++dst_it)
|
||||
{
|
||||
CHECK(dst_it->first == src_it->first);
|
||||
CHECK(dst_it->second == src_it->second);
|
||||
}
|
||||
}
|
||||
|
||||
// -Wself-assign-overloaded was introduced in Clang 7. Gate the pragma on
|
||||
// __has_warning so older Clang versions do not error with "unknown warning
|
||||
// group". The __has_warning check has to stay inside the __clang__ branch
|
||||
// because GCC does not provide it and would tokenize-error on the argument.
|
||||
#if defined(__clang__) && defined(__has_warning)
|
||||
#if __has_warning("-Wself-assign-overloaded")
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wself-assign-overloaded")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
TEST_CASE("regression test #5122 - nlohmann::ordered_map copy-assignment is self-assignment safe")
|
||||
{
|
||||
nlohmann::ordered_map<std::string, std::string> m;
|
||||
m.emplace("first", "1");
|
||||
m.emplace("second", "2");
|
||||
|
||||
// Insertion order is preserved by ordered_map, so we can check it directly.
|
||||
m = m;
|
||||
|
||||
REQUIRE(m.size() == 2);
|
||||
auto it = m.begin();
|
||||
CHECK(it->first == "first");
|
||||
CHECK(it->second == "1");
|
||||
++it;
|
||||
CHECK(it->first == "second");
|
||||
CHECK(it->second == "2");
|
||||
}
|
||||
|
||||
#if defined(__clang__) && defined(__has_warning)
|
||||
#if __has_warning("-Wself-assign-overloaded")
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
#endif
|
||||
#endif
|
||||
|
||||
TEST_CASE("regression test #5122 - nlohmann::ordered_map move-assignment transfers contents")
|
||||
{
|
||||
nlohmann::ordered_map<std::string, std::string> src;
|
||||
src.emplace("first", "1");
|
||||
src.emplace("second", "2");
|
||||
|
||||
nlohmann::ordered_map<std::string, std::string> dst;
|
||||
dst.emplace("stale", "x");
|
||||
dst = std::move(src);
|
||||
|
||||
REQUIRE(dst.size() == 2);
|
||||
auto it = dst.begin();
|
||||
CHECK(it->first == "first");
|
||||
CHECK(it->second == "1");
|
||||
++it;
|
||||
CHECK(it->first == "second");
|
||||
CHECK(it->second == "2");
|
||||
|
||||
// Re-assigning into the moved-from object must leave it in a usable state.
|
||||
src = nlohmann::ordered_map<std::string, std::string> {};
|
||||
src.emplace("after-move", "3");
|
||||
REQUIRE(src.size() == 1);
|
||||
CHECK(src.begin()->first == "after-move");
|
||||
}
|
||||
|
||||
// Stand-in for a third-party library (e.g., Eigen as of 3.4, which added
|
||||
// STL-compatible begin()/end() to its vector types), living in its own
|
||||
// namespace with its own to_json overload for its vector type.
|
||||
namespace issue_4320_eigen
|
||||
{
|
||||
// "array-compatible" from the library's point of view (it has begin()/end()),
|
||||
// but for which this (fake) third-party namespace provides its own to_json.
|
||||
struct vector3
|
||||
{
|
||||
double v[3]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-use-default-member-init,modernize-use-default-member-init)
|
||||
vector3(double x, double y, double z) : v{x, y, z} {} // NOLINT(hicpp-member-init,cppcoreguidelines-pro-type-member-init)
|
||||
double x() const
|
||||
{
|
||||
return v[0];
|
||||
}
|
||||
double y() const
|
||||
{
|
||||
return v[1];
|
||||
}
|
||||
double z() const
|
||||
{
|
||||
return v[2];
|
||||
}
|
||||
double* begin()
|
||||
{
|
||||
return v;
|
||||
}
|
||||
double* end()
|
||||
{
|
||||
return v + 3;
|
||||
}
|
||||
const double* begin() const
|
||||
{
|
||||
return v;
|
||||
}
|
||||
const double* end() const
|
||||
{
|
||||
return v + 3;
|
||||
}
|
||||
};
|
||||
|
||||
inline void to_json(json& j, const vector3& v) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
j = {{"x", v.x()}, {"y", v.y()}, {"z", v.z()}};
|
||||
}
|
||||
} // namespace issue_4320_eigen
|
||||
|
||||
// The user's own namespace, using the (fake) Eigen type as an implementation
|
||||
// detail behind a payload type that has nothing to do with vectors/arrays.
|
||||
namespace issue_4320
|
||||
{
|
||||
// Publicly derives from issue_4320_eigen::vector3 but does *not* define its
|
||||
// own to_json - it is only ever used as a temporary to reach the base
|
||||
// class's to_json via ADL.
|
||||
struct vector3_wrapper : issue_4320_eigen::vector3
|
||||
{
|
||||
using issue_4320_eigen::vector3::vector3;
|
||||
};
|
||||
|
||||
struct payload
|
||||
{
|
||||
double x, y, z;
|
||||
};
|
||||
|
||||
inline vector3_wrapper to_eigen(const payload& p) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
return {p.x, p.y, p.z};
|
||||
}
|
||||
|
||||
inline void to_json(json& j, const payload& p) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
// Unqualified call, passing a *derived* vector3_wrapper: relies on ADL
|
||||
// finding issue_4320_eigen::to_json(json&, const vector3&) through the
|
||||
// vector3 base class, via a derived-to-base conversion. Must NOT resolve
|
||||
// to the library's own generic array-compatible to_json (an exact-match
|
||||
// template for vector3_wrapper, since it also has begin()/end()), which
|
||||
// would serialize this as [x, y, z] instead of {"x":x, "y":y, "z":z}.
|
||||
to_json(j, to_eigen(p));
|
||||
}
|
||||
} // namespace issue_4320
|
||||
|
||||
TEST_CASE("issue #4320 - custom base class must not leak nlohmann::detail into ADL")
|
||||
{
|
||||
// Before the fix, basic_json unconditionally derived from a type living in
|
||||
// nlohmann::detail (json_default_base), which made nlohmann::detail an
|
||||
// associated namespace of every basic_json for ADL purposes. That leaked
|
||||
// the library's internal generic-array to_json overload into unqualified
|
||||
// to_json() calls made from user code, silently bypassing user-defined
|
||||
// to_json overloads reached via a derived-to-base conversion.
|
||||
const issue_4320::payload p{1.0, 2.0, 3.0};
|
||||
|
||||
json j;
|
||||
to_json(j, p);
|
||||
CHECK(j == json({{"x", 1.0}, {"y", 2.0}, {"z", 3.0}}));
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5338 - truncated CBOR tagged binary subtype is rejected")
|
||||
{
|
||||
const std::vector<std::vector<std::uint8_t>> truncated_tags =
|
||||
{
|
||||
{0xD8},
|
||||
{0xD9, 0x00},
|
||||
{0xDA, 0x00, 0x00, 0x00},
|
||||
{0xDB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
};
|
||||
|
||||
for (const auto& data : truncated_tags)
|
||||
{
|
||||
CAPTURE(data);
|
||||
for (const auto tag_handler :
|
||||
{
|
||||
json::cbor_tag_handler_t::ignore, json::cbor_tag_handler_t::store
|
||||
})
|
||||
{
|
||||
CAPTURE(tag_handler);
|
||||
const auto result = json::from_cbor(data, true, false, tag_handler);
|
||||
CHECK(result.is_discarded());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5402 - update(merge_objects=true) overwrites a primitive with an object")
|
||||
{
|
||||
json t = {{"k", 1}};
|
||||
t.update(json{{"k", {{"x", 2}}}}, true);
|
||||
CHECK(t == json({{"k", {{"x", 2}}}}));
|
||||
|
||||
json mixed = {{"keep", {{"a", 1}}}, {"replace", 1}};
|
||||
mixed.update(json{{"keep", {{"b", 2}}}, {"replace", {{"x", 2}}}}, true);
|
||||
CHECK(mixed == json({{"keep", {{"a", 1}, {"b", 2}}}, {"replace", {{"x", 2}}}}));
|
||||
}
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
|
||||
@@ -0,0 +1,899 @@
|
||||
// __ _____ _____ _____
|
||||
// __| | __| | | | JSON for Modern C++ (supporting code)
|
||||
// | | |__ | | | | | | version 3.12.0
|
||||
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
|
||||
//
|
||||
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// cmake/test.cmake selects the C++ standard versions with which to build a
|
||||
// unit test based on the presence of JSON_HAS_CPP_<VERSION> macros.
|
||||
// When using macros that are only defined for particular versions of the standard
|
||||
// (e.g., JSON_HAS_FILESYSTEM for C++17 and up), please mention the corresponding
|
||||
// version macro in a comment close by, like this:
|
||||
// JSON_HAS_CPP_<VERSION> (do not remove; see note at top of file)
|
||||
|
||||
#include "doctest_compatibility.h"
|
||||
|
||||
// for some reason including this after the json header leads to linker errors with VS 2017...
|
||||
#include <locale>
|
||||
|
||||
#define JSON_TESTS_PRIVATE
|
||||
#include <nlohmann/json.hpp>
|
||||
using json = nlohmann::json;
|
||||
using ordered_json = nlohmann::ordered_json;
|
||||
#ifdef JSON_TEST_NO_GLOBAL_UDLS
|
||||
using namespace nlohmann::literals; // NOLINT(google-build-using-namespace)
|
||||
#endif
|
||||
|
||||
#include <cstdio>
|
||||
#include <list>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#include <any>
|
||||
#include <variant>
|
||||
#endif
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#if __has_include(<optional>)
|
||||
#include <optional>
|
||||
#elif __has_include(<experimental/optional>)
|
||||
#endif
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #4804
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
using json_4804 = nlohmann::basic_json<std::map, // ObjectType
|
||||
std::vector, // ArrayType
|
||||
std::string, // StringType
|
||||
bool, // BooleanType
|
||||
std::int64_t, // NumberIntegerType
|
||||
std::uint64_t, // NumberUnsignedType
|
||||
double, // NumberFloatType
|
||||
std::allocator, // AllocatorType
|
||||
nlohmann::adl_serializer, // JSONSerializer
|
||||
std::vector<std::byte>, // BinaryType
|
||||
void // CustomBaseClass
|
||||
>;
|
||||
#endif
|
||||
|
||||
#ifdef JSON_HAS_CPP_20
|
||||
#if __has_include(<span>)
|
||||
#include <span>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #4825 - explicitly instantiating basic_json must compile; this
|
||||
// forces instantiation of binary_writer::write_bjdata_ndarray, whose
|
||||
// static_cast<string_t> was ambiguous under explicit instantiation on
|
||||
// C++17. Merely compiling this translation unit is the regression test.
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
template class nlohmann::basic_json<>;
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #4440
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
#if JSON_HAS_RANGES == 1
|
||||
#include <ranges>
|
||||
#endif
|
||||
|
||||
// NLOHMANN_JSON_SERIALIZE_ENUM uses a static std::pair
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3077
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
class FooAlloc
|
||||
{};
|
||||
|
||||
class Foo
|
||||
{
|
||||
public:
|
||||
explicit Foo(const FooAlloc& /* unused */ = FooAlloc()) {}
|
||||
|
||||
bool value = false;
|
||||
};
|
||||
|
||||
class FooBar
|
||||
{
|
||||
public:
|
||||
Foo foo{}; // NOLINT(readability-redundant-member-init)
|
||||
};
|
||||
|
||||
inline void from_json(const nlohmann::json& j, FooBar& fb) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
j.at("value").get_to(fb.foo.value);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3171
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct for_3171_base // NOLINT(cppcoreguidelines-special-member-functions)
|
||||
{
|
||||
for_3171_base(const std::string& /*unused*/ = {}) {}
|
||||
virtual ~for_3171_base();
|
||||
|
||||
for_3171_base(const for_3171_base& other) // NOLINT(hicpp-use-equals-default,modernize-use-equals-default)
|
||||
: str(other.str)
|
||||
{}
|
||||
|
||||
for_3171_base& operator=(const for_3171_base& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
str = other.str;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
for_3171_base(for_3171_base&& other) noexcept
|
||||
: str(std::move(other.str))
|
||||
{}
|
||||
|
||||
for_3171_base& operator=(for_3171_base&& other) noexcept
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
str = std::move(other.str);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
virtual void _from_json(const json& j)
|
||||
{
|
||||
j.at("str").get_to(str);
|
||||
}
|
||||
|
||||
std::string str{}; // NOLINT(readability-redundant-member-init)
|
||||
};
|
||||
|
||||
for_3171_base::~for_3171_base() = default;
|
||||
|
||||
struct for_3171_derived : public for_3171_base
|
||||
{
|
||||
for_3171_derived() = default;
|
||||
~for_3171_derived() override;
|
||||
explicit for_3171_derived(const std::string& /*unused*/) { }
|
||||
|
||||
for_3171_derived(const for_3171_derived& other) // NOLINT(hicpp-use-equals-default,modernize-use-equals-default)
|
||||
: for_3171_base(other)
|
||||
{}
|
||||
|
||||
for_3171_derived& operator=(const for_3171_derived& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
for_3171_base::operator=(other); // Call base class assignment operator
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
for_3171_derived(for_3171_derived&& other) noexcept
|
||||
: for_3171_base(std::move(other))
|
||||
{}
|
||||
|
||||
for_3171_derived& operator=(for_3171_derived&& other) noexcept
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
for_3171_base::operator=(std::move(other)); // Call base class move assignment operator
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
|
||||
for_3171_derived::~for_3171_derived() = default;
|
||||
|
||||
inline void from_json(const json& j, for_3171_base& tb) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
tb._from_json(j);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3312
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifdef JSON_HAS_CPP_20
|
||||
struct for_3312
|
||||
{
|
||||
std::string name;
|
||||
};
|
||||
|
||||
inline void from_json(const json& j, for_3312& obj) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
j.at("name").get_to(obj.name);
|
||||
}
|
||||
#endif
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3204
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct for_3204_foo
|
||||
{
|
||||
for_3204_foo() = default;
|
||||
explicit for_3204_foo(std::string /*unused*/) {} // NOLINT(performance-unnecessary-value-param)
|
||||
};
|
||||
|
||||
struct for_3204_bar
|
||||
{
|
||||
enum constructed_from_t // NOLINT(cppcoreguidelines-use-enum-class)
|
||||
{
|
||||
constructed_from_none = 0,
|
||||
constructed_from_foo = 1,
|
||||
constructed_from_json = 2
|
||||
};
|
||||
|
||||
explicit for_3204_bar(std::function<void(for_3204_foo)> /*unused*/) noexcept // NOLINT(performance-unnecessary-value-param)
|
||||
: constructed_from(constructed_from_foo) {}
|
||||
explicit for_3204_bar(std::function<void(json)> /*unused*/) noexcept // NOLINT(performance-unnecessary-value-param)
|
||||
: constructed_from(constructed_from_json) {}
|
||||
|
||||
constructed_from_t constructed_from = constructed_from_none;
|
||||
};
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3333
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct for_3333 final
|
||||
{
|
||||
for_3333(int x_ = 0, int y_ = 0) : x(x_), y(y_) {}
|
||||
|
||||
template <class T>
|
||||
for_3333(const T& /*unused*/)
|
||||
{
|
||||
CHECK(false);
|
||||
}
|
||||
|
||||
int x = 0;
|
||||
int y = 0;
|
||||
};
|
||||
|
||||
template <>
|
||||
inline for_3333::for_3333(const json& j)
|
||||
: for_3333(j.value("x", 0), j.value("y", 0))
|
||||
{}
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #3810
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
struct Example_3810
|
||||
{
|
||||
int bla{};
|
||||
|
||||
Example_3810() = default;
|
||||
};
|
||||
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Example_3810, bla) // NOLINT(misc-use-internal-linkage)
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// for #4740
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
struct Example_4740
|
||||
{
|
||||
std::optional<std::string> host = std::nullopt;
|
||||
std::optional<int> port = std::nullopt;
|
||||
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Example_4740, host, port)
|
||||
};
|
||||
#endif
|
||||
|
||||
TEST_CASE("regression tests 3")
|
||||
{
|
||||
#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
|
||||
// JSON_HAS_CPP_17 (do not remove; see note at top of file)
|
||||
SECTION("issue #3070 - Version 3.10.3 breaks backward-compatibility with 3.10.2 ")
|
||||
{
|
||||
nlohmann::detail::std_fs::path text_path("/tmp/text.txt");
|
||||
const json j(text_path);
|
||||
|
||||
const auto j_path = j.get<nlohmann::detail::std_fs::path>();
|
||||
CHECK(j_path == text_path);
|
||||
|
||||
#if DOCTEST_CLANG || DOCTEST_GCC >= DOCTEST_COMPILER(8, 4, 0)
|
||||
// only known to work on Clang and GCC >=8.4
|
||||
CHECK_THROWS_WITH_AS(nlohmann::detail::std_fs::path(json(1)), "[json.exception.type_error.302] type must be string, but is number", json::type_error);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("issue #3077 - explicit constructor with default does not compile")
|
||||
{
|
||||
json j;
|
||||
j[0]["value"] = true;
|
||||
std::vector<FooBar> foo;
|
||||
j.get_to(foo);
|
||||
}
|
||||
|
||||
SECTION("issue #3108 - ordered_json doesn't support range based erase")
|
||||
{
|
||||
ordered_json j = {1, 2, 2, 4};
|
||||
|
||||
auto last = std::unique(j.begin(), j.end());
|
||||
j.erase(last, j.end());
|
||||
|
||||
CHECK(j.dump() == "[1,2,4]");
|
||||
|
||||
j.erase(std::remove_if(j.begin(), j.end(), [](const ordered_json & val)
|
||||
{
|
||||
return val == 2;
|
||||
}), j.end());
|
||||
|
||||
CHECK(j.dump() == "[1,4]");
|
||||
}
|
||||
|
||||
SECTION("issue #3343 - json and ordered_json are not interchangeable")
|
||||
{
|
||||
json::object_t jobj({ { "product", "one" } });
|
||||
ordered_json::object_t ojobj({{"product", "one"}});
|
||||
|
||||
auto jit = jobj.begin();
|
||||
auto ojit = ojobj.begin();
|
||||
|
||||
CHECK(jit->first == ojit->first);
|
||||
CHECK(jit->second.get<std::string>() == ojit->second.get<std::string>());
|
||||
}
|
||||
|
||||
SECTION("issue #3171 - if class is_constructible from std::string wrong from_json overload is being selected, compilation failed")
|
||||
{
|
||||
const json j{{ "str", "value"}};
|
||||
|
||||
// failed with: error: no match for ‘operator=’ (operand types are ‘for_3171_derived’ and ‘const nlohmann::basic_json<>::string_t’
|
||||
// {aka ‘const std::__cxx11::basic_string<char>’})
|
||||
// s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
|
||||
auto td = j.get<for_3171_derived>();
|
||||
|
||||
CHECK(td.str == "value");
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_20
|
||||
SECTION("issue #3312 - Parse to custom class from unordered_json breaks on G++11.2.0 with C++20")
|
||||
{
|
||||
// see test for #3171
|
||||
const ordered_json j = {{"name", "class"}};
|
||||
for_3312 obj{};
|
||||
|
||||
j.get_to(obj);
|
||||
|
||||
CHECK(obj.name == "class");
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(JSON_HAS_CPP_17) && JSON_USE_IMPLICIT_CONVERSIONS
|
||||
SECTION("issue #3428 - Error occurred when converting nlohmann::json to std::any")
|
||||
{
|
||||
const json j;
|
||||
const std::any a1 = j;
|
||||
std::any&& a2 = j;
|
||||
|
||||
CHECK(a1.type() == typeid(j));
|
||||
CHECK(a2.type() == typeid(j));
|
||||
}
|
||||
#endif
|
||||
|
||||
SECTION("issue #3204 - ambiguous regression")
|
||||
{
|
||||
const for_3204_bar bar_from_foo([](for_3204_foo) noexcept {}); // NOLINT(performance-unnecessary-value-param)
|
||||
const for_3204_bar bar_from_json([](json) noexcept {}); // NOLINT(performance-unnecessary-value-param)
|
||||
|
||||
CHECK(bar_from_foo.constructed_from == for_3204_bar::constructed_from_foo);
|
||||
CHECK(bar_from_json.constructed_from == for_3204_bar::constructed_from_json);
|
||||
}
|
||||
|
||||
SECTION("issue #3333 - Ambiguous conversion from nlohmann::basic_json<> to custom class")
|
||||
{
|
||||
const json j
|
||||
{
|
||||
{"x", 1},
|
||||
{"y", 2}
|
||||
};
|
||||
const for_3333 p = j;
|
||||
|
||||
CHECK(p.x == 1);
|
||||
CHECK(p.y == 2);
|
||||
}
|
||||
|
||||
SECTION("issue #3810 - ordered_json doesn't support construction from C array of custom type")
|
||||
{
|
||||
Example_3810 states[45]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
||||
|
||||
// fix "not used" warning
|
||||
states[0].bla = 1;
|
||||
|
||||
const auto* const expected = R"([{"bla":1},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0},{"bla":0}])";
|
||||
|
||||
// This works:
|
||||
nlohmann::json j;
|
||||
j["test"] = states;
|
||||
CHECK(j["test"].dump() == expected);
|
||||
|
||||
// This doesn't compile:
|
||||
nlohmann::ordered_json oj;
|
||||
oj["test"] = states;
|
||||
CHECK(oj["test"].dump() == expected);
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
SECTION("issue #4740 - build issue with std::optional")
|
||||
{
|
||||
const auto t1 = Example_4740();
|
||||
const auto j1 = nlohmann::json(t1);
|
||||
CHECK(j1.dump() == "{\"host\":null,\"port\":null}");
|
||||
const auto t2 = j1.get<Example_4740>();
|
||||
CHECK(!t2.host.has_value());
|
||||
CHECK(!t2.port.has_value());
|
||||
|
||||
// improve coverage
|
||||
auto t3 = Example_4740();
|
||||
t3.port = 80;
|
||||
t3.host = "example.com";
|
||||
const auto j2 = nlohmann::json(t3);
|
||||
CHECK(j2.dump() == "{\"host\":\"example.com\",\"port\":80}");
|
||||
const auto t4 = j2.get<Example_4740>();
|
||||
CHECK(t4.host.has_value());
|
||||
CHECK(t4.port.has_value());
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !defined(_MSVC_LANG)
|
||||
// MSVC returns garbage on invalid enum values, so this test is excluded
|
||||
// there.
|
||||
SECTION("issue #4762 - json exception 302 with unhelpful explanation : type must be number, but is number")
|
||||
{
|
||||
// In #4762, the main issue was that a json object with an invalid type
|
||||
// returned "number" as type_name(), because this was the default case.
|
||||
// This test makes sure we now return "invalid" instead.
|
||||
json j;
|
||||
j.m_data.m_type = static_cast<json::value_t>(100); // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange)
|
||||
CHECK(j.type_name() == "invalid");
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
SECTION("issue #4804: from_cbor incompatible with std::vector<std::byte> as binary_t")
|
||||
{
|
||||
const std::vector<std::uint8_t> data = {0x80};
|
||||
const auto decoded = json_4804::from_cbor(data);
|
||||
CHECK((decoded == json_4804::array()));
|
||||
}
|
||||
|
||||
SECTION("discussion #4209 - custom BinaryType direct assignment and round-tripping")
|
||||
{
|
||||
// Test that assigning a custom BinaryType directly creates a binary value, not an array
|
||||
const std::vector<std::byte> original{std::byte{1}, std::byte{2}, std::byte{3}};
|
||||
const json_4804 j = original;
|
||||
CHECK(j.is_binary());
|
||||
CHECK(!j.is_array());
|
||||
|
||||
// Test round-tripping: extracting the binary value back as the custom container type
|
||||
const auto extracted = j.get<std::vector<std::byte>>();
|
||||
CHECK(extracted == original);
|
||||
|
||||
// Test that the default json alias behavior is unchanged: std::vector<uint8_t> -> array
|
||||
const json default_json = std::vector<std::uint8_t> {1, 2, 3};
|
||||
CHECK(default_json.is_array());
|
||||
CHECK(!default_json.is_binary());
|
||||
}
|
||||
|
||||
SECTION("discussion #4209 - custom BinaryType extraction from parsed array")
|
||||
{
|
||||
// Test that extracting a custom BinaryType from a parsed JSON array still works
|
||||
// (not just from a binary-typed node)
|
||||
const auto j = json_4804::parse("[1,2,3]");
|
||||
CHECK(j.is_array());
|
||||
CHECK(!j.is_binary());
|
||||
|
||||
// Extracting as custom BinaryType should work from arrays
|
||||
const auto extracted = j.get<std::vector<std::byte>>();
|
||||
CHECK(extracted.size() == 3);
|
||||
CHECK(extracted[0] == std::byte{1});
|
||||
CHECK(extracted[1] == std::byte{2});
|
||||
CHECK(extracted[2] == std::byte{3});
|
||||
}
|
||||
|
||||
SECTION("issue #5046 - implicit conversion of return json to std::optional no longer implicit")
|
||||
{
|
||||
const json jval{};
|
||||
auto GetValue = [](const json & valRoot) -> std::optional<json>
|
||||
{
|
||||
if (valRoot.contains("default"))
|
||||
{
|
||||
return valRoot.at("default");
|
||||
}
|
||||
return std::nullopt;
|
||||
};
|
||||
auto result = GetValue(jval);
|
||||
CHECK(!result.has_value());
|
||||
}
|
||||
#endif
|
||||
|
||||
#if JSON_HAS_RANGES == 1
|
||||
SECTION("issue #4440 - assert when using std::views::filter and GCC 10")
|
||||
{
|
||||
auto noOpFilter = std::views::filter([](auto&&) noexcept
|
||||
{
|
||||
return true;
|
||||
});
|
||||
json j = {1, 2, 3};
|
||||
auto filtered = j | noOpFilter;
|
||||
CHECK(*filtered.begin() == 1);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||
SECTION("issue #4916 - constructing array from C++20 ranges view does not work")
|
||||
{
|
||||
std::vector<int> nums{1, 2, 37, 42, 21};
|
||||
auto filteredNums = nums | std::views::filter([](int i)
|
||||
{
|
||||
return i > 10;
|
||||
});
|
||||
json const j(filteredNums);
|
||||
CHECK(j.type() == json::value_t::array);
|
||||
CHECK(j == json({37, 42, 21}));
|
||||
}
|
||||
#endif
|
||||
|
||||
// owning_view is not available in libstdc++ < 12
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__) && !(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)
|
||||
{
|
||||
return i > 10;
|
||||
}));
|
||||
CHECK(j.type() == json::value_t::array);
|
||||
CHECK(j == json({37, 42, 21}));
|
||||
}
|
||||
#endif
|
||||
|
||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||
SECTION("issue #4916 - constructing array from C++20 transform view (prvalue elements)")
|
||||
{
|
||||
std::vector<int> nums{1, 2, 3};
|
||||
auto t = nums | std::views::transform([](int i) noexcept
|
||||
{
|
||||
return i * 2;
|
||||
});
|
||||
json const j(t);
|
||||
CHECK(j.type() == json::value_t::array);
|
||||
CHECK(j == json({2, 4, 6}));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_CASE_TEMPLATE("issue #4798 - nlohmann::json::to_msgpack() encode float NaN as double", T, double, float) // NOLINT(readability-math-missing-parentheses, bugprone-throwing-static-initialization)
|
||||
{
|
||||
// With issue #4798, we encode NaN, infinity, and -infinity as float instead
|
||||
// of double to allow for smaller encodings.
|
||||
const json jx = std::numeric_limits<T>::quiet_NaN();
|
||||
const json jy = std::numeric_limits<T>::infinity();
|
||||
const json jz = -std::numeric_limits<T>::infinity();
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// MessagePack
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// expected MessagePack values
|
||||
const std::vector<std::uint8_t> msgpack_x = {{0xCA, 0x7F, 0xC0, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> msgpack_y = {{0xCA, 0x7F, 0x80, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> msgpack_z = {{0xCA, 0xFF, 0x80, 0x00, 0x00}};
|
||||
|
||||
CHECK(json::to_msgpack(jx) == msgpack_x);
|
||||
CHECK(json::to_msgpack(jy) == msgpack_y);
|
||||
CHECK(json::to_msgpack(jz) == msgpack_z);
|
||||
|
||||
CHECK(std::isnan(json::from_msgpack(msgpack_x).get<T>()));
|
||||
CHECK(json::from_msgpack(msgpack_y).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_msgpack(msgpack_z).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
|
||||
// Make sure the other MessagePakc encodings for NaN, infinity, and
|
||||
// -infinity are still supported.
|
||||
const std::vector<std::uint8_t> msgpack_x_2 = {{0xCB, 0x7F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> msgpack_y_2 = {{0xCB, 0x7F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> msgpack_z_2 = {{0xCB, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
CHECK(std::isnan(json::from_msgpack(msgpack_x_2).get<T>()));
|
||||
CHECK(json::from_msgpack(msgpack_y_2).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_msgpack(msgpack_z_2).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// CBOR
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// expected CBOR values
|
||||
const std::vector<std::uint8_t> cbor_x = {{0xF9, 0x7E, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_y = {{0xF9, 0x7C, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_z = {{0xF9, 0xfC, 0x00}};
|
||||
|
||||
CHECK(json::to_cbor(jx) == cbor_x);
|
||||
CHECK(json::to_cbor(jy) == cbor_y);
|
||||
CHECK(json::to_cbor(jz) == cbor_z);
|
||||
|
||||
CHECK(std::isnan(json::from_cbor(cbor_x).get<T>()));
|
||||
CHECK(json::from_cbor(cbor_y).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_cbor(cbor_z).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
|
||||
// Make sure the other CBOR encodings for NaN, infinity, and -infinity are
|
||||
// still supported.
|
||||
const std::vector<std::uint8_t> cbor_x_2 = {{0xFA, 0x7F, 0xC0, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_y_2 = {{0xFA, 0x7F, 0x80, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_z_2 = {{0xFA, 0xFF, 0x80, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_x_3 = {{0xFB, 0x7F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_y_3 = {{0xFB, 0x7F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
const std::vector<std::uint8_t> cbor_z_3 = {{0xFB, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
|
||||
CHECK(std::isnan(json::from_cbor(cbor_x_2).get<T>()));
|
||||
CHECK(json::from_cbor(cbor_y_2).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_cbor(cbor_z_2).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
CHECK(std::isnan(json::from_cbor(cbor_x_3).get<T>()));
|
||||
CHECK(json::from_cbor(cbor_y_3).get<T>() == std::numeric_limits<T>::infinity());
|
||||
CHECK(json::from_cbor(cbor_z_3).get<T>() == -std::numeric_limits<T>::infinity());
|
||||
}
|
||||
|
||||
TEST_CASE("regression test #5074 - portable workaround for single-element brace init")
|
||||
{
|
||||
json const j_obj = {{"key", "value"}};
|
||||
|
||||
json const j = json::array({j_obj});
|
||||
CHECK(j.is_array());
|
||||
CHECK(j.size() == 1);
|
||||
CHECK(j[0] == j_obj);
|
||||
}
|
||||
|
||||
#if defined(JSON_BRACE_INIT_COPY_SEMANTICS) && (JSON_BRACE_INIT_COPY_SEMANTICS == 1)
|
||||
TEST_CASE("regression test #5074 - single-element brace init with JSON_BRACE_INIT_COPY_SEMANTICS")
|
||||
{
|
||||
// with JSON_BRACE_INIT_COPY_SEMANTICS: single-element brace init copies/moves
|
||||
json const j_obj = {{"key", "value"}, {"num", 42}};
|
||||
json const j_arr = {1, 2, 3};
|
||||
|
||||
// object: brace init copies instead of wrapping
|
||||
json const j1{j_obj};
|
||||
CHECK(j1.is_object());
|
||||
CHECK(j1 == j_obj);
|
||||
|
||||
// array: brace init copies instead of wrapping
|
||||
json const j2{j_arr};
|
||||
CHECK(j2.is_array());
|
||||
CHECK(j2.size() == 3);
|
||||
CHECK(j2 == j_arr);
|
||||
|
||||
// primitives still work as initializer lists
|
||||
json const j3{true};
|
||||
CHECK(j3.is_boolean());
|
||||
|
||||
json const j4{42};
|
||||
CHECK(j4.is_number_integer());
|
||||
}
|
||||
#endif
|
||||
|
||||
struct Example_5122
|
||||
{
|
||||
float b = 2;
|
||||
nlohmann::ordered_map<std::string, std::string> c{}; // NOLINT(readability-redundant-member-init): needed for GCC -Weffc++
|
||||
int a = 1;
|
||||
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Example_5122, b, c, a)
|
||||
};
|
||||
|
||||
TEST_CASE("regression test #5122 - from_json into types holding nlohmann::ordered_map")
|
||||
{
|
||||
Example_5122 src;
|
||||
src.c.emplace("first", "1");
|
||||
src.c.emplace("second", "2");
|
||||
|
||||
ordered_json const j = src;
|
||||
Example_5122 const dst = j.get<Example_5122>();
|
||||
|
||||
CHECK(dst.b == src.b);
|
||||
CHECK(dst.a == src.a);
|
||||
REQUIRE(dst.c.size() == src.c.size());
|
||||
auto src_it = src.c.begin();
|
||||
auto dst_it = dst.c.begin();
|
||||
for (; src_it != src.c.end(); ++src_it, ++dst_it)
|
||||
{
|
||||
CHECK(dst_it->first == src_it->first);
|
||||
CHECK(dst_it->second == src_it->second);
|
||||
}
|
||||
}
|
||||
|
||||
// -Wself-assign-overloaded was introduced in Clang 7. Gate the pragma on
|
||||
// __has_warning so older Clang versions do not error with "unknown warning
|
||||
// group". The __has_warning check has to stay inside the __clang__ branch
|
||||
// because GCC does not provide it and would tokenize-error on the argument.
|
||||
#if defined(__clang__) && defined(__has_warning)
|
||||
#if __has_warning("-Wself-assign-overloaded")
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING("-Wself-assign-overloaded")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
TEST_CASE("regression test #5122 - nlohmann::ordered_map copy-assignment is self-assignment safe")
|
||||
{
|
||||
nlohmann::ordered_map<std::string, std::string> m;
|
||||
m.emplace("first", "1");
|
||||
m.emplace("second", "2");
|
||||
|
||||
// Insertion order is preserved by ordered_map, so we can check it directly.
|
||||
m = m;
|
||||
|
||||
REQUIRE(m.size() == 2);
|
||||
auto it = m.begin();
|
||||
CHECK(it->first == "first");
|
||||
CHECK(it->second == "1");
|
||||
++it;
|
||||
CHECK(it->first == "second");
|
||||
CHECK(it->second == "2");
|
||||
}
|
||||
|
||||
#if defined(__clang__) && defined(__has_warning)
|
||||
#if __has_warning("-Wself-assign-overloaded")
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
#endif
|
||||
#endif
|
||||
|
||||
TEST_CASE("regression test #5122 - nlohmann::ordered_map move-assignment transfers contents")
|
||||
{
|
||||
nlohmann::ordered_map<std::string, std::string> src;
|
||||
src.emplace("first", "1");
|
||||
src.emplace("second", "2");
|
||||
|
||||
nlohmann::ordered_map<std::string, std::string> dst;
|
||||
dst.emplace("stale", "x");
|
||||
dst = std::move(src);
|
||||
|
||||
REQUIRE(dst.size() == 2);
|
||||
auto it = dst.begin();
|
||||
CHECK(it->first == "first");
|
||||
CHECK(it->second == "1");
|
||||
++it;
|
||||
CHECK(it->first == "second");
|
||||
CHECK(it->second == "2");
|
||||
|
||||
// Re-assigning into the moved-from object must leave it in a usable state.
|
||||
src = nlohmann::ordered_map<std::string, std::string> {};
|
||||
src.emplace("after-move", "3");
|
||||
REQUIRE(src.size() == 1);
|
||||
CHECK(src.begin()->first == "after-move");
|
||||
}
|
||||
|
||||
// Stand-in for a third-party library (e.g., Eigen as of 3.4, which added
|
||||
// STL-compatible begin()/end() to its vector types), living in its own
|
||||
// namespace with its own to_json overload for its vector type.
|
||||
namespace issue_4320_eigen
|
||||
{
|
||||
// "array-compatible" from the library's point of view (it has begin()/end()),
|
||||
// but for which this (fake) third-party namespace provides its own to_json.
|
||||
struct vector3
|
||||
{
|
||||
double v[3]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-use-default-member-init,modernize-use-default-member-init)
|
||||
vector3(double x, double y, double z) : v{x, y, z} {} // NOLINT(hicpp-member-init,cppcoreguidelines-pro-type-member-init)
|
||||
double x() const
|
||||
{
|
||||
return v[0];
|
||||
}
|
||||
double y() const
|
||||
{
|
||||
return v[1];
|
||||
}
|
||||
double z() const
|
||||
{
|
||||
return v[2];
|
||||
}
|
||||
double* begin()
|
||||
{
|
||||
return v;
|
||||
}
|
||||
double* end()
|
||||
{
|
||||
return v + 3;
|
||||
}
|
||||
const double* begin() const
|
||||
{
|
||||
return v;
|
||||
}
|
||||
const double* end() const
|
||||
{
|
||||
return v + 3;
|
||||
}
|
||||
};
|
||||
|
||||
inline void to_json(json& j, const vector3& v) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
j = {{"x", v.x()}, {"y", v.y()}, {"z", v.z()}};
|
||||
}
|
||||
} // namespace issue_4320_eigen
|
||||
|
||||
// The user's own namespace, using the (fake) Eigen type as an implementation
|
||||
// detail behind a payload type that has nothing to do with vectors/arrays.
|
||||
namespace issue_4320
|
||||
{
|
||||
// Publicly derives from issue_4320_eigen::vector3 but does *not* define its
|
||||
// own to_json - it is only ever used as a temporary to reach the base
|
||||
// class's to_json via ADL.
|
||||
struct vector3_wrapper : issue_4320_eigen::vector3
|
||||
{
|
||||
using issue_4320_eigen::vector3::vector3;
|
||||
};
|
||||
|
||||
struct payload
|
||||
{
|
||||
double x, y, z;
|
||||
};
|
||||
|
||||
inline vector3_wrapper to_eigen(const payload& p) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
return {p.x, p.y, p.z};
|
||||
}
|
||||
|
||||
inline void to_json(json& j, const payload& p) // NOLINT(misc-use-internal-linkage)
|
||||
{
|
||||
// Unqualified call, passing a *derived* vector3_wrapper: relies on ADL
|
||||
// finding issue_4320_eigen::to_json(json&, const vector3&) through the
|
||||
// vector3 base class, via a derived-to-base conversion. Must NOT resolve
|
||||
// to the library's own generic array-compatible to_json (an exact-match
|
||||
// template for vector3_wrapper, since it also has begin()/end()), which
|
||||
// would serialize this as [x, y, z] instead of {"x":x, "y":y, "z":z}.
|
||||
to_json(j, to_eigen(p));
|
||||
}
|
||||
} // namespace issue_4320
|
||||
|
||||
TEST_CASE("issue #4320 - custom base class must not leak nlohmann::detail into ADL")
|
||||
{
|
||||
// Before the fix, basic_json unconditionally derived from a type living in
|
||||
// nlohmann::detail (json_default_base), which made nlohmann::detail an
|
||||
// associated namespace of every basic_json for ADL purposes. That leaked
|
||||
// the library's internal generic-array to_json overload into unqualified
|
||||
// to_json() calls made from user code, silently bypassing user-defined
|
||||
// to_json overloads reached via a derived-to-base conversion.
|
||||
const issue_4320::payload p{1.0, 2.0, 3.0};
|
||||
|
||||
json j;
|
||||
to_json(j, p);
|
||||
CHECK(j == json({{"x", 1.0}, {"y", 2.0}, {"z", 3.0}}));
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5338 - truncated CBOR tagged binary subtype is rejected")
|
||||
{
|
||||
const std::vector<std::vector<std::uint8_t>> truncated_tags =
|
||||
{
|
||||
{0xD8},
|
||||
{0xD9, 0x00},
|
||||
{0xDA, 0x00, 0x00, 0x00},
|
||||
{0xDB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
};
|
||||
|
||||
for (const auto& data : truncated_tags)
|
||||
{
|
||||
CAPTURE(data);
|
||||
for (const auto tag_handler :
|
||||
{
|
||||
json::cbor_tag_handler_t::ignore, json::cbor_tag_handler_t::store
|
||||
})
|
||||
{
|
||||
CAPTURE(tag_handler);
|
||||
const auto result = json::from_cbor(data, true, false, tag_handler);
|
||||
CHECK(result.is_discarded());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("issue #5402 - update(merge_objects=true) overwrites a primitive with an object")
|
||||
{
|
||||
json t = {{"k", 1}};
|
||||
t.update(json{{"k", {{"x", 2}}}}, true);
|
||||
CHECK(t == json({{"k", {{"x", 2}}}}));
|
||||
|
||||
json mixed = {{"keep", {{"a", 1}}}, {"replace", 1}};
|
||||
mixed.update(json{{"keep", {{"b", 2}}}, {"replace", {{"x", 2}}}}, true);
|
||||
CHECK(mixed == json({{"keep", {{"a", 1}, {"b", 2}}}, {"replace", {{"x", 2}}}}));
|
||||
}
|
||||
|
||||
|
||||
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||
@@ -52,23 +52,6 @@ TEST_CASE("std::formatter<nlohmann::json>")
|
||||
CHECK(std::format("{:2}", j) == j.dump(2));
|
||||
CHECK(std::format("{:#2}", j) == j.dump(2));
|
||||
CHECK(std::format("{:8}", j) == j.dump(8));
|
||||
// multi-digit widths must accumulate every digit, not just the first
|
||||
CHECK(std::format("{:12}", j) == j.dump(12));
|
||||
CHECK(std::format("{:#12}", j) == j.dump(12));
|
||||
CHECK(std::format("{:10}", j) == j.dump(10));
|
||||
}
|
||||
|
||||
SECTION("bare alignment with no fill character defaults to a space indent character")
|
||||
{
|
||||
const json j = {{"foo", 1}, {"bar", {1, 2, 3}}};
|
||||
// without a preceding fill character, the alignment character itself must not
|
||||
// be mistaken for the indent character -- the default space is kept
|
||||
CHECK(std::format("{:<}", j) == j.dump());
|
||||
CHECK(std::format("{:>}", j) == j.dump());
|
||||
CHECK(std::format("{:^}", j) == j.dump());
|
||||
CHECK(std::format("{:<3}", j) == j.dump(3, ' '));
|
||||
CHECK(std::format("{:>3}", j) == j.dump(3, ' '));
|
||||
CHECK(std::format("{:^3}", j) == j.dump(3, ' '));
|
||||
}
|
||||
|
||||
SECTION("fill-and-align sets the indent character, like dump(indent, indent_char)")
|
||||
|
||||
@@ -2149,6 +2149,172 @@ TEST_CASE("UBJSON")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("UBJSON nesting does not consume the call stack")
|
||||
{
|
||||
// Containers used to be read by calling back into the value reader once
|
||||
// per element, so the native call stack grew with the nesting depth of the
|
||||
// input. '[' alone opens a container, so a payload of repeated '[' crashed
|
||||
// the process (#5104), as did the optimized forms, which reach the same
|
||||
// path through a type or size annotation. The containers are kept on a
|
||||
// heap stack now.
|
||||
//
|
||||
// Deeply nested values must not be compared, copied or dumped here: those
|
||||
// operations are still recursive and would reintroduce the crash.
|
||||
json _;
|
||||
|
||||
SECTION("containers that end at a marker")
|
||||
{
|
||||
const std::vector<uint8_t> input(500000, '[');
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_ubjson(input), "[json.exception.parse_error.110] parse error at byte 500001: syntax error while parsing UBJSON value: unexpected end of input", json::parse_error&);
|
||||
CHECK(json::from_ubjson(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("containers with a size")
|
||||
{
|
||||
std::vector<uint8_t> input;
|
||||
for (std::size_t i = 0; i < 100000; ++i)
|
||||
{
|
||||
input.push_back('[');
|
||||
input.push_back('#');
|
||||
input.push_back('i');
|
||||
input.push_back(1);
|
||||
}
|
||||
CHECK_THROWS_AS(_ = json::from_ubjson(input), json::parse_error&);
|
||||
CHECK(json::from_ubjson(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("containers with a type and a size")
|
||||
{
|
||||
// '[' is a permitted optimized type in UBJSON, so each element of such
|
||||
// a container is itself a container, read without a marker of its own
|
||||
std::vector<uint8_t> input;
|
||||
for (std::size_t i = 0; i < 100000; ++i)
|
||||
{
|
||||
const std::vector<uint8_t> level = {'[', '$', '[', '#', 'i', 1};
|
||||
input.insert(input.end(), level.begin(), level.end());
|
||||
}
|
||||
CHECK_THROWS_AS(_ = json::from_ubjson(input), json::parse_error&);
|
||||
CHECK(json::from_ubjson(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("a well-formed deep value is read through the SAX interface")
|
||||
{
|
||||
std::vector<uint8_t> input(100000, '[');
|
||||
input.insert(input.end(), 100000, ']');
|
||||
|
||||
SaxCountdown accept_all(1000000);
|
||||
CHECK(json::sax_parse(input, &accept_all, json::input_format_t::ubjson));
|
||||
}
|
||||
|
||||
SECTION("a well-formed deep value is read into a value")
|
||||
{
|
||||
const std::size_t depth = 10000;
|
||||
std::vector<uint8_t> input(depth, '[');
|
||||
input.insert(input.end(), depth, ']');
|
||||
|
||||
json j = json::from_ubjson(input);
|
||||
|
||||
std::size_t measured = 0;
|
||||
const json* p = &j;
|
||||
while (p->is_array() && !p->empty())
|
||||
{
|
||||
p = &p->front();
|
||||
++measured;
|
||||
}
|
||||
// the innermost array is empty, so the descent stops one level short
|
||||
CHECK(measured == depth - 1);
|
||||
}
|
||||
|
||||
SECTION("containers are still read the same way")
|
||||
{
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', ']'})) == json::array());
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'{', '}'})) == json::object());
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '#', 'i', 0})) == json::array());
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'{', '#', 'i', 0})) == json::object());
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '$', 'i', '#', 'i', 2, 1, 2})) == json({1, 2}));
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '#', 'i', 2, 'i', 1, 'i', 2})) == json({1, 2}));
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'{', '$', 'i', '#', 'i', 1, 'i', 1, 'a', 1})) == json({{"a", 1}}));
|
||||
// a no-op is not a value, so a container of them holds none
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '$', 'N', '#', 'i', 2})) == json::array());
|
||||
// sized and unsized forms nested inside one another
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '[', '#', 'i', 2, 'i', 1, 'i', 2, ']'})) == json({{1, 2}}));
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '#', 'i', 1, '[', 'i', 1, ']'})) == json({{1}}));
|
||||
// an optimized container of containers
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '$', '[', '#', 'i', 2, 'i', 1, ']', 'i', 2, ']'})) == json({{1}, {2}}));
|
||||
}
|
||||
|
||||
SECTION("BJData containers are still read the same way")
|
||||
{
|
||||
// the ND-array wrapper and the binary shortcut are complete values,
|
||||
// not containers the reader descends into
|
||||
CHECK(json::from_bjdata(std::vector<uint8_t>({'[', '$', 'U', '#', '[', '$', 'i', '#', 'i', 2, 2, 3, 1, 2, 3, 4, 5, 6})) ==
|
||||
json({{"_ArrayType_", "uint8"}, {"_ArraySize_", {2, 3}}, {"_ArrayData_", {1, 2, 3, 4, 5, 6}}}));
|
||||
CHECK(json::from_bjdata(std::vector<uint8_t>({'[', '$', 'i', '#', 'i', 2, 1, 2})) == json({1, 2}));
|
||||
CHECK(json::from_bjdata(std::vector<uint8_t>({'[', '[', 'i', 1, ']', ']'})) == json({{1}}));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("UBJSON optimized arrays of a valueless type are bounded")
|
||||
{
|
||||
// An element of type 'Z', 'T' or 'F' is encoded by its marker alone, so an
|
||||
// optimized array of one of those has no payload and the declared count is
|
||||
// the only thing deciding how much is allocated. Ten bytes used to produce
|
||||
// billions of values (#2793); every other type costs at least one byte per
|
||||
// element and is bounded by the end of the input.
|
||||
json _;
|
||||
|
||||
SECTION("an excessive count is rejected")
|
||||
{
|
||||
// 'l' is a big-endian int32: 0x7FFFFFFF elements, about 34 GB of value
|
||||
for (const auto marker :
|
||||
{'Z', 'T', 'F'
|
||||
})
|
||||
{
|
||||
const std::vector<uint8_t> input = {'[', '$', static_cast<uint8_t>(marker), '#', 'l', 0x7F, 0xFF, 0xFF, 0xFF};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_ubjson(input), "[json.exception.out_of_range.408] syntax error while parsing UBJSON size: excessive array size", json::out_of_range&);
|
||||
CHECK(json::from_ubjson(input, true, false).is_discarded());
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("ordinary counts are unaffected")
|
||||
{
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '$', 'Z', '#', 'i', 3})) == json({nullptr, nullptr, nullptr}));
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '$', 'T', '#', 'i', 2})) == json({true, true}));
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '$', 'F', '#', 'i', 2})) == json({false, false}));
|
||||
// 'N' is a no-op rather than a value, and still yields an empty array
|
||||
CHECK(json::from_ubjson(std::vector<uint8_t>({'[', '$', 'N', '#', 'i', 2})) == json::array());
|
||||
}
|
||||
|
||||
SECTION("a type with a payload is unaffected")
|
||||
{
|
||||
// A count past the limit is not rejected for 'U', which costs a byte
|
||||
// per element and is bounded by the end of the input instead. The
|
||||
// count is kept just past the limit rather than made huge, because a
|
||||
// count that also exceeds the array's max_size() is reported as
|
||||
// out_of_range before the input runs out, and max_size() depends on
|
||||
// the width of std::size_t.
|
||||
const std::vector<uint8_t> input = {'[', '$', 'U', '#', 'l', 0x00, 0x10, 0x00, 0x01};
|
||||
CHECK_THROWS_WITH_AS(_ = json::from_ubjson(input), "[json.exception.parse_error.110] parse error at byte 10: syntax error while parsing UBJSON number: unexpected end of input", json::parse_error&);
|
||||
CHECK(json::from_ubjson(input, true, false).is_discarded());
|
||||
}
|
||||
|
||||
SECTION("the writer stays within what the reader accepts")
|
||||
{
|
||||
// below the limit the optimized form is used and is tiny; above it the
|
||||
// writer falls back so that the result can still be read back
|
||||
json const at_limit(1048576, nullptr);
|
||||
const auto v_at_limit = json::to_ubjson(at_limit, true, true);
|
||||
CHECK(v_at_limit.size() == 9);
|
||||
CHECK(v_at_limit.at(1) == '$');
|
||||
CHECK(json::from_ubjson(v_at_limit) == at_limit);
|
||||
|
||||
json const above_limit(1048577, nullptr);
|
||||
const auto v_above_limit = json::to_ubjson(above_limit, true, true);
|
||||
CHECK(v_above_limit.at(1) != '$');
|
||||
CHECK(json::from_ubjson(v_above_limit) == above_limit);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Universal Binary JSON Specification Examples 1")
|
||||
{
|
||||
SECTION("Null Value")
|
||||
|
||||
Reference in New Issue
Block a user