Compare commits

..
33 Commits
Author SHA1 Message Date
Niels Lohmann 109cab33c1 Exclude all json_view test files from Infer's reports
The same std::unique_ptr false positive (USE_AFTER_DELETE) also shows for
two json_documents parsed in one lambda in unit-json_view_dump.cpp
(ci_infer). It affects any test that holds several documents, so the
exclusion now covers tests/src/unit-json_view*.cpp; ASan and Valgrind
cover these tests.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:34:08 +02:00
Niels Lohmann 32a4b0feb3 Regenerate the amalgamated headers
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:06:05 +02:00
Niels Lohmann 7b66cdb9d8 Address the review of json_view dump() and comparisons
From gregmarr's review of #5624:

- The output buffer takes string literals without a length.
- write_float() names the IEEE single/double condition once, as the
  library's serializer does.
- equal() checks the types first and compares with !=; the reference to
  the top frame is noted as dangling after pop_back().
- dump.md: one paragraph per case in the notes.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:06:04 +02:00
Niels Lohmann be59fb2a57 Keep the stream includes of json_view.hpp for IWYU
json_view.hpp uses std::istream and std::ostream itself, but IWYU sees
them through the exported json.hpp and asked to remove both includes,
which fails ci_single_binaries (single_json_view).

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:06:03 +02:00
Niels Lohmann 321965e0ad Follow the renames from the review of the view builder
The review of #5620 renamed document_data's tape/tape_size/tape_cap to
nodes/node_count/node_capacity and made the decode arena a
std::vector<char>; adapt the code of this change to it.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:06:02 +02:00
Niels Lohmann a8cc0a1379 Regenerate the amalgamated headers
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:06:01 +02:00
Niels Lohmann e7eceb7869 Make json_view.hpp pass include-what-you-use
ci_single_binaries runs IWYU with --error on every header. For json_view.hpp
it suggested adding <array> (std::array is used), the headers that json.hpp
already provides (abi_config, abi_macros, input_adapters, json_pointer,
cpp_future, string_concat, value_t, json_fwd), and <version> for
std::nullptr_t, and removing <cstddef>.

