* Add editable json_documents: set, push_back, insert, and erase basic_json_document gets a second template parameter, Editable (false by default), plus the aliases json_editable_document, json_editable_view, ordered_json_editable_document and ordered_json_editable_view. Editable documents can change values and structure without rewriting the source text: set()/push_back() on values, keys, array indices and JSON pointers; insert() before an array element; erase() of an object key, array index or JSON pointer. New values and element sequences go into edit storage that the document owns and never moves, so views keep referring to their value across edits and a parsed node never moves. Read-only documents walk the plain node array and are unaffected. Strings are checked for UTF-8 on entry, so dump() of an editable document never throws type_error.316. Binary values cannot be stored (type_error.319). A seeded differential test applies random edits to an editable document and to the equivalent ordered_json and compares both after every step. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix old clang and MSVC C4127 in editable json documents Value-initialize the const std::less in find_parent (clang 3.4/3.6 do not implement DR 253), and test the Editable template argument through a function to avoid MSVC C4127. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Copy nested values into a document without recursion Counting and copying the nodes of a view or a basic_json value into an editable document recursed once per nesting level, so that a deeply nested value overflowed the stack. The four functions now walk the value with an explicit stack, as materialize() does. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Do not leave a half-assigned container when set_moved() throws assign() rewrote the kind, length and extent of a slot before set_moved() registered its new element sequence. set_moved() can throw (std::bad_alloc from reserving the bookkeeping vectors) for a slot that is not moved yet, which left a container without the moved flag that showed its old children. The bookkeeping is now reserved first (reserve_moved()), so that nothing after the first write to the slot can throw. block_of() reserves before it marks anything for the same reason. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Check strings copied from another document for valid UTF-8 An editable document only holds valid UTF-8, but copy_scalar() copied the strings and keys of a view of another document unchecked. A document of a weaker check (or a borrowed text that changed after parsing) could therefore bring ill-formed UTF-8 into it. The copy is checked now, with the error that dump() reports for the string; copies within the same document stay unchecked. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Allow the edit arena to grow up to 4 GiB - 1 bytes append_text() doubled the capacity of the arena and rejected the result if it exceeded 4 GiB, so that an arena of more than 2 GiB could not grow even though the 32-bit offsets of nodes address 4 GiB - 1 bytes. The capacity is now clamped to that limit (text_capacity()), and an append is rejected only if the bytes themselves do not fit. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Set a null value below a pointer as basic_json does set(json_pointer, value) turned a null parent into an object for every last reference token, so "/a/0" and "/a/-" below {"a":null} made {"a":{"0":1}}, where basic_json's operator[](json_pointer) makes an array. A null parent now becomes an array for "-" and for digit tokens (filled with nulls up to the index) and an object otherwise. An invalid index is reported before the parent changes. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Replace a container by a scalar in constant time once it is linked Replacing an array or object that spans several nodes by a scalar looks up its parent from the root (find_parent), which is linear in the size of the document: setting every element of a 20,000 element array took more than half a second. The parent only has to switch to links once; afterward the extent of the replaced value no longer matters. Nodes that an entry of a moved sequence links to are now marked (node_flags::linked), and assign() skips the lookup for them. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Update the json_view banner and type_error.319 for editable documents The banner still described a read-only view, and the documentation of type_error.319 listed set and push_back only, although insert rejects binary values as well. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Assign the member that lookups find when set() meets duplicate keys An editable document reads the last member of a repeated key (as the read-only document does), but set(object, key, value) assigned the first one: a view taken from object[key] before the call did not show the new value. It now assigns the last member's value, keeps the key at the position of its first occurrence (where materialize() puts it), and drops the other members. The seeded differential test now also edits documents whose objects repeat keys and compares every lookup (operator[], at, find, value, contains, count, and JSON pointers) with the parsed basic_json value. A targeted test covers duplicates before and after edits that move the object, in large objects with an index, in moved arrays, and in values copied from other documents. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Assign the first member when set() meets duplicate keys again Lookups find the first member of a repeated key again, so set(object, key, value) assigns that member (keeping the key where it is) and drops the others, as documented before, and a view taken from object[key] shows the new value. This undoes the code and documentation changes of5cbb8e6d6. Lookups in edited objects (navigation of editable documents) stop at the first match, like those of parsed objects. The tests that commit added expect the first member from lookups now. In the seeded differential test, the documents with repeated keys repeat them after the real members; the reference holds the first members, which the edits address and the lookups are compared with, while materialize() is compared with what parse() makes of the document's dump. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix MSVC C4127 in the lookups of editable json documents Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix clang-tidy 22 findings in the json_view headers Silence bugprone-casting-through-void for the SSE loads (a reinterpret_cast would trip -Wcast-align=strict), use auto for a cast initialiser, add parentheses to a mixed expression, and name bugprone-std-namespace-modification in the NOLINTs of the tuple_size/tuple_element specialisations. Signed-off-by: Niels Lohmann <mail@nlohmann.me> (cherry picked from commit0effbaa7a2) * Fix clang-tidy 22 findings in unit-json_view_edit.cpp and edit.hpp Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Keep a raw string with a backslash out of a CHECK (MSVC C2017) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * 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), and the headers that json.hpp already provides (abi_config, abi_macros, input_adapters, json_pointer, cpp_future, string_concat, value_t, json_fwd), plus <version> for std::nullptr_t, and removing <cstddef> and edit_storage.hpp. - 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 - drop edit_storage.hpp, which edit.hpp includes Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Keep the view's edit headers clean for clang-tidy in C++17 mode clang-tidy 22 checks the headers with -std=gnu++17 as well, where it asks for a transparent comparator and std::make_unique. The regions map uses its default comparator, and the allocation of the edit state keeps new (the library is C++11) with a NOLINT. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate the amalgamated headers Signed-off-by: Niels Lohmann <mail@nlohmann.me> * 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> * Expect count() to count every member in the edit tests Since #5622, count() counts every member with the key, so documents with duplicate keys no longer give 1. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Count matching keys as unsigned in the json_view edit tests Like in the access test, adding the int result of the conditional to a std::size_t fails -Werror=sign-conversion with GCC. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Address the review of erase() in editable json documents From gregmarr's review of #5630: - invalid_iterator.202 is thrown by overloads 1 and 2 only; the page said "every overload" and then excluded 3 in parentheses. - The note on links says what moves (the links after the removed element, as insert() moves them the other way) and that every iterator over the container is invalidated, not only those after the removed element. - edit.hpp compares keys with document_data::key_equals(). Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate the amalgamated headers Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Address the review of editable json documents From gregmarr's review of #5630: - set() with a JSON pointer below a null value checks for "-" before scanning the token for digits. - node_flags::storage is defined as escaped | edited, and the comment on document_data::base says that the fourth slot is unused. - source_extent() names its root check. - The integer-index overloads of set(), insert(), and erase() use a named trait instead of a negated condition, which astyle formats like the library's other enable_ifs. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate the amalgamated headers Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Address the rest of the review of editable json documents From gregmarr's review of #5630: - alloc_nodes() gives a request of half of the next chunk or more a chunk of its own, so that the rest of the current chunk stays available for smaller requests instead of being abandoned. - The comments on edit_state, append_text(), and reserve_moved() say that views stay valid across every edit (not just the first), that n is 0 for empty strings, and why both capacities are checked. - The architecture page names flag bits 3, 4, and 5 (linked) separately and says that a discarded view has no node; erase.md rewords overload 3 and says why it never throws invalid_iterator.202. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Call alloc_nodes() before reading chunks.back() in the json_view chunk test The operands of == are unsequenced, and MSVC evaluated d->edits->chunks.back() before alloc_nodes() added the new chunk, so the check compared the result with the previous chunk and failed on msvc-arm64 (Debug and Release). Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
282 lines
11 KiB
C++
282 lines
11 KiB
C++
// __ _____ _____ _____
|
|
// __| | __| | | | JSON for Modern C++
|
|
// | | |__ | | | | | | version 3.12.0
|
|
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
|
|
//
|
|
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
#pragma once
|
|
|
|
#include <algorithm> // max, min
|
|
#include <cstddef> // size_t
|
|
#include <cstdint> // uint8_t, uint32_t
|
|
#include <cstring> // memcpy
|
|
#include <functional> // less
|
|
#include <memory> // unique_ptr
|
|
#include <utility> // move
|
|
|
|
#include <nlohmann/json.hpp>
|
|
#include <nlohmann/detail/view/document_data.hpp>
|
|
#include <nlohmann/detail/view/errors.hpp>
|
|
#include <nlohmann/detail/view/macro_scope.hpp>
|
|
#include <nlohmann/detail/view/node.hpp>
|
|
|
|
// The storage of edits. Edits never move or resize the parsed index: every
|
|
// value keeps its node, so views stay valid. New values and element sequences
|
|
// live in chunks that never move; strings and number tokens written by edits
|
|
// live in the edit arena. An array/object whose elements change gets
|
|
// node_flags::moved: its elements then live in a separate sequence (a header
|
|
// node, then the entries), whose entries link to the values (kind_link).
|
|
|
|
NLOHMANN_JSON_NAMESPACE_BEGIN
|
|
namespace detail
|
|
{
|
|
namespace view
|
|
{
|
|
|
|
inline document_data::edit_state& edit_state_of(document_data& d)
|
|
{
|
|
if (!d.edits)
|
|
{
|
|
d.edits.reset(new document_data::edit_state()); // NOLINT(cppcoreguidelines-owning-memory,modernize-make-unique): owned by the unique_ptr; std::make_unique is C++14
|
|
}
|
|
return *d.edits;
|
|
}
|
|
|
|
/// k consecutive nodes that never move (new values and blocks)
|
|
inline node* alloc_nodes(document_data& d, std::size_t k)
|
|
{
|
|
document_data::edit_state& e = edit_state_of(d);
|
|
if (NLOHMANN_VIEW_UNLIKELY(static_cast<std::size_t>(e.chunk_end - e.chunk_cur) < k))
|
|
{
|
|
if (k >= e.chunk_next / 2)
|
|
{
|
|
// a large request (half of the next chunk or more) gets a chunk of
|
|
// its own, so that the rest of the current chunk stays available
|
|
// for smaller ones
|
|
std::unique_ptr<node[]> own(new node[k]()); // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
|
e.chunks.push_back(std::move(own));
|
|
e.bytes += k * sizeof(node);
|
|
return e.chunks.back().get();
|
|
}
|
|
// a smaller request leaves the rest of the current chunk unused
|
|
// (fewer than k nodes, and k is less than half of the new chunk)
|
|
const std::size_t count = e.chunk_next;
|
|
std::unique_ptr<node[]> fresh(new node[count]()); // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
|
e.chunks.push_back(std::move(fresh));
|
|
e.chunk_cur = e.chunks.back().get();
|
|
e.chunk_end = e.chunk_cur + count;
|
|
e.chunk_next = (std::min)(e.chunk_next * 2, std::size_t{65536});
|
|
e.bytes += count * sizeof(node);
|
|
}
|
|
node* const r = e.chunk_cur;
|
|
e.chunk_cur += k;
|
|
return r;
|
|
}
|
|
|
|
/// The capacity of the edit arena after it grows by n bytes (`used` of `cap`
|
|
/// are taken): doubled, or what is needed plus some room, but never more than
|
|
/// the 4 GiB - 1 bytes that the 32-bit offsets of nodes can address. An error
|
|
/// if n more bytes do not fit even then.
|
|
inline std::size_t text_capacity(std::size_t cap, std::size_t used, std::size_t n)
|
|
{
|
|
constexpr std::size_t limit = 0xFFFFFFFFu;
|
|
if (NLOHMANN_VIEW_UNLIKELY(used > limit || n > limit - used))
|
|
{
|
|
throw_out_of_range(416, "edits of 4 GiB or more are not supported by json_document");
|
|
}
|
|
const std::size_t needed = used + n;
|
|
const std::size_t wanted = needed + (std::min)(limit - needed, std::size_t{256});
|
|
const std::size_t doubled = cap > limit / 2 ? limit : cap * 2;
|
|
return (std::max)(doubled, wanted);
|
|
}
|
|
|
|
/// copy n bytes into the edit arena and return their offset; a new buffer
|
|
/// leaves the old one alive, so that string views into it remain valid; n is
|
|
/// 0 for an empty string (written by an edit, or the key of a new member)
|
|
inline std::uint32_t append_text(document_data& d, const char* s, std::size_t n)
|
|
{
|
|
document_data::edit_state& e = edit_state_of(d);
|
|
if (NLOHMANN_VIEW_UNLIKELY(e.text_cap - e.text_used < n))
|
|
{
|
|
const std::size_t cap = text_capacity(e.text_cap, e.text_used, n);
|
|
std::unique_ptr<char[]> fresh(new char[cap]); // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
|
if (NLOHMANN_VIEW_LIKELY(e.text_used != 0)) // (0 only for the first buffer, and then texts is empty)
|
|
{
|
|
std::memcpy(fresh.get(), e.texts.back().get(), e.text_used);
|
|
}
|
|
e.texts.push_back(std::move(fresh));
|
|
e.text_cap = cap;
|
|
e.bytes += cap;
|
|
d.base[2] = e.texts.back().get();
|
|
}
|
|
const auto off = static_cast<std::uint32_t>(e.text_used);
|
|
if (n != 0)
|
|
{
|
|
std::memcpy(e.texts.back().get() + e.text_used, s, n);
|
|
}
|
|
e.text_used += n;
|
|
return off;
|
|
}
|
|
|
|
/// the capacity in nodes of the block of a moved container (0: a fixed
|
|
/// sequence, the elements of a new value)
|
|
inline std::size_t moved_capacity(const document_data& d, const node* n) noexcept
|
|
{
|
|
return d.edits->moved_cap[n->off];
|
|
}
|
|
|
|
/// Make room for one more moved container. This is the part of set_moved()
|
|
/// that can throw: a caller that changes a node before it calls set_moved()
|
|
/// calls this first, so that a failure leaves the node as it was.
|
|
inline void reserve_moved(document_data& d)
|
|
{
|
|
document_data::edit_state& e = edit_state_of(d);
|
|
if (e.moved.size() >= 0xFFFFFFFFu)
|
|
{
|
|
throw_out_of_range(416, "more than 4294967295 edited arrays and objects are not supported by json_document"); // LCOV_EXCL_LINE
|
|
}
|
|
if (e.moved.size() == e.moved.capacity() || e.moved_cap.size() == e.moved_cap.capacity())
|
|
{
|
|
// both grow before either changes, so that the push_backs cannot throw
|
|
// (both conditions are needed: reserve() may allocate more than asked,
|
|
// so the two capacities can differ)
|
|
e.moved.reserve((e.moved.size() * 2) + 16);
|
|
e.moved_cap.reserve((e.moved.size() * 2) + 16);
|
|
}
|
|
}
|
|
|
|
/// let container n take its elements from `seq` (header node first); cannot
|
|
/// throw if n is moved already or reserve_moved() was called
|
|
inline void set_moved(document_data& d, node* n, node* seq, std::size_t cap)
|
|
{
|
|
document_data::edit_state& e = edit_state_of(d);
|
|
if ((n->flags & node_flags::moved) != 0)
|
|
{
|
|
e.moved[n->off] = seq;
|
|
e.moved_cap[n->off] = cap;
|
|
return;
|
|
}
|
|
reserve_moved(d);
|
|
e.moved.push_back(seq);
|
|
e.moved_cap.push_back(cap);
|
|
n->off = static_cast<std::uint32_t>(e.moved.size() - 1);
|
|
n->flags = static_cast<std::uint8_t>(n->flags | node_flags::moved | node_flags::is_new);
|
|
}
|
|
|
|
/// Make the elements of container n a growable block with room for `extra`
|
|
/// more nodes, and return its header. The entries link to the existing
|
|
/// values, which stay where they are. A block that grows is copied (its old
|
|
/// space is not reused).
|
|
inline node* block_of(document_data& d, node* n, std::size_t extra)
|
|
{
|
|
if ((n->flags & node_flags::moved) != 0 && moved_capacity(d, n) != 0)
|
|
{
|
|
node* const h = d.edits->moved[n->off];
|
|
if (h->next + extra <= moved_capacity(d, n))
|
|
{
|
|
return h;
|
|
}
|
|
const std::size_t cap = (std::max)(2 * moved_capacity(d, n), h->next + extra);
|
|
node* const nh = alloc_nodes(d, cap);
|
|
std::memcpy(nh, h, h->next * sizeof(node));
|
|
set_moved(d, n, nh, cap);
|
|
return nh;
|
|
}
|
|
reserve_moved(d); // (so that set_moved() below cannot throw: the links are marked before)
|
|
const bool object = n->kind == static_cast<std::uint8_t>(value_t::object);
|
|
const std::size_t used = 1 + (static_cast<std::size_t>(n->len) * (object ? 2 : 1));
|
|
const std::size_t cap = used + extra;
|
|
node* const h = alloc_nodes(d, cap);
|
|
*h = node{};
|
|
h->kind = n->kind;
|
|
h->len = n->len;
|
|
h->next = static_cast<std::uint32_t>(used);
|
|
node* o = h + 1;
|
|
for (const node* c = d.first_child_edited(n), *e = d.child_end_edited(n); c != e;)
|
|
{
|
|
if (object)
|
|
{
|
|
*o++ = *c++; // the key
|
|
}
|
|
make_link(*o, const_cast<node*>(document_data::deref(c))); // NOLINT(cppcoreguidelines-pro-type-const-cast): the nodes belong to the document
|
|
++o;
|
|
c = document_data::after(c);
|
|
}
|
|
set_moved(d, n, h, cap);
|
|
return h;
|
|
}
|
|
|
|
/// The container whose elements include `target`; nullptr for the root, for
|
|
/// a value that is no longer part of the document, and for a value that is
|
|
/// only reached through a link. Values never move between allocations, so
|
|
/// the path to `target` stays inside the allocation that holds it (the parsed
|
|
/// index, or one new value), where the extent of each container (`next`)
|
|
/// still covers its original subtree.
|
|
inline node* find_parent(const document_data& d, const node* target)
|
|
{
|
|
const std::less<const node*> lt{};
|
|
const node* lo = d.nodes;
|
|
const node* hi = d.nodes + d.node_count;
|
|
const node* c = d.nodes;
|
|
if (lt(target, lo) || !lt(target, hi))
|
|
{
|
|
if (!d.edits)
|
|
{
|
|
return nullptr; // LCOV_EXCL_LINE (nodes outside the index exist only after edits)
|
|
}
|
|
auto it = d.edits->regions.upper_bound(target);
|
|
if (it == d.edits->regions.begin())
|
|
{
|
|
return nullptr; // LCOV_EXCL_LINE (an array/object with elements is in the index or a new value)
|
|
}
|
|
--it;
|
|
lo = it->first;
|
|
hi = lo + lo->next;
|
|
if (!lt(target, hi))
|
|
{
|
|
return nullptr; // LCOV_EXCL_LINE (a single-node value, reached through a link)
|
|
}
|
|
// the root of a new value is the element sequence of its owner, or a linked value
|
|
c = it->second != nullptr ? it->second : lo;
|
|
}
|
|
if (target == lo)
|
|
{
|
|
return nullptr;
|
|
}
|
|
for (;;)
|
|
{
|
|
if (!is_container(*c))
|
|
{
|
|
return nullptr; // LCOV_EXCL_LINE (the value is inside c)
|
|
}
|
|
const bool object = c->kind == static_cast<std::uint8_t>(value_t::object);
|
|
const node* down = nullptr;
|
|
for (const node* p = d.first_child_edited(c), *e = d.child_end_edited(c); p != e;)
|
|
{
|
|
const node* const at = object ? p + 1 : p;
|
|
const node* const v = document_data::deref(at);
|
|
if (v == target)
|
|
{
|
|
return const_cast<node*>(c); // NOLINT(cppcoreguidelines-pro-type-const-cast): the nodes belong to the document
|
|
}
|
|
if (is_container(*v) && !lt(v, lo) && lt(v, target) && lt(target, v + v->next))
|
|
{
|
|
down = v;
|
|
break;
|
|
}
|
|
p = document_data::after(at);
|
|
}
|
|
if (down == nullptr)
|
|
{
|
|
return nullptr;
|
|
}
|
|
c = down;
|
|
}
|
|
}
|
|
|
|
} // namespace view
|
|
} // namespace detail
|
|
NLOHMANN_JSON_NAMESPACE_END
|