mirror of
https://github.com/nlohmann/json.git
synced 2026-10-01 04:00:31 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
023ab67ecc |
@@ -62,6 +62,7 @@ By default, `#!cpp JSON_NO_AUTOMATIC_UDLS` is not defined, and `<nlohmann/json.h
|
||||
- [`operator""_json`](../operator_literal_json.md)
|
||||
- [`operator""_json_pointer`](../operator_literal_json_pointer.md)
|
||||
- [`JSON_USE_GLOBAL_UDLS`](json_use_global_udls.md) - place user-defined string literals (UDLs) into the global namespace
|
||||
- [Compile times](../../integration/compile_times.md) - options to reduce compile times
|
||||
|
||||
## Version history
|
||||
|
||||
|
||||
@@ -18,10 +18,6 @@ Deserializes an input stream to a JSON value.
|
||||
|
||||
the stream `i`
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in `j`.
|
||||
|
||||
## Exceptions
|
||||
|
||||
- Throws [`parse_error.101`](../home/exceptions.md#jsonexceptionparse_error101) in case of an unexpected token, or if
|
||||
@@ -129,5 +125,3 @@ being read.
|
||||
the stream; planned to become the default in version 4.0.0.
|
||||
- Fixed a null pointer dereference for an `std::istream` without a stream buffer (now throws `parse_error.101`), and a
|
||||
crash (`std::terminate`) when `i` has `eofbit` in its exception mask, in version 3.13.0.
|
||||
- Changed to the strong exception safety guarantee in version 3.13.0: `j` is no longer left with a partially parsed
|
||||
value if parsing throws.
|
||||
|
||||
@@ -389,7 +389,6 @@ using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
|
||||
| Functionality | Additional requirement |
|
||||
|-----------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| [`diff`](../../api/basic_json/diff.md), [`items`](../../api/basic_json/items.md), [`std::hash`](../../api/basic_json/std_hash.md) | conversion of a `#!cpp std::size_t` to `StringType`: either assignability from the result of `#!cpp std::to_string`, or an ADL overload `#!cpp void int_to_string(StringType&, std::size_t)` |
|
||||
| [`operator/(std::size_t)`](../../api/json_pointer/operator_slash.md) | the same conversion of a `#!cpp std::size_t` to `StringType` as `diff`, `items`, and `std::hash` above |
|
||||
| [`std::hash<basic_json>`](../../api/basic_json/std_hash.md) | additionally a specialization of `#!cpp std::hash<StringType>` |
|
||||
| [`to_bson`](../../api/basic_json/to_bson.md) | `find(value_type)` and `npos` |
|
||||
| [`parse`](../../api/basic_json/parse.md) from a `string_t` | the input adapters must accept it; otherwise pass a character range |
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
# Compile times
|
||||
|
||||
The library is header-only and makes heavy use of templates, so every translation unit that includes
|
||||
`<nlohmann/json.hpp>` pays for parsing the header and instantiating what it uses. This page lists the options to reduce
|
||||
that cost, ordered by how much they typically save.
|
||||
|
||||
!!! info "Measurements"
|
||||
|
||||
The numbers below are medians of nine runs compiling a single translation unit with `-std=c++17 -c` against the
|
||||
single-header version, with Apple clang and GCC 16 on macOS (Apple silicon). They show the order of magnitude to
|
||||
expect; measure your own code before and after a change.
|
||||
|
||||
## Include `json_fwd.hpp` in headers
|
||||
|
||||
Header files that only need to *name* the `json` type — for function declarations, members held by pointer or
|
||||
reference, or friend declarations — can include `<nlohmann/json_fwd.hpp>` instead of `<nlohmann/json.hpp>`. It only
|
||||
forward-declares `basic_json`, `json`, `ordered_json`, `json_pointer`, and `adl_serializer`. The translation units that
|
||||
actually use the values then include `<nlohmann/json.hpp>`.
|
||||
|
||||
```cpp title="person.hpp"
|
||||
#pragma once
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
|
||||
struct person;
|
||||
void to_json(nlohmann::json& j, const person& p);
|
||||
void from_json(const nlohmann::json& j, person& p);
|
||||
```
|
||||
|
||||
```cpp title="person.cpp"
|
||||
#include "person.hpp"
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
void to_json(nlohmann::json& j, const person& p) { /* ... */ }
|
||||
void from_json(const nlohmann::json& j, person& p) { /* ... */ }
|
||||
```
|
||||
|
||||
| Compiler | `json.hpp` (`-O0`) | `json_fwd.hpp` (`-O0`) | Change |
|
||||
|-------------|-------------------:|-----------------------:|-------:|
|
||||
| Apple clang | 704 ms | 329 ms | −53% |
|
||||
| GCC 16 | 779 ms | 242 ms | −69% |
|
||||
|
||||
This is the most effective option, because it avoids the full header in every translation unit that includes
|
||||
*your* headers.
|
||||
|
||||
## Opt out of the automatic user-defined string literals
|
||||
|
||||
The user-defined string literals [`operator""_json`](../api/operator_literal_json.md) and
|
||||
[`operator""_json_pointer`](../api/operator_literal_json_pointer.md) are ordinary inline functions whose bodies call the
|
||||
parser. As `<nlohmann/json.hpp>` includes them by default, every translation unit instantiates the parser, even if it
|
||||
never parses anything itself.
|
||||
|
||||
Define [`JSON_NO_AUTOMATIC_UDLS`](../api/macros/json_no_automatic_udls.md) for the whole project and include
|
||||
`<nlohmann/json_literals.hpp>` only in the files that use the literals:
|
||||
|
||||
```cmake
|
||||
target_compile_definitions(my_target PRIVATE JSON_NO_AUTOMATIC_UDLS)
|
||||
```
|
||||
|
||||
```cpp
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <nlohmann/json_literals.hpp> // only where "..."_json is used
|
||||
```
|
||||
|
||||
The saving applies to translation units that do not parse JSON, for example ones that define types and their
|
||||
conversions or only pass `json` values around:
|
||||
|
||||
| Compiler | Translation unit | Default (`-O0` / `-O2`) | `JSON_NO_AUTOMATIC_UDLS` (`-O0` / `-O2`) | Change |
|
||||
|-------------|------------------|------------------------:|-----------------------------------------:|------------:|
|
||||
| Apple clang | model | 776 ms / 846 ms | 629 ms / 692 ms | −19% / −18% |
|
||||
| GCC 16 | model | 1022 ms / 1120 ms | 882 ms / 965 ms | −14% / −14% |
|
||||
| Apple clang | parsing | 992 ms / 1815 ms | 1006 ms / 1823 ms | +1% / 0% |
|
||||
| GCC 16 | parsing | 2018 ms / 3420 ms | 1990 ms / 3454 ms | −1% / +1% |
|
||||
|
||||
Translation units that include only the header save up to a third. Translation units that parse anyway instantiate
|
||||
the parser regardless and see no difference.
|
||||
|
||||
## Instantiate `basic_json` once
|
||||
|
||||
Each translation unit instantiates the member functions of `nlohmann::json` it uses. An explicit instantiation
|
||||
declaration tells the compiler that the non-template members are instantiated elsewhere, so it can skip them:
|
||||
|
||||
```cpp title="json_instance.hpp"
|
||||
#pragma once
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
extern template class nlohmann::basic_json<>;
|
||||
```
|
||||
|
||||
```cpp title="json_instance.cpp"
|
||||
#include "json_instance.hpp"
|
||||
|
||||
template class nlohmann::basic_json<>;
|
||||
```
|
||||
|
||||
Include `json_instance.hpp` instead of `<nlohmann/json.hpp>` and compile and link `json_instance.cpp` once.
|
||||
|
||||
| Compiler | Translation unit | Default (`-O0` / `-O2`) | `extern template` (`-O0` / `-O2`) | Change |
|
||||
|-------------|---------------------|------------------------:|----------------------------------:|------------:|
|
||||
| Apple clang | parsing | 992 ms / 1815 ms | 953 ms / 1625 ms | −4% / −10% |
|
||||
| GCC 16 | parsing | 2018 ms / 3420 ms | 1522 ms / 2728 ms | −25% / −20% |
|
||||
| Apple clang | `json_instance.cpp` | — | 2166 ms / 4660 ms | — |
|
||||
| GCC 16 | `json_instance.cpp` | — | 5085 ms / 10616 ms | — |
|
||||
|
||||
Notes:
|
||||
|
||||
- The saving grows with the number of translation units that use `json`, while the instantiation translation unit is
|
||||
compiled only once (and is rarely recompiled, as it does not depend on your code).
|
||||
- Member function templates (such as `get<T>()`, `parse(InputType&&)`, or `value(key, default)`) are not covered by
|
||||
the explicit instantiation and are still instantiated where they are used.
|
||||
- The declaration covers exactly `nlohmann::json`. Add the same lines for `nlohmann::ordered_json`
|
||||
(`nlohmann::basic_json<nlohmann::ordered_map>`) or your own `basic_json` specializations if you use them.
|
||||
|
||||
## Use C++20 modules
|
||||
|
||||
With a toolchain that supports named modules, `import nlohmann.json;` compiles the library once into a module and
|
||||
avoids parsing the header in every translation unit. See [Modules](../features/modules.md) for requirements and known
|
||||
issues. Module support is experimental and currently depends heavily on the compiler version.
|
||||
|
||||
## Use precompiled headers
|
||||
|
||||
Build systems can precompile `<nlohmann/json.hpp>` together with other stable headers, for example with CMake's
|
||||
[`target_precompile_headers`](https://cmake.org/cmake/help/latest/command/target_precompile_headers.html):
|
||||
|
||||
```cmake
|
||||
target_precompile_headers(my_target PRIVATE <nlohmann/json.hpp>)
|
||||
```
|
||||
|
||||
This removes the cost of parsing the header, but not of instantiating templates in each translation unit, so it
|
||||
combines well with the options above.
|
||||
|
||||
## Options without effect on compile times
|
||||
|
||||
Some configuration macros change what the library declares, but do not measurably change compile times:
|
||||
|
||||
| Macro | Apple clang, model (`-O0` / `-O2`) | GCC 16, model (`-O0` / `-O2`) |
|
||||
|------------------------------------------------------------------------|-----------------------------------:|------------------------------:|
|
||||
| default | 776 ms / 846 ms | 1022 ms / 1120 ms |
|
||||
| [`JSON_NO_IO`](../api/macros/json_no_io.md) | 764 ms / 836 ms | 1022 ms / 1117 ms |
|
||||
| [`JSON_USE_GLOBAL_UDLS`](../api/macros/json_use_global_udls.md)`=0` | 763 ms / 852 ms | 1019 ms / 1106 ms |
|
||||
|
||||
`JSON_USE_GLOBAL_UDLS` only controls *where* the literals are declared; to avoid their cost, use
|
||||
`JSON_NO_AUTOMATIC_UDLS` instead.
|
||||
|
||||
## See also
|
||||
|
||||
- [`JSON_NO_AUTOMATIC_UDLS`](../api/macros/json_no_automatic_udls.md) - do not include the user-defined string
|
||||
literals automatically
|
||||
- [Modules](../features/modules.md) - C++20 module support
|
||||
- [Header only](index.md) - including the library
|
||||
@@ -15,7 +15,7 @@ Clang).
|
||||
|
||||
You can further use file
|
||||
[`single_include/nlohmann/json_fwd.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/json_fwd.hpp)
|
||||
for forward declarations, and file
|
||||
for forward declarations (see [Compile times](compile_times.md)), and file
|
||||
[`single_include/nlohmann/json_literals.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/json_literals.hpp)
|
||||
for the user-defined string literals if you define
|
||||
[`JSON_NO_AUTOMATIC_UDLS`](../api/macros/json_no_automatic_udls.md).
|
||||
|
||||
@@ -106,6 +106,7 @@ nav:
|
||||
- integration/cmake.md
|
||||
- integration/package_managers.md
|
||||
- integration/pkg-config.md
|
||||
- integration/compile_times.md
|
||||
- API Documentation:
|
||||
- basic_json:
|
||||
- 'Overview': api/basic_json/index.md
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
#include <nlohmann/detail/macro_scope.hpp>
|
||||
#include <nlohmann/detail/string_concat.hpp>
|
||||
#include <nlohmann/detail/string_escape.hpp>
|
||||
#include <nlohmann/detail/string_utils.hpp>
|
||||
#include <nlohmann/detail/value_t.hpp>
|
||||
|
||||
NLOHMANN_JSON_NAMESPACE_BEGIN
|
||||
@@ -117,7 +116,7 @@ class json_pointer
|
||||
/// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
|
||||
json_pointer& operator/=(std::size_t array_idx)
|
||||
{
|
||||
return *this /= detail::to_string<string_t>(array_idx);
|
||||
return *this /= std::to_string(array_idx);
|
||||
}
|
||||
|
||||
/// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
|
||||
@@ -753,7 +752,7 @@ class json_pointer
|
||||
// would throw out_of_range.404 -- contains() must not throw (see #5395)
|
||||
return false;
|
||||
}
|
||||
if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !('0' <= reference_token[0] && reference_token[0] <= '9')))
|
||||
if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
|
||||
{
|
||||
// invalid char
|
||||
return false;
|
||||
@@ -781,7 +780,7 @@ class json_pointer
|
||||
// not throw (see #5395), so such a reference token is treated as "not found"
|
||||
errno = 0; // strtoull() does not reset errno on success
|
||||
char* p_end = nullptr; // NOLINT(misc-const-correctness)
|
||||
const unsigned long long magnitude = std::strtoull(reference_token.data(), &p_end, 10); // NOLINT(runtime/int)
|
||||
const unsigned long long magnitude = std::strtoull(reference_token.c_str(), &p_end, 10); // NOLINT(runtime/int)
|
||||
if (JSON_HEDLEY_UNLIKELY(errno == ERANGE // the value exceeds ULLONG_MAX
|
||||
|| magnitude >= static_cast<unsigned long long>((std::numeric_limits<typename BasicJsonType::size_type>::max)()))) // NOLINT(runtime/int)
|
||||
{
|
||||
|
||||
@@ -189,37 +189,6 @@ struct actual_object_comparator
|
||||
template<typename BasicJsonType>
|
||||
using actual_object_comparator_t = typename actual_object_comparator<BasicJsonType>::type;
|
||||
|
||||
template<typename T>
|
||||
using detect_key_comp = decltype(std::declval<const T&>().key_comp());
|
||||
|
||||
// whether ObjectType can be constructed from a pair of Iterator together with
|
||||
// a copy of its own comparator, the way std::map can: it needs a nested
|
||||
// key_compare, a const key_comp() convertible to it, and a matching
|
||||
// (Iterator, Iterator, const key_compare&) constructor.
|
||||
//
|
||||
// used to preserve a stateful comparator when a copy is built from a range
|
||||
// past the iterative deep copy's nesting bound (see copy_object_level); an
|
||||
// object type that does not satisfy this, such as nlohmann::ordered_map
|
||||
// (which has key_compare for its std::map-like interface, but no key_comp()),
|
||||
// keeps default-constructing its comparator, just as it always has
|
||||
template<typename ObjectType, typename Iterator, typename = void>
|
||||
struct is_comparator_constructible_object_type_impl : std::false_type {};
|
||||
|
||||
template<typename ObjectType, typename Iterator>
|
||||
struct is_comparator_constructible_object_type_impl <
|
||||
ObjectType, Iterator, enable_if_t<is_detected<detect_key_compare, ObjectType>::value >>
|
||||
{
|
||||
using key_compare = typename ObjectType::key_compare;
|
||||
|
||||
static constexpr bool value =
|
||||
is_detected_convertible<key_compare, detect_key_comp, ObjectType>::value &&
|
||||
std::is_constructible<ObjectType, Iterator, Iterator, const key_compare&>::value;
|
||||
};
|
||||
|
||||
template<typename ObjectType, typename Iterator>
|
||||
struct is_comparator_constructible_object_type
|
||||
: is_comparator_constructible_object_type_impl<ObjectType, Iterator> {};
|
||||
|
||||
/////////////////
|
||||
// char_traits //
|
||||
/////////////////
|
||||
|
||||
@@ -1127,27 +1127,6 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief create the object type from a range, preserving @a src_object's
|
||||
/// comparator when the object type supports it
|
||||
/// Enabled for object types that provide a key_comp() and a matching
|
||||
/// range-plus-comparator constructor, such as std::map. Other object
|
||||
/// types, such as nlohmann::ordered_map, fall back to the plain range
|
||||
/// constructor and default-construct their comparator, just as they
|
||||
/// always have (@ref detail::is_comparator_constructible_object_type).
|
||||
template<typename Iterator, detail::enable_if_t<
|
||||
detail::is_comparator_constructible_object_type<object_t, Iterator>::value, int> = 0>
|
||||
static object_t* create_object_with_comparator(const object_t& src_object, Iterator first, Iterator last)
|
||||
{
|
||||
return create<object_t>(first, last, src_object.key_comp());
|
||||
}
|
||||
|
||||
template<typename Iterator, detail::enable_if_t<
|
||||
detail::negation<detail::is_comparator_constructible_object_type<object_t, Iterator>>::value, int> = 0>
|
||||
static object_t* create_object_with_comparator(const object_t& /*src_object*/, Iterator first, Iterator last)
|
||||
{
|
||||
return create<object_t>(first, last);
|
||||
}
|
||||
|
||||
/// @brief create the copy of the object @a src in @a dst
|
||||
/// @note structured values are appended to @a worklist instead
|
||||
static void copy_object_level(const basic_json& src, basic_json& dst,
|
||||
@@ -1165,8 +1144,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
scratch.emplace_back(element.first, basic_json());
|
||||
}
|
||||
|
||||
dst.m_data.m_value.object = create_object_with_comparator(src_object,
|
||||
std::make_move_iterator(scratch.begin()),
|
||||
dst.m_data.m_value.object = create<object_t>(std::make_move_iterator(scratch.begin()),
|
||||
std::make_move_iterator(scratch.end()));
|
||||
// only now that the object exists may dst stop being a null value
|
||||
dst.m_data.m_type = value_t::object;
|
||||
@@ -5114,10 +5092,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
|
||||
friend std::istream& operator>>(std::istream& i, basic_json& j)
|
||||
{
|
||||
// parse into a temporary so that j is left unchanged if parsing fails
|
||||
basic_json result;
|
||||
parser(detail::input_adapter(i)).parse(false, result);
|
||||
j = std::move(result);
|
||||
parser(detail::input_adapter(i)).parse(false, j);
|
||||
return i;
|
||||
}
|
||||
#endif // JSON_NO_IO
|
||||
|
||||
@@ -4197,37 +4197,6 @@ struct actual_object_comparator
|
||||
template<typename BasicJsonType>
|
||||
using actual_object_comparator_t = typename actual_object_comparator<BasicJsonType>::type;
|
||||
|
||||
template<typename T>
|
||||
using detect_key_comp = decltype(std::declval<const T&>().key_comp());
|
||||
|
||||
// whether ObjectType can be constructed from a pair of Iterator together with
|
||||
// a copy of its own comparator, the way std::map can: it needs a nested
|
||||
// key_compare, a const key_comp() convertible to it, and a matching
|
||||
// (Iterator, Iterator, const key_compare&) constructor.
|
||||
//
|
||||
// used to preserve a stateful comparator when a copy is built from a range
|
||||
// past the iterative deep copy's nesting bound (see copy_object_level); an
|
||||
// object type that does not satisfy this, such as nlohmann::ordered_map
|
||||
// (which has key_compare for its std::map-like interface, but no key_comp()),
|
||||
// keeps default-constructing its comparator, just as it always has
|
||||
template<typename ObjectType, typename Iterator, typename = void>
|
||||
struct is_comparator_constructible_object_type_impl : std::false_type {};
|
||||
|
||||
template<typename ObjectType, typename Iterator>
|
||||
struct is_comparator_constructible_object_type_impl <
|
||||
ObjectType, Iterator, enable_if_t<is_detected<detect_key_compare, ObjectType>::value >>
|
||||
{
|
||||
using key_compare = typename ObjectType::key_compare;
|
||||
|
||||
static constexpr bool value =
|
||||
is_detected_convertible<key_compare, detect_key_comp, ObjectType>::value &&
|
||||
std::is_constructible<ObjectType, Iterator, Iterator, const key_compare&>::value;
|
||||
};
|
||||
|
||||
template<typename ObjectType, typename Iterator>
|
||||
struct is_comparator_constructible_object_type
|
||||
: is_comparator_constructible_object_type_impl<ObjectType, Iterator> {};
|
||||
|
||||
/////////////////
|
||||
// char_traits //
|
||||
/////////////////
|
||||
@@ -19667,8 +19636,6 @@ NLOHMANN_JSON_NAMESPACE_END
|
||||
|
||||
// #include <nlohmann/detail/string_escape.hpp>
|
||||
|
||||
// #include <nlohmann/detail/string_utils.hpp>
|
||||
|
||||
// #include <nlohmann/detail/value_t.hpp>
|
||||
|
||||
|
||||
@@ -19760,7 +19727,7 @@ class json_pointer
|
||||
/// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
|
||||
json_pointer& operator/=(std::size_t array_idx)
|
||||
{
|
||||
return *this /= detail::to_string<string_t>(array_idx);
|
||||
return *this /= std::to_string(array_idx);
|
||||
}
|
||||
|
||||
/// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
|
||||
@@ -20396,7 +20363,7 @@ class json_pointer
|
||||
// would throw out_of_range.404 -- contains() must not throw (see #5395)
|
||||
return false;
|
||||
}
|
||||
if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !('0' <= reference_token[0] && reference_token[0] <= '9')))
|
||||
if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
|
||||
{
|
||||
// invalid char
|
||||
return false;
|
||||
@@ -20424,7 +20391,7 @@ class json_pointer
|
||||
// not throw (see #5395), so such a reference token is treated as "not found"
|
||||
errno = 0; // strtoull() does not reset errno on success
|
||||
char* p_end = nullptr; // NOLINT(misc-const-correctness)
|
||||
const unsigned long long magnitude = std::strtoull(reference_token.data(), &p_end, 10); // NOLINT(runtime/int)
|
||||
const unsigned long long magnitude = std::strtoull(reference_token.c_str(), &p_end, 10); // NOLINT(runtime/int)
|
||||
if (JSON_HEDLEY_UNLIKELY(errno == ERANGE // the value exceeds ULLONG_MAX
|
||||
|| magnitude >= static_cast<unsigned long long>((std::numeric_limits<typename BasicJsonType::size_type>::max)()))) // NOLINT(runtime/int)
|
||||
{
|
||||
@@ -28085,27 +28052,6 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief create the object type from a range, preserving @a src_object's
|
||||
/// comparator when the object type supports it
|
||||
/// Enabled for object types that provide a key_comp() and a matching
|
||||
/// range-plus-comparator constructor, such as std::map. Other object
|
||||
/// types, such as nlohmann::ordered_map, fall back to the plain range
|
||||
/// constructor and default-construct their comparator, just as they
|
||||
/// always have (@ref detail::is_comparator_constructible_object_type).
|
||||
template<typename Iterator, detail::enable_if_t<
|
||||
detail::is_comparator_constructible_object_type<object_t, Iterator>::value, int> = 0>
|
||||
static object_t* create_object_with_comparator(const object_t& src_object, Iterator first, Iterator last)
|
||||
{
|
||||
return create<object_t>(first, last, src_object.key_comp());
|
||||
}
|
||||
|
||||
template<typename Iterator, detail::enable_if_t<
|
||||
detail::negation<detail::is_comparator_constructible_object_type<object_t, Iterator>>::value, int> = 0>
|
||||
static object_t* create_object_with_comparator(const object_t& /*src_object*/, Iterator first, Iterator last)
|
||||
{
|
||||
return create<object_t>(first, last);
|
||||
}
|
||||
|
||||
/// @brief create the copy of the object @a src in @a dst
|
||||
/// @note structured values are appended to @a worklist instead
|
||||
static void copy_object_level(const basic_json& src, basic_json& dst,
|
||||
@@ -28123,8 +28069,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
scratch.emplace_back(element.first, basic_json());
|
||||
}
|
||||
|
||||
dst.m_data.m_value.object = create_object_with_comparator(src_object,
|
||||
std::make_move_iterator(scratch.begin()),
|
||||
dst.m_data.m_value.object = create<object_t>(std::make_move_iterator(scratch.begin()),
|
||||
std::make_move_iterator(scratch.end()));
|
||||
// only now that the object exists may dst stop being a null value
|
||||
dst.m_data.m_type = value_t::object;
|
||||
@@ -32072,10 +32017,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/
|
||||
friend std::istream& operator>>(std::istream& i, basic_json& j)
|
||||
{
|
||||
// parse into a temporary so that j is left unchanged if parsing fails
|
||||
basic_json result;
|
||||
parser(detail::input_adapter(i)).parse(false, result);
|
||||
j = std::move(result);
|
||||
parser(detail::input_adapter(i)).parse(false, j);
|
||||
return i;
|
||||
}
|
||||
#endif // JSON_NO_IO
|
||||
|
||||
@@ -352,41 +352,6 @@ TEST_CASE("alternative string type")
|
||||
CHECK(j2.flatten().unflatten() == j2);
|
||||
}
|
||||
|
||||
SECTION("contains(json_pointer)")
|
||||
{
|
||||
// contains(json_pointer) must compile and work with a string_t that has
|
||||
// no c_str() and no comparison with const char* (see #5666)
|
||||
auto j = alt_json::parse(R"({"foo": ["bar", "baz"]})");
|
||||
|
||||
// present: object key and array indices
|
||||
CHECK(j.contains(alt_json::json_pointer("/foo")));
|
||||
CHECK(j.contains(alt_json::json_pointer("/foo/0")));
|
||||
CHECK(j.contains(alt_json::json_pointer("/foo/1")));
|
||||
|
||||
// missing: absent object key and out-of-range array index
|
||||
CHECK_FALSE(j.contains(alt_json::json_pointer("/bar")));
|
||||
CHECK_FALSE(j.contains(alt_json::json_pointer("/foo/2")));
|
||||
|
||||
// "-" always fails the range check
|
||||
CHECK_FALSE(j.contains(alt_json::json_pointer("/foo/-")));
|
||||
|
||||
// an array index must not have a leading zero
|
||||
CHECK_FALSE(j.contains(alt_json::json_pointer("/foo/01")));
|
||||
|
||||
// a reference token that is not a number
|
||||
CHECK_FALSE(j.contains(alt_json::json_pointer("/foo/bar")));
|
||||
}
|
||||
|
||||
SECTION("operator/(std::size_t)")
|
||||
{
|
||||
// json_pointer::operator/=(std::size_t) must compile without string_t
|
||||
// being constructible from std::string (see #5666)
|
||||
auto j = alt_json::parse(R"({"foo": ["bar", "baz"]})");
|
||||
|
||||
CHECK(j.at(alt_json::json_pointer("/foo") / std::size_t(0)) == j["foo"][0]);
|
||||
CHECK(j.at(alt_json::json_pointer("/foo") / std::size_t(1)) == j["foo"][1]);
|
||||
}
|
||||
|
||||
SECTION("patch")
|
||||
{
|
||||
alt_json const patch1 = alt_json::parse(R"([{ "op": "add", "path": "/a/b", "value": [ "foo", "bar" ] }])");
|
||||
|
||||
@@ -827,46 +827,6 @@ Json nest(Json j, const std::size_t depth)
|
||||
return j;
|
||||
}
|
||||
|
||||
// a std::map comparator with state: case-insensitive, unless constructed
|
||||
// case-sensitive. Used to check that copying an object copies the original's
|
||||
// comparator rather than default-constructing a new one (see #5649).
|
||||
struct key_case_less
|
||||
{
|
||||
key_case_less() = default;
|
||||
explicit key_case_less(const bool cs) noexcept : case_sensitive(cs) {}
|
||||
|
||||
bool operator()(const std::string& a, const std::string& b) const
|
||||
{
|
||||
if (case_sensitive)
|
||||
{
|
||||
return a < b;
|
||||
}
|
||||
return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(),
|
||||
[](unsigned char x, unsigned char y)
|
||||
{
|
||||
return std::tolower(x) < std::tolower(y);
|
||||
});
|
||||
}
|
||||
|
||||
bool case_sensitive = false;
|
||||
};
|
||||
|
||||
template<class Key, class Value, class /*Compare*/, class Allocator>
|
||||
using key_case_map = std::map<Key, Value, key_case_less, Allocator>;
|
||||
using key_case_json = nlohmann::basic_json<key_case_map>;
|
||||
|
||||
// the innermost value of a chain of single-element arrays
|
||||
template<typename Json>
|
||||
const Json& innermost(const Json& j)
|
||||
{
|
||||
const Json* p = &j;
|
||||
while (p->is_array())
|
||||
{
|
||||
p = &(*p)[0];
|
||||
}
|
||||
return *p;
|
||||
}
|
||||
|
||||
// orders keys case-insensitively, so "key" and "KEY" compare equivalent
|
||||
// (neither less than the other) although they are not equal
|
||||
struct case_insensitive_less
|
||||
@@ -931,47 +891,6 @@ TEST_CASE("equality of objects whose entries have no fixed order")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("copying an object preserves its comparator's state")
|
||||
{
|
||||
// Past the iterative deep copy's nesting bound, an object copy used to be
|
||||
// built with a default-constructed comparator instead of a copy of the
|
||||
// original's. For an object type whose comparator carries state - here, a
|
||||
// std::map that compares keys case-sensitively only when created that way
|
||||
// - this reordered the copy's keys and could even drop entries that the
|
||||
// original's comparator kept distinct (see #5649).
|
||||
key_case_json object = key_case_json::object_t(key_case_less(true)); // case-sensitive
|
||||
object["b"] = 1;
|
||||
object["B"] = 2;
|
||||
object["a"] = 3;
|
||||
REQUIRE(object.dump() == R"({"B":2,"a":3,"b":1})");
|
||||
|
||||
for (const std::size_t depth : std::vector<std::size_t> {0, 127, 128, 200})
|
||||
{
|
||||
CAPTURE(depth);
|
||||
|
||||
key_case_json original = object;
|
||||
for (std::size_t i = 0; i < depth; ++i)
|
||||
{
|
||||
original = key_case_json::array({std::move(original)});
|
||||
}
|
||||
|
||||
{
|
||||
const key_case_json copy = original; // NOLINT(performance-unnecessary-copy-initialization)
|
||||
CHECK(innermost(copy).size() == 3);
|
||||
CHECK(innermost(copy).dump() == R"({"B":2,"a":3,"b":1})");
|
||||
CHECK(copy == original);
|
||||
}
|
||||
|
||||
{
|
||||
key_case_json copy = key_case_json::array();
|
||||
copy = original;
|
||||
CHECK(innermost(copy).size() == 3);
|
||||
CHECK(innermost(copy).dump() == R"({"B":2,"a":3,"b":1})");
|
||||
CHECK(copy == original);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("equality of an object whose comparator treats different keys as equivalent")
|
||||
{
|
||||
// https://github.com/nlohmann/json/issues/5655: past the nesting bound,
|
||||
|
||||
@@ -19,7 +19,6 @@ using nlohmann::json;
|
||||
|
||||
#include <map>
|
||||
#include <unordered_map>
|
||||
#include <sstream>
|
||||
|
||||
TEST_CASE("Better diagnostics")
|
||||
{
|
||||
@@ -493,21 +492,6 @@ TEST_CASE("Regression tests for extended diagnostics")
|
||||
CHECK(copy == j);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("Regression test for issue #5652 - operator>> leaves a partial value in its target on a parse error")
|
||||
{
|
||||
json j = "old value";
|
||||
std::istringstream is("[1, x");
|
||||
CHECK_THROWS_WITH_AS(is >> j, "[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid literal; last read: '1, x'", json::parse_error);
|
||||
|
||||
// j must be left unchanged, as json::parse() guarantees for its result
|
||||
CHECK(j == "old value");
|
||||
|
||||
// copying j must not trigger assert_invariant(): a failed parse must
|
||||
// not leave array/object elements without a parent pointer
|
||||
json const copy = j; // NOLINT(performance-unnecessary-copy-initialization)
|
||||
CHECK(copy == j);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Better diagnostics past the descent bound of update() and merge_patch()")
|
||||
|
||||
Reference in New Issue
Block a user