- include <array>
- keep <cstddef> (nullptr_t, size_t; IWYU attributes them to <version> and <cstring>)
- tell IWYU not to suggest the headers that json.hpp provides: the amalgamated
  json_view.hpp only includes json.hpp, so including them here would duplicate
  their definitions

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:06:00 +02:00
Niels Lohmann b2fb4dfcbd Split the dump and comparison tests off unit-json_view.cpp
The MinGW linker of the Windows clang jobs cannot link object files with more
than 32767 sections ("relocation truncated to fit: IMAGE_REL_AMD64_REL32
against `.rdata'"). unit-json_view.cpp reaches that limit as the stack
grows, so its "json_view dump" and "json_view comparison" test cases move
into unit-json_view_dump.cpp. The test generator and has_duplicate_keys()
that both files use move into json_view_test_helpers.hpp.

The new file mentions JSON_HAS_CPP_17, so it is built for C++17 like the file
it was split from.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:59 +02:00
Niels Lohmann 32d759564b Fix the clang-tidy 22 findings in json_view and its tests
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:58 +02:00
Niels Lohmann 40503139ea Document and test first-wins lookups next to dump() and ==
dump() writes every member and == resolves duplicate keys as parse()
does, whereas lookups find the first member of a duplicate key.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:58 +02:00
Niels Lohmann 5fc53651cb Do not shrink the output of dump()
finish() copied the whole output when the buffer was more than twice as
large as the result (citm dump +11%). The tighter source_extent()
estimate already keeps the buffer of a small value small.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:57 +02:00
Niels Lohmann 4c31665346 Hold the documents of the dump and comparison tests in names
root() of a temporary document is deleted: its views would dangle.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:56 +02:00
Niels Lohmann ee19cddf3b Size the dump buffer of a small value by its own extent
The source extent of a value was read from the next node, falling back to the rest of the document when that node held a decoded string. dump() of a small value could thus allocate a buffer as large as the document. Skip a few such nodes, cap the fallback estimate, and shrink a buffer that is much larger than its output.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:55 +02:00
Niels Lohmann 809063e9f2 Avoid raw string with escapes inside CHECK macro (MSVC C2017)
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:54 +02:00
Niels Lohmann e3ddc9869e Add dump() and comparisons to json_view
Add basic_json_view::dump() and the comparison operators, and read
floats from the parser's digit layout instead of rescanning the
token.

dump(indent, indent_char, ensure_ascii, number_format) writes a
value the way ordered_json::parse(text).dump() writes it for the
same arguments: members in document order, all of them should a
key occur more than once; strings escaped by the same rules, using
the library's scanning kernels; floats written with the library's
to_chars conversion, so the output equals basic_json's byte for
byte; integers copied from the source, where they are already
canonical, except -0, which parse() reads as 0. There is no
error_handler argument, because the view only holds valid UTF-8.
number_format::source copies numbers exactly as they appear in the
source (e.g. "1.50", "1E2", "-0"), which basic_json cannot provide.
operator<< takes the indentation from the stream width, as for
basic_json. The writer walks iteratively, so nesting depth is
limited by memory only.

operator== and operator!= compare two views, or a view and a
basic_json value in either order, by the rules basic_json's
operator== uses: numbers compare by value across their types,
objects compare by their members with duplicate keys resolved as
parse() resolves them, member order matters only where the object
type keeps one, and discarded views compare as discarded basic_json
values do, including under JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON.
Nothing is materialized except single scalars.

While parsing, the view now records where the integer digits, the
fraction digits, and the exponent of a float token are, so floats
and doubles with at most 19 digits are read from that layout with
the library's decimal_to_float() instead of rescanning the token.
Both round correctly, so the values are those of parse(). get<double>(),
materialize(), dump(), and the comparisons all use it.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:53 +02:00
Niels Lohmann 1b3cb9df75 Regenerate the amalgamated headers
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:52 +02:00
Niels Lohmann 7b755737b4 Address the review of json_view element access
From gregmarr's review of #5622:

- count() counts every member with the key, so count(key) > 1 detects
  duplicate keys; it was contains() as 0/1 before.
- get_to() passes types that get<T>() does not convert directly to
  from_json with the existing value, as basic_json::get_to() does, so that
  a from_json which sets only the fields present keeps the others.
- array_index() checks the empty token and "-" first; the results are
  unchanged.
- Docs: no "if an exception is thrown" where a view never changes
  anything; the borrowed source must also stay unmodified; items() on a
  temporary view is safe; back()/front() notes shortened; the basic_json
  see-also entries say how the view's results can differ.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 10:05:51 +02:00
Niels Lohmann f2582daa62 Report one-character non-numeric array indices like basic_json in the view
Develop's #5800 made basic_json report a JSON pointer array index such as
"/a" as parse_error.109 instead of out_of_range.404, as longer ones were;
the view's array_index() follows, with "-" and the empty token still
unresolved.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:33 +02:00
Niels Lohmann 01f45b844d Regenerate the amalgamated headers
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:32 +02:00
Niels Lohmann 412ef7419a Fix the clang-tidy 22 findings in json_view and its tests
The same changes as on the dump branch, where they were first made, so
that this branch passes clang-tidy on its own.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:31 +02:00
Niels Lohmann a183f99d21 Make json_view.hpp pass include-what-you-use
ci_single_binaries runs IWYU with --error on every header. For json_view.hpp
it suggested adding <array> (std::array is used), the headers that json.hpp
already provides (abi_config, abi_macros, input_adapters, json_pointer,
cpp_future, string_concat, value_t, json_fwd), and <version> for
std::nullptr_t, and removing <cstddef>.

- include <array>
- keep <cstddef> (nullptr_t, size_t; IWYU attributes them to <version> and <cstring>)
- tell IWYU not to suggest the headers that json.hpp provides: the amalgamated
  json_view.hpp only includes json.hpp, so including them here would duplicate
  their definitions

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:31 +02:00
Niels Lohmann 7c4bf1eb0d Avoid GCC useless-cast warnings in the integer index tests
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:30 +02:00
Niels Lohmann 2a6d1f376f Make json_view.hpp pass include-what-you-use
Mark the includes that are needed by design (json.hpp, the macro
unscope, <tuple> for the tuple_size specialization), take size_t from
<cstring>, and drop the forward declaration of basic_json_document that
the friend declaration makes redundant.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:29 +02:00
Niels Lohmann e62fc0ba93 Do not force-inline the view's functions on MSVC
__forceinline makes MSVC report C4714 for function templates it cannot
inline (get<std::string>), an error under /WX. The forced inlining is
only a performance hint, so use plain inline there.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:28 +02:00
Niels Lohmann 9cc0ff977e Return the first member of duplicate keys from lookups again
Looking up the last member of a duplicate key cannot stop at a match, so
every lookup scanned the whole object (1.6 to 3.4 times slower for small
objects). operator[](key), at, find, value, contains, count, and JSON
pointer resolution return the first member again, as yyjson and simdjson
do; materialize() and get<map>() keep the last value, as parse().

The documentation says so in the feature page and on each lookup page,
and explains how to get the value parse() would give. The integer index
templates and the discarded chaining of operator[] stay.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:27 +02:00
Niels Lohmann a1d74c55a7 Test discarded views with is_discarded() in the operator[] docs and examples
The explicit conversion to bool of basic_json_view is gone.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:27 +02:00
Niels Lohmann f60b822476 Use named documents in the json_view tests that called root() on a temporary
root() of an rvalue document is deleted, because the views would dangle.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:26 +02:00
Niels Lohmann 760352de24 Replace the removed operator bool of basic_json_view in the header and its tests
A view is tested with is_discarded(); the lookups in at(), value() and
contains(json_pointer) and the unit tests no longer rely on the explicit
conversion to bool.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:25 +02:00
Niels Lohmann 5948b89182 Make view lookups last-wins and chained access safe
* Lookups (operator[], at, find, contains, count, value, JSON pointers)
  return the last member of a duplicate key, as materialize() and
  parse() keep it.
* operator[] on a discarded view returns a discarded view instead of
  throwing, so v["a"]["b"] is safe for a missing "a".
* operator[] and at() take any integer type (not only int and size_t),
  fixing ambiguous calls with unsigned, long, std::int64_t, ...
* Fix the operator[] documentation, which claimed a discarded view for
  a type mismatch where type_error.305 is thrown.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:24 +02:00
Niels Lohmann 383b27eefc Add element access, iteration, values, and JSON pointers to json_view
Give basic_json_view the read-only access functions of basic_json:
operator[] and at() with keys and indices, front()/back(), find(),
contains(), count(), begin()/end() and cbegin()/cend(), items()
with structured bindings from C++17 on, and type_name().

Exceptions have the ids and messages of the const functions of
basic_json. Where basic_json has undefined behavior the view
answers safely: operator[] with a missing key or an out-of-range
index returns a discarded view, and front()/back() of an empty
container throw invalid_iterator.214. Objects are iterated in
document order, and all members are visited; duplicate-key lookups
find the first member (as yyjson and simdjson do), while parse(),
materialize(), and the map conversions keep the last value, as
parse() does. Keys of up to 16 bytes are compared with two
overlapping loads.

Add value conversions: get<T>()/get_to() for arithmetic types,
bool, nullptr_t, strings (std::basic_string copied,
string_view_t without a copy), BasicJsonType, views, std::vector,
and maps with string keys; get_string() for the string without a
copy; number_token() for the number exactly as written in the
source; value() with keys and JSON pointers; and operator[]/at()/
contains() with JSON pointers. Everything else, including types
with from_json(), goes through materialize() of that subtree.
get<T>() of arithmetic types is inlined down to the conversion, so
reading an integer needs no call.

detail::json_pointer_access exposes a pointer's reference tokens
to code outside basic_json.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:24 +02:00
Niels Lohmann f8895c72a9 Exclude the view builder test from Infer's reports
Infer's std::unique_ptr model confuses the values that the test's build()
helper returns by value and reports USE_AFTER_DELETE for one of them after
the destructor of an unrelated temporary (ci_infer, 12 reports, all in
tests/src/unit-json_view_builder.cpp). AddressSanitizer is clean on the
same tests.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-18 06:23:22 +02:00
Niels Lohmann badbe685a5 Do not copy an empty run into an unallocated arena
memcpy() must not be passed a null pointer even for zero bytes, which
arena_run() did for an empty run while the arena was still empty
(ci_test_clang_sanitizer: "null pointer passed as argument 1" in
builder.hpp). Only the slow path can see such a run.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-17 23:07:04 +02:00
Niels Lohmann a43bad747a Rename emit() in the view builder for Qt compatibility
Qt defines emit as an empty macro, so a Qt header included before
json_view.hpp broke the declaration of the builder's emit(), see
issue #5865. It is now called push_node().

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-17 14:21:09 +02:00
33 changed files with 414 additions and 200 deletions

No files matched your search

+4
View File
@@ -1,6 +1,7 @@
{
"_comment": "Used by the ci_infer CMake target (#5715 item 4b). fail-on-issue makes CI fail on Infer findings; disable-issue-type is a type-level baseline for the ~174 pre-existing findings (all PULSE_UNNECESSARY_COPY*/PULSE_RESOURCE_LEAK/PULSE_CONST_REFABLE, mostly in test code) triaged in run https://github.com/nlohmann/json/actions/runs/35829411620 on commit 1054b2097, so CI fails only on a NEW issue type. Remove an entry here once its findings have been fixed or explicitly accepted.",
"_comment_pulse": "Pulse stops exploring paths after pulse-max-disjuncts (default 20). With the default, basic_json::replace_value() (destroy + assert_invariant) exceeds the limit, Pulse loses the stored type, and reports false NULLPTR_DEREFERENCE findings for get_ptr() results in tests/src/unit-pointer_access.cpp.",
"_comment_view": "Infer's model of std::unique_ptr mixes up values that are returned by value and own one: basic_json_document (parse() results) and the `built` values of the build() helper in tests/src/unit-json_view_builder.cpp. It reports USE_AFTER_DELETE for one of them after the destructor of an unrelated object (e.g. ~built() on line 345 invalidating `shallow` on line 350 of that file, or two documents parsed in one lambda in tests/src/unit-json_view_dump.cpp). AddressSanitizer and Valgrind are clean on the same tests, so reports for the json_view test files are excluded; findings reported in the library headers are still reported.",
"pulse-max-disjuncts": 40,
"fail-on-issue": true,
"disable-issue-type": [
@@ -10,5 +11,8 @@
"PULSE_UNNECESSARY_COPY_OPTIONAL",
"PULSE_RESOURCE_LEAK",
"PULSE_CONST_REFABLE"
],
"report-block-list-path-regex": [
"tests/src/unit-json_view.*\\.cpp"
]
}
+2 -1
View File
@@ -93,7 +93,8 @@ Logarithmic in the size of the JSON object.
- [count](count.md) returns the number of occurrences of a key
- [contains](contains.md) checks whether a key exists
- [basic_json_view::find](../basic_json_view/find.md) - the same lookup on a zero-copy view
- [basic_json_view::find](../basic_json_view/find.md) - the same lookup on a zero-copy view (a duplicate key resolves
to the first member, whereas `parse()` keeps the last)
## Version history
+2 -1
View File
@@ -51,7 +51,8 @@ Constant.
## See also
- [back](back.md) to access the last element
- [basic_json_view::front](../basic_json_view/front.md) - the same access on a zero-copy view
- [basic_json_view::front](../basic_json_view/front.md) - the same access on a zero-copy view (document order, not
sorted; duplicate keys are visited)
## Version history
+1 -1
View File
@@ -100,7 +100,7 @@ When iterating over an array, `key()` will return the index of the element as st
- [begin](begin.md) returns an iterator to the first element
- [end](end.md) returns an iterator to one past the last element
- [basic_json_view::items](../basic_json_view/items.md) - the same range on a zero-copy view (`#!cpp const auto`,
not `#!cpp const auto&`: items are produced on the fly)
not `#!cpp const auto&`: items are produced on the fly; document order, not sorted; duplicate keys are visited)
## Version history
@@ -275,8 +275,9 @@ Strong exception safety: if an exception occurs, the original value stays intact
- documentation on [runtime assertions](../../features/assertions.md)
- see [`at`](at.md) for access by reference with range checking
- see [`value`](value.md) for access with default value
- [basic_json_view::operator[]](../basic_json_view/operator%5B%5D.md) - the same access on a zero-copy view (always
returns a discarded view instead of assuming undefined behavior)
- [basic_json_view::operator[]](../basic_json_view/operator%5B%5D.md) - the same access on a zero-copy view (a duplicate
key resolves to the first member, whereas `parse()` keeps the last; a missing key gives a discarded view instead of
undefined behavior)
## Version history
+1 -1
View File
@@ -41,7 +41,7 @@ basic_json_view at(const json_pointer& ptr) const;
## Exception safety
Strong exception safety: if an exception is thrown, there are no changes to the view or the document it refers to.
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
+2 -3
View File
@@ -13,7 +13,7 @@ The last element or member value. For a primitive value (number, string, boolean
## Exception safety
Strong exception safety: if an exception is thrown, there are no changes to the view or the document it refers to.
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
@@ -33,8 +33,7 @@ index.
## Notes
Unlike [`BasicJsonType::back()`](../basic_json/back.md), which has undefined behavior for an empty array or object,
`back()` throws `invalid_iterator.214` in that case -- the same way it already does for `#!json null` and for a
discarded view, where `BasicJsonType::back()` also throws.
`back()` throws `invalid_iterator.214` for an empty array, an empty object, a null value, or a discarded view.
## Examples
@@ -23,7 +23,7 @@ Constant.
## Notes
For an object, iteration visits **every** member, including all occurrences of a duplicate key -- unlike
[`operator[]`](operator[].md), [`at`](at.md), [`find`](find.md), [`contains`](contains.md), and [`count`](count.md),
[`operator[]`](operator[].md), [`at`](at.md), [`find`](find.md), and [`contains`](contains.md),
which all resolve to the *first* member with a given key. See the
[Notes on duplicate keys](operator[].md#notes) of `operator[]`.
@@ -31,6 +31,10 @@ Because objects are iterated in document order rather than sorted by key, the or
iterating the [`materialize()`](materialize.md)d `BasicJsonType` value would produce: a `#!cpp basic_json` object
(`std::map`-backed by default) sorts its keys, while a view does not.
An `ordered_json` value also keeps document order, but it keeps only one entry per key: as `parse()` does, it keeps the
*last* value, at the position of the key's *first* occurrence. The view, in contrast, visits every member, including
the duplicates.
## Examples
??? example
@@ -53,7 +53,8 @@ view.
!!! info "Postconditions"
If `#!cpp v.contains(key)` returns `#!cpp true`, then `#!cpp v[key]` is not [discarded](is_discarded.md). If
If `#!cpp v.contains(key)` returns `#!cpp true`, then `#!cpp v[key]` is not [discarded](is_discarded.md) and
`#!cpp v.at(key)` does not throw. If
`#!cpp v.contains(ptr)` returns `#!cpp true`, then `#!cpp v[ptr]` is not discarded and `#!cpp v.at(ptr)` does not
throw.
+16 -19
View File
@@ -6,7 +6,8 @@ size_type count(const char* key) const;
size_type count(const string_t& key) const;
```
Returns `#!cpp 1` if the value is an object with a member with key `key`, `#!cpp 0` otherwise.
Returns the number of members with key `key` if the value is an object, `#!cpp 0` otherwise. Members with a repeated
key are all counted.
## Parameters
@@ -15,7 +16,8 @@ Returns `#!cpp 1` if the value is an object with a member with key `key`, `#!cpp
## Return value
`#!cpp 1` if the value is an object and has a member with key `key`, `#!cpp 0` otherwise.
the number of members of the object with key `key` (duplicates included), or `#!cpp 0` if the value is not an object
or has no such member.
## Exception safety
@@ -23,34 +25,29 @@ No-throw guarantee: this function never throws exceptions.
## Complexity
Linear in the number of members: as for [`ordered_json`](../ordered_json.md), members are compared one after another,
in document order, stopping at the first match. Each comparison first checks the key's length
-- already known from the index, without reading the key bytes -- before comparing its content.
Linear in the number of members: unlike the lookup functions, `count()` does not stop at the first match, because it
has to count every member with the key. Members are compared one after another, in document order. Each comparison
first checks the key's length -- already known from the index, without reading the key bytes -- before comparing its
content.
## Notes
!!! warning "Duplicate keys: the first member wins"
If the source text repeats a key, this resolves to the *first* member with it, not to the last one that
[`materialize()`](materialize.md) and `parse()` keep. See the [Notes on duplicate keys](operator[].md#notes) of
`operator[]` and [Duplicate keys](../../features/json_view.md#duplicate-keys) for the reasons and for how to get
the last value.
This method always returns `#!cpp 0` when the value is not an object -- including a [discarded](is_discarded.md)
view.
Unlike [`BasicJsonType::count()`](../basic_json/count.md), whose return value can in principle exceed `#!cpp 1` for
an `ObjectType` that allows multiple entries per key, `count()` here never does: it is exactly
[`contains()`](contains.md) as `#!cpp 0`/`#!cpp 1`. This holds even if the source text has a duplicate key -- see the
[Notes on duplicate keys](operator[].md#notes) of `operator[]` -- because a `#!cpp count() > 1` result would require
counting every member with a matching key (the lookup functions resolve to the *first* one).
If the source text repeats a key, `count()` returns more than `#!cpp 1` for it, even though the
[materialized](materialize.md) value (like the result of `parse()`) would have only one member with that key. Hence
`#!cpp count(key) > 1` detects duplicate keys. This is unlike the lookup functions
([`operator[]`](operator[].md), [`at`](at.md), [`find`](find.md), [`contains`](contains.md)), which resolve to the
*first* member; see the [Notes on duplicate keys](operator[].md#notes) of `operator[]`.
## Examples
??? example
The example below validates that every transaction of a batch carries a mandatory `amount` field, using
`count()` before deciding whether to materialize a transaction at all.
The example below validates that every transaction of a batch carries exactly one `amount` field, using
`count()` before deciding whether to materialize a transaction at all. It reports a transaction with no `amount`
field and one with a duplicated `amount` field.
```cpp
--8<-- "examples/basic_json_view__count.cpp"
+4 -2
View File
@@ -60,11 +60,13 @@ Linear in the size of the output text.
The walk over the subtree is iterative, so the nesting depth it can write is limited by available memory only, not by
the call stack -- as for [`materialize()`](materialize.md).
Strings are escaped by the same rules as [`BasicJsonType::dump`](../basic_json/dump.md). With
`#!cpp numbers == number_format::shortest`, floats are written with the library's shortest round-trip conversion,
Strings are escaped by the same rules as [`BasicJsonType::dump`](../basic_json/dump.md).
With `#!cpp numbers == number_format::shortest`, floats are written with the library's shortest round-trip conversion,
exactly as [`BasicJsonType::dump`](../basic_json/dump.md) would (e.g. `#!cpp 1.5`, `#!cpp 100.0`, `#!cpp 1e+100`), and
integers are copied from the source text -- already canonical in JSON, so this matches their shortest form too --
except that `#!cpp -0` is written as `#!cpp 0`, the way [`BasicJsonType::parse()`](../basic_json/parse.md) reads it.
`#!cpp number_format::source` copies every number exactly as written in the source text instead, with no exception
for `#!cpp -0` -- `#!cpp 1.50`, `#!cpp 1E2`, `#!cpp -0.0`, `#!cpp -0`, or all digits of an integer literal with more
digits than any number type holds (such a literal is itself classified as a float, see
@@ -13,7 +13,7 @@ The first element or member value. For a primitive value (number, string, boolea
## Exception safety
Strong exception safety: if an exception is thrown, there are no changes to the view or the document it refers to.
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
@@ -31,8 +31,8 @@ Constant.
## Notes
Unlike [`BasicJsonType::front()`](../basic_json/front.md), which has undefined behavior for an empty array or
object, `front()` throws `invalid_iterator.214` in that case -- the same way it already does for `#!json null` and
for a discarded view, where `BasicJsonType::front()` also throws.
object, `front()` throws `invalid_iterator.214` for an empty array, an empty object, a null value, or a discarded
view.
## Examples
+10 -7
View File
@@ -10,8 +10,8 @@ Converts the value to `T`.
For the types below, the conversion works directly on the flat index -- no `BasicJsonType` value is built for it:
- `#!cpp bool`
- arithmetic types other than `#!cpp bool` (from a number; from a boolean, as `#!cpp 0`/`#!cpp 1`, exactly as
[`BasicJsonType::get<T>()`](../basic_json/get.md) converts a boolean)
- arithmetic types other than `#!cpp bool` (for a boolean, `#!cpp 0`/`#!cpp 1`, exactly as for
[`BasicJsonType::get<T>()`](../basic_json/get.md))
- `#!cpp std::nullptr_t`
- `#!cpp std::basic_string<char, Traits, Alloc>` (including `string_t`) -- a copy of the string
- [`string_view_t`](index.md#member-types) -- **no copy**: the returned view points into the document's
@@ -19,10 +19,10 @@ For the types below, the conversion works directly on the flat index -- no `Basi
document's own buffer of decoded strings (see [`get_string()`](get_string.md))
- `BasicJsonType` -- equivalent to [`materialize()`](materialize.md)
- `basic_json_view` -- returns `#!cpp *this`
- `#!cpp std::vector<U, A>` -- element by element, each converted with `#!cpp get<U>()`; `#!cpp
- `#!cpp std::vector<U, A>` -- from an array, element by element, each converted with `#!cpp get<U>()`; `#!cpp
std::vector<basic_json_view>` keeps a view of every element instead of a value
- `#!cpp std::map<K, V, C, A>` and `#!cpp std::unordered_map<K, V, H, E, A>`, if `K` is constructible from a `#!cpp
(const char*, std::size_t)` pair -- member by member, each value converted with `#!cpp get<V>()`; with a repeated
(const char*, std::size_t)` pair -- from an object, member by member, each value converted with `#!cpp get<V>()`; with a repeated
key, the *last* value is kept, as [`BasicJsonType::parse()`](../basic_json/parse.md) (and
[`materialize()`](materialize.md)) does; `#!cpp std::map<std::string, basic_json_view>` keeps views of the members
instead of values
@@ -43,7 +43,7 @@ the value, converted to `T`
## Exception safety
Strong exception safety: if an exception is thrown, there are no changes to the view or the document it refers to.
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
@@ -62,6 +62,9 @@ None of the exceptions thrown directly by this function (the first three bullets
[`JSON_DIAGNOSTICS`](../macros/json_diagnostics.md) path: the view has no `BasicJsonType` value to point at. An
exception thrown while converting through `materialize()` (the last bullet) is different: it is thrown by a real
`BasicJsonType` value, so it **does** carry a `JSON_DIAGNOSTICS` path if `BasicJsonType` was built with it enabled.
That path is relative to the root of the view's subtree, because `materialize()` builds only the subtree (with parent
pointers): it is empty if the failing value is the subtree's root itself, and it never is the path within the whole
document.
## Complexity
@@ -73,8 +76,8 @@ exception thrown while converting through `materialize()` (the last bullet) is d
- `#!cpp std::map`/`#!cpp std::unordered_map`: linear in the number of members for walking them, plus the container's
own insertion cost per member (logarithmic for `#!cpp std::map`, amortized constant for `#!cpp
std::unordered_map`), times the complexity of converting one member to the mapped type.
- every other `T`: linear in the size of the subtree (building the `BasicJsonType` value), plus the complexity of
[`BasicJsonType::get<T>()`](../basic_json/get.md) on it.
- every other `T`: the cost of [`materialize()`](materialize.md) and of destroying the `BasicJsonType` value
afterwards, plus that of [`BasicJsonType::get<T>()`](../basic_json/get.md).
## Notes
@@ -15,7 +15,7 @@ had to be decoded once when the document was parsed).
## Exception safety
Strong exception safety: if an exception is thrown, there are no changes to the view or the document it refers to.
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
@@ -37,9 +37,14 @@ hand out a reference to a stored `string_t`. `get_string()` (equivalently, [`get
zero-copy alternative: [`BasicJsonType::get_ref<const string_t&>()`](../basic_json/get_ref.md) is its closest
counterpart, except that it returns a view instead of a reference to a value that must already exist.
`get_string()` borrows the string: nothing is copied, whereas [`get<std::string>()`](get.md) copies it. For a borrowed
document, the returned [`string_view_t`](index.md#member-types) is valid as long as the caller's buffer; for an owned
one, as long as the document.
The returned [`string_view_t`](index.md#member-types) is valid exactly as long as the view that produced it -- see the
[validity rules](index.md) of `basic_json_view` -- and, for a string with no escapes, for as long as the document's
source text.
source text, which for a borrowed document must remain valid **and unmodified** for as long as the document exists,
since floating-point values and unescaped strings are read from the source lazily.
## Examples
+23 -8
View File
@@ -5,12 +5,15 @@ template<typename T>
T& get_to(T& v) const;
```
Converts the value to `T` and assigns it to `v`. Equivalent to
Converts the value to `T` and stores it in `v`, in one of two ways:
```cpp
v = get<T>();
return v;
```
- For the types that [`get<T>()`](get.md) converts directly -- arithmetic types, `#!cpp bool`,
`#!cpp std::nullptr_t`, [`string_view_t`](index.md#member-types), `#!cpp std::basic_string`, `BasicJsonType`,
`basic_json_view`, `#!cpp std::vector`, and `#!cpp std::map`/`#!cpp std::unordered_map` with string keys -- `v` is
assigned: `#!cpp v = get<T>()`.
- For every other type, the subtree is built into a `BasicJsonType` value and `#!cpp materialize().get_to(v)` is
called, i.e. `from_json()` is invoked with the existing `v`, exactly as
[`BasicJsonType::get_to()`](../basic_json/get_to.md) does.
## Template parameters
@@ -28,15 +31,27 @@ return v;
## Exception safety
Strong exception safety: if an exception is thrown, `v` is not modified.
- For the directly converted types: strong exception safety. If an exception is thrown, `v` is not modified.
- For every other type: as for [`BasicJsonType::get_to()`](../basic_json/get_to.md). `materialize()` throws before `v`
is touched, but a `from_json()` that throws may leave `v` partly modified.
## Exceptions
Whatever [`get<T>()`](get.md) throws for the same value and `T`.
- For the directly converted types: whatever [`get<T>()`](get.md) throws for the same value and `T`.
- For every other type: whatever [`materialize()`](materialize.md) and
[`BasicJsonType::get_to()`](../basic_json/get_to.md) throw.
## Complexity
Whatever [`get<T>()`](get.md) has for the same `T`.
- For the directly converted types: whatever [`get<T>()`](get.md) has for the same `T`.
- For every other type: that of [`materialize()`](materialize.md), plus that of
[`BasicJsonType::get_to()`](../basic_json/get_to.md).
## Notes
The difference between the two ways matters for a `from_json()` that sets only the fields present in the JSON: since
it runs on the existing `v`, the other fields of `v` keep their values, whereas assigning `get<T>()` would replace
them with those of a default-constructed `T`.
## Examples
+17 -9
View File
@@ -14,18 +14,27 @@ to the document and a pointer into its index), trivially copyable. A view is val
- the document has not been re-parsed with [`read()`](../basic_json_document/read.md) (or
[`parse()`](../basic_json_document/parse.md) into it) or shrunk with
[`shrink_to_fit()`](../basic_json_document/shrink_to_fit.md) since the view was taken, and
- if the document borrows its source text, that text is still alive.
- if the document borrows its source text, that text is still alive and unmodified (floating-point values and
unescaped strings are read from it lazily).
Moving the document itself does not invalidate its views: the index is heap-allocated independently of the
`basic_json_document` object.
`basic_json_view` provides the read-only part of the `BasicJsonType` interface: the type-inspection functions, element
access, lookup, iteration, conversion, and comparison -- [`get<T>()`](get.md), [`get_string()`](get_string.md),
[`number_token()`](number_token.md), and [`materialize()`](materialize.md) to build the `BasicJsonType` value of a
subtree on demand. [`operator[]`](operator%5B%5D.md), [`at`](at.md), [`contains`](contains.md), and
[`value`](value.md) also accept a [`json_pointer`](../json_pointer/index.md). [`operator==`](operator_eq.md) and
[`operator!=`](operator_ne.md) compare two views, or a view and a `BasicJsonType` value, without ever building a
`BasicJsonType` value for a view; no ordering comparison (`#!cpp operator<`) is provided.
`basic_json_view` provides the read-only part of the `BasicJsonType` interface:
- the type-inspection functions,
- element access,
- lookup,
- iteration,
- conversion: [`get<T>()`](get.md), [`get_string()`](get_string.md), [`number_token()`](number_token.md), and
[`materialize()`](materialize.md) to build the `BasicJsonType` value of a subtree on demand, and
- comparison: [`operator==`](operator_eq.md) and [`operator!=`](operator_ne.md) compare two views, or a view and a
`BasicJsonType` value, without ever building a `BasicJsonType` value for a view; no ordering comparison
(`#!cpp operator<`) is provided.
[`operator[]`](operator%5B%5D.md), [`at`](at.md), [`contains`](contains.md), and [`value`](value.md) also accept a
[`json_pointer`](../json_pointer/index.md). Unlike `basic_json`, there are no implicit conversion operators (no
`#!cpp operator ValueType()`), and no `#!cpp get_ptr()` or `#!cpp get_ref()`; see [`get`](get.md).
## Template parameters
@@ -47,7 +56,6 @@ subtree on demand. [`operator[]`](operator%5B%5D.md), [`at`](at.md), [`contains`
- **string_view_t** - `#!cpp std::string_view` on C++17 and newer, a minimal internal substitute otherwise
- **iterator**, **const_iterator** - a forward iterator over the elements of an array or the member values of an
object, in document order; both names refer to the same type, since a view is always read-only
- **item** - a (key, value) pair produced by [`items()`](items.md)
- [**number_format**](number_format.md) - how [`dump()`](dump.md) writes numbers
## Member functions
@@ -4,9 +4,9 @@
/* unspecified */ items() const noexcept;
```
Returns a range of [`item`](index.md#member-types) values -- (key, value) pairs -- for use in range-based for loops.
The key of an array element is its index, converted to a string, as for
[`BasicJsonType::items()`](../basic_json/items.md).
Returns a range of items -- (key, value) pairs -- for use in range-based for loops. An item's `#!cpp key()` is a
`#!cpp string_view_t` (for an array element, its index converted to a string, as for
[`BasicJsonType::items()`](../basic_json/items.md)), and its `#!cpp value()` is a `basic_json_view` of the element.
The returned type is not part of the public API and may change between versions; use a range-based for loop (see the
example), or `#!cpp decltype(v.items())` if you need to name it.
@@ -33,8 +33,8 @@ is nothing for a reference to bind to.
## Return value
A range whose iterators dereference to [`item`](index.md#member-types) and whose `#!cpp begin()`/`#!cpp end()` are
equivalent to [`basic_json_view::begin()`](begin.md)/[`end()`](end.md), in document order.
A range whose iterators dereference to an item (with `#!cpp key()` and `#!cpp value()`, see above) and whose
`#!cpp begin()`/`#!cpp end()` are equivalent to [`basic_json_view::begin()`](begin.md)/[`end()`](end.md), in document order.
## Exception safety
@@ -48,14 +48,14 @@ Constant.
As for [`begin()`](begin.md)/[`end()`](end.md), `items()` visits **every** member of an object, including all
occurrences of a duplicate key -- unlike [`operator[]`](operator[].md), [`at`](at.md), [`find`](find.md),
[`contains`](contains.md), and [`count`](count.md), which resolve to the *first* member with a given key. See the
and [`contains`](contains.md), which resolve to the *first* member with a given key. See the
[Notes on duplicate keys](operator[].md#notes) of `operator[]`.
!!! danger "Lifetime issues"
As for `BasicJsonType::items()`, calling `items()` on a temporary view (or a temporary document) is dangerous:
the range refers back to the document, so the document must outlive the loop. See
[#2040](https://github.com/nlohmann/json/issues/2040) for the `BasicJsonType` background.
Unlike `BasicJsonType::items()` (see [#2040](https://github.com/nlohmann/json/issues/2040)), calling `items()` on
a temporary view is safe, for instance `#!cpp for (auto item : v["a"].items())`: the returned range holds a copy
of the view. What must outlive the loop is the document and, for a borrowed document, the source buffer.
## Examples
@@ -15,7 +15,7 @@ and [`materialize()`](materialize.md) can only represent approximately, as a `nu
## Exception safety
Strong exception safety: if an exception is thrown, there are no changes to the view or the document it refers to.
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
@@ -50,7 +50,7 @@ basic_json_view operator[](const json_pointer& ptr) const;
## Exception safety
Strong exception safety: if an exception is thrown, there are no changes to the view or the document it refers to.
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
@@ -108,7 +108,7 @@ document.
!!! warning "Duplicate keys: the first member wins"
If the source text has an object with a duplicate key, `#!cpp operator[]` (and [`at`](at.md), [`find`](find.md),
[`contains`](contains.md), [`count`](count.md), [`value`](value.md), and JSON pointer resolution) all resolve to
[`contains`](contains.md), [`value`](value.md), and JSON pointer resolution) all resolve to
the *first* member with that key, because a lookup can stop as soon as it finds a match. This is different from
[`materialize()`](materialize.md) (and [`BasicJsonType::parse()`](../basic_json/parse.md)), which replay every
member in order and so keep the *last* value for a repeated key, so `#!cpp v["a"]` and
@@ -14,14 +14,14 @@ same string for a discarded `BasicJsonType` value).
a string representation of the type ([`value_t`](../basic_json/value_t.md)):
| Value type | return value |
|-----------------------------------------------------|---------------|
| `#!json null` | `"null"` |
| boolean | `"boolean"` |
| string | `"string"` |
| number (integer, unsigned integer, floating-point) | `"number"` |
| object | `"object"` |
| array | `"array"` |
| discarded | `"discarded"` |
|----------------------------------------------------|---------------|
| `#!json null` | `"null"` |
| boolean | `"boolean"` |
| string | `"string"` |
| number (integer, unsigned integer, floating-point) | `"number"` |
| object | `"object"` |
| array | `"array"` |
| discarded | `"discarded"` |
`type_name()` never returns `#!cpp "binary"`, since a JSON text has no binary values (see
[`is_binary()`](is_binary.md)); it also never returns `#!cpp "invalid"`, since a view's `#!cpp kind` always comes
@@ -44,7 +44,7 @@ equivalent) deduce `string_t`, not `const char*`, for their return type and for
## Exception safety
Strong exception safety: if an exception is thrown, there are no changes to the view or the document it refers to.
Strong guarantee: there are no changes to the view or the document it refers to.
## Exceptions
@@ -5,13 +5,14 @@ using json_document = nlohmann::json_document;
int main()
{
// validate that every transaction of a batch carries a mandatory
// validate that every transaction of a batch carries exactly one
// "amount" field before materializing any of them into a nlohmann::json
// value -- count() returns 0 or 1 for an object
// value -- count() counts every member with the key
json_document batch = json_document::parse(R"(
[
{"id": 1, "amount": 9.99},
{"id": 2}
{"id": 2},
{"id": 3, "amount": 5.00, "amount": 500.00}
]
)");
@@ -19,9 +20,10 @@ int main()
for (std::size_t i = 0; i < transactions.size(); ++i)
{
const auto transaction = transactions[i];
if (transaction.count("amount") == 0)
const auto amounts = transaction.count("amount");
if (amounts != 1)
{
std::cout << "transaction " << i << " is missing \"amount\"\n";
std::cout << "transaction " << i << " has " << amounts << " \"amount\" fields\n";
continue;
}
std::cout << "transaction " << i << ": " << transaction["amount"].materialize().dump() << '\n';
@@ -1,2 +1,3 @@
transaction 0: 9.99
transaction 1 is missing "amount"
transaction 1 has 0 "amount" fields
transaction 2 has 2 "amount" fields
+9 -8
View File
@@ -67,9 +67,10 @@ table). [`parse_copy()`](../api/basic_json_document/parse_copy.md) always owns a
!!! warning "A borrowed document depends on your buffer"
If a document borrows its text, that text **must outlive the document** (and every view taken from it). Reading
or writing through a view after the underlying buffer is gone is undefined behavior, exactly as it would be for
a dangling `#!cpp std::string_view`.
If a document borrows its text, that text **must outlive the document** (and every view taken from it) and must
stay **unmodified** for as long as the document exists, since floating-point values and unescaped strings are
read from it lazily. Reading or writing through a view after the underlying buffer is gone is undefined behavior,
exactly as it would be for a dangling `#!cpp std::string_view`.
A view is valid only while all of the following hold:
@@ -77,7 +78,7 @@ A view is valid only while all of the following hold:
- the document has not been re-parsed since the view was taken (with [`read()`](../api/basic_json_document/read.md)
or [`parse()`](../api/basic_json_document/parse.md) into it),
- the document has not had [`shrink_to_fit()`](../api/basic_json_document/shrink_to_fit.md) called on it since, and
- if the document borrows its source text, that text is still alive.
- if the document borrows its source text, that text is still alive and unmodified.
Moving the `basic_json_document<>` itself is fine and does **not** invalidate its views: the index is a separate heap
allocation that keeps its address across the move. Take a fresh view from [`root()`](../api/basic_json_document/root.md)
@@ -167,10 +168,10 @@ document: `#!cpp auto v = json_document::parse(text).root();` does not compile.
If an object in the source text repeats a key, [`operator[]`](../api/basic_json_view/operator%5B%5D.md),
[`at`](../api/basic_json_view/at.md), [`find`](../api/basic_json_view/find.md),
[`value`](../api/basic_json_view/value.md), [`contains`](../api/basic_json_view/contains.md),
[`count`](../api/basic_json_view/count.md), and JSON pointer resolution all return the **first** member with that
key. `basic_json::parse()` instead keeps the **last** value of a repeated key, so for `#!cpp {"a":1,"a":2}`,
`#!cpp view["a"]` is `#!cpp 1` while `#!cpp parse(text)["a"]` is `#!cpp 2`.
[`value`](../api/basic_json_view/value.md), [`contains`](../api/basic_json_view/contains.md), and JSON pointer
resolution all return the **first** member with that key. `basic_json::parse()` instead keeps the **last** value
of a repeated key, so for `#!cpp {"a":1,"a":2}`, `#!cpp view["a"]` is `#!cpp 1` while `#!cpp parse(text)["a"]` is
`#!cpp 2`. [`count`](../api/basic_json_view/count.md) counts every member with the key, so it is `#!cpp 2` here.
[`begin()`](../api/basic_json_view/begin.md)/[`end()`](../api/basic_json_view/end.md) and
[`items()`](../api/basic_json_view/items.md) visit *every* occurrence, in document order, and
+10 -8
View File
@@ -415,8 +415,10 @@ class builder
arena_ensure(16);
std::memcpy(m_arena_write, r, 16);
}
else
else if (n != 0)
{
// (an empty run leaves an empty arena unallocated, and memcpy()
// must not be passed its null pointer even for zero bytes)
arena_ensure(n);
std::memcpy(m_arena_write, r, n);
}
@@ -829,7 +831,7 @@ indent_done:
/// append a node: (kind, flags, extra, off) and the second word (len, or
/// an integer's value); two stores on little-endian targets
NLOHMANN_VIEW_ALWAYS_INLINE node* emit(value_t k, std::uint8_t flags, std::uint16_t extra, std::size_t off, std::uint64_t second)
NLOHMANN_VIEW_ALWAYS_INLINE node* push_node(value_t k, std::uint8_t flags, std::uint16_t extra, std::size_t off, std::uint64_t second)
{
if (NLOHMANN_VIEW_UNLIKELY(out == cap))
{
@@ -859,9 +861,9 @@ indent_done:
NLOHMANN_VIEW_ALWAYS_INLINE void open(value_t k)
{
// (base is read after emit(), which moves the node array when it
// (base is read after push_node(), which moves the node array when it
// grows; in one expression the order of the two is unspecified)
const node* const n = emit(k, 0, 0, static_cast<std::size_t>(p - b), 0);
const node* const n = push_node(k, 0, 0, static_cast<std::size_t>(p - b), 0);
const auto idx = static_cast<std::uint32_t>(n - base);
if (depth != 0)
{
@@ -914,7 +916,7 @@ indent_done:
{
return fail(error_code::invalid_literal);
}
emit(k, flags, 0, static_cast<std::size_t>(p - b), n);
push_node(k, flags, 0, static_cast<std::size_t>(p - b), n);
p += n;
return true;
}
@@ -1022,7 +1024,7 @@ indent_done:
// of the negative std::int64_t)
second = negative ? 0 - m : m;
}
emit(kind, 0, layout, static_cast<std::size_t>(s - b), second);
push_node(kind, 0, layout, static_cast<std::size_t>(s - b), second);
return true;
}
@@ -1034,7 +1036,7 @@ indent_done:
p = scan_string_run(p, e);
if (NLOHMANN_VIEW_LIKELY(p != e && *p == '"'))
{
emit(value_t::string, 0, 0, static_cast<std::size_t>(s - b), static_cast<std::uint64_t>(p - s));
push_node(value_t::string, 0, 0, static_cast<std::size_t>(s - b), static_cast<std::uint64_t>(p - s));
++p;
return true;
}
@@ -1044,7 +1046,7 @@ indent_done:
return false;
}
p = r.p;
emit(value_t::string, node_flags::escaped, 0, r.start, r.len);
push_node(value_t::string, node_flags::escaped, 0, r.start, r.len);
return true;
}
};
+9 -6
View File
@@ -201,6 +201,11 @@ class json_side
const BasicJsonType* m_json;
};
inline bool is_number(value_t t) noexcept
{
return t == value_t::number_integer || t == value_t::number_unsigned || t == value_t::number_float;
}
/// whether two sides are equal; iterative, so that the nesting depth is
/// limited by memory only
template<typename BasicJsonType, typename A, typename B>
@@ -225,8 +230,6 @@ bool equal(const A& a0, const B& b0)
{
const value_t ta = a.type();
const value_t tb = b.type();
const bool numbers = (ta == value_t::number_integer || ta == value_t::number_unsigned || ta == value_t::number_float)
&& (tb == value_t::number_integer || tb == value_t::number_unsigned || tb == value_t::number_float);
if (ta == value_t::discarded || tb == value_t::discarded)
{
// basic_json decides (JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON)
@@ -237,13 +240,13 @@ bool equal(const A& a0, const B& b0)
}
else
{
if (!numbers && ta != tb)
if (ta != tb && !(is_number(ta) && is_number(tb))) // numbers of different types can be equal
{
return false;
}
if (ta == value_t::string)
{
if (!(a.string() == b.string()))
if (a.string() != b.string())
{
return false;
}
@@ -272,7 +275,7 @@ bool equal(const A& a0, const B& b0)
}
stack.push_back(std::move(f));
}
else if (!(a.scalar() == b.scalar())) // numbers (also of different types), null, boolean
else if (a.scalar() != b.scalar()) // numbers (also of different types), null, boolean
{
return false;
}
@@ -289,7 +292,7 @@ bool equal(const A& a0, const B& b0)
const std::size_t count = f.object ? f.members_a.size() : f.elements_a.size();
if (f.next == count)
{
stack.pop_back();
stack.pop_back(); // (f dangles now, and is bound again after continue)
continue;
}
if (f.object)
+15
View File
@@ -113,6 +113,21 @@ inline const node* find_member(const document_data& d, const node* object, const
return nullptr;
}
/// the number of members of an object with this key (duplicates included)
inline std::size_t count_members(const document_data& d, const node* object, const char* key, std::size_t n) noexcept
{
std::size_t result = 0;
const node* const end = document_data::child_end(object);
for (const node* m = document_data::first_child(object); m != end; m = document_data::after(m + 1))
{
if (m->len == n && (n == 0 || std::memcmp(d.str(*m), key, n) == 0))
{
++result;
}
}
return result;
}
/// whether an integer type is accepted as an array index by the view's
/// operator[] and at(): every integer type but bool and size_t, which has its
/// own overload
+12 -12
View File
@@ -47,24 +47,24 @@ enum class index_status
template<typename StringType>
index_status array_index(const StringType& s, std::size_t& idx) noexcept
{
// as basic_json: the empty token and "-" (past the last element) are
// unresolved rather than not a number
if (s.empty() || (s.size() == 1 && s[0] == '-'))
{
return index_status::unresolved;
}
if (s[0] < '0' || s[0] > '9')
{
return index_status::not_number;
}
if (s.size() > 1 && s[0] == '0')
{
return index_status::leading_zero;
}
// as basic_json: also a single character, but "-" and the empty token are
// left to the conversion below and reported as unresolved
if (!s.empty() && !(s.size() == 1 && s[0] == '-') && !(s[0] >= '0' && s[0] <= '9'))
{
return index_status::not_number;
}
if (s.empty())
{
return index_status::unresolved;
}
std::uint64_t v = 0;
for (std::size_t i = 0; i < s.size(); ++i)
for (const auto c : s)
{
const auto d = static_cast<unsigned>(static_cast<unsigned char>(s[i])) - '0';
const auto d = static_cast<unsigned>(static_cast<unsigned char>(c)) - '0';
if (d > 9 || v > ((std::numeric_limits<std::uint64_t>::max)() - d) / 10)
{
return index_status::unresolved; // not a number, or beyond unsigned long long
+25 -16
View File
@@ -69,6 +69,13 @@ class output_buffer
m_pos += n;
}
/// a string literal, without its terminating NUL
template<std::size_t N>
NLOHMANN_VIEW_ALWAYS_INLINE void put(const char (&s)[N])
{
put(s, N - 1);
}
void put_repeated(char c, std::size_t n)
{
reserve(n);
@@ -170,7 +177,7 @@ class view_serializer
frame& f = stack.back();
if (f.pos == f.end)
{
const bool object = f.object;
const bool object = f.object; // (f dangles after pop_back)
stack.pop_back();
newline(stack.size());
m_out.put(object ? '}' : ']');
@@ -187,7 +194,7 @@ class view_serializer
write_string(*f.pos);
if (m_style.pretty)
{
m_out.put(": ", 2);
m_out.put(": ");
}
else
{
@@ -220,16 +227,16 @@ class view_serializer
switch (static_cast<value_t>(n.kind))
{
case value_t::null:
m_out.put("null", 4);
m_out.put("null");
break;
case value_t::boolean:
if ((n.flags & node_flags::is_true) != 0)
{
m_out.put("true", 4);
m_out.put("true");
}
else
{
m_out.put("false", 5);
m_out.put("false");
}
break;
case value_t::string:
@@ -274,12 +281,14 @@ class view_serializer
{
if (!std::isfinite(x))
{
m_out.put("null", 4);
m_out.put("null");
return;
}
write_float(x, std::integral_constant < bool,
(std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128)
|| (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024) > {});
static constexpr bool is_ieee_single_or_double
= std::numeric_limits<number_float_t>::is_iec559
&& ((std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128)
|| (std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024));
write_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
}
void write_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
@@ -364,25 +373,25 @@ class view_serializer
switch (codepoint)
{
case 0x08:
m_out.put("\\b", 2);
m_out.put("\\b");
return;
case 0x09:
m_out.put("\\t", 2);
m_out.put("\\t");
return;
case 0x0A:
m_out.put("\\n", 2);
m_out.put("\\n");
return;
case 0x0C:
m_out.put("\\f", 2);
m_out.put("\\f");
return;
case 0x0D:
m_out.put("\\r", 2);
m_out.put("\\r");
return;
case 0x22:
m_out.put("\\\"", 2);
m_out.put("\\\"");
return;
case 0x5C:
m_out.put("\\\\", 2);
m_out.put("\\\\");
return;
default:
break;
+22
View File
@@ -8,6 +8,7 @@
#pragma once
#include <cstddef> // nullptr_t, size_t
#include <cstdint> // int64_t
#include <map> // map
#include <string> // basic_string
@@ -103,6 +104,27 @@ Map map_value(const View& v)
template<typename Key>
struct is_string_key : std::is_constructible<Key, const char*, std::size_t> {};
/// whether View::get<T>() converts to T without materialize(); get_to()
/// assigns these, and passes the others to from_json
template<typename T, typename BasicJsonType, typename View>
struct is_direct_value : std::integral_constant < bool,
std::is_arithmetic<T>::value || std::is_same<T, std::nullptr_t>::value
|| std::is_same<T, typename View::string_view_t>::value
|| std::is_same<T, BasicJsonType>::value || std::is_same<T, View>::value >
{};
template<typename Traits, typename Alloc, typename BasicJsonType, typename View>
struct is_direct_value<std::basic_string<char, Traits, Alloc>, BasicJsonType, View> : std::true_type {};
template<typename U, typename A, typename BasicJsonType, typename View>
struct is_direct_value<std::vector<U, A>, BasicJsonType, View> : std::true_type {};
template<typename K, typename V, typename C, typename A, typename BasicJsonType, typename View>
struct is_direct_value<std::map<K, V, C, A>, BasicJsonType, View> : is_string_key<K> {};
template<typename K, typename V, typename H, typename E, typename A, typename BasicJsonType, typename View>
struct is_direct_value<std::unordered_map<K, V, H, E, A>, BasicJsonType, View> : is_string_key<K> {};
} // namespace view
} // namespace detail
NLOHMANN_JSON_NAMESPACE_END
+26 -9
View File
@@ -28,12 +28,12 @@
#include <array> // array
#include <cstddef> // nullptr_t, size_t // IWYU pragma: keep
#include <cstring> // memcpy, strlen
#include <istream> // istream
#include <istream> // istream // IWYU pragma: keep
#include <iterator> // distance, input_iterator_tag, iterator_traits
#include <map> // map
#include <memory> // unique_ptr
#ifndef JSON_NO_IO
#include <ostream> // ostream
#include <ostream> // ostream // IWYU pragma: keep
#endif
#include <string> // string
#include <tuple> // tuple_element, tuple_size // IWYU pragma: keep
@@ -257,7 +257,7 @@ class basic_json_view
{
if (is_discarded())
{
return basic_json_view();
return {};
}
detail::view::throw_type_error(305, "cannot use operator[] with a string argument with ", type_name());
}
@@ -283,7 +283,7 @@ class basic_json_view
{
if (is_discarded())
{
return basic_json_view();
return {};
}
detail::view::throw_type_error(305, "cannot use operator[] with a numeric argument with ", type_name());
}
@@ -306,7 +306,7 @@ class basic_json_view
{
if (NLOHMANN_VIEW_UNLIKELY(is_discarded()))
{
return basic_json_view();
return {};
}
return detail::view::resolve_pointer(*this, detail::json_pointer_access::reference_tokens(ptr), detail::view::pointer_mode::unchecked);
}
@@ -479,11 +479,11 @@ class basic_json_view
return !detail::view::resolve_pointer(*this, detail::json_pointer_access::reference_tokens(ptr), detail::view::pointer_mode::contains).is_discarded();
}
/// 1 if this is an object with a member with this key, else 0 (duplicate
/// keys count once)
/// the number of members with this key (more than 1 if the key occurs
/// more than once); 0 if this is not an object
size_type count(string_view_t key) const
{
return contains(key) ? 1 : 0;
return is_object() ? detail::view::count_members(*m_doc, m_node, key.data(), key.size()) : 0;
}
size_type count(const char* key) const
@@ -550,10 +550,12 @@ class basic_json_view
return get_impl(detail::view::value_tag<T> {}, detail::priority_tag<2> {});
}
/// as BasicJsonType::get_to(): the types get<T>() converts directly are
/// assigned, all others are passed to from_json with v as it is
template<typename T>
T& get_to(T& v) const
{
v = get<T>();
get_to_impl(v, detail::view::is_direct_value<T, BasicJsonType, basic_json_view> {});
return v;
}
@@ -824,6 +826,21 @@ class basic_json_view
return materialize().template get<T>();
}
// --- get_to() dispatch ---
template<typename T>
void get_to_impl(T& v, std::true_type /*direct*/) const
{
v = get<T>();
}
/// from_json may keep parts of v (members a JSON object lacks, say)
template<typename T>
void get_to_impl(T& v, std::false_type /*direct*/) const
{
materialize().get_to(v);
}
const document_data* m_doc = nullptr;
const node* m_node = nullptr;
};
+119 -51
View File
@@ -28,12 +28,12 @@
#include <array> // array
#include <cstddef> // nullptr_t, size_t // IWYU pragma: keep
#include <cstring> // memcpy, strlen
#include <istream> // istream
#include <istream> // istream // IWYU pragma: keep
#include <iterator> // distance, input_iterator_tag, iterator_traits
#include <map> // map
#include <memory> // unique_ptr
#ifndef JSON_NO_IO
#include <ostream> // ostream
#include <ostream> // ostream // IWYU pragma: keep
#endif
#include <string> // string
#include <tuple> // tuple_element, tuple_size // IWYU pragma: keep
@@ -1049,8 +1049,10 @@ class builder
arena_ensure(16);
std::memcpy(m_arena_write, r, 16);
}
else
else if (n != 0)
{
// (an empty run leaves an empty arena unallocated, and memcpy()
// must not be passed its null pointer even for zero bytes)
arena_ensure(n);
std::memcpy(m_arena_write, r, n);
}
@@ -1463,7 +1465,7 @@ indent_done:
/// append a node: (kind, flags, extra, off) and the second word (len, or
/// an integer's value); two stores on little-endian targets
NLOHMANN_VIEW_ALWAYS_INLINE node* emit(value_t k, std::uint8_t flags, std::uint16_t extra, std::size_t off, std::uint64_t second)
NLOHMANN_VIEW_ALWAYS_INLINE node* push_node(value_t k, std::uint8_t flags, std::uint16_t extra, std::size_t off, std::uint64_t second)
{
if (NLOHMANN_VIEW_UNLIKELY(out == cap))
{
@@ -1493,9 +1495,9 @@ indent_done:
NLOHMANN_VIEW_ALWAYS_INLINE void open(value_t k)
{
// (base is read after emit(), which moves the node array when it
// (base is read after push_node(), which moves the node array when it
// grows; in one expression the order of the two is unspecified)
const node* const n = emit(k, 0, 0, static_cast<std::size_t>(p - b), 0);
const node* const n = push_node(k, 0, 0, static_cast<std::size_t>(p - b), 0);
const auto idx = static_cast<std::uint32_t>(n - base);
if (depth != 0)
{
@@ -1548,7 +1550,7 @@ indent_done:
{
return fail(error_code::invalid_literal);
}
emit(k, flags, 0, static_cast<std::size_t>(p - b), n);
push_node(k, flags, 0, static_cast<std::size_t>(p - b), n);
p += n;
return true;
}
@@ -1656,7 +1658,7 @@ indent_done:
// of the negative std::int64_t)
second = negative ? 0 - m : m;
}
emit(kind, 0, layout, static_cast<std::size_t>(s - b), second);
push_node(kind, 0, layout, static_cast<std::size_t>(s - b), second);
return true;
}
@@ -1668,7 +1670,7 @@ indent_done:
p = scan_string_run(p, e);
if (NLOHMANN_VIEW_LIKELY(p != e && *p == '"'))
{
emit(value_t::string, 0, 0, static_cast<std::size_t>(s - b), static_cast<std::uint64_t>(p - s));
push_node(value_t::string, 0, 0, static_cast<std::size_t>(s - b), static_cast<std::uint64_t>(p - s));
++p;
return true;
}
@@ -1678,7 +1680,7 @@ indent_done:
return false;
}
p = r.p;
emit(value_t::string, node_flags::escaped, 0, r.start, r.len);
push_node(value_t::string, node_flags::escaped, 0, r.start, r.len);
return true;
}
};
@@ -1924,6 +1926,11 @@ class json_side
const BasicJsonType* m_json;
};
inline bool is_number(value_t t) noexcept
{
return t == value_t::number_integer || t == value_t::number_unsigned || t == value_t::number_float;
}
/// whether two sides are equal; iterative, so that the nesting depth is
/// limited by memory only
template<typename BasicJsonType, typename A, typename B>
@@ -1948,8 +1955,6 @@ bool equal(const A& a0, const B& b0)
{
const value_t ta = a.type();
const value_t tb = b.type();
const bool numbers = (ta == value_t::number_integer || ta == value_t::number_unsigned || ta == value_t::number_float)
&& (tb == value_t::number_integer || tb == value_t::number_unsigned || tb == value_t::number_float);
if (ta == value_t::discarded || tb == value_t::discarded)
{
// basic_json decides (JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON)
@@ -1960,13 +1965,13 @@ bool equal(const A& a0, const B& b0)
}
else
{
if (!numbers && ta != tb)
if (ta != tb && !(is_number(ta) && is_number(tb))) // numbers of different types can be equal
{
return false;
}
if (ta == value_t::string)
{
if (!(a.string() == b.string()))
if (a.string() != b.string())
{
return false;
}
@@ -1995,7 +2000,7 @@ bool equal(const A& a0, const B& b0)
}
stack.push_back(std::move(f));
}
else if (!(a.scalar() == b.scalar())) // numbers (also of different types), null, boolean
else if (a.scalar() != b.scalar()) // numbers (also of different types), null, boolean
{
return false;
}
@@ -2012,7 +2017,7 @@ bool equal(const A& a0, const B& b0)
const std::size_t count = f.object ? f.members_a.size() : f.elements_a.size();
if (f.next == count)
{
stack.pop_back();
stack.pop_back(); // (f dangles now, and is bound again after continue)
continue;
}
if (f.object)
@@ -2768,6 +2773,21 @@ inline const node* find_member(const document_data& d, const node* object, const
return nullptr;
}
/// the number of members of an object with this key (duplicates included)
inline std::size_t count_members(const document_data& d, const node* object, const char* key, std::size_t n) noexcept
{
std::size_t result = 0;
const node* const end = document_data::child_end(object);
for (const node* m = document_data::first_child(object); m != end; m = document_data::after(m + 1))
{
if (m->len == n && (n == 0 || std::memcmp(d.str(*m), key, n) == 0))
{
++result;
}
}
return result;
}
/// whether an integer type is accepted as an array index by the view's
/// operator[] and at(): every integer type but bool and size_t, which has its
/// own overload
@@ -3186,24 +3206,24 @@ enum class index_status
template<typename StringType>
index_status array_index(const StringType& s, std::size_t& idx) noexcept
{
// as basic_json: the empty token and "-" (past the last element) are
// unresolved rather than not a number
if (s.empty() || (s.size() == 1 && s[0] == '-'))
{
return index_status::unresolved;
}
if (s[0] < '0' || s[0] > '9')
{
return index_status::not_number;
}
if (s.size() > 1 && s[0] == '0')
{
return index_status::leading_zero;
}
// as basic_json: also a single character, but "-" and the empty token are
// left to the conversion below and reported as unresolved
if (!s.empty() && !(s.size() == 1 && s[0] == '-') && !(s[0] >= '0' && s[0] <= '9'))
{
return index_status::not_number;
}
if (s.empty())
{
return index_status::unresolved;
}
std::uint64_t v = 0;
for (std::size_t i = 0; i < s.size(); ++i)
for (const auto c : s)
{
const auto d = static_cast<unsigned>(static_cast<unsigned char>(s[i])) - '0';
const auto d = static_cast<unsigned>(static_cast<unsigned char>(c)) - '0';
if (d > 9 || v > ((std::numeric_limits<std::uint64_t>::max)() - d) / 10)
{
return index_status::unresolved; // not a number, or beyond unsigned long long
@@ -3387,6 +3407,13 @@ class output_buffer
m_pos += n;
}
/// a string literal, without its terminating NUL
template<std::size_t N>
NLOHMANN_VIEW_ALWAYS_INLINE void put(const char (&s)[N])
{
put(s, N - 1);
}
void put_repeated(char c, std::size_t n)
{
reserve(n);
@@ -3488,7 +3515,7 @@ class view_serializer
frame& f = stack.back();
if (f.pos == f.end)
{
const bool object = f.object;
const bool object = f.object; // (f dangles after pop_back)
stack.pop_back();
newline(stack.size());
m_out.put(object ? '}' : ']');
@@ -3505,7 +3532,7 @@ class view_serializer
write_string(*f.pos);
if (m_style.pretty)
{
m_out.put(": ", 2);
m_out.put(": ");
}
else
{
@@ -3538,16 +3565,16 @@ class view_serializer
switch (static_cast<value_t>(n.kind))
{
case value_t::null:
m_out.put("null", 4);
m_out.put("null");
break;
case value_t::boolean:
if ((n.flags & node_flags::is_true) != 0)
{
m_out.put("true", 4);
m_out.put("true");
}
else
{
m_out.put("false", 5);
m_out.put("false");
}
break;
case value_t::string:
@@ -3592,12 +3619,14 @@ class view_serializer
{
if (!std::isfinite(x))
{
m_out.put("null", 4);
m_out.put("null");
return;
}
write_float(x, std::integral_constant < bool,
(std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128)
|| (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024) > {});
static constexpr bool is_ieee_single_or_double
= std::numeric_limits<number_float_t>::is_iec559
&& ((std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128)
|| (std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024));
write_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
}
void write_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
@@ -3682,25 +3711,25 @@ class view_serializer
switch (codepoint)
{
case 0x08:
m_out.put("\\b", 2);
m_out.put("\\b");
return;
case 0x09:
m_out.put("\\t", 2);
m_out.put("\\t");
return;
case 0x0A:
m_out.put("\\n", 2);
m_out.put("\\n");
return;
case 0x0C:
m_out.put("\\f", 2);
m_out.put("\\f");
return;
case 0x0D:
m_out.put("\\r", 2);
m_out.put("\\r");
return;
case 0x22:
m_out.put("\\\"", 2);
m_out.put("\\\"");
return;
case 0x5C:
m_out.put("\\\\", 2);
m_out.put("\\\\");
return;
default:
break;
@@ -3864,6 +3893,7 @@ NLOHMANN_JSON_NAMESPACE_END
#include <cstddef> // nullptr_t, size_t
#include <cstdint> // int64_t
#include <map> // map
#include <string> // basic_string
@@ -3964,6 +3994,27 @@ Map map_value(const View& v)
template<typename Key>
struct is_string_key : std::is_constructible<Key, const char*, std::size_t> {};
/// whether View::get<T>() converts to T without materialize(); get_to()
/// assigns these, and passes the others to from_json
template<typename T, typename BasicJsonType, typename View>
struct is_direct_value : std::integral_constant < bool,
std::is_arithmetic<T>::value || std::is_same<T, std::nullptr_t>::value
|| std::is_same<T, typename View::string_view_t>::value
|| std::is_same<T, BasicJsonType>::value || std::is_same<T, View>::value >
{};
template<typename Traits, typename Alloc, typename BasicJsonType, typename View>
struct is_direct_value<std::basic_string<char, Traits, Alloc>, BasicJsonType, View> : std::true_type {};
template<typename U, typename A, typename BasicJsonType, typename View>
struct is_direct_value<std::vector<U, A>, BasicJsonType, View> : std::true_type {};
template<typename K, typename V, typename C, typename A, typename BasicJsonType, typename View>
struct is_direct_value<std::map<K, V, C, A>, BasicJsonType, View> : is_string_key<K> {};
template<typename K, typename V, typename H, typename E, typename A, typename BasicJsonType, typename View>
struct is_direct_value<std::unordered_map<K, V, H, E, A>, BasicJsonType, View> : is_string_key<K> {};
} // namespace view
} // namespace detail
NLOHMANN_JSON_NAMESPACE_END
@@ -4148,7 +4199,7 @@ class basic_json_view
{
if (is_discarded())
{
return basic_json_view();
return {};
}
detail::view::throw_type_error(305, "cannot use operator[] with a string argument with ", type_name());
}
@@ -4174,7 +4225,7 @@ class basic_json_view
{
if (is_discarded())
{
return basic_json_view();
return {};
}
detail::view::throw_type_error(305, "cannot use operator[] with a numeric argument with ", type_name());
}
@@ -4197,7 +4248,7 @@ class basic_json_view
{
if (NLOHMANN_VIEW_UNLIKELY(is_discarded()))
{
return basic_json_view();
return {};
}
return detail::view::resolve_pointer(*this, detail::json_pointer_access::reference_tokens(ptr), detail::view::pointer_mode::unchecked);
}
@@ -4370,11 +4421,11 @@ class basic_json_view
return !detail::view::resolve_pointer(*this, detail::json_pointer_access::reference_tokens(ptr), detail::view::pointer_mode::contains).is_discarded();
}
/// 1 if this is an object with a member with this key, else 0 (duplicate
/// keys count once)
/// the number of members with this key (more than 1 if the key occurs
/// more than once); 0 if this is not an object
size_type count(string_view_t key) const
{
return contains(key) ? 1 : 0;
return is_object() ? detail::view::count_members(*m_doc, m_node, key.data(), key.size()) : 0;
}
size_type count(const char* key) const
@@ -4441,10 +4492,12 @@ class basic_json_view
return get_impl(detail::view::value_tag<T> {}, detail::priority_tag<2> {});
}
/// as BasicJsonType::get_to(): the types get<T>() converts directly are
/// assigned, all others are passed to from_json with v as it is
template<typename T>
T& get_to(T& v) const
{
v = get<T>();
get_to_impl(v, detail::view::is_direct_value<T, BasicJsonType, basic_json_view> {});
return v;
}
@@ -4715,6 +4768,21 @@ class basic_json_view
return materialize().template get<T>();
}
// --- get_to() dispatch ---
template<typename T>
void get_to_impl(T& v, std::true_type /*direct*/) const
{
v = get<T>();
}
/// from_json may keep parts of v (members a JSON object lacks, say)
template<typename T>
void get_to_impl(T& v, std::false_type /*direct*/) const
{
materialize().get_to(v);
}
const document_data* m_doc = nullptr;
const node* m_node = nullptr;
};
+35 -2
View File
@@ -682,7 +682,12 @@ void check_access(const ordered_json_view& v, const ordered_json& j)
++members;
const std::string key(it.key().data(), it.key().size());
CHECK(v.contains(key));
CHECK(v.count(key) == 1);
std::size_t occurrences = 0;
for (auto other = v.begin(); other != v.end(); ++other)
{
occurrences += other.key() == it.key() ? 1 : 0;
}
CHECK(v.count(key) == occurrences);
// lookups find the first member with the key, which is this one if
// there is no earlier one
if (std::find(keys.begin(), keys.end(), key) != keys.end())
@@ -790,7 +795,8 @@ TEST_CASE("json_view element access and iteration")
CHECK(v.find("a") == v.begin());
CHECK(v.find("a").value().materialize() == 1);
CHECK(v.find("b") == std::next(v.begin()));
CHECK(v.count("a") == 1);
CHECK(v.count("a") == 2); // every member, unlike materialize()
CHECK(v.count("b") == 1);
CHECK(v.contains("a"));
CHECK(v.value("a", 0) == 1);
CHECK(v.materialize()["a"] == 3); // materialize() keeps the last value, unlike the lookups
@@ -1187,6 +1193,25 @@ void from_json(const json& j, record& r)
j.at("name").get_to(r.name);
j.at("count").get_to(r.count);
}
struct defaults
{
int a = 1;
int b = 2;
};
// sets only the members the JSON value has
void from_json(const json& j, defaults& d)
{
if (j.contains("a"))
{
j.at("a").get_to(d.a);
}
if (j.contains("b"))
{
j.at("b").get_to(d.b);
}
}
} // namespace
TEST_CASE("json_view values")
@@ -1316,6 +1341,14 @@ TEST_CASE("json_view values")
CHECK(name == "widget");
CHECK(count == 3);
// other types go to from_json with the existing value, as basic_json::get_to()
defaults def;
def.b = 5;
const json_document partial = json_document::parse(R"({"a":4})");
partial.root().get_to(def);
CHECK(def.a == 4);
CHECK(def.b == 5);
// a duplicate key: the last value, as parse()
const json_document dup = json_document::parse(R"({"a":1,"a":2})");
CHECK((dup.root().get<std::map<std::string, int>>() == std::map<std::string, int> {{"a", 2}}));