diff --git a/AGENTS.md b/AGENTS.md index c4d7db5..c544b15 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,17 @@ specific to document. - No floating point outside `js_traits` and its codec; no hashed container; nodes are built in place (`emplace`), never copied from a temporary; the allocator zeroes every block it hands out and frees. +- Every allocation an operation makes outside the image goes through the document's allocator, + rebound (`detail::rebound`, constructed from it, never converted to), and is made before the + operation's first change, so that with exceptions an allocator's failure, which + `detail::unless_allocation_fails` alone catches (`std::bad_alloc`, a type derived from it, or + Boost.Interprocess's `bad_alloc`), is `errc::capacity` with the document's content as it was; an + erasure, a lookup and `==` allocate nothing, and a `const` operation allocates in the document's + allocator only as the page's "Reads from several threads" lists. An image's blocks the allocator + gives at another alignment than 16 are given back, and a change a place cannot take is refused + before its value is prepared. The `allocator*` tests count the global `operator new` and fail an + operation at each of its allocations: a container of the standard allocator in an operation fails + them. Boost.JSON's suspension stack, in a parse fed in chunks, is the one exception. - The values of `errc` and `kind`, the category's identity `0x646f63756d656e74` ("document") and the image's header layout never change; a layout change raises the image's format version. - Boost.MultiIndex erases an element whose `modify` throws: a `modify` only swaps prepared values. @@ -44,15 +55,16 @@ specific to document. - `doc/document.adoc` includes one file per section, in this order: `introduction.adoc`, `gains.adoc`, `js-module.adoc`, `javascript.adoc`, `handles.adoc`, `numbers.adoc`, `strings.adoc`, `order.adoc`, `arrays.adoc`, `containers.adoc`, `stringify.adoc`, - `parsing.adoc`, `streams.adoc`, `selectors.adoc`, `traits.adoc`, `images.adoc`, `wire.adoc`, - `sharing.adoc`, `boost-json.adoc`, `exceptions.adoc`, `errors.adoc`, `testing.adoc`, - `benchmarks.adoc`, then the reference and the changelog. + `parsing.adoc`, `streams.adoc`, `selectors.adoc`, `traits.adoc`, `images.adoc`, + `allocation.adoc`, `wire.adoc`, `sharing.adoc`, `boost-json.adoc`, `exceptions.adoc`, + `errors.adoc`, `testing.adoc`, `benchmarks.adoc`, then the reference and the changelog. `b2 libs/document/doc` builds it with the strict reference. - Each `@see ""` of a Doc Comment names a section's title: "Introduction", "What C++ gives JavaScript", "Using it from JavaScript", "From JavaScript", "Handles", "Numbers", "Strings, dates and bytes", "Key order", "Arrays", "Containers", "Writing JSON", "Parsing", "Streams of - documents", "Selectors", "Traits", "Images", "Images on the wire", "Sealed images", "Sharing", - "Compared with Boost.JSON", "The sugar that throws", "Errors", "Testing", "Benchmarks". + documents", "Selectors", "Traits", "Images", "Allocators", "Images on the wire", "Sealed + images", "Sharing", "Compared with Boost.JSON", "The sugar that throws", "Errors", "Testing", + "Benchmarks". Renaming a section renames its `@see` lines in the same commit; doc-check fails otherwise. - The guide's programs are `example/document_<topic>.cpp`, each with its `.expected`, whose lines are what Node prints for the same JavaScript wherever the page does not say otherwise; check a @@ -67,5 +79,9 @@ specific to document. ways. - `document_image.expected` holds a digest of an image, which is the same on every target: a change to the image's layout, or to what the example stores, changes it on every target at once. +- `document_allocators.expected` is C++'s alone, which its section says: its JSON lines are what + Node prints for the same steps, and it prints nothing that depends on where a resource's bytes go + (a count or size of allocations), which libstdc++'s and libc++'s growth policies and small-string + buffers make differ between targets. - The README copies `example/document_quick_start.cpp[tag=program]` and its output; doc-check compares the copy at every doc build. diff --git a/doc/allocation.adoc b/doc/allocation.adoc new file mode 100644 index 0000000..dae06c3 --- /dev/null +++ b/doc/allocation.adoc @@ -0,0 +1,337 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#document-allocators] +== Allocators + +A document's storage carries an allocator, as a standard container does, and the document allocates +through it: its image, when it owns one, and the working state of every operation on it. The +default is `std::allocator<std::byte>`, the global heap. A program that gives a +`std::pmr::memory_resource` instead keeps a document's memory where it chooses: in a buffer of its +own, in an arena released at the end of a request, or in a resource that counts. This section names +the storages, shows a document in a resource, lists how documents are made in an allocator, how +moves and copies treat it and what happens when it has no room, names what stays outside it, lists +the reads that allocate in it, and says which of document's types can be shared between +processes. + +[#document-allocators-storages] +=== The storages + +A document's second template parameter is its storage, `wd::basic_owned<Allocator>` or +`wd::basic_external<Allocator>`, of any allocator of `std::byte`: + +[cols="2,2,3",options="header"] +|=== +| Storage | Allocator | The image + +| `wd::owned`, the default +| `std::allocator<std::byte>` +| the document's own, from the global aligned `operator new` + +| `wd::external` +| `std::allocator<std::byte>` +| a buffer its user owns (<<document-images-storage>>) + +| `wd::pmr::owned` +| `std::pmr::polymorphic_allocator<std::byte>` +| the document's own, from the allocator's `std::pmr::memory_resource` + +| `wd::pmr::external` +| `std::pmr::polymorphic_allocator<std::byte>` +| a buffer its user owns + +| `wd::basic_owned<Allocator>` +| any allocator of `std::byte`, a stateful one of the program's own among them +| the document's own, from the allocator + +| `wd::basic_external<Allocator>` +| any allocator of `std::byte` +| a buffer its user owns +|=== + +The namespace `wd::pmr` names the rest for a memory resource, as `std::pmr` does for the standard +containers: `wd::pmr::document`, the default traits' document of `wd::pmr::owned`; +`wd::pmr::basic_document<Traits>`, the same for other traits; its handles `wd::pmr::value` and +`wd::pmr::const_value`; and its parser, `wd::pmr::parser`. A document's `allocator_type` names the +allocator, and `get_allocator()` returns a copy of it. + +*An owned image* is allocated, grown and freed through the allocator rebound to blocks of 16 bytes, +16-aligned, `std::allocator_traits<Allocator>::rebind_alloc` of a block, so that the allocator is +asked for the alignment the image's heap needs: a memory resource is asked for an alignment of 16, +which it gives. The allocator must give it. A 16-aligned block is over-aligned wherever the +alignment of `std::max_align_t` is 8, as on arm64 macOS and on MSVC, and an allocator that ignores +an over-aligned request may give less: a buffer that is not 16-aligned is given back at once, and +the operation returns `errc::capacity` and changes nothing, as when the allocator has no room. The +allocator's pointer to the image is kept as the allocator gave it, and the image is given back +through it: an allocator whose pointer is not a plain one, which may carry a segment or a tag +besides an address, gets back what it handed out. Inside the image, every pointer is an offset +(<<document-allocators-shareable>>). The image grows by doubling, as <<document-images-reserve>> +says, a new buffer allocated before the old one is freed. A monotonic resource never reuses what was +freed, so an image built large in one is sized once with `reserve`. The standard allocator's image +comes from the global aligned `operator new` in its form that returns null. + +*The working state* of every operation on a document, owned or external, is in the same allocator, +rebound: the records a change stages before it changes anything, the stack of a deep copy and of a +compaction, the parser's frames, path and pending text, its selectors and their callbacks, the +frames of the stack of `stringify_to` past the 16 it has room for and the piece it holds back for +its sink once it holds more than its own room of 4096 bytes, the key a handle of a missing member +holds, the buffers in which a value is prepared to be stored, and the keys `Object.assign` takes +from its source. For an external document that is all the allocator holds. A lookup by key allocates +nothing, whatever the key's length, and neither does a comparison with `==`, which walks both trees +through their nodes' links, nor an erasure, `delete` of a member, `pop_back` or a truncation, which +lists the nodes it erases through the erased nodes themselves and so cannot run out of room, though +it still returns `errc::type` for what is no object or no array and `errc::range` for elements past +the end. + +[#document-allocators-resource] +=== A document in a resource + +This program gives a document 64 KiB of its own memory, through a +`std::pmr::monotonic_buffer_resource` whose upstream is `std::pmr::null_memory_resource()`, which +refuses every allocation: what passes the buffer's end fails, and nothing of the document reaches +the global heap. It parses a text into a `wd::pmr::document`, changes it, and writes it with +`stringify_to` into a `std::pmr::string` of the same resource: + +[source] +---- +include::{examples}/document_allocators.cpp[tag=resource,indent=0] +---- + +[listing] +---- +include::{examples}/document_allocators.expected[lines=1] +---- + +The program's output is {cpp}'s alone: its JSON text is what Node prints for the same steps, and its +other lines say where each document lives, which JavaScript does not show. + +[#document-allocators-making] +=== Making documents in an allocator + +Each way to make a document has a form that takes its allocator: + +[cols="2,3",options="header"] +|=== +| Call | The document + +| `wd::pmr::document::create(alloc, max_bytes)`, the static `create` of any owned document's type +| a new owned document, holding `null` + +| `wd::parse(text, options, alloc)` +| the document of a JSON text (<<document-parsing>>) + +| `wd::parse_into(buffer, text, options, alloc)` +| the same in a buffer of the program's, the allocator holding the working state + +| `wd::basic_parser<Traits, Storage>(options, alloc)`, or `(buffer, options, alloc)` for an external + document +| the document a parser builds, the parser's own working state in the same allocator + (<<document-parsing-chunks>>) + +| `wd::from_image(bytes, alloc)` +| an owned copy of an image (<<document-images-bytes>>) + +| `wd::format(buffer, alloc)`, `wd::open(buffer, alloc)` +| an external document, formatted or opened in place + +| `doc.clone()`, `doc.clone(alloc)` +| a copy, owned, in the document's own allocator or in the one given + +| `wd::pmr::document::nothing(alloc)`, the static `nothing` of any document's type +| a document that holds nothing, as a moved-from one does: no image, nothing allocated and no + failure, its root reading `undefined`, a change and `clone` refused with `errc::type`, until a + move assignment gives it an image + +| `doc.compact_into(buffer)` +| the compact image in a buffer, an external document in the document's allocator + (<<document-images-compact>>) + +| `pop`, `shift`, `splice`, `slice`, `concat` +| the values they return, owned documents in the source's allocator, an external source's + included (<<document-arrays>>) +|=== + +`clone(alloc)` copies a document into another allocator, which is how a document crosses from one +resource to another. The copy below is made in a second buffer, where it changes alone, and +`stringify_to` writes it to the standard output piece by piece, with no text kept whole: + +[source] +---- +include::{examples}/document_allocators.cpp[tag=clone,indent=0] +---- + +[listing] +---- +include::{examples}/document_allocators.expected[lines=2..3] +---- + +[#document-allocators-moves] +=== Moves and copies + +A document is allocator-aware as the standard containers are: + +* *A move* takes the image and the allocator. The document moved from holds nothing. +* *A move assignment* takes the image when the allocator propagates on a move assignment, or when + two of its allocators are always equal, as the standard allocator's are. Polymorphic allocators + of different resources do neither: an owned image is then copied into the target's resource, one + copy of its bytes, the source's image is freed in its own resource, and the source holds nothing + after it. An external image, which no allocator holds, is taken as it is. The copy can fail, and + an assignment has no result to return the failure in: it throws `std::bad_alloc` through + `boost::throw_exception`, and leaves both documents as they were; without exceptions, + `boost::throw_exception` is the program's own, which does not return. For allocators that + propagate or are always equal, and for an external document, whose image is taken as it is, the + move assignment is `noexcept`. +* *The copy constructor,* with exceptions only (<<document-exceptions>>), asks the allocator's + `select_on_container_copy_construction`, which for a polymorphic allocator gives the default + resource, `std::pmr::get_default_resource()`, and not the source's. The allocator-extended copy, + `wd::pmr::document copy(doc, alloc);`, takes the allocator given, and + `wd::pmr::document empty(alloc);` makes a document holding `null` in it. + +The program's first document is assigned the copy, of the second resource, by a move: the image is +copied into the first resource, at its 4,096 bytes, and the copy holds nothing after it: + +[source] +---- +include::{examples}/document_allocators.cpp[tag=move,indent=0] +---- + +[listing] +---- +include::{examples}/document_allocators.expected[lines=4..5] +---- + +[#document-allocators-failure] +=== When an allocator has no room + +*With exceptions,* an allocator that has no room throws `std::bad_alloc`, a type derived from it, or +Boost.Interprocess's `boost::interprocess::bad_alloc`, which its allocators throw and which derives +from `std::exception` alone. The document catches these where the operation can still return: the +operation returns `errc::capacity` and the document's content is as it was, as for a full image. Its +bytes may differ where the heap keeps its free space (<<document-images-bytes>>), and a failed +`wd::parse_into` leaves its buffer formatted, with the part of the document it had built. An +allocator that throws anything else ends the program, since what it throws leaves a `noexcept` +operation. A change allocates all of its working state before its first change to the document, +which then changes by steps that cannot allocate, so a failure at any of its allocations leaves the +document's content as it was. A few places have their own way to say it: + +* a parser that runs out fails with `errc::capacity` and stays failed until `reset()`, as after + any error, and a selector it has no room for is not added: `on` and `observe` return + `errc::capacity`; +* `stringify_to` stops with `errc::capacity`, its sink not called again, so the sink holds a part + of the text; +* a handle of a missing member whose key finds no room reads `undefined`, and a change through it + is `errc::capacity`; +* the move assignment between allocators that differ, which has no result to return the failure + in, throws `std::bad_alloc` (<<document-allocators-moves>>); and the sugar throws its + `wd::capacity_error` (<<document-exceptions>>). + +The MSVC STL's checked iterators (`_ITERATOR_DEBUG_LEVEL` above 0, the default of a debug build) +add an allocation of their own: each standard container allocates a proxy through its allocator, +rebound, whenever it is constructed or moved, in its `noexcept` constructors as well. An allocator +that has no room for such a proxy ends the program there, as it would for any standard container +in that build, before the document can return `errc::capacity`. A release build allocates no proxy. + +*Without exceptions,* an allocator cannot return null, so an allocator that fails ends the program, +as it does for any standard container. A program built without exceptions sizes its resource for +what it does, as the example's 64 KiB are sized for its documents, or gives the resource an upstream +that does not fail. The standard allocator's image is the exception: the `operator new` it comes +from returns null, so an image the global heap has no room for is `errc::capacity` in either build. + +[#document-allocators-outside] +=== What stays outside the allocator + +A few allocations are not in the document's allocator, each for a reason of its own: + +* *A parse in chunks.* When a chunk ends inside a value, Boost.JSON's parser saves where it stopped + on a stack of its own, so that the next chunk resumes there, and allocates that stack in the + global heap: Boost.JSON offers no way to place it. It allocates once at the first suspension, + and again at each suspension deeper than every earlier one, and keeps the last stack until the + parser is destroyed, across `reset()`. A complete text, given to `wd::parse`, to `wd::parse_into` + or to the `finish_with(last)` of a parser that was given no text before, never suspends, and + allocates nothing there. +* *What the program gets back.* A value returned to the program is of the program's own type, in + the standard allocator: the `std::string` that `stringify` returns, with the stack it writes it + with, so that `stringify` asks the document's allocator for nothing, the `std::string` of + `get<std::string>()` and the other reads into a type that owns its memory, the text of + `path_view::to_string()`, the message of an error code, and the exceptions of the sugar, which + hold that message. `get` is `noexcept`, so the standard allocator's failure in a read ends the + program. `stringify_to` writes to a sink, and so into a string of the program's choosing, as the + example's `std::pmr::string` is. +* *Literals.* `wd::object`, `wd::array` and `wd::literal` hold their values in the standard + allocator, as the program builds them. Storing one copies it into the document, in the document's + allocator. +* *Streams and pools.* The streams of documents, `wd::basic_stream_parser` and + `wd::async_read_document` (<<document-streams>>), and the shared and leased documents, + `wd::shared_document` and `wd::leased_document` (<<document-sharing>>, <<document-wire>>), keep + the default storage: their documents are `wd::owned` or `wd::external`. A `wd::image_pool` + allocates its blocks once, from the global heap; a `wd::shared_pool` formats memory the program + gives. + +[#document-allocators-reads] +=== Reads from several threads + +A standard container allocates nothing in a `const` member, so several threads may read one at +once, whatever its resource. Most of a document's `const` operations allocate nothing either: a +lookup by key, `get` into a scalar or a view, `==`, iteration and the containers' views, `image`, +`compact_size`, and `stringify`, which keeps its text and its stack in the standard allocator. A +few allocate in the document's allocator, rebound: + +* `stringify_to`, for a value nested more than 16 containers deep, the frames of its stack past its + own room, and for a chunk larger than 4096 bytes, the piece it holds back once it holds more than + its own room; +* `operator[]` of a document or a handle, for a missing member whose key is longer than a + `std::basic_string` holds without allocating, which its standard library decides (with the MSVC + STL's checked iterators, none: each string allocates a proxy, <<document-allocators-failure>>): + the handle holds a copy of the key, and so does each copy of such a handle; +* `clone()`, `slice` and `concat`, which make documents in it, and `compact_into`, whose external + document keeps it, with their working state. + +Several threads that use these on one document at once need a resource that is safe to use from +several threads, as `std::pmr::synchronized_pool_resource` is and as +`std::pmr::monotonic_buffer_resource` and `std::pmr::unsynchronized_pool_resource` are not. The +standard allocator is, so a `wd::document` and the documents a `wd::shared_document` shares are read +by any number of threads at once with every `const` operation (<<document-sharing>>), and so are the +reads into a type of the program's own, `get<std::string>()` among them, which allocate there. + +[#document-allocators-shareable] +=== What can be shared + +A shareable type is one that can be built in memory that several processes map, each at an address +of its own, and used there in place. document's is the image. Every pointer inside it is an offset +from where it is stored, and every size a 64-bit integer, so it is relocatable and the same bytes at +any address and on every target (<<document-images>>): a `wd::shared_pool` in a segment of shared +memory, the blocks of a `wd::image_pool`, `wd::open` over bytes another process wrote, +`wd::from_image` of them, and external storage over a segment of shared memory all use it as it is. + +A `basic_document` object is not shareable, nor are its handles, its parsers, its writers or the +views of the pools: each holds addresses of the process that made it, the image's and its +allocator's among them. Each process that maps an image opens it with a document of its own +(<<document-sharing-processes>>). + +[#document-allocators-proof] +=== How it is proven + +The tests `allocator`, `allocator_tree`, `allocator_values`, `allocator_parse` and +`allocator_stringify` replace the global `operator new` and `operator delete`, every form, and count +their calls. Each runs the operations it lists on documents in a counting resource over a monotonic +buffer whose upstream is the null resource, and checks that they made no call of the global +`operator new` and that the resource is given back all it handed out: the image made, grown, copied +and moved; the tree's changes and compaction; the handles, the conversions, `Object.assign`, the +array methods and the containers' views; a parse of a whole text, with selectors and revivers; and +`stringify_to` into a `std::pmr::string` of the same resource, at every indent and chunk, a document +nested 10,000 levels deep among them. Where the global heap is reached on purpose, the count is +exact: a parse in chunks calls `operator new` as often as Boost.JSON's stack grows, and `stringify` +as often as its `std::string` and the frames of its stack past its own room need, while it asks the +document's resource for nothing. A dozen small texts written by `stringify_to` in a 64 KiB arena, as +the example's, take nothing of it. With exceptions, each operation runs again over a resource that +fails at its first allocation, then its second, and so on until the operation succeeds, and every +failure must be `errc::capacity`, or the `std::bad_alloc` of the places that throw it, with the +document equal to what it was. Under the MSVC STL's checked iterators, the resources neither count +nor refuse a block of a proxy's size and alignment, which they cannot tell from the document's own: +the proxies come back with the rest, and a failure at the document's blocks of that size is proven +on the other standard libraries. Both traits are covered, `js_traits` with its UTF-16 strings and +keys among them, with strings and keys longer than any small-string buffer. The tests run on every +target, natively, on emscripten, and for wasm32-wasip2 and wasm32-wasip3 (<<document-testing>>). diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 513d174..0a95f83 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,6 +16,15 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] +* *Breaking change:* Changed `owned` and `external` into aliases of `basic_owned<>` and + `basic_external<>`: a forward declaration `struct owned;` includes `<webcpp/document/storage.hpp>` + instead. +* Added allocators to the storages, `pmr::document` among them, holding the image and every + operation's working state. +* Improved allocation failures: with exceptions, an allocator with no room, Boost.Interprocess's + among them, makes an operation return `errc::capacity`. +* Added `finish_with`, which ends a parser's text with its last chunk or the whole text. +* Added `quote`, which appends a string to a string of the caller's as `JSON.stringify` quotes it. // end::unreleased[] [#document-changelog-0-1-0] diff --git a/doc/document.adoc b/doc/document.adoc index 1974c32..994df0a 100644 --- a/doc/document.adoc +++ b/doc/document.adoc @@ -65,6 +65,8 @@ include::traits.adoc[] include::images.adoc[] +include::allocation.adoc[] + include::wire.adoc[] include::sharing.adoc[] diff --git a/doc/errors.adoc b/doc/errors.adoc index b58506a..3087119 100644 --- a/doc/errors.adoc +++ b/doc/errors.adoc @@ -35,7 +35,8 @@ unchanged, in its own category. | `wd::range_error` | `capacity`, 4 -| no room: a full external buffer, an owned document at its `max_bytes`, a parser's limit +| no room: a full external buffer, an owned document at its `max_bytes`, a parser's limit, an + allocator that has none, with exceptions (<<document-allocators-failure>>) | none; `RangeError` from the module | `wd::capacity_error` @@ -78,7 +79,7 @@ include::{examples}/document_no_exceptions.cpp[tag=errors,indent=0] include::{examples}/document_no_exceptions.expected[lines=1..8] ---- -An operation that fails changes nothing, so the program goes on with the document as it was: +An operation that fails leaves the document's content as it was, so the program goes on with it: [source] ---- @@ -90,8 +91,11 @@ include::{examples}/document_no_exceptions.cpp[tag=compare,indent=0] include::{examples}/document_no_exceptions.expected[lines=9] ---- -A failure of the process heap is not an error value. The image's heap is never exhausted by -surprise, since every operation finds its room first, but a few things live on the process heap: -the text `stringify` returns, the key a handle of a missing member holds, and the parser's frames. -The standard library's `std::bad_alloc` there is thrown with exceptions and ends the program -without them, as it does for any {cpp} container. +The image's heap is never exhausted by surprise, since every operation finds its room first, and the +working state of an operation, the records of a change, the parser's frames and the key a handle of +a missing member holds among them, is in the document's allocator. With exceptions, an allocator +that has no room is `errc::capacity`, and the document's content is as it was; without them, an +allocator that fails ends the program, as it does for any {cpp} container +(<<document-allocators-failure>>). What the program gets back in the standard allocator, the text +`stringify` returns among them, fails as any `std::string` does, with `std::bad_alloc` +(<<document-allocators-outside>>). diff --git a/doc/exceptions.adoc b/doc/exceptions.adoc index 27c3175..c6abff7 100644 --- a/doc/exceptions.adoc +++ b/doc/exceptions.adoc @@ -69,6 +69,9 @@ include::{examples}/document_javascript.expected[lines=23..29] `as<std::string>()`. * *`wd::document d;` holds `null`,* and the copy constructor gives an equal and independent copy. Both are for owned documents only: an external document has no buffer to be made or copied into. + The copy is in the allocator that `select_on_container_copy_construction` gives, as a standard + container's copy is: for a `wd::pmr::document`, the default resource, where `doc.clone()` keeps + the document's own (<<document-allocators-moves>>). * *An external document throws `wd::capacity_error` when it is full,* where `set` would return `errc::capacity`. diff --git a/doc/images.adoc b/doc/images.adoc index ea47117..d4adde5 100644 --- a/doc/images.adoc +++ b/doc/images.adoc @@ -120,20 +120,23 @@ changed by accident and is not authentication: *never open an image from a sourc [#document-images-storage] === Owned and external storage -A document's second template parameter is its storage: +A document's second template parameter is its storage, which also carries the allocator the +document allocates through (<<document-allocators>>): [cols="1,2,3",options="header"] |=== | Storage | The buffer | When it is full -| `wd::owned`, the default -| the document's own, 16-aligned +| `wd::owned`, the default; `wd::basic_owned<Allocator>` +| the document's own, 16-aligned, from its allocator: for `wd::owned`, the global aligned + `operator new` | it grows: a buffer twice the size, or what the operation needs if more, the image copied and the heap grown, up to the `max_bytes` of `create` or `from_image`, 1 GiB unless told otherwise; past - it, `errc::capacity` + it, or when the allocator has no room, `errc::capacity` -| `wd::external` -| a `std::span<std::byte>` its user owns and keeps alive, such as a browser's memory, 16-aligned +| `wd::external`; `wd::basic_external<Allocator>` +| a `std::span<std::byte>` its user owns and keeps alive, such as a browser's memory, 16-aligned; + the allocator holds only the working state of the document's operations | the operation returns `errc::capacity` and changes nothing |=== @@ -235,4 +238,5 @@ The image's size afterwards is `compact_size()`, which is also its `capacity()`, that needs room grows it. A moved document takes the image of the one it is moved from, which then holds nothing: its -handles, and those of the document moved into, are invalid. +handles, and those of the document moved into, are invalid. A move assignment between allocators +that are not equal and do not propagate copies the image instead (<<document-allocators-moves>>). diff --git a/doc/introduction.adoc b/doc/introduction.adoc index 6c21b04..11e24a3 100644 --- a/doc/introduction.adoc +++ b/doc/introduction.adoc @@ -166,8 +166,9 @@ handles that read and write a document; <<document-numbers>>, <<document-strings array methods. <<document-stringify>>, <<document-parsing>>, <<document-streams>> and <<document-selectors>> write and read JSON text, whole or in pieces, and <<document-containers>> shows the containers a {cpp} program walks. <<document-traits>> chooses what a document stores; -<<document-images>> shows the binary image, <<document-wire>> sends it, and <<document-sharing>> -shares it. <<document-vs-boost-json>> compares document with Boost.JSON, <<document-exceptions>> -teaches the sugar that throws, and <<document-errors>> lists every error. <<document-testing>> shows +<<document-images>> shows the binary image, <<document-allocators>> places it and every +operation's memory in an allocator, <<document-wire>> sends it, and <<document-sharing>> shares it. +<<document-vs-boost-json>> compares document with Boost.JSON, <<document-exceptions>> teaches the +sugar that throws, and <<document-errors>> lists every error. <<document-testing>> shows how document is tested, <<document-benchmarks>> what it costs, and the <<reference,reference>> closes the page. diff --git a/doc/parsing.adoc b/doc/parsing.adoc index 173fec7..d4e73a0 100644 --- a/doc/parsing.adoc +++ b/doc/parsing.adoc @@ -15,8 +15,10 @@ document's parser never throws: its input is the network's, and every failure is `wd::parse<Traits>` parses into a document of other traits, as `wd::parse<wd::js_traits>(text)` does in <<document-numbers>>; `wd::parse_into(buffer, text)` parses into a buffer the program owns -(<<document-images>>); and `wd::parse_or_throw(text)`, with exceptions only, throws as -`JSON.parse` does (<<document-exceptions>>). +(<<document-images>>); `wd::parse(text, options, alloc)` and +`wd::parse_into(buffer, text, options, alloc)` parse into a document of an allocator's, which holds +the parse's working state too (<<document-allocators>>); and `wd::parse_or_throw(text)`, with +exceptions only, throws as `JSON.parse` does (<<document-exceptions>>). [#document-parsing-options] === Limits and revivers @@ -71,8 +73,9 @@ builds itself, with `create`, keeps a limit of 1 GiB (<<document-images>>). `wd::parser` is the parser itself, `wd::basic_parser<Traits, Storage>` for other traits or a buffer of the program's: `write(chunk)` takes the text in chunks of any size, split anywhere, inside a string, a number, an escape or a character's bytes, down to one byte at a time, and -`finish()` ends the text and returns the document. The document a parser builds is the one a -whole parse builds, however the text is split: +`finish()` ends the text and returns the document; `finish_with(last)` takes a last chunk, or the +whole text, and ends it. The document a parser builds is the one a whole parse builds, however the +text is split: [source] ---- @@ -86,7 +89,11 @@ include::{examples}/document_streaming.expected[lines=1] The parser builds the document node by node as each chunk arrives, so the document may grow and its image move between two chunks; `finish` returns it. `reset()` makes the parser ready for -another text, its selectors kept (<<document-selectors>>). +another text, its selectors kept (<<document-selectors>>). The parser's working state, its frames, +the path and the pending text of a value, and its selectors and their callbacks, is in its +document's allocator, a memory resource's for `wd::pmr::parser`. The stack where Boost.JSON's +parser saves its place when a chunk ends inside a value is in the global heap; a text given whole +to `finish_with(last)`, as `wd::parse` gives it, never needs one (<<document-allocators-outside>>). [#document-parsing-errors] === Errors and offsets @@ -94,7 +101,9 @@ another text, its selectors kept (<<document-selectors>>). Malformed text is `errc::syntax`, JavaScript's `SyntaxError`. `offset()` is the count of bytes consumed, which after a syntax error is the offset where it was found, the same however the text was split, and `cause()` is the code of Boost.JSON's parser behind it. A number the traits refuse -is `errc::range` (<<document-numbers-refused>>), and a limit passed `errc::capacity`. +is `errc::range` (<<document-numbers-refused>>), and a limit passed `errc::capacity`, as is, with +exceptions, an allocator that has no room for the document or for the parse's working state +(<<document-allocators-failure>>). A parser reads one text: anything but whitespace after it is `errc::syntax`, whose `cause()` is Boost.JSON's `extra_data`, at the offset where the second text begins, whether it comes in the same diff --git a/doc/sharing.adoc b/doc/sharing.adoc index 51a967a..90885e9 100644 --- a/doc/sharing.adoc +++ b/doc/sharing.adoc @@ -43,6 +43,13 @@ include::{examples}/document_threads.expected[lines=1..4] Every document arrived with the image the producer sent: no byte was copied and nothing was parsed on the consumer's side. +Threads that read one document at once read it through `const` operations. A document of the +standard allocator, `wd::document` and the documents of the pools below among them, may be read by +any number of threads at once with every one of them. A document of a memory resource allocates in +it in a few `const` operations, which <<document-allocators-reads>> lists: threads that use them on +one document at once need a resource that is safe to use from several threads, such as +`std::pmr::synchronized_pool_resource`. + [#document-sharing-pool] === Shared documents diff --git a/doc/stringify.adoc b/doc/stringify.adoc index 133b57d..1788731 100644 --- a/doc/stringify.adoc +++ b/doc/stringify.adoc @@ -21,8 +21,10 @@ include::{examples}/document_quick_start.cpp[tag=stringify,indent=0] The indent is JavaScript's: 0 writes compactly, a larger one is clamped to 10 spaces, and an empty array or object is written `[]` or `{}` at any indent. A value that is `undefined`, a handle of nothing or a document that holds `undefined`, writes no text, as `JSON.stringify(undefined)` -returns none. `stringify` returns a `std::string`, so its only failure is the standard library's -`std::bad_alloc`; a program that must not meet even that writes to a sink of its own. +returns none. `stringify` returns a `std::string`, in the standard allocator whatever the +document's, and keeps its stack there too (<<document-allocators-outside>>): it asks the document's +allocator for nothing, and its failure is the standard allocator's `std::bad_alloc`. A program that +must not meet one, or that keeps its text in memory of its own, writes to a sink. [#document-stringify-to] === In pieces, to a sink @@ -45,3 +47,38 @@ include::{examples}/document_streaming.expected[lines=12..13] The first sink writes a bar after each piece of 8 bytes; the second keeps the first piece, then fails, which stops the writing there. + +`stringify_to` keeps its stack, which takes the place of recursion, and the chunk it has not yet +handed to the sink in room of its own, 16 levels of the stack and 4096 bytes of the chunk, and +allocates only past them, in the document's allocator (<<document-allocators>>): a value nested 16 +deep or less, written in chunks of at most 4096 bytes, allocates nothing. With exceptions, an +allocator that has no room for them is `errc::capacity`, which stops the writing as a sink's failure +does. A sink that appends to a string of the program's choosing, a +`std::pmr::string` among them, keeps the text in memory the program chooses +(<<document-allocators-resource>>). + +[#document-stringify-quote] +=== A string alone, quoted + +`wd::quote(text, out)` is `JSON.stringify` of a string alone: it appends the string to `out` as a +JSON string literal, its quotes included, with the bytes `stringify` writes of the same string, +from the same code. `out` is a string of the program's own, a `std::string`, a `std::pmr::string` +or any type with `append(const char*, std::size_t)`, and the only thing that allocates, so a JSON +text of a fixed shape is written field by field into memory the program chooses, without a +document: + +[source] +---- +include::{examples}/document_streaming.cpp[tag=quote,indent=0] +---- + +[listing] +---- +include::{examples}/document_streaming.expected[lines=14..15] +---- + +Text in a `std::string_view` is UTF-8, which `quote` checks: text that is not UTF-8, which no +JavaScript string is, returns `wd::errc::type` and leaves `out` as it was, as the last line shows, +which is {cpp}'s alone. Text in a `std::u16string_view` is UTF-16, any sequence of code units, with a +lone surrogate written as `\u` and its four lowercase hex digits, as JavaScript writes it since +ES2019; that overload has no failure of its own, and returns nothing. diff --git a/doc/testing.adoc b/doc/testing.adoc index 150caf7..eef1fbf 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -77,6 +77,22 @@ document's tests are lightweight_test programs, one per subject, under `test/`, operations, no byte left of an erased secret, shrunk, a full external buffer, a buffer that is not 16-aligned, and a header whose container offset lies. +| `allocator` +| A document's allocator, with the global `operator new` counted: the image created, grown, shrunk, + cloned, moved and move-assigned in a memory resource and between two, with no call of it; the + same image in any allocator, one of the test's own among them; external documents that carry + their allocator; the copy's allocator; and, with exceptions, an allocator with no room, + `errc::capacity` with nothing changed (<<document-allocators-proof>>). + +| `allocator_tree`, `allocator_values`, `allocator_parse`, `allocator_stringify` +| The working state of each operation in the document's allocator, with no call of the global + `operator new`: what a change stages and compaction's walk; the handles, missing members' keys, + deep equality, `Object.assign`, the array methods and the containers' views; a whole text parsed, + with selectors and revivers; `stringify_to` into a `std::pmr::string`. A parse in chunks calls it + exactly as often as Boost.JSON's stack grows, and `stringify` as often as its string does. Both + traits, strings and keys longer than any small-string buffer, and, with exceptions, a resource + that fails at each allocation in turn, every failure `errc::capacity` with the document unchanged. + | `stringify` | `stringify` and `stringify_to` against Node's text: indentation, empty containers, escapes, numbers, dates, bytes under each policy, a lone surrogate under `js_traits`, an undefined root, diff --git a/example/Jamfile b/example/Jamfile index 2217534..ab02054 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -30,6 +30,7 @@ webcpp.example document_streaming.cpp ; webcpp.example document_selectors.cpp ; webcpp.example document_traits.cpp ; webcpp.example document_image.cpp ; +webcpp.example document_allocators.cpp ; # The core in a build without exceptions, whatever the build asks. webcpp.example document_no_exceptions.cpp : <exception-handling>off ; diff --git a/example/document_allocators.cpp b/example/document_allocators.cpp new file mode 100644 index 0000000..83253eb --- /dev/null +++ b/example/document_allocators.cpp @@ -0,0 +1,86 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A document whose memory is a resource of the program's own: parsed, changed and written into a +// buffer the program gave, with the null resource past its end; cloned into a second buffer; and +// moved back across the two, which copies the image into the target's resource once. + +#include <webcpp/document.hpp> + +#include <cstddef> +#include <iostream> +#include <memory_resource> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +namespace wd = webcpp::document; + +int main() { + // tag::resource[] + // 64 KiB of the program's own. Past their end the null resource refuses, so nothing of the + // document can reach the global heap. + std::vector<std::byte> memory(std::size_t{64} * 1024); + std::pmr::monotonic_buffer_resource arena(memory.data(), memory.size(), + std::pmr::null_memory_resource()); + const std::pmr::polymorphic_allocator<std::byte> alloc(&arena); + + // JSON.parse(text): the image and the parse's working state in the arena. + wd::result<wd::pmr::document> made = wd::parse( + R"({"user":"Ada","langs":["Analytical"],"draft":true})", wd::parse_options(), alloc); + if (made.has_error()) { + std::cout << "error: " << made.error().message() << '\n'; + return 1; + } + wd::pmr::document& doc = *made; + + // doc.user = "Lovelace"; doc.langs.push("Note G"); delete doc.draft; their staging in the + // arena. + if (!doc["user"].set("Lovelace") || !doc["langs"].push("Note G") || + !doc.root().erase("draft")) { + std::cout << "error: the arena is full\n"; + return 1; + } + + // JSON.stringify(doc), into a string of the same arena. + std::pmr::string text(&arena); + if (!wd::stringify_to(doc, [&text](std::string_view piece) { text.append(piece); })) { + return 1; + } + std::cout << text << '\n'; + // end::resource[] + + // tag::clone[] + // structuredClone(doc), into a second buffer of the program's own. + std::vector<std::byte> other_memory(std::size_t{64} * 1024); + std::pmr::monotonic_buffer_resource other(other_memory.data(), other_memory.size(), + std::pmr::null_memory_resource()); + wd::result<wd::pmr::document> copy = + doc.clone(std::pmr::polymorphic_allocator<std::byte>(&other)); + if (copy.has_error() || !(*copy)["user"].set("Byron")) { + return 1; + } + std::cout << std::boolalpha + << "the copy in the second arena: " << (copy->get_allocator().resource() == &other) + << '\n'; + // JSON.stringify(copy), piece by piece to the standard output. + if (!wd::stringify_to(*copy, [](std::string_view piece) { std::cout << piece; })) { + return 1; + } + std::cout << '\n'; + // end::clone[] + + // tag::move[] + // The arenas differ, so the move assignment copies the copy's image into the first arena, one + // copy of its bytes, and leaves the copy holding nothing. + doc = std::move(*copy); + std::cout << "doc in the first arena: " << (doc.get_allocator().resource() == &arena) << ", " + << doc.image().size() << " bytes: " << doc["user"].value_or(std::string_view()) + << '\n'; + std::cout << "the copy: " << copy->image().size() << " bytes\n"; + // end::move[] +} diff --git a/example/document_allocators.expected b/example/document_allocators.expected new file mode 100644 index 0000000..418a7f3 --- /dev/null +++ b/example/document_allocators.expected @@ -0,0 +1,5 @@ +{"user":"Lovelace","langs":["Analytical","Note G"]} +the copy in the second arena: true +{"user":"Byron","langs":["Analytical","Note G"]} +doc in the first arena: true, 4096 bytes: Byron +the copy: 0 bytes diff --git a/example/document_streaming.cpp b/example/document_streaming.cpp index eb2f306..1eebfb6 100644 --- a/example/document_streaming.cpp +++ b/example/document_streaming.cpp @@ -6,14 +6,18 @@ // Streaming in both directions: JSON text fed to the parser in chunks split inside a string and a // number, a syntax error and the offset where it was found, a parser that stays failed or finished -// until it is reset, the limits of a parse, and a document written in pieces to a sink. +// until it is reset, the limits of a parse, a document written in pieces to a sink, and a JSON text +// written field by field, its strings quoted as JSON.stringify quotes them. #include <webcpp/document.hpp> +#include <cstddef> #include <cstdint> #include <iostream> +#include <memory_resource> #include <string> #include <string_view> +#include <vector> namespace wd = webcpp::document; @@ -93,4 +97,30 @@ int main() { 0, 8); std::cout << kept << " then " << stopped.error().message() << '\n'; // end::stringify_to[] + + // tag::quote[] + // A JSON text written field by field, without a document, into a string of the program's own + // resource, which alone allocates. + std::vector<std::byte> storage(1024); + std::pmr::monotonic_buffer_resource arena(storage.data(), storage.size()); + std::pmr::string message(&arena); + message += R"({"type":)"; + if (const wd::result<void> quoted = wd::quote("offer", message); quoted.has_error()) { + return 1; + } + message += R"(,"sdp":)"; + if (const wd::result<void> quoted = wd::quote("v=0\r\ns=\"-\"\r\n", message); + quoted.has_error()) { + return 1; + } + // UTF-16 that ends in half of a pair, which JSON.stringify writes as an escape. + message += R"(,"label":)"; + wd::quote(std::u16string{u'a', 0xD83D}, message); + message += '}'; + std::cout << message << '\n'; + + // Text that is not UTF-8 is refused, and the string is left as it was. + const wd::result<void> refused = wd::quote("\xff", message); + std::cout << refused.error().message() << ", " << message.size() << " bytes kept\n"; + // end::quote[] } diff --git a/example/document_streaming.expected b/example/document_streaming.expected index 23cee79..50f9bd0 100644 --- a/example/document_streaming.expected +++ b/example/document_streaming.expected @@ -11,3 +11,5 @@ write [2]]: no room left at 5 [[[1]]]: no room left {"name":|"Ada","t|ags":["m|ath"],"n|":1500}| {"name": then no room left +{"type":"offer","sdp":"v=0\r\ns=\"-\"\r\n","label":"a\ud83d"} +a value of another kind, 61 bytes kept diff --git a/include/webcpp/document.hpp b/include/webcpp/document.hpp index 7eecdbd..d65ae99 100644 --- a/include/webcpp/document.hpp +++ b/include/webcpp/document.hpp @@ -25,7 +25,9 @@ #include <webcpp/document/number.hpp> #include <webcpp/document/parse.hpp> #include <webcpp/document/parser.hpp> +#include <webcpp/document/quote.hpp> #include <webcpp/document/shared.hpp> +#include <webcpp/document/storage.hpp> #include <webcpp/document/stream.hpp> #include <webcpp/document/stringify.hpp> #include <webcpp/document/traits.hpp> diff --git a/include/webcpp/document/containers.hpp b/include/webcpp/document/containers.hpp index 0510142..66dbe73 100644 --- a/include/webcpp/document/containers.hpp +++ b/include/webcpp/document/containers.hpp @@ -43,12 +43,10 @@ #include <optional> #include <ranges> #include <span> -#include <string> #include <string_view> #include <tuple> #include <type_traits> #include <utility> -#include <vector> namespace webcpp::document { @@ -113,7 +111,9 @@ struct walker { static constexpr bool sorted_keys = std::same_as<typename Traits::object, sorted>; /** The container of an attached tree's nodes. */ - static const container<Traits>& nodes_of(const tree<Traits>& t) noexcept { return *t.nodes(); } + static const container<Traits>& nodes_of(const tree_view<Traits>& t) noexcept { + return *t.nodes(); + } /** Whether a walk of `w` over the children of a node of kind `k` is by key. */ static bool by_keys(walk w, webcpp::document::kind k) noexcept { @@ -121,7 +121,8 @@ struct walker { } /** The first child of `parent` in the walk's order, or null. */ - static const node_type* first(const tree<Traits>& t, std::uint64_t parent, walk w) noexcept { + static const node_type* first(const tree_view<Traits>& t, std::uint64_t parent, + walk w) noexcept { const node_type* p = t.find(parent); if (p == nullptr) { return nullptr; @@ -132,7 +133,8 @@ struct walker { } /** The last child of `parent` in the walk's order, or null. */ - static const node_type* last(const tree<Traits>& t, std::uint64_t parent, walk w) noexcept { + static const node_type* last(const tree_view<Traits>& t, std::uint64_t parent, + walk w) noexcept { const node_type* p = t.find(parent); if (p == nullptr) { return nullptr; @@ -143,7 +145,7 @@ struct walker { } /** The child after (`forward`) or before `child` in the walk's order, or null. */ - static const node_type* step(const tree<Traits>& t, const node_type& child, walk w, + static const node_type* step(const tree_view<Traits>& t, const node_type& child, walk w, bool forward) noexcept { const container<Traits>& nodes = nodes_of(t); // Under sorted, members are all in the key group and elements in the index group. @@ -152,32 +154,24 @@ struct walker { : step_in(nodes.template get<by_order>(), child, forward); } - // A key is transcoded on the process heap with utf16, whose exhaustion ends the program, as - // the library tolerates. - // NOLINTBEGIN(bugprone-exception-escape) /** The first member of `object` whose key is not before (`upper` false) or is after (`upper` true) `utf8` in key order, or null; null for a key that is not valid UTF-8. */ - static const node_type* bound(const tree<Traits>& t, std::uint64_t object, + static const node_type* bound(const tree_view<Traits>& t, std::uint64_t object, std::string_view utf8, bool upper) noexcept { if (!valid_utf8(utf8)) { return nullptr; } const auto& keys = nodes_of(t).template get<by_key>(); if constexpr (std::same_as<typename Traits::string, utf16>) { - std::vector<char16_t> units(static_cast<std::size_t>(utf16_length(utf8))); - to_utf16(utf8, units.data()); - const std::span<const std::byte> bytes = std::as_bytes(std::span(units)); - return bound_in(keys, object, - {reinterpret_cast<const char*>(bytes.data()), bytes.size()}, upper); + // The index compares the UTF-8 with the stored keys as it decodes it: no copy is made. + return bound_in(keys, object, utf8_lookup{utf8}, upper); } else { return bound_in(keys, object, utf8, upper); } } - // NOLINTEND(bugprone-exception-escape) - /** The first child of `parent` in `index`, or null. */ template <class Index> static const node_type* first_in(const Index& index, std::uint64_t parent) noexcept { @@ -212,11 +206,14 @@ struct walker { return it->parent != child.parent ? nullptr : &*it; } - /** The bound of the key `stored`, in the traits' encoding, among the members of `object`. */ - template <class Index> - static const node_type* bound_in(const Index& keys, std::uint64_t object, - std::string_view stored, bool upper) noexcept { - const auto probe = std::make_tuple(object, stored); + /** + The bound of `key` among the members of `object`: in the traits' encoding as a + `std::string_view`, or in UTF-8 as a @ref utf8_lookup. + */ + template <class Index, class Key> + static const node_type* bound_in(const Index& keys, std::uint64_t object, const Key& key, + bool upper) noexcept { + const auto probe = std::make_tuple(object, key); const auto it = upper ? keys.upper_bound(probe) : keys.lower_bound(probe); return it == keys.end() || it->parent != object ? nullptr : &*it; } @@ -226,7 +223,7 @@ struct walker { template <class Traits, class Storage> const node<Traits>* container_node(basic_document<Traits, Storage>* doc, std::uint64_t id, webcpp::document::kind k) noexcept { - const tree<Traits>* t = doc == nullptr ? nullptr : access::tree_of(std::as_const(*doc)); + const tree_view<Traits>* t = doc == nullptr ? nullptr : access::tree_of(std::as_const(*doc)); const node<Traits>* n = t == nullptr ? nullptr : t->find(id); return n == nullptr || n->kind != k ? nullptr : n; } @@ -247,11 +244,12 @@ inline constexpr bool is_document<basic_document<Traits, Storage>> = true; It reads a source through @ref access alone, not through `detail/value_array.hpp`'s helpers, which are not yet declared when that header is the one a program includes first. */ -template <class Traits, class T> +template <class Traits, class Allocator, class T> requires settable<Traits, T> -result<void> prepare_for_view(const T& v, prepared<Traits>& out, bool undefined_is_null) noexcept { +result<void> prepare_for_view(const T& v, prepared<Traits, Allocator>& out, + bool undefined_is_null) noexcept { if constexpr (copy_source<Traits, T>) { - const tree<Traits>* from = access::tree_of(v); + const tree_view<Traits>* from = access::tree_of(v); if (from == nullptr) { return errc::type; } @@ -326,9 +324,6 @@ class WEBCPP_DOCUMENT_NO_DANGLING child_iterator { child_iterator(document_type* doc, std::uint64_t parent, std::uint64_t child) noexcept : doc_(doc), parent_(parent), child_(child) {} - // A handle of a node holds no key, so making one allocates nothing; were it to, the process - // heap's exhaustion would end the program, as the library tolerates. - // NOLINTBEGIN(bugprone-exception-escape) /** The current child. */ reference operator*() const noexcept { auto h = access::handle_at<Handle>(doc_, child_); @@ -352,11 +347,9 @@ class WEBCPP_DOCUMENT_NO_DANGLING child_iterator { /** The current child, held, for `it->second` and `it->get<T>()`. */ pointer operator->() const noexcept { return pointer(**this); } - // NOLINTEND(bugprone-exception-escape) - /** Moves to the next child, or to the end after the last. */ child_iterator& operator++() noexcept { - const tree<traits>* t = tree_ptr(); + const tree_view<traits>* t = tree_ptr(); const node<traits>* n = t == nullptr ? nullptr : t->find(child_); const node<traits>* next = n == nullptr ? nullptr : walker<traits>::step(*t, *n, Walk, true); @@ -373,7 +366,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING child_iterator { /** Moves to the previous child, or to the last from the end. */ child_iterator& operator--() noexcept { - const tree<traits>* t = tree_ptr(); + const tree_view<traits>* t = tree_ptr(); const node<traits>* previous = nullptr; if (t != nullptr && child_ == 0) { previous = walker<traits>::last(*t, parent_, Walk); @@ -402,7 +395,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING child_iterator { private: /** The tree of the document, or null when there is none. */ - [[nodiscard]] const tree<traits>* tree_ptr() const noexcept { + [[nodiscard]] const tree_view<traits>* tree_ptr() const noexcept { return doc_ == nullptr ? nullptr : access::tree_of(std::as_const(*doc_)); } @@ -560,7 +553,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_object_by_key { : doc_(doc), id_(id) {} /** The tree of the document; the object's node must be there. */ - [[nodiscard]] const detail::tree<traits_type>* tree_ptr() const noexcept { + [[nodiscard]] const detail::tree_view<traits_type>* tree_ptr() const noexcept { return detail::access::tree_of(std::as_const(*doc_)); } @@ -883,13 +876,16 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_object_ref { return detail::container_node(doc_, id_, webcpp::document::kind::object); } + /** The allocator of the document's working state. */ + using allocator_type = storage_type::allocator_type; + /** The tree of the document; the object's node must be there. */ - [[nodiscard]] const detail::tree<traits_type>* tree_ptr() const noexcept { + [[nodiscard]] const detail::tree<traits_type, allocator_type>* tree_ptr() const noexcept { return detail::access::tree_of(std::as_const(*doc_)); } /** The tree of the document, to write; the object's node must be there. */ - [[nodiscard]] detail::tree<traits_type>* writable_tree() const noexcept { + [[nodiscard]] detail::tree<traits_type, allocator_type>* writable_tree() const noexcept { return detail::access::tree_of(*doc_); } @@ -902,7 +898,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_object_ref { template <class T> [[nodiscard]] result<std::pair<iterator, bool>> put(std::string_view key, const T& v, bool created) const noexcept { - detail::prepared<traits_type> p; + detail::prepared<traits_type, allocator_type> p(writable_tree()->get_allocator()); if (const auto made = detail::prepare_for_view(v, p, false); !made.has_value()) { return made.error(); } @@ -913,25 +909,12 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_object_ref { return std::pair(iterator(doc_, id_, id.unsafe_value()), created); } - // A UTF-16 key is turned into UTF-8 on the process heap, whose exhaustion ends the program, as - // the library tolerates. - // NOLINTBEGIN(bugprone-exception-escape) - /** Erases the member `m` of the object, which needs no room. */ + /** Erases the member `m` of the object, by its id, which needs no room and cannot fail. */ void erase_member(const detail::node<traits_type>& m) const noexcept { - // The tree finds the member by its key before it frees anything, so a key read from the - // image may be given as it is. - if constexpr (std::same_as<typename traits_type::string, utf16>) { - const std::u16string_view units = m.key.units(); - std::string key(static_cast<std::size_t>(detail::utf8_size(units)), '\0'); - detail::to_utf8(units, key.data()); - static_cast<void>(writable_tree()->erase_member(id_, key)); - } else { - static_cast<void>(writable_tree()->erase_member(id_, m.key.chars())); - } + [[maybe_unused]] const auto erased = writable_tree()->erase_member_by_id(id_, m.id); + BOOST_ASSERT(erased.has_value() && erased.unsafe_value()); } - // NOLINTEND(bugprone-exception-escape) - basic_document<traits_type, storage_type>* doc_ = nullptr; std::uint64_t id_ = 0; }; @@ -1124,12 +1107,12 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_array_ref { if (!index.has_value()) { return errc::type; } - detail::prepared<traits_type> p; + detail::tree<traits_type, allocator_type>* t = writable_tree(); + detail::prepared<traits_type, allocator_type> p(t->get_allocator()); if (const auto made = detail::prepare_for_view(v, p, true); !made.has_value()) { return made.error(); } const detail::item<traits_type> item = p.value(); - detail::tree<traits_type>* t = writable_tree(); if (const auto done = t->insert_elements(id_, *index, std::span(&item, 1)); !done.has_value()) { return done.error(); @@ -1252,13 +1235,16 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_array_ref { return detail::container_node(doc_, id_, webcpp::document::kind::array); } + /** The allocator of the document's working state. */ + using allocator_type = storage_type::allocator_type; + /** The tree of the document; the array's node must be there. */ - [[nodiscard]] const detail::tree<traits_type>* tree_ptr() const noexcept { + [[nodiscard]] const detail::tree<traits_type, allocator_type>* tree_ptr() const noexcept { return detail::access::tree_of(std::as_const(*doc_)); } /** The tree of the document, to write; the array's node must be there. */ - [[nodiscard]] detail::tree<traits_type>* writable_tree() const noexcept { + [[nodiscard]] detail::tree<traits_type, allocator_type>* writable_tree() const noexcept { return detail::access::tree_of(*doc_); } @@ -1297,7 +1283,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_array_ref { if (n == 0) { return; } - // A removal allocates nothing in the image, so its probe always finds room. + // A removal allocates nothing, in the image or in the allocator, so it cannot fail. [[maybe_unused]] const auto removed = writable_tree()->erase_elements(id_, index, n); BOOST_ASSERT(removed.has_value()); } diff --git a/include/webcpp/document/detail/allocation.hpp b/include/webcpp/document/detail/allocation.hpp new file mode 100644 index 0000000..7ecae22 --- /dev/null +++ b/include/webcpp/document/detail/allocation.hpp @@ -0,0 +1,54 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + What an allocator's failure is, and how an operation that allocates turns it into a value: with + exceptions, an allocator fails by throwing `std::bad_alloc`, a type derived from it, or + Boost.Interprocess's `bad_alloc`, which its allocators throw and which derives from + `std::exception` alone. Anything else an allocator throws leaves a `noexcept` operation, and ends + the program; without exceptions, an allocator that fails ends the program, as it does itself. +*/ + +#ifndef WEBCPP_DOCUMENT_DETAIL_ALLOCATION_HPP +#define WEBCPP_DOCUMENT_DETAIL_ALLOCATION_HPP + +#include <webcpp/document/config.hpp> + +#include <boost/interprocess/exceptions.hpp> // lint-world: its allocators' failure, no segment + +#include <new> +#include <utility> + +namespace webcpp::document::detail { + +/** + Runs `run` and returns what it returns, or, with exceptions, what `failed` returns when an + allocator fails in it: by throwing `std::bad_alloc`, a type derived from it, or + Boost.Interprocess's `bad_alloc`. Anything else `run` throws propagates. + + @param run What allocates. + @param failed What gives the result of a failure, of the type `run` returns. + @return What `run` or `failed` returned. +*/ +template <class Run, class Failed> +auto unless_allocation_fails(Run&& run, [[maybe_unused]] Failed&& failed) + -> decltype(std::forward<Run>(run)()) { +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + try { + return std::forward<Run>(run)(); + } catch (const std::bad_alloc&) { + return failed(); + } catch (const boost::interprocess::bad_alloc&) { + return failed(); + } +#else + return std::forward<Run>(run)(); +#endif +} + +} // namespace webcpp::document::detail + +#endif // WEBCPP_DOCUMENT_DETAIL_ALLOCATION_HPP diff --git a/include/webcpp/document/detail/convert.hpp b/include/webcpp/document/detail/convert.hpp index 7c6662c..c840700 100644 --- a/include/webcpp/document/detail/convert.hpp +++ b/include/webcpp/document/detail/convert.hpp @@ -25,8 +25,10 @@ #include <webcpp/document/kind.hpp> #include <webcpp/document/literal.hpp> #include <webcpp/document/number.hpp> +#include <webcpp/document/storage.hpp> #include <webcpp/document/traits.hpp> +#include <boost/config.hpp> #include <boost/decimal/decimal128_t.hpp> #include <algorithm> @@ -39,6 +41,8 @@ #include <cstddef> #include <cstdint> #include <limits> +#include <memory> +#include <new> #include <optional> #include <span> #include <string> @@ -49,6 +53,24 @@ namespace webcpp::document::detail { +// Only the allocator's failure can leave `f`: the sizes it asks are of what memory already holds, +// below every container's max_size, so no std::length_error. +// NOLINTBEGIN(bugprone-exception-escape) + +/** + Calls `f`, which returns a `result`, and with exceptions turns an allocator's failure + (@ref unless_allocation_fails) into @ref errc::capacity, what an operation whose working state + did not fit returns before it changed anything. Without exceptions an allocator that fails ends + the program, as it does. +*/ +template <class F> +auto bad_alloc_as_capacity(F&& f) noexcept -> decltype(std::forward<F>(f)()) { + using result_type = decltype(std::forward<F>(f)()); + return unless_allocation_fails(std::forward<F>(f), [] { return result_type(errc::capacity); }); +} + +// NOLINTEND(bugprone-exception-escape) + /** An integer type that is a number: any but `bool` and the character types. */ template <class T> concept number_integer = std::integral<T> && !std::same_as<T, bool> && !std::same_as<T, char> && @@ -84,7 +106,7 @@ concept readable = std::same_as<T, std::u16string_view> || std::same_as<T, date_ms> || std::same_as<T, std::vector<std::byte>> || std::same_as<T, std::span<const std::byte>>; -template <class Traits> +template <class Traits, class Allocator = std::allocator<std::byte>> struct converter; /** @@ -92,13 +114,20 @@ struct converter; traits' encoding and a literal's entries, owned here until the tree has copied them. Text and bytes the caller gives in the traits' encoding, and a literal's keys, are not copied: the - item points at them, which must outlive it. + item points at them, which must outlive it. What it owns is allocated through `Allocator`, rebound: + the allocator of the document the value is stored in. */ -template <class Traits> +template <class Traits, class Allocator = std::allocator<std::byte>> class prepared { public: - /** A value holding `null`. */ - prepared() noexcept = default; + /** A value holding `null`, its buffers in a default-constructed allocator. */ + prepared() noexcept(std::is_nothrow_default_constructible_v<Allocator>) + : prepared(Allocator()) {} + + /** A value holding `null`, its buffers in `alloc`. */ + explicit prepared(const Allocator& alloc) noexcept + // Each list constructs its allocator from `alloc`, which need not convert to it. + : alloc_(alloc), utf8_(alloc), utf16_(alloc), bytes_(alloc), entries_(alloc) {} /** A prepared value is not copied: its item points into it. */ prepared(const prepared&) = delete; @@ -109,13 +138,17 @@ class prepared { /** Moves a prepared value, its item pointing into its new place. */ prepared(prepared&& other) noexcept // A vector moved keeps its buffer, so the item still points at what it held. - : item_(std::exchange(other.item_, item<Traits>{})), + : alloc_(other.alloc_), + item_(std::exchange(other.item_, item<Traits>{})), utf8_(std::move(other.utf8_)), utf16_(std::move(other.utf16_)), bytes_(std::move(other.bytes_)), entries_(std::move(other.entries_)) {} - /** Moves a prepared value, its item pointing into its new place. */ + /** + Moves a prepared value, its item pointing into its new place; both hold buffers of the same + allocator. + */ prepared& operator=(prepared&& other) noexcept { if (this != &other) { item_ = std::exchange(other.item_, item<Traits>{}); @@ -133,28 +166,94 @@ class prepared { /** The item, valid while this object lives and is not changed. */ [[nodiscard]] const item<Traits>& value() const noexcept { return item_; } + /** The allocator of what it owns. */ + [[nodiscard]] Allocator get_allocator() const noexcept { return alloc_; } + /** Makes the item a deep copy of the node `id` of `from`, which may be the tree it is stored in. */ - void copy_of(const tree<Traits>& from, std::uint64_t id) noexcept { + void copy_of(const tree_view<Traits>& from, std::uint64_t id) noexcept { clear(); item_.from = &from; item_.from_id = id; } private: - template <class> + template <class, class> friend struct converter; - /** Holds `null` again, and owns nothing. */ + /** A buffer of `T` in the allocator. */ + template <class T> + using buffer = std::vector<T, rebound<Allocator, T>>; + + /** + The buffers of `T` in the allocator, and how many of them hold the item's values: those past + them are kept, with their room, for the values prepared next. + */ + template <class T> + struct buffers { + /** No buffer, in `alloc`. */ + explicit buffers(const Allocator& alloc) noexcept + : list(rebound<Allocator, buffer<T>>(alloc)) {} + + /** Buffers are not copied: an item points into them. */ + buffers(const buffers&) = delete; + + /** Buffers are not copied: an item points into them. */ + buffers& operator=(const buffers&) = delete; + + /** Takes the buffers of `other`, which holds none after it. */ + buffers(buffers&& other) noexcept + : list(std::move(other.list)), used(std::exchange(other.used, 0)) {} + + /** Takes the buffers of `other`, of the same allocator, which holds none after it. */ + buffers& operator=(buffers&& other) noexcept { + list = std::move(other.list); + used = std::exchange(other.used, 0); + return *this; + } + + /** Gives back every buffer. */ + ~buffers() = default; + + /** The buffers, each in the allocator. */ + std::vector<buffer<T>, rebound<Allocator, buffer<T>>> list; + + /** How many of them hold the item's values. */ + std::size_t used = 0; + }; + + /** + A buffer of `size` values of `T`, each value-initialized, in the allocator: the next of `b`'s + kept buffers when there is one, which allocates only when it has less room, else a new one. + */ + template <class T> + buffer<T>& add(buffers<T>& b, std::size_t size) { + if (b.used < b.list.size()) { + buffer<T>& kept = b.list[b.used]; + kept.assign(size, T{}); + ++b.used; + return kept; + } + // Made, then moved in: a polymorphic allocator constructs an element with itself after the + // arguments, which a size and an allocator already are. + buffer<T>& made = b.list.emplace_back(buffer<T>(size, rebound<Allocator, T>(alloc_))); + ++b.used; + return made; + } + + /** Holds `null` again, its buffers kept, with their room, for the values prepared next. */ void clear() noexcept { item_ = item<Traits>{}; - utf8_.clear(); - utf16_.clear(); - bytes_.clear(); - entries_.clear(); + utf8_.used = 0; + utf16_.used = 0; + bytes_.used = 0; + entries_.used = 0; } + /** The allocator. */ + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS Allocator alloc_; + /** The item. */ item<Traits> item_; @@ -162,23 +261,23 @@ class prepared { // is added after it. /** Text transcoded to UTF-8. */ - std::vector<std::vector<char>> utf8_; + buffers<char> utf8_; /** Text transcoded to UTF-16. */ - std::vector<std::vector<char16_t>> utf16_; + buffers<char16_t> utf16_; /** Bytes decoded from text. */ - std::vector<std::vector<std::byte>> bytes_; + buffers<std::byte> bytes_; /** The entries of each literal container, a nested one pointing at its own. */ - std::vector<std::vector<literal_entry<Traits>>> entries_; + buffers<literal_entry<Traits>> entries_; }; /** The conversions' work, with access to what a @ref prepared value owns: C++ values into items, and nodes back into C++ values. */ -template <class Traits> +template <class Traits, class Allocator> struct converter { /** The traits' number. */ using number_type = Traits::number; @@ -190,7 +289,7 @@ struct converter { using kind_t = webcpp::document::kind; /** A prepared value of these traits. */ - using prepared_t = prepared<Traits>; + using prepared_t = prepared<Traits, Allocator>; /** An item of these traits. */ using item_t = item<Traits>; @@ -199,7 +298,7 @@ struct converter { using node_t = node<Traits>; /** A tree of these traits. */ - using tree_t = tree<Traits>; + using tree_t = tree_view<Traits>; /** Whether strings are stored as UTF-16 code units. */ static constexpr bool utf16_text = std::same_as<typename Traits::string, utf16>; @@ -210,11 +309,27 @@ struct converter { /** Whether bytes are base64url text rather than base64. */ static constexpr bool url = std::same_as<typename Traits::bytes, base64url>; + /** A buffer of bytes in `A`, rebound. */ + template <class A> + using bytes_in = std::vector<std::byte, rebound<A, std::byte>>; + + /** + How many characters of UTF-16 text become ASCII at a time, on the stack, to read as base64: a + whole number of base64's groups of four. + */ + static constexpr std::size_t ascii_block = 256; + + /** + Room for the longest text Date.prototype.toJSON writes, `+275760-09-13T00:00:00.000Z`, of 27 + characters: longer text is no date. + */ + static constexpr std::size_t date_text_room = 32; + /** Prepares `v` from nothing; on failure `out` holds `null`. */ template <class T> - static result<void> prepare_value(const T& v, prepared_t& out) { + static result<void> prepare_value(const T& v, prepared_t& out) noexcept { out.clear(); - result<void> held = hold(out, v); + result<void> held = bad_alloc_as_capacity([&] { return hold(out, v); }); if (!held.has_value()) { out.clear(); } @@ -233,9 +348,10 @@ struct converter { /** Prepares a JSON string from nothing, revived as asked; on failure `out` holds `null`. */ static result<void> prepare_json_string(std::string_view utf8, bool revive_dates, - bool revive_bytes, prepared_t& out) { + bool revive_bytes, prepared_t& out) noexcept { out.clear(); - result<void> held = hold_json_string(out, utf8, revive_dates, revive_bytes); + result<void> held = bad_alloc_as_capacity( + [&] { return hold_json_string(out, utf8, revive_dates, revive_bytes); }); if (!held.has_value()) { out.clear(); } @@ -402,12 +518,14 @@ struct converter { return hold_form(owner, owner.item_, *date); } } - // Under javascript_bytes, bytes are an object's shape, which no string has. + // Under javascript_bytes, bytes are an object's shape, which no string has. Text that is + // not base64 is known for it before anything is allocated. if constexpr (!javascript_shape) { if (revive_bytes) { - if (result<std::vector<std::byte>> decoded = decode(text); decoded.has_value()) { - const std::vector<std::byte>& bytes = - owner.bytes_.emplace_back(std::move(decoded).unsafe_value()); + if (const result<std::uint64_t> size = base64_bytes(text); size.has_value()) { + auto& bytes = + owner.add(owner.bytes_, static_cast<std::size_t>(size.unsafe_value())); + decode_into(text, bytes.data()); return hold_form(owner, owner.item_, std::span<const std::byte>(bytes)); } } @@ -492,8 +610,7 @@ struct converter { } out.kind = kind_t::string; if constexpr (utf16_text) { - std::vector<char16_t>& units = - owner.utf16_.emplace_back(static_cast<std::size_t>(utf16_length(v))); + auto& units = owner.add(owner.utf16_, static_cast<std::size_t>(utf16_length(v))); to_utf16(v, units.data()); out.text = std::as_bytes(std::span(units)); } else { @@ -512,8 +629,7 @@ struct converter { if (!valid_utf16(v)) { return errc::type; } - std::vector<char>& chars = - owner.utf8_.emplace_back(static_cast<std::size_t>(utf8_size(v))); + auto& chars = owner.add(owner.utf8_, static_cast<std::size_t>(utf8_size(v))); to_utf8(v, chars.data()); out.kind = kind_t::string; out.text = std::as_bytes(std::span(chars)); @@ -552,8 +668,7 @@ struct converter { if (members.empty()) { return {}; } - const std::span<literal_entry<Traits>> entries = - owner.entries_.emplace_back(members.size()); + const std::span<literal_entry<Traits>> entries = owner.add(owner.entries_, members.size()); out.entries = entries.data(); out.entry_count = entries.size(); for (std::size_t i = 0; i < members.size(); ++i) { @@ -577,8 +692,7 @@ struct converter { if (elements.empty()) { return {}; } - const std::span<literal_entry<Traits>> entries = - owner.entries_.emplace_back(elements.size()); + const std::span<literal_entry<Traits>> entries = owner.add(owner.entries_, elements.size()); out.entries = entries.data(); out.entry_count = entries.size(); for (std::size_t i = 0; i < elements.size(); ++i) { @@ -590,18 +704,85 @@ struct converter { return {}; } - /** Base64 or base64url text, by the policy, decoded: @ref errc::type when it is not. */ - static result<std::vector<std::byte>> decode(std::string_view text) { - // Four characters make at most three bytes, and the last group of base64url's fewer. - std::vector<std::byte> out(((text.size() / 4) * 3) + 3); - const result<std::uint64_t> size = read_base64(text, out.data(), url); + /** + The size of the bytes that base64 or base64url text, by the policy, holds, read without + allocating: @ref errc::type when it is not such text. + */ + static result<std::uint64_t> base64_bytes(std::string_view text) noexcept { + const result<std::uint64_t> size = read_base64(text, nullptr, url); if (!size.has_value()) { return errc::type; } - out.resize(static_cast<std::size_t>(size.unsafe_value())); + return size; + } + + /** As @ref base64_bytes, of UTF-16 text. */ + static result<std::uint64_t> base64_bytes(std::u16string_view units) noexcept { + return read_units(units, nullptr); + } + + /** Decodes text that @ref base64_bytes read into `out`, which has room for its bytes. */ + static void decode_into(std::string_view text, std::byte* out) noexcept { + static_cast<void>(read_base64(text, out, url)); + } + + /** As @ref decode_into, of UTF-16 text. */ + static void decode_into(std::u16string_view units, std::byte* out) noexcept { + static_cast<void>(read_units(units, out)); + } + + /** + Base64 or base64url text, by the policy, decoded into a buffer of `alloc` of exactly its + bytes' size, read first, so that text that is not base64 allocates nothing: + @ref errc::type when it is not. + */ + template <class A, class Text> + static result<bytes_in<A>> decode(Text text, const A& alloc) { + const result<std::uint64_t> size = base64_bytes(text); + if (!size.has_value()) { + return size.error(); + } + bytes_in<A> out(static_cast<std::size_t>(size.unsafe_value()), + rebound<A, std::byte>(alloc)); + decode_into(text, out.data()); return out; } + /** A UTF-16 unit as its ASCII character, or a zero, which no date's or base64's text holds. */ + static constexpr char ascii_of(char16_t unit) noexcept { + return unit < 0x80 ? static_cast<char>(unit) : '\0'; + } + + /** + Reads UTF-16 base64 text, by the policy, a block at a time, made ASCII on the stack, so that no + copy of the text is allocated, its bytes written at `out` when it is not null: their size, or + @ref errc::type when it is not base64. + */ + static result<std::uint64_t> read_units(std::u16string_view units, std::byte* out) noexcept { + // Every block but the last holds whole groups, which decode alone, three bytes each; as + // padding only ends the text, one of them that ends in '=' is not base64. + std::array<char, ascii_block> chars{}; + std::size_t done = 0; + std::uint64_t written = 0; + do { + const std::size_t count = std::min(units.size() - done, ascii_block); + std::ranges::transform(std::u16string_view(units.data() + done, count), chars.begin(), + ascii_of); + done += count; + if (done != units.size() && chars[count - 1] == '=') { + return errc::type; + } + const result<std::uint64_t> size = + read_base64(std::string_view(chars.data(), count), + out == nullptr ? nullptr : out + written, url); + if (!size.has_value()) { + return errc::type; + } + written += size.unsafe_value(); + } while (done != units.size()); + return written; + } + /** Reads a node of a kind @ref read reads, as `T`. */ template <class T> static result<T> read_as(const tree_t& t, const node_t& n) { @@ -626,7 +807,7 @@ struct converter { } else if constexpr (std::same_as<T, date_ms>) { return read_date_of(n); } else if constexpr (std::same_as<T, std::vector<std::byte>>) { - return read_bytes(t, n); + return read_bytes(t, n, std::allocator<std::byte>()); } else { if (n.kind != kind_t::bytes) { return errc::type; @@ -815,86 +996,96 @@ struct converter { } } - /** - Calls `f` with a string node's text as `std::string_view`: with `utf16`, its ASCII units, and - a zero for each other, which no date's or base64's text holds. - */ - template <class F> - static auto with_ascii(const node_t& n, F&& f) { + /** A string node's text, as Date.prototype.toJSON's, as a date: else nothing. */ + static std::optional<date_ms> date_of_text(const node_t& n) noexcept { if constexpr (utf16_text) { + // A date's text is short: longer text is none, and shorter is made ASCII on the stack. const std::u16string_view units = n.text.units(); - std::string chars(units.size(), '\0'); - std::ranges::transform(units, chars.begin(), [](char16_t unit) { - return unit < 0x80 ? static_cast<char>(unit) : '\0'; - }); - return std::forward<F>(f)(std::string_view(chars)); + std::array<char, date_text_room> chars{}; + if (units.size() > chars.size()) { + return std::nullopt; + } + std::ranges::transform(units, chars.begin(), ascii_of); + return read_date(std::string_view(chars.data(), units.size())); } else { - return std::forward<F>(f)(n.text.chars()); + return read_date(n.text.chars()); } } /** A date node, or a string that is exactly Date.prototype.toJSON's text, as a date. */ - static result<date_ms> read_date_of(const node_t& n) { + static result<date_ms> read_date_of(const node_t& n) noexcept { if (n.kind == kind_t::date) { return n.template load<date_ms>(); } if (n.kind != kind_t::string) { return errc::type; } - const std::optional<date_ms> date = - with_ascii(n, [](std::string_view text) { return read_date(text); }); + const std::optional<date_ms> date = date_of_text(n); if (!date) { return errc::type; } return *date; } - /** A bytes node, or what the bytes policy reads as bytes, as bytes. */ - static result<std::vector<std::byte>> read_bytes(const tree_t& t, const node_t& n) { + /** A bytes node, or what the bytes policy reads as bytes, as bytes in a buffer of `alloc`. */ + template <class A> + static result<bytes_in<A>> read_bytes(const tree_t& t, const node_t& n, const A& alloc) { if (n.kind == kind_t::bytes) { const std::span<const std::byte> bytes = n.text.view(); - return std::vector<std::byte>(bytes.begin(), bytes.end()); + return bytes_in<A>(bytes.begin(), bytes.end(), rebound<A, std::byte>(alloc)); } if constexpr (javascript_shape) { if (n.kind != kind_t::object) { return errc::type; } - return read_byte_object(t, n); + return read_byte_object(t, n, alloc); } else { if (n.kind != kind_t::string) { return errc::type; } - return with_ascii(n, [](std::string_view text) { return decode(text); }); + if constexpr (utf16_text) { + return decode(n.text.units(), alloc); + } else { + return decode(n.text.chars(), alloc); + } } } /** - An object as bytes when it has the shape `JSON.stringify` gives a Uint8Array: keys exactly - `"0"` to `"n-1"`, each holding an integer from 0 to 255. + An object as bytes in a buffer of `alloc` when it has the shape `JSON.stringify` gives a + Uint8Array: keys exactly `"0"` to `"n-1"`, each holding an integer from 0 to 255. The shape is + checked before the buffer is allocated, so that an object of another shape allocates nothing. */ - static result<std::vector<std::byte>> read_byte_object(const tree_t& t, const node_t& n) { + template <class A> + static result<bytes_in<A>> read_byte_object(const tree_t& t, const node_t& n, const A& alloc) { // As many keys as the indices, each found: the keys are exactly those. const std::uint64_t count = t.count(n.id); - std::vector<std::byte> out; - out.reserve(static_cast<std::size_t>(count)); for (std::uint64_t i = 0; i < count; ++i) { - std::array<char, 24> key{}; - const std::to_chars_result written = - std::to_chars(key.data(), key.data() + key.size(), i); - const node_t* element = t.member( - n.id, - std::string_view(key.data(), static_cast<std::size_t>(written.ptr - key.data()))); - const result<std::uint8_t> byte = element == nullptr - ? result<std::uint8_t>(errc::type) - : read_integer<std::uint8_t>(*element); - if (!byte.has_value()) { + if (!byte_at(t, n, i).has_value()) { return errc::type; } - out.push_back(static_cast<std::byte>(byte.unsafe_value())); + } + bytes_in<A> out(static_cast<std::size_t>(count), rebound<A, std::byte>(alloc)); + for (std::uint64_t i = 0; i < count; ++i) { + out[static_cast<std::size_t>(i)] = + static_cast<std::byte>(byte_at(t, n, i).unsafe_value()); } return out; } + /** The byte the member `"i"` of the object `n` holds: @ref errc::type when it holds none. */ + static result<std::uint8_t> byte_at(const tree_t& t, const node_t& n, + std::uint64_t i) noexcept { + std::array<char, 24> key{}; + const std::to_chars_result written = std::to_chars(key.data(), key.data() + key.size(), i); + const node_t* element = t.member( + n.id, std::string_view(key.data(), static_cast<std::size_t>(written.ptr - key.data()))); + if (element == nullptr) { + return errc::type; + } + return read_integer<std::uint8_t>(*element); + } + /** Whether two nodes have the same kind and scalar, and a container the same size. */ static bool same_value(const tree_t& a, const node_t& x, const tree_t& b, const node_t& y) noexcept { @@ -926,88 +1117,92 @@ struct converter { return x.template load<number_type>() == y.template load<number_type>(); } - /** The member of the object `object` of `t` whose key is the key of `child`, or null. */ - static const node_t* member_like(const tree_t& t, std::uint64_t object, const node_t& child) { - if constexpr (utf16_text) { - // Keys enter in UTF-8, so a stored one always has its UTF-8. - const std::u16string_view units = child.key.units(); - std::string key(static_cast<std::size_t>(utf8_size(units)), '\0'); - to_utf8(units, key.data()); - return t.member(object, key); - } else { - return t.member(object, child.key.chars()); - } + /** + The member of the object `object` of `t` whose key is the key of `child`, or null: the two + trees have the same traits, so the key is looked for as it is stored. + */ + static const node_t* member_like(const tree_t& t, std::uint64_t object, + const node_t& child) noexcept { + return t.member_stored(object, child.key.chars()); } /** - Pairs the children of two containers of the same kind and size to compare: elements by index, - members by key; false when a key of `x` is not in `y`. + The node of `b` that stands where `child`, a child of the node `x` of `a`, stands under `y`: + the element of the same index, the member of the same key. */ - static bool pair_children(const tree_t& a, const node_t& x, const tree_t& b, const node_t& y, - std::vector<std::pair<const node_t*, const node_t*>>& pending) { + static const node_t* counterpart(const tree_t& b, const node_t& x, const node_t& y, + const node_t& child) noexcept { if (x.kind == kind_t::array) { - const node_t* d = b.first_child(y.id); - for (const node_t* c = a.first_child(x.id); c != nullptr && d != nullptr; - c = a.next_sibling(*c)) { - pending.emplace_back(c, d); - d = b.next_sibling(*d); - } - return true; + return b.element(y.id, child.ordinal); } - for (const node_t* c = a.first_child(x.id); c != nullptr; c = a.next_sibling(*c)) { - const node_t* d = member_like(b, y.id, *c); - if (d == nullptr) { - return false; - } - pending.emplace_back(c, d); - } - return true; + return member_like(b, y.id, child); } - /** Whether two subtrees are equal, walked with a stack of their own rather than recursion. */ - static bool equal_trees(const tree_t& a, const node_t* x, const tree_t& b, const node_t* y) { + /** + Whether two subtrees are equal: `x` walked in document order through its nodes' links, each + node paired with its counterpart in `y`, so that no stack is allocated and nothing can fail. + */ + static bool equal_trees(const tree_t& a, const node_t* x, const tree_t& b, + const node_t* y) noexcept { if (x == nullptr || y == nullptr) { return x == y; } - std::vector<std::pair<const node_t*, const node_t*>> pending{{x, y}}; - while (!pending.empty()) { - const auto [p, q] = pending.back(); - pending.pop_back(); + const node_t* p = x; + const node_t* q = y; + while (true) { if (!same_value(a, *p, b, *q)) { return false; } - const bool container = p->kind == kind_t::array || p->kind == kind_t::object; - if (container && !pair_children(a, *p, b, *q, pending)) { - return false; + // Down to the first child: containers of one kind and size, so `q` has as many. + if (const node_t* child = a.first_child(p->id)) { + q = counterpart(b, *p, *q, *child); + p = child; + if (q == nullptr) { + return false; + } + continue; + } + // Else to the next sibling of the nearest node that has one, up to `x`. + while (true) { + if (p == x) { + return true; + } + const node_t* parent_p = a.find(p->parent); + const node_t* parent_q = b.find(q->parent); + if (const node_t* sibling = a.next_sibling(*p)) { + q = counterpart(b, *parent_p, *parent_q, *sibling); + p = sibling; + if (q == nullptr) { + return false; + } + break; + } + p = parent_p; + q = parent_q; } } - return true; } }; -// A conversion ends the program where the process heap, which holds a prepared value's transcoded -// text and literal entries, a value read as a std::string or a std::vector, or equal's stack, runs -// out, as the library tolerates. -// NOLINTBEGIN(bugprone-exception-escape) - /** Turns a C++ value into an item: @ref errc::type for text invalid in its encoding or a floating-point value into traits whose `number` is not binary, @ref errc::range for a non-finite decimal or a date out of JavaScript's range. */ -template <class T, class Traits> +template <class T, class Traits, class Allocator> requires preparable<Traits, T> -result<void> prepare(const T& v, prepared<Traits>& out) noexcept { - return converter<Traits>::prepare_value(v, out); +result<void> prepare(const T& v, prepared<Traits, Allocator>& out) noexcept { + return converter<Traits, Allocator>::prepare_value(v, out); } /** Turns a JSON number's text into an item, by value: @ref errc::range when the traits' `number` refuses it. */ -template <class Traits> -result<void> prepare_number(std::string_view json_number, prepared<Traits>& out) noexcept { - return converter<Traits>::prepare_number_text(json_number, out); +template <class Traits, class Allocator> +result<void> prepare_number(std::string_view json_number, + prepared<Traits, Allocator>& out) noexcept { + return converter<Traits, Allocator>::prepare_number_text(json_number, out); } /** @@ -1015,10 +1210,10 @@ result<void> prepare_number(std::string_view json_number, prepared<Traits>& out) is exactly Date.prototype.toJSON's text, or with `revive_bytes` bytes when it is text of the traits' base64 policy; @ref errc::type for text that is not valid UTF-8 after all. */ -template <class Traits> +template <class Traits, class Allocator> result<void> prepare_string(std::string_view utf8, bool revive_dates, bool revive_bytes, - prepared<Traits>& out) noexcept { - return converter<Traits>::prepare_json_string(utf8, revive_dates, revive_bytes, out); + prepared<Traits, Allocator>& out) noexcept { + return converter<Traits, Allocator>::prepare_json_string(utf8, revive_dates, revive_bytes, out); } /** The item of an empty container, `null`, or for a root @ref kind::undefined. */ @@ -1032,6 +1227,10 @@ item<Traits> empty_item(webcpp::document::kind k) noexcept { return made; } +// A value read as a std::string, a std::u16string or a std::vector is the program's own, in the +// standard allocator, not the document's: its exhaustion ends the program, as the library +// tolerates of what it hands the program; read_bytes_with reads bytes into an allocator softly. +// NOLINTBEGIN(bugprone-exception-escape) /** Reads a node as `T`: @ref errc::type for a null node (undefined) or another kind, @ref errc::range for a number that is not an integer, does not fit `T`, or that `T` cannot hold exactly. @@ -1044,26 +1243,41 @@ item<Traits> empty_item(webcpp::document::kind k) noexcept { */ template <class T, class Traits> requires readable<Traits, T> -result<T> read(const tree<Traits>& t, const node<Traits>* n) noexcept { +result<T> read(const tree_view<Traits>& t, const node<Traits>* n) noexcept { if (n == nullptr) { return errc::type; } return converter<Traits>::template read_as<T>(t, *n); } +// NOLINTEND(bugprone-exception-escape) + +/** + Reads a node as bytes, as @ref read reads `std::vector<std::byte>`, into a buffer of `alloc`: a + bytes node, text of the traits' base64 policy, or under `javascript_bytes` an object of a + Uint8Array's shape; @ref errc::type for a null node or another, and with exceptions + @ref errc::capacity when `alloc` has no room for the bytes. +*/ +template <class Traits, class Allocator> +result<std::vector<std::byte, rebound<Allocator, std::byte>>> read_bytes_with( + const tree_view<Traits>& t, const node<Traits>* n, const Allocator& alloc) noexcept { + if (n == nullptr) { + return errc::type; + } + return bad_alloc_as_capacity([&] { return converter<Traits>::read_bytes(t, *n, alloc); }); +} + /** Whether two subtrees are equal, structurally: the same kind; numbers by value; strings, dates and bytes by value; arrays element by element; objects with the same keys, each with an equal value, in any order. A null node is undefined, equal only to another. */ template <class Traits> -bool equal(const tree<Traits>& a, const node<Traits>* x, const tree<Traits>& b, +bool equal(const tree_view<Traits>& a, const node<Traits>* x, const tree_view<Traits>& b, const node<Traits>* y) noexcept { return converter<Traits>::equal_trees(a, x, b, y); } -// NOLINTEND(bugprone-exception-escape) - } // namespace webcpp::document::detail #endif // WEBCPP_DOCUMENT_DETAIL_CONVERT_HPP diff --git a/include/webcpp/document/detail/fwd.hpp b/include/webcpp/document/detail/fwd.hpp index e3f9c7a..db60222 100644 --- a/include/webcpp/document/detail/fwd.hpp +++ b/include/webcpp/document/detail/fwd.hpp @@ -15,12 +15,11 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/storage.hpp> #include <webcpp/document/traits.hpp> namespace webcpp::document { -struct owned; -struct external; struct parse_options; class literal; class object; diff --git a/include/webcpp/document/detail/handler.hpp b/include/webcpp/document/detail/handler.hpp index 3bcbc24..f2fb5dd 100644 --- a/include/webcpp/document/detail/handler.hpp +++ b/include/webcpp/document/detail/handler.hpp @@ -12,7 +12,8 @@ Under an object a value is set as a member, a repeated key replacing the value in place, as JavaScript does; under an array it is appended; at the top it is the root. The handler keeps the text's path of the value being read, keys and indices in the text, which the selectors match and - `on` does not renumber. + `on` does not renumber. What it keeps, the frames, the path and its keys, the pending text and + the value being stored, is allocated through the document's allocator, rebound. */ #ifndef WEBCPP_DOCUMENT_DETAIL_HANDLER_HPP @@ -58,7 +59,12 @@ struct frame { std::uint64_t next_index = 0; }; -/** The handler of Boost.JSON's `basic_parser` that builds the document of a @ref basic_parser. */ +/** + The handler of Boost.JSON's `basic_parser` that builds the document of a @ref basic_parser. + + What a callback allocates, in the allocator, may throw: Boost.JSON's parser lets the exception + out of its `write_some`, where the parser turns it into an error. +*/ template <class Traits, class Storage> class handler { public: @@ -74,8 +80,15 @@ class handler { /** The largest string Boost.JSON hands the handler: no limit of its own. */ static constexpr std::size_t max_string_size = static_cast<std::size_t>(-1); - /** The handler of `owner`, which outlives it. */ - explicit handler(basic_parser<Traits, Storage>& owner) noexcept : owner_(&owner) {} + /** The handler of `owner`, which outlives it, its working state in `owner`'s allocator. */ + explicit handler(basic_parser<Traits, Storage>& owner) noexcept + : owner_(&owner), + frames_(rebound<allocator_type, frame>(owner.alloc_)), + path_(rebound<allocator_type, path_step>(owner.alloc_)), + keys_(rebound<allocator_type, string_type>(owner.alloc_)), + key_(rebound<allocator_type, char>(owner.alloc_)), + text_(rebound<allocator_type, char>(owner.alloc_)), + value_(owner.alloc_) {} /** The text begins: the document is made, or formatted in the external buffer. */ bool on_document_begin(boost::system::error_code& ec) { @@ -207,15 +220,23 @@ class handler { } private: + /** The allocator of the document and of the parser. */ + using allocator_type = Storage::allocator_type; + + /** Text in the allocator. */ + using string_type = + std::basic_string<char, std::char_traits<char>, rebound<allocator_type, char>>; + /** The bytes policy whose bytes are an object's shape, revived when the object ends. */ static constexpr bool bytes_as_objects = std::same_as<typename Traits::bytes, javascript_bytes>; /** A new document: owned, within the options' limit, or formatted in the external buffer. */ result<basic_document<Traits, Storage>> make_document() noexcept { - if constexpr (std::same_as<Storage, owned>) { - return basic_document<Traits, owned>::create(owner_->options_.max_document_bytes); + if constexpr (owned_storage<Storage>) { + return basic_document<Traits, Storage>::create(owner_->alloc_, + owner_->options_.max_document_bytes); } else { - return format<Traits>(owner_->buffer_); + return format<Traits>(owner_->buffer_, owner_->alloc_); } } @@ -226,7 +247,9 @@ class handler { } /** The tree of the document being built. */ - [[nodiscard]] tree<Traits>& tree_of() const noexcept { return *access::tree_of(document()); } + [[nodiscard]] tree<Traits, typename Storage::allocator_type>& tree_of() const noexcept { + return *access::tree_of(document()); + } /** Records `error` as the parser's failure and hands it to Boost.JSON, which stops. */ bool fail(boost::system::error_code& ec, boost::system::error_code error) noexcept { @@ -235,28 +258,51 @@ class handler { return false; } - /** Steps into the value that begins: its key, or its index in the text, joins the path. */ + /** + Steps into the value that begins: its key, or its index in the text, joins the path. + + A member's step views its key in `keys_`, at the step's depth, which keeps its buffer for the + next value at that depth. + */ void enter() { if (frames_.empty()) { return; } if (steps_ == path_.size()) { - path_.emplace_back(); + deepen(); } - // A step keeps its key's buffer when it is left, for the next value at its depth. path_step& step = path_[steps_++]; frame& parent = frames_.back(); step.is_index = parent.is_array; if (parent.is_array) { - step.key.clear(); + step.key = {}; step.index = parent.next_index++; } else { - step.key.assign(key_); + string_type& key = keys_[steps_ - 1]; + key.assign(key_); + step.key = key; step.index = 0; key_.clear(); } } + /** + Makes room for one step more than the path has had: a key's buffer, unless an allocation + that failed left one, then the step, so that `keys_` has a buffer for each step of `path_`. + */ + void deepen() { + if (keys_.size() == path_.size()) { + keys_.push_back(string_type(rebound<allocator_type, char>(owner_->alloc_))); + // The buffers moved as keys_ grew, and a short key's bytes, held inline, with them. + for (std::size_t i = 0; i < steps_; ++i) { + if (!path_[i].is_index) { + path_[i].key = keys_[i]; + } + } + } + path_.push_back(path_step{}); + } + /** Steps out of the value that completed. */ void leave() noexcept { if (!frames_.empty()) { @@ -269,7 +315,7 @@ class handler { replaces the value in its first place), or an element appended; returns its id. */ result<std::uint64_t> place(const item<Traits>& v) noexcept { - tree<Traits>& t = tree_of(); + auto& t = tree_of(); if (frames_.empty()) { if (const result<void> done = t.assign(root_id, v); !done.has_value()) { return done.error(); @@ -339,15 +385,22 @@ class handler { return complete(done.id, ec); } - /** Turns the object `id` into bytes when it has the shape `JSON.stringify` gives a Uint8Array. - */ + /** + Turns the object `id` into bytes when it has the shape `JSON.stringify` gives a Uint8Array, + its bytes read into the allocator; an allocator with no room for them is + @ref errc::capacity. + */ result<void> revive_bytes(std::uint64_t id) noexcept { - tree<Traits>& t = tree_of(); - result<std::vector<std::byte>> bytes = read<std::vector<std::byte>>(t, t.find(id)); + auto& t = tree_of(); + const auto bytes = read_bytes_with(t, t.find(id), owner_->alloc_); if (!bytes.has_value()) { - return {}; + // An object of another shape stays an object; an allocator with no room fails. + if (bytes.error() != errc::capacity) { + return {}; + } + return bytes.error(); } - prepared<Traits> made; + prepared<Traits, allocator_type> made(owner_->alloc_); if (const result<void> held = prepare(std::span<const std::byte>(bytes.unsafe_value()), made); !held.has_value()) { @@ -412,7 +465,7 @@ class handler { the array's last, a member is found by its key, and the root is left holding `undefined`. */ result<void> take_out() noexcept { - tree<Traits>& t = tree_of(); + auto& t = tree_of(); if (frames_.empty()) { return t.assign(root_id, empty_item<Traits>(webcpp::document::kind::undefined)); } @@ -431,22 +484,28 @@ class handler { basic_parser<Traits, Storage>* owner_; /** The containers being read, the innermost last. */ - std::vector<frame> frames_; + std::vector<frame, rebound<allocator_type, frame>> frames_; /** The text's path of the value being read, its first `steps_` entries; the rest are spare. */ - std::vector<path_step> path_; + std::vector<path_step, rebound<allocator_type, path_step>> path_; + + /** + The keys of the path's members, one buffer for each entry of `path_`, which a member's step + views; at least as many as `path_` has. + */ + std::vector<string_type, rebound<allocator_type, string_type>> keys_; /** How many entries of `path_` are the path. */ std::size_t steps_ = 0; /** The key being read, or read and waiting for its value. */ - std::string key_; + string_type key_; /** The string or number being read. */ - std::string text_; + string_type text_; /** The scalar being stored, kept to reuse its buffers. */ - prepared<Traits> value_; + prepared<Traits, allocator_type> value_; }; } // namespace webcpp::document::detail diff --git a/include/webcpp/document/detail/heap.hpp b/include/webcpp/document/detail/heap.hpp index 9762eb8..11ed0f2 100644 --- a/include/webcpp/document/detail/heap.hpp +++ b/include/webcpp/document/detail/heap.hpp @@ -7,7 +7,7 @@ /** The heap of a document's image: Boost.Interprocess's `rbtree_best_fit`, used directly, its allocator, which zeroes every block it hands out and frees, the strings it holds, and the region, - the bytes of the image, owned and growing or external and fixed. + the bytes of the image, owned and growing through the document's allocator or external and fixed. Only `offset_ptr.hpp`, `mem_algo/rbtree_best_fit.hpp` and `sync/null_mutex.hpp` are included from Boost.Interprocess: its `managed_external_buffer`, `segment_manager`, `allocator` and @@ -19,8 +19,11 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/detail/allocation.hpp> #include <webcpp/document/errors.hpp> +#include <boost/assert.hpp> +#include <boost/config.hpp> #include <boost/interprocess/mem_algo/rbtree_best_fit.hpp> // lint-world: a heap in a buffer #include <boost/interprocess/offset_ptr.hpp> // lint-world: an offset, no process #include <boost/interprocess/sync/null_mutex.hpp> // lint-world: a mutex that locks nothing @@ -28,13 +31,16 @@ #include <algorithm> #include <array> +#include <concepts> #include <cstddef> #include <cstdint> #include <cstring> #include <limits> +#include <memory> #include <new> #include <span> #include <string_view> +#include <type_traits> #include <utility> namespace webcpp::document::detail { @@ -110,8 +116,9 @@ class allocator { /** Allocates in the heap `h`, which outlives the allocator. */ explicit allocator(heap* h) noexcept : heap_(h) {} - // The Allocator requirements convert an allocator to its rebound type implicitly, hence the - // exemption from misc-explicit-constructor. + // The Allocator requirements ask only that a rebound allocator be constructed from this one, + // `A a(b)`; the conversion is kept implicit, as std::allocator's is, for the tree's + // Boost.MultiIndex container, hence the exemption from misc-explicit-constructor. /** The allocator of another type over the same heap. */ template <class U> allocator(const allocator<U>& other) noexcept // NOLINT(misc-explicit-constructor) @@ -324,33 +331,113 @@ inline heap_costs measure_heap_costs() noexcept { } /** - The bytes of an image: owned, which the region allocates, zeroes and grows, or external, a span - its user owns, which never grows. + The unit an owned image is allocated in: 16 bytes, 16-aligned, so that an allocator rebound to it + is asked for the alignment the heap needs, a memory resource for an alignment of 16. A buffer an + allocator gives at another alignment is given back, and the region has no room. */ -class region { +struct alignas(16) image_block { + /** The block's bytes. */ + std::array<std::byte, 16> bytes; +}; + +template <class Allocator> +class basic_region; + +/** + The bytes of an image, whatever allocated them: where they are, how many, the size an owned image + never grows past, and whether they are owned. The tree reads an image through it. +*/ +class region_bytes { public: + /** The first byte, 16-aligned, or null when empty. */ + [[nodiscard]] std::byte* data() const noexcept { return data_; } + + /** How many bytes. */ + [[nodiscard]] std::uint64_t size() const noexcept { return size_; } + + /** The size an owned region never grows past. */ + [[nodiscard]] std::uint64_t max_bytes() const noexcept { return max_bytes_; } + + /** Whether the region owns its bytes, and so may grow. */ + [[nodiscard]] bool is_owned() const noexcept { return owned_; } + +protected: + /** No bytes. */ + region_bytes() noexcept = default; + + /** The bytes of a region are moved by the region, which knows their allocator. */ + region_bytes(const region_bytes&) noexcept = default; + + /** The bytes of a region are moved by the region, which knows their allocator. */ + region_bytes& operator=(const region_bytes&) noexcept = default; + + /** Destroyed by the region, which frees what it owns. */ + ~region_bytes() = default; + + /** Takes the fields of `other`, which is left empty. */ + void take(region_bytes& other) noexcept { + data_ = std::exchange(other.data_, nullptr); + size_ = std::exchange(other.size_, 0); + max_bytes_ = std::exchange(other.max_bytes_, 0); + owned_ = std::exchange(other.owned_, false); + } + +private: + template <class> + friend class basic_region; + + /** The first byte, or null. */ + std::byte* data_ = nullptr; + + /** How many bytes. */ + std::uint64_t size_ = 0; + + /** The size an owned region never grows past. */ + std::uint64_t max_bytes_ = 0; + + /** Whether the bytes are owned. */ + bool owned_ = false; +}; + +/** + The bytes of an image: owned, which the region allocates through `Allocator`, zeroes and grows, + or external, a span its user owns, which never grows; and the allocator, which also holds the + working state of the operations on the image. + + The allocator's pointer to an owned image's blocks is kept as the allocator gave it, and the + blocks are given back through it: a pointer that is not a plain one may carry more than an + address, a segment or a tag, which a pointer rebuilt from the address would not. + + @tparam Allocator An allocator of `std::byte`, rebound to @ref image_block for the image. +*/ +template <class Allocator> +class basic_region : public region_bytes { +public: + /** The allocator of the image and of the working state. */ + using allocator_type = Allocator; + /** A new owned region of `size` bytes, zeroed, with an empty heap after the header. */ - static result<region> owned(std::uint64_t size, std::uint64_t max_bytes) noexcept { + static result<basic_region> owned(std::uint64_t size, std::uint64_t max_bytes, + const Allocator& a = Allocator()) noexcept { if (size > max_bytes || size < smallest() || size > largest()) { return errc::capacity; } - std::byte* bytes = allocate(size); - if (bytes == nullptr) { + basic_region made(a); + const buffer allocated = made.allocate(size); + if (allocated.bytes == nullptr) { return errc::capacity; } - std::memset(bytes, 0, static_cast<std::size_t>(size)); - region made; - made.data_ = bytes; - made.size_ = size; + std::memset(allocated.bytes, 0, static_cast<std::size_t>(size)); + made.hold(allocated, size); made.max_bytes_ = max_bytes; - made.owned_ = true; - make_heap(bytes, size); + make_heap(allocated.bytes, size); return made; } /** An owned copy of an image's bytes, whose heap is the image's own. */ - static result<region> owned_copy(std::span<const std::byte> bytes, - std::uint64_t max_bytes) noexcept { + static result<basic_region> owned_copy(std::span<const std::byte> bytes, + std::uint64_t max_bytes, + const Allocator& a = Allocator()) noexcept { if (bytes.size() > max_bytes) { return errc::capacity; } @@ -358,22 +445,21 @@ class region { if (bytes.size() < smallest()) { return errc::not_a_document; } - std::byte* copy = allocate(bytes.size()); - if (copy == nullptr) { + basic_region made(a); + const buffer copy = made.allocate(bytes.size()); + if (copy.bytes == nullptr) { return errc::capacity; } - std::memcpy(copy, bytes.data(), bytes.size()); - region made; - made.data_ = copy; - made.size_ = bytes.size(); + std::memcpy(copy.bytes, bytes.data(), bytes.size()); + made.hold(copy, bytes.size()); made.max_bytes_ = max_bytes; - made.owned_ = true; return made; } /** An external region over `buffer`, as it is: for an image already there. */ - static region external(std::span<std::byte> buffer) noexcept { - region made; + static basic_region external(std::span<std::byte> buffer, + const Allocator& a = Allocator()) noexcept { + basic_region made(a); made.data_ = buffer.data(); made.size_ = buffer.size(); made.max_bytes_ = buffer.size(); @@ -381,7 +467,8 @@ class region { } /** An external region over `buffer`, zeroed, with an empty heap after the header. */ - static result<region> external_empty(std::span<std::byte> buffer) noexcept { + static result<basic_region> external_empty(std::span<std::byte> buffer, + const Allocator& a = Allocator()) noexcept { // The heap's offsets are the same at every 16-aligned address, and only there. if (buffer.size() < smallest() || reinterpret_cast<std::uintptr_t>(buffer.data()) % 16 != 0) { @@ -389,52 +476,51 @@ class region { } std::memset(buffer.data(), 0, buffer.size()); make_heap(buffer.data(), buffer.size()); - return external(buffer); + return external(buffer, a); } - /** An empty region, which holds no bytes. */ - region() noexcept = default; + /** An empty region, which holds no bytes, with a default allocator. */ + basic_region() noexcept(std::is_nothrow_default_constructible_v<Allocator>) = default; - /** Takes the bytes of `other`, which is left empty. */ - region(region&& other) noexcept - : data_(std::exchange(other.data_, nullptr)), - size_(std::exchange(other.size_, 0)), - max_bytes_(std::exchange(other.max_bytes_, 0)), - owned_(std::exchange(other.owned_, false)) {} + /** An empty region, which holds no bytes, with the allocator `a`. */ + explicit basic_region(const Allocator& a) noexcept : alloc_(a) {} - /** Frees its own bytes, then takes the bytes of `other`, which is left empty. */ - region& operator=(region&& other) noexcept { + /** Takes the bytes and a copy of the allocator of `other`, which is left empty. */ + basic_region(basic_region&& other) noexcept + : alloc_(other.alloc_), kept_(std::exchange(other.kept_, kept_pointer{})) { + take(other); + } + + /** + Frees its own bytes, then takes the bytes of `other`, which is left empty; the allocator is + taken only when it propagates on a move, else it equals `other`'s or `other` owns nothing. + */ + basic_region& operator=(basic_region&& other) noexcept { if (this == &other) { return *this; } release(); - data_ = std::exchange(other.data_, nullptr); - size_ = std::exchange(other.size_, 0); - max_bytes_ = std::exchange(other.max_bytes_, 0); - owned_ = std::exchange(other.owned_, false); + if constexpr (block_traits::propagate_on_container_move_assignment::value) { + alloc_ = other.alloc_; + } else { + BOOST_ASSERT(alloc_ == other.alloc_ || !other.owned_); + } + take(other); + kept_ = std::exchange(other.kept_, kept_pointer{}); return *this; } /** A region is not copied: an image is copied by @ref owned_copy. */ - region(const region&) = delete; + basic_region(const basic_region&) = delete; /** A region is not copied: an image is copied by @ref owned_copy. */ - region& operator=(const region&) = delete; + basic_region& operator=(const basic_region&) = delete; /** Frees an owned region's bytes. */ - ~region() { release(); } + ~basic_region() { release(); } - /** The first byte, 16-aligned, or null when empty. */ - [[nodiscard]] std::byte* data() const noexcept { return data_; } - - /** How many bytes. */ - [[nodiscard]] std::uint64_t size() const noexcept { return size_; } - - /** The size an owned region never grows past. */ - [[nodiscard]] std::uint64_t max_bytes() const noexcept { return max_bytes_; } - - /** Whether the region owns its bytes, and so may grow. */ - [[nodiscard]] bool is_owned() const noexcept { return owned_; } + /** The allocator. */ + [[nodiscard]] Allocator get_allocator() const noexcept { return alloc_; } /** Grows an owned region to twice its size or `at_least`, the larger, rounded up to 16, at most @@ -452,16 +538,15 @@ class region { if (new_size <= size_) { return false; } - std::byte* bigger = allocate(new_size); - if (bigger == nullptr) { + const buffer bigger = allocate(new_size); + if (bigger.bytes == nullptr) { return false; } const std::uint64_t old_size = size_; - std::memcpy(bigger, data_, static_cast<std::size_t>(old_size)); - std::memset(bigger + old_size, 0, static_cast<std::size_t>(new_size - old_size)); - deallocate(data_); - data_ = bigger; - size_ = new_size; + std::memcpy(bigger.bytes, data_, static_cast<std::size_t>(old_size)); + std::memset(bigger.bytes + old_size, 0, static_cast<std::size_t>(new_size - old_size)); + deallocate(held(), old_size); + hold(bigger, new_size); // The heap's links are offsets, so the copy is a heap already: it only takes the new end. own_heap().grow(new_size - old_size); return true; @@ -481,18 +566,47 @@ class region { if (size == size_) { return true; } - std::byte* smaller = allocate(size); - if (smaller == nullptr) { + const buffer smaller = allocate(size); + if (smaller.bytes == nullptr) { return false; } - std::memcpy(smaller, data_, static_cast<std::size_t>(size)); - deallocate(data_); - data_ = smaller; - size_ = size; + std::memcpy(smaller.bytes, data_, static_cast<std::size_t>(size)); + deallocate(held(), size_); + hold(smaller, size); return true; } private: + /** The allocator of the image's blocks. */ + using block_allocator = std::allocator_traits<Allocator>::template rebind_alloc<image_block>; + + /** Its traits. */ + using block_traits = std::allocator_traits<block_allocator>; + + /** Its pointer to the image's blocks. */ + using block_pointer = block_traits::pointer; + + /** Whether that pointer is a plain one, which the bytes' address gives back exactly. */ + static constexpr bool plain_pointer = std::is_pointer_v<block_pointer>; + + /** What is kept in the place of a plain pointer, which the bytes' address is: nothing. */ + struct no_pointer {}; + + /** The allocator's pointer to an owned image's blocks, kept when it is not a plain one. */ + using kept_pointer = std::conditional_t<plain_pointer, no_pointer, block_pointer>; + + /** A buffer the allocator gave: its bytes, and its pointer when it is not a plain one. */ + struct buffer { + /** The first byte, 16-aligned, or null when the allocator gave none. */ + std::byte* bytes = nullptr; + + /** The allocator's pointer to it. */ + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS kept_pointer pointer{}; + }; + + /** Whether the allocator is the standard one, whose `allocate` is the global operator new. */ + static constexpr bool standard = std::same_as<Allocator, std::allocator<std::byte>>; + /** The fewest bytes that hold a header and an empty heap. */ static std::uint64_t smallest() noexcept { return header_bytes + heap::get_min_size(sizeof(heap)); @@ -503,15 +617,85 @@ class region { return std::numeric_limits<std::size_t>::max(); } - /** A new buffer of `size` bytes, 16-aligned and uninitialized, or null. */ - static std::byte* allocate(std::uint64_t size) noexcept { - return static_cast<std::byte*>( - ::operator new(static_cast<std::size_t>(size), std::align_val_t{16}, std::nothrow)); + /** How many blocks hold `size` bytes. */ + static std::size_t blocks_of(std::uint64_t size) noexcept { + return static_cast<std::size_t>((size + sizeof(image_block) - 1) / sizeof(image_block)); + } + + /** + A new buffer of `size` bytes, 16-aligned and uninitialized, or none when the allocator has + none: with exceptions, its failure is caught (@ref unless_allocation_fails). A buffer the + allocator gives at another alignment, as one that ignores an over-aligned request may, is + given back, and is none too. + */ + buffer allocate(std::uint64_t size) noexcept { + if constexpr (standard) { + // std::allocator allocates with the global operator new: its form that returns null + // keeps a failure a value without exceptions too. + buffer made; + made.bytes = static_cast<std::byte*>( + ::operator new(static_cast<std::size_t>(size), std::align_val_t{16}, std::nothrow)); + return made; + } else { + block_allocator blocks(alloc_); + const std::size_t count = blocks_of(size); + if (count > block_traits::max_size(blocks)) { + return {}; + } + return unless_allocation_fails( + [&] { + return aligned_or_given_back(blocks, block_traits::allocate(blocks, count), + count); + }, + [] { return buffer{}; }); + } + } + + /** + The buffer of the `count` blocks at `p`, which `blocks` allocated, when they are 16-aligned; + else none, the blocks given back: the heap's offsets hold at 16-aligned addresses alone. + */ + static buffer aligned_or_given_back(block_allocator& blocks, block_pointer p, + std::size_t count) noexcept { + auto* bytes = reinterpret_cast<std::byte*>(std::to_address(p)); + if (bytes == nullptr) { + return {}; + } + if (reinterpret_cast<std::uintptr_t>(bytes) % alignof(image_block) != 0) { + block_traits::deallocate(blocks, std::move(p), count); + return {}; + } + buffer made{bytes}; + if constexpr (!plain_pointer) { + made.pointer = std::move(p); + } + return made; + } + + /** Frees a buffer of `size` bytes that @ref allocate made, through the allocator's pointer. */ + void deallocate(const buffer& b, std::uint64_t size) noexcept { + if constexpr (standard) { + ::operator delete(b.bytes, std::align_val_t{16}); + } else { + block_allocator blocks(alloc_); + if constexpr (plain_pointer) { + block_traits::deallocate(blocks, reinterpret_cast<image_block*>(b.bytes), + blocks_of(size)); + } else { + block_traits::deallocate(blocks, b.pointer, blocks_of(size)); + } + } } - /** Frees a buffer @ref allocate made. */ - static void deallocate(std::byte* bytes) noexcept { - ::operator delete(bytes, std::align_val_t{16}); + /** The owned buffer it holds. */ + [[nodiscard]] buffer held() const noexcept { return {data_, kept_}; } + + /** Holds `b`, of `size` bytes, as its owned bytes. */ + void hold(const buffer& b, std::uint64_t size) noexcept { + data_ = b.bytes; + kept_ = b.pointer; + size_ = size; + owned_ = true; } /** Its heap, as @ref heap_of finds it. */ @@ -530,22 +714,26 @@ class region { /** Frees its bytes when it owns them, and leaves it empty. */ void release() noexcept { if (owned_ && data_ != nullptr) { - deallocate(data_); + deallocate(held(), size_); } data_ = nullptr; + kept_ = kept_pointer{}; size_ = 0; max_bytes_ = 0; owned_ = false; } - std::byte* data_ = nullptr; - std::uint64_t size_ = 0; - std::uint64_t max_bytes_ = 0; - bool owned_ = false; + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS Allocator alloc_{}; + + /** The allocator's pointer to an owned image's blocks, when it is not a plain one. */ + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS kept_pointer kept_{}; }; +/** The region of an image in the standard allocator. */ +using region = basic_region<std::allocator<std::byte>>; + /** The heap of a region, at offset @ref header_bytes. */ -inline heap& heap_of(const region& r) noexcept { +inline heap& heap_of(const region_bytes& r) noexcept { return *std::launder(reinterpret_cast<heap*>(r.data() + header_bytes)); } diff --git a/include/webcpp/document/detail/selector.hpp b/include/webcpp/document/detail/selector.hpp index c67000c..fbf5947 100644 --- a/include/webcpp/document/detail/selector.hpp +++ b/include/webcpp/document/detail/selector.hpp @@ -19,7 +19,9 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/detail/allocation.hpp> #include <webcpp/document/errors.hpp> +#include <webcpp/document/storage.hpp> #include <charconv> #include <cstddef> @@ -32,12 +34,21 @@ #include <utility> #include <vector> +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS +#include <new> +#endif + namespace webcpp::document::detail { -/** One step of a value's path in the text: a member's key, in UTF-8, or an element's index. */ +/** + One step of a value's path in the text: a member's key, in UTF-8, or an element's index. + + The step views its key, which the parser's handler holds, in the document's allocator, while the + step is on the path: a step names no allocator, so that a @ref path_view of any parser reads it. +*/ struct path_step { /** The member's key, in UTF-8; empty for an element. */ - std::string key; + std::string_view key; /** The element's index in the text; 0 for a member. */ std::uint64_t index = 0; @@ -61,39 +72,46 @@ enum class step_kind : std::uint8_t { any_member, }; -/** One step of a selector. */ -struct selector_step { +/** One step of a selector, its key held in `Allocator`, rebound. */ +template <class Allocator> +struct basic_selector_step { /** What the step matches. */ step_kind kind = step_kind::key; /** The key of a @ref step_kind::key step, unescaped, in UTF-8. */ - std::string key; + std::basic_string<char, std::char_traits<char>, rebound<Allocator, char>> key; /** The index of a @ref step_kind::index step. */ std::uint64_t index = 0; }; -/** A parsed selector: the steps after `$`, which match a path of the same length step by step. */ -class selector { +/** One step of a selector held in the standard allocator. */ +using selector_step = basic_selector_step<std::allocator<std::byte>>; + +/** + A parsed selector: the steps after `$`, which match a path of the same length step by step, held + in `Allocator`, rebound: the allocator of the parser that registered it. +*/ +template <class Allocator> +class basic_selector { public: - // The steps are held on the process heap: a failed allocation there ends the program, as - // this function's noexcept, which the parser's on and observe rely on, intends. - /** Parses a selector's text; @ref errc::type for text outside the grammar. */ + /** A step of the selector. */ + using step_type = basic_selector_step<Allocator>; + + /** + Parses a selector's text, its steps allocated through `alloc`; @ref errc::type for text + outside the grammar, and with exceptions @ref errc::capacity when `alloc` has no room. + + Without exceptions an allocator that fails ends the program, as the allocator itself does. + */ + // Only an allocation throws here, and an allocator's failure is caught: the std::length_error + // of a string or a vector past its max_size() cannot come of a text that a std::string_view + // holds. // NOLINTNEXTLINE(bugprone-exception-escape) - static result<selector> parse(std::string_view text) noexcept { - if (text.empty() || text.front() != '$') { - return errc::type; - } - selector parsed; - std::string_view rest = text.substr(1); - while (!rest.empty()) { - std::optional<selector_step> step = read_step(rest); - if (!step) { - return errc::type; - } - parsed.steps_.push_back(std::move(*step)); - } - return parsed; + static result<basic_selector> parse(std::string_view text, + const Allocator& alloc = Allocator()) noexcept { + return unless_allocation_fails([&] { return read(text, alloc); }, + [] { return result<basic_selector>(errc::capacity); }); } /** Whether a path matches: as many steps as the selector, each matched by its step. */ @@ -110,13 +128,46 @@ class selector { } /** The steps after `$`; none for `$` alone, which matches the root. */ - [[nodiscard]] std::span<const selector_step> steps() const noexcept { return steps_; } + [[nodiscard]] std::span<const step_type> steps() const noexcept { return steps_; } private: + /** A key's text in the allocator. */ + using string_type = std::basic_string<char, std::char_traits<char>, rebound<Allocator, char>>; + + /** A selector without steps, which holds them in `alloc`. */ + explicit basic_selector(const Allocator& alloc) noexcept + : steps_(rebound<Allocator, step_type>(alloc)) {} + + /** Parses a selector's text, its steps allocated through `alloc`, which may throw. */ + static result<basic_selector> read(std::string_view text, const Allocator& alloc) { + if (text.empty() || text.front() != '$') { + return errc::type; + } + basic_selector parsed(alloc); + std::string_view rest = text.substr(1); + while (!rest.empty()) { + std::optional<step_type> step = read_step(rest, alloc); + if (!step) { + return errc::type; + } + parsed.steps_.push_back(std::move(*step)); + } + return parsed; + } + + /** A step of kind `kind` whose key, empty, is held in `alloc`. */ + static step_type make_step(step_kind kind, const Allocator& alloc) noexcept { + return step_type{ + .kind = kind, + .key = string_type(rebound<Allocator, char>(alloc)), + .index = 0, + }; + } + /** Whether one step of a selector matches one step of a path. */ - static bool step_matches(const selector_step& step, const path_step& at) noexcept { + static bool step_matches(const step_type& step, const path_step& at) noexcept { switch (step.kind) { - case step_kind::key: return !at.is_index && at.key == step.key; + case step_kind::key: return !at.is_index && at.key == std::string_view(step.key); case step_kind::index: return at.is_index && at.index == step.index; case step_kind::any_element: return at.is_index; case step_kind::any_member: return !at.is_index; @@ -135,28 +186,26 @@ class selector { static bool continues_name(char c) noexcept { return starts_name(c) || (c >= '0' && c <= '9'); } /** Reads the step `rest` starts with, at its `.` or `[`, and drops it from `rest`. */ - static std::optional<selector_step> read_step(std::string_view& rest) { + static std::optional<step_type> read_step(std::string_view& rest, const Allocator& alloc) { const char opening = rest.front(); rest.remove_prefix(1); if (opening == '.') { - return read_dotted(rest); + return read_dotted(rest, alloc); } if (opening == '[') { - return read_bracketed(rest); + return read_bracketed(rest, alloc); } return std::nullopt; } /** Reads what follows a dot, `*` or a name, and drops it from `rest`. */ - static std::optional<selector_step> read_dotted(std::string_view& rest) { + static std::optional<step_type> read_dotted(std::string_view& rest, const Allocator& alloc) { if (rest.empty()) { return std::nullopt; } - selector_step step; if (rest.front() == '*') { rest.remove_prefix(1); - step.kind = step_kind::any_member; - return step; + return make_step(step_kind::any_member, alloc); } if (!starts_name(rest.front())) { return std::nullopt; @@ -165,27 +214,26 @@ class selector { while (length < rest.size() && continues_name(rest[length])) { ++length; } - step.key = rest.substr(0, length); + step_type step = make_step(step_kind::key, alloc); + step.key.assign(rest.substr(0, length)); rest.remove_prefix(length); return step; } /** Reads `*`, a quoted key or an index, then `]`, and drops them from `rest`. */ - static std::optional<selector_step> read_bracketed(std::string_view& rest) { + static std::optional<step_type> read_bracketed(std::string_view& rest, const Allocator& alloc) { if (rest.empty()) { return std::nullopt; } - selector_step step; + step_type step = make_step(step_kind::key, alloc); if (rest.front() == '*') { rest.remove_prefix(1); step.kind = step_kind::any_element; } else if (rest.front() == '\'') { rest.remove_prefix(1); - std::optional<std::string> key = read_quoted(rest); - if (!key) { + if (!read_quoted(rest, step.key)) { return std::nullopt; } - step.key = std::move(*key); } else { const std::optional<std::uint64_t> index = read_index(rest); if (!index) { @@ -202,31 +250,30 @@ class selector { } /** - Reads a quoted key's characters through its closing quote, unescaped, and drops them from - `rest`. + Reads a quoted key's characters through its closing quote, unescaped, into `key`, and drops + them from `rest`; false when the key does not close or holds an escape of neither. `\'` and `\\` are the only escapes, so that a backslash before anything else, which another reader might take for an escape of its own, is refused rather than guessed. */ - static std::optional<std::string> read_quoted(std::string_view& rest) { - std::string key; + static bool read_quoted(std::string_view& rest, string_type& key) { while (!rest.empty()) { const char c = rest.front(); rest.remove_prefix(1); if (c == '\'') { - return key; + return true; } if (c != '\\') { key.push_back(c); continue; } if (rest.empty() || (rest.front() != '\'' && rest.front() != '\\')) { - return std::nullopt; + return false; } key.push_back(rest.front()); rest.remove_prefix(1); } - return std::nullopt; + return false; } /** Reads an index's decimal digits, without a leading zero but `0` itself, from `rest`. */ @@ -249,9 +296,12 @@ class selector { } /** The steps after `$`, in order. */ - std::vector<selector_step> steps_; + std::vector<step_type, rebound<Allocator, step_type>> steps_; }; +/** A parsed selector held in the standard allocator. */ +using selector = basic_selector<std::allocator<std::byte>>; + } // namespace webcpp::document::detail #endif // WEBCPP_DOCUMENT_DETAIL_SELECTOR_HPP diff --git a/include/webcpp/document/detail/tree.hpp b/include/webcpp/document/detail/tree.hpp index 01f9456..7a19f03 100644 --- a/include/webcpp/document/detail/tree.hpp +++ b/include/webcpp/document/detail/tree.hpp @@ -9,13 +9,24 @@ with three ordered indices, the key order of the traits' object policy, and the operations that change it, each of which finds its room before it changes anything. - Every mutation runs in three phases. Room: it lists the blocks it will take (@ref node_probe_bytes + Every mutation that writes runs in three phases. Room: it stages what it writes in the region's + allocator, rebound, the only memory outside the image it takes: the nodes it writes, the values + still to read, the roots of the subtrees it erases, the sizes of its blocks (@ref node_probe_bytes per node it creates, counting a literal's entries and a copied subtree's nodes, and each string's - exact size) and probes the heap for them; while the probe fails, an owned region grows, and when it - cannot, the operation returns @ref errc::capacity before anything changed. Growth moves the image, - so no pointer into it is held across this phase. Allocate: the strings, then each node by - `emplace`, built in place. Arrange: what allocates nothing, a `modify` that swaps a prepared - string or scalar into a node, ordinals shifted, a subtree erased children first. + exact size), and, when the image must grow, a copy of what it views there; with exceptions, an + allocator that fails is @ref errc::capacity, before anything changed. Then it probes the heap for + its blocks; while the probe fails, an owned region grows, and when it cannot, the operation returns + @ref errc::capacity before anything changed. Growth moves the image, so no pointer into it is held + across this phase. Allocate: the strings, a key given in UTF-8 written as UTF-16 straight into its + block, then each node by `emplace`, built in place. Arrange: what allocates nothing, a `modify` + that swaps a prepared string or scalar into a node, ordinals shifted, subtrees erased children + first, listed through their own nodes. + + An erasure alone, of a member or of elements with nothing inserted, needs no room: it allocates + nothing at all and cannot run out of room, though it still returns @ref errc::type for what is no + object or no array and @ref errc::range for elements past the end. Without exceptions, an + allocator that fails ends the program, as it does itself. A lookup by a key in UTF-8 allocates + nothing, whatever the encoding and the key's length. */ #ifndef WEBCPP_DOCUMENT_DETAIL_TREE_HPP @@ -23,12 +34,14 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/detail/allocation.hpp> #include <webcpp/document/detail/heap.hpp> #include <webcpp/document/detail/utf.hpp> #include <webcpp/document/errors.hpp> #include <webcpp/document/image.hpp> #include <webcpp/document/kind.hpp> #include <webcpp/document/number.hpp> +#include <webcpp/document/storage.hpp> #include <webcpp/document/traits.hpp> #include <boost/assert.hpp> @@ -40,12 +53,13 @@ #include <algorithm> #include <array> +#include <compare> #include <cstddef> #include <cstdint> #include <cstring> #include <functional> #include <limits> -#include <map> +#include <memory> #include <new> #include <optional> #include <ranges> @@ -181,12 +195,40 @@ struct with_zero_byte : F { std::uint8_t zero = 0; }; +/** + A key in valid UTF-8 that the index @ref by_key looks up whatever the traits' encoding: under + `utf16` its order compares the UTF-16 code units it decodes to with a stored key's, one character + at a time, so that a lookup transcodes nothing into memory. +*/ +struct utf8_lookup { + /** The key's bytes, valid UTF-8. */ + std::string_view text; +}; + /** The order of keys in the index @ref by_key, by their UTF-16 code units, whatever the encoding: the order the `sorted` policy writes, as JavaScript's sort and RFC 8785 order keys. */ template <class Traits> struct key_less { + /** Whether the key `a`, in UTF-8, comes before the stored key `b`. */ + bool operator()(utf8_lookup a, std::string_view b) const noexcept { + if constexpr (std::same_as<typename Traits::string, utf16>) { + return std::is_lt(units_order(a.text, b)); + } else { + return (*this)(a.text, b); + } + } + + /** Whether the stored key `a` comes before the key `b`, in UTF-8. */ + bool operator()(std::string_view a, utf8_lookup b) const noexcept { + if constexpr (std::same_as<typename Traits::string, utf16>) { + return std::is_gt(units_order(b.text, a)); + } else { + return (*this)(a, b.text); + } + } + /** Whether `a` comes before `b`, each the bytes of a key in the traits' encoding. */ bool operator()(std::string_view a, std::string_view b) const noexcept { if constexpr (std::same_as<typename Traits::string, utf16>) { @@ -235,6 +277,39 @@ struct key_less { return byte_at(a, i) < byte_at(b, i); } } + +private: + /** + The order of valid UTF-8 text and a stored key's UTF-16 code units, held in the machine's + byte order, by their code units, as the order of two stored keys is. + */ + static std::strong_ordering units_order(std::string_view utf8, + std::string_view stored) noexcept { + const std::size_t units = stored.size() / sizeof(char16_t); + std::size_t unit = 0; + std::size_t i = 0; + while (i < utf8.size()) { + // One character, decoded to its one unit or its surrogate pair; a byte that starts + // none, which valid UTF-8 has not, is taken alone. + const std::size_t length = std::max<std::size_t>(lead_of(byte_at(utf8, i)).length, 1); + const std::string_view character(utf8.data() + i, std::min(length, utf8.size() - i)); + std::array<char16_t, 2> decoded{}; + const auto count = static_cast<std::size_t>(to_utf16(character, decoded.data())); + i += character.size(); + for (std::size_t k = 0; k < count; ++k, ++unit) { + if (unit == units) { + return std::strong_ordering::greater; + } + char16_t stored_unit = 0; + std::memcpy(&stored_unit, stored.data() + (unit * sizeof(char16_t)), + sizeof stored_unit); + if (decoded[k] != stored_unit) { + return decoded[k] <=> stored_unit; + } + } + } + return unit == units ? std::strong_ordering::equal : std::strong_ordering::less; + } }; /** @@ -330,6 +405,9 @@ template <class Traits> inline constexpr std::uint64_t node_probe_bytes = sizeof(node<Traits>) + 128; template <class Traits> +class tree_view; + +template <class Traits, class Allocator = std::allocator<std::byte>> class tree; template <class Traits> @@ -362,8 +440,8 @@ struct item { /** How many entries. */ std::size_t entry_count = 0; - /** The tree of a subtree to copy deeply, or null. */ - const tree<Traits>* from = nullptr; + /** The tree of a subtree to copy deeply, of a document of any allocator, or null. */ + const tree_view<Traits>* from = nullptr; /** The id of the subtree's node in `from`. */ std::uint64_t from_id = 0; @@ -408,112 +486,18 @@ constexpr std::uint32_t layout_tag() noexcept { } /** - The tree of a document, a light handle on a region: it holds no pointer into the image, so it - stays valid when the region grows and its bytes move. + The reading half of a tree: a light handle on the bytes of a region, whatever allocated them, which + finds nodes and walks them. It holds no pointer into the image, so it stays valid when the region + grows and its bytes move. - Every operation that changes the tree either completes or changes nothing, and returns - @ref errc::capacity when there is no room. Keys are given in UTF-8; with `utf16` the tree - transcodes them before it stores or looks them up, and a key it cannot transcode finds nothing. + A deep copy reads its source through it, so that a value of a document of any allocator is copied + into a document of any other. */ template <class Traits> -class tree { +class tree_view { public: - // An operation ends the program where the process heap, which holds what it stages, runs - // out, as the library tolerates, and where an allocation in the image fails after its probe - // passed, a bug of the document's, which the allocator reports by boost::throw_exception. - // NOLINTBEGIN(bugprone-exception-escape) - /** - Formats a region that holds an empty heap: the header, the container, a root holding `null`. - */ - static result<tree> format(region& r) noexcept { - if (r.data() == nullptr || r.size() < smallest_image()) { - return errc::capacity; - } - // The container's block, the header node its constructor allocates, and the root. - const std::array<std::uint64_t, 3> sizes{ - sizeof(nodes_type), - node_probe_bytes<Traits>, - node_probe_bytes<Traits>, - }; - while (!probe(heap_of(r), sizes)) { - if (!r.grow(grown_size(r, sizes[0] + sizes[1] + sizes[2]))) { - return errc::capacity; - } - } - heap& h = heap_of(r); - void* block = h.allocate_aligned(sizeof(nodes_type), alignof(nodes_type)); - if (block == nullptr) { - boost::throw_exception(std::bad_alloc()); - } - std::memset(block, 0, sizeof(nodes_type)); - // The container is the heap's first block, where attach requires it. - BOOST_ASSERT(std::cmp_equal(static_cast<std::byte*>(block) - r.data(), container_offset)); - auto* nodes = new (block) nodes_type(allocator<node_type>(&h)); - const byte_string empty; - const scalar_type zero{}; - nodes->emplace(root_id, std::uint64_t{0}, index_group, std::uint64_t{0}, empty, - kind_t::null, repr::none, zero, empty); - - image_header header{}; - header.magic = image_magic; - header.version = format_version; - header.byte_order = byte_order_mark; - header.reserved_4 = 0; - header.layout = layout_tag<Traits>(); - header.size = r.size(); - header.container = container_offset; - header.next_id = root_id + 1; - std::memcpy(r.data(), &header, sizeof header); - tree t; - t.region_ = &r; - return t; - } - - // NOLINTEND(bugprone-exception-escape) - - /** - Attaches to an image already in a region: checks its header, its heap's sanity, and that the - pointers it follows to the root lie inside the image. - */ - static result<tree> attach(region& r) noexcept { - // Fewer bytes than a header and a heap would have the heap's check read past them. - if (r.data() == nullptr || r.size() < smallest_image() || - reinterpret_cast<std::uintptr_t>(r.data()) % 16 != 0) { - return errc::not_a_document; - } - // A seal is checked by whoever opens the image, before it attaches. - const std::span<const std::byte> bytes(r.data(), static_cast<std::size_t>(r.size())); - if (const auto checked = check_image(bytes, layout_tag<Traits>(), verify::none); - !checked.has_value()) { - return checked.error(); - } - image_header header{}; - std::memcpy(&header, r.data(), sizeof header); - if (header.container != container_offset || - header.size < container_offset + sizeof(nodes_type) || header.next_id <= root_id) { - return errc::not_a_document; - } - heap& h = heap_of(r); - if (h.get_size() > header.size - header_bytes || !h.check_sanity()) { - return errc::not_a_document; - } - tree t; - t.region_ = &r; - const node_type* root = t.first_by_id(header.size); - if (root == nullptr || root->id != root_id || root->parent != 0) { - return errc::not_a_document; - } - return t; - } - - /** A tree attached to nothing, which reads as nothing and changes nothing. */ - tree() noexcept = default; - - /** Attaches the tree to `r`, the same image after the region that held it was moved. */ - void rebind(region& r) noexcept { region_ = &r; } - - /** The region it is attached to. */ - [[nodiscard]] region& storage() const noexcept { return *region_; } + /** A tree attached to nothing, which reads as nothing. */ + tree_view() noexcept = default; /** The root's id, @ref root_id. */ [[nodiscard]] std::uint64_t root() const noexcept { return root_id; } @@ -524,39 +508,37 @@ class tree { return nodes == nullptr ? nullptr : find_in(*nodes, id); } - // A lookup ends the program where the process heap cannot hold a long key's UTF-16, as the - // library tolerates. - // NOLINTBEGIN(bugprone-exception-escape) - /** The member `key`, in UTF-8, of the object `object`, or null. */ + /** + The member `key`, in UTF-8, of the object `object`, or null: under `utf16` the key is compared + with the stored ones as it is decoded, so a key of any length allocates nothing. + */ [[nodiscard]] const node<Traits>* member(std::uint64_t object, std::string_view key) const noexcept { const nodes_type* nodes = nodes_of(); if (nodes == nullptr || !is_kind(find_in(*nodes, object), kind_t::object)) { return nullptr; } + // Text that is not UTF-8 is no stored key's, and the UTF-16 order decodes only UTF-8. if constexpr (utf16_text) { if (!valid_utf8(key)) { return nullptr; } - // Most keys are short: they are transcoded on the stack. - std::array<char16_t, 64> small{}; - std::vector<char16_t> large; - const std::uint64_t units = utf16_length(key); - char16_t* out = small.data(); - if (units > small.size()) { - large.resize(static_cast<std::size_t>(units)); - out = large.data(); - } - to_utf16(key, out); - return member_in( - *nodes, object, - as_chars(std::as_bytes(std::span(out, static_cast<std::size_t>(units))))); - } else { - return member_in(*nodes, object, key); } + return member_in(*nodes, object, lookup_key(key)); } - // NOLINTEND(bugprone-exception-escape) + /** + The member of the object `object` whose key is `stored`, its bytes in the traits' encoding, as + a node holds a key, or null: nothing is transcoded. + */ + [[nodiscard]] const node<Traits>* member_stored(std::uint64_t object, + std::string_view stored) const noexcept { + const nodes_type* nodes = nodes_of(); + if (nodes == nullptr || !is_kind(find_in(*nodes, object), kind_t::object)) { + return nullptr; + } + return member_in(*nodes, object, stored); + } /** The element `index` of the array `array`, or null. */ [[nodiscard]] const node<Traits>* element(std::uint64_t array, @@ -623,163 +605,599 @@ class tree { return nodes == nullptr ? 0 : nodes->size(); } - // An operation ends the program where the process heap, which holds what it stages, runs - // out, as the library tolerates, and where an allocation in the image fails after its probe - // passed, a bug of the document's, which the allocator reports by boost::throw_exception. - // NOLINTBEGIN(bugprone-exception-escape) /** - Replaces the value of node `id` with `v`, its children erased after the new value is in place. + The exact size of the image @ref compact_to builds from this tree: the header, the heap's own + bytes, the container's two blocks, and for each node its block and those of its key and text. + + It reads every node and allocates nothing; 0 when the tree is attached to nothing. */ - result<void> assign(std::uint64_t id, const item<Traits>& v) noexcept { + [[nodiscard]] std::uint64_t compact_bytes() const noexcept { const nodes_type* nodes = nodes_of(); - const node_type* target = nodes == nullptr ? nullptr : find_in(*nodes, id); - if (target == nullptr) { - return errc::type; + if (nodes == nullptr) { + return 0; } - change c = start_change(); - add_existing(c, *target, v, id == root_id); - if (const auto read = read_values(c); !read.has_value()) { - return read; + const costs c = measure_costs(); + std::uint64_t total = header_bytes + c.heap.overhead + c.container + c.header_node; + for (const node_type& n : nodes->template get<by_id>()) { + total = saturated_sum(total, c.node); + total = saturated_sum(total, c.heap.block(n.key.size)); + total = saturated_sum(total, c.heap.block(n.text.size)); } - return write(c, [] {}); + return total; } /** - Sets the member `key`: an existing one is assigned and keeps its place, a new one takes the - policy's place; returns its id. + The container of the nodes, for what walks its indices itself, both ways or by a bound; null + when the tree is attached to nothing. */ - result<std::uint64_t> set_member(std::uint64_t object, std::string_view key, - const item<Traits>& v) noexcept { - const nodes_type* nodes = nodes_of(); - const node_type* o = nodes == nullptr ? nullptr : find_in(*nodes, object); - if (!is_kind(o, kind_t::object)) { - return errc::type; - } - change c = start_change(); - const auto stored = encode_key(c, key); - if (!stored.has_value()) { - return errc::type; - } - if (const node_type* existing = member_in(*nodes, object, as_chars(*stored))) { - const std::uint64_t id = existing->id; - if (const auto done = assign(id, v); !done.has_value()) { - return done.error(); - } - return id; - } - scalar_type counts = o->scalar; - std::uint64_t next = word(counts, next_insertion_at); - const std::uint64_t id = add_member(c, object, key, *stored, next, v); - if (const auto read = read_values(c); !read.has_value()) { - return read.error(); - } - if (const auto done = write(c, [] {}); !done.has_value()) { - return done.error(); - } - set_word(counts, next_insertion_at, next); - set_word(counts, key_count_at, word(counts, key_count_at) + 1); - set_scalar(object, counts); - return id; - } + [[nodiscard]] const container<Traits>* nodes() const noexcept { return nodes_of(); } - /** Sets each entry's member in order, as one operation: `Object.assign`. */ - result<void> set_members(std::uint64_t object, - std::span<const literal_entry<Traits>> members) noexcept { - const nodes_type* nodes = nodes_of(); - const node_type* o = nodes == nullptr ? nullptr : find_in(*nodes, object); - if (!is_kind(o, kind_t::object)) { - return errc::type; - } - change c = start_change(); - scalar_type counts = o->scalar; - std::uint64_t next = word(counts, next_insertion_at); - std::uint64_t added = 0; - auto placed = place_members(c, object, members, next, added, true); - if (!placed.has_value()) { - return placed; - } - if (const auto read = read_values(c); !read.has_value()) { - return read; - } - if (const auto done = write(c, [] {}); !done.has_value()) { - return done; - } - set_word(counts, next_insertion_at, next); - set_word(counts, key_count_at, word(counts, key_count_at) + added); - set_scalar(object, counts); - return {}; - } +protected: + /** The node of this tree. */ + using node_type = node<Traits>; - /** Erases the member `key` and its subtree; whether it was there. */ - result<bool> erase_member(std::uint64_t object, std::string_view key) noexcept { - const node_type* o = find(object); - if (!is_kind(o, kind_t::object)) { - return errc::type; - } - const node_type* m = member(object, key); - if (m == nullptr) { - return false; - } - scalar_type counts = o->scalar; - erase_subtree(m->id); - set_word(counts, key_count_at, word(counts, key_count_at) - 1); - set_scalar(object, counts); - sync_header(read_header().next_id); - return true; - } + /** The container of this tree's nodes. */ + using nodes_type = container<Traits>; - /** - Sets the element `index`: assigned when it exists, else the array filled with `null` up to it - and `v` appended, as one operation. - */ - result<void> set_element(std::uint64_t array, std::uint64_t index, - const item<Traits>& v) noexcept { - const node_type* a = find(array); - if (!is_kind(a, kind_t::array)) { - return errc::type; - } - const std::uint64_t length = word(a->scalar, length_at); - if (index < length) { - return assign(element_in(*nodes_of(), array, index)->id, v); - } - return append(array, length, index - length, &v); - } + /** A node's scalar. */ + using scalar_type = std::array<std::byte, scalar_bytes<Traits>>; - /** Inserts `v` before the element `at`, the later elements renumbered. */ - result<void> insert_elements(std::uint64_t array, std::uint64_t at, - std::span<const item<Traits>> v) noexcept { - return splice(array, at, 0, v); - } + /** The kinds of values, which a node's member `kind` hides inside it. */ + using kind_t = webcpp::document::kind; - /** Erases `n` elements from `at` and their subtrees, the later elements renumbered. */ - result<void> erase_elements(std::uint64_t array, std::uint64_t at, std::uint64_t n) noexcept { - return splice(array, at, n, {}); - } + /** Whether keys and strings are stored as UTF-16 code units. */ + static constexpr bool utf16_text = std::same_as<typename Traits::string, utf16>; - /** Erases `remove` elements from `at` and inserts `v` there, as one operation. */ - result<void> splice(std::uint64_t array, std::uint64_t at, std::uint64_t remove, - std::span<const item<Traits>> v) noexcept { - const node_type* a = find(array); - if (!is_kind(a, kind_t::array)) { - return errc::type; + /** Whether objects walk their members by key. */ + static constexpr bool sorted_keys = std::same_as<typename Traits::object, sorted>; + + /** Where an array's length is in its scalar. */ + static constexpr std::size_t length_at = 0; + + /** Where an object's next insertion number is in its scalar. */ + static constexpr std::size_t next_insertion_at = 0; + + /** Where an object's key count is in its scalar. */ + static constexpr std::size_t key_count_at = 8; + + /** + What a compact image's blocks take, measured once per call: the heap's, the container's, the + container's header node and a node. + */ + struct costs { + /** The heap's own. */ + heap_costs heap; + + /** The block of the container itself. */ + std::uint64_t container = 0; + + /** The block of the container's header node, which its constructor takes. */ + std::uint64_t header_node = 0; + + /** The block of each node. */ + std::uint64_t node = 0; + }; + + // The scratch heap is sized for what is built in it, so no allocation fails; were one to, the + // allocator would report it by boost::throw_exception, as the library tolerates. + // NOLINTBEGIN(bugprone-exception-escape) + /** + Measures @ref costs in a scratch heap on the stack, by building in it what a tree does: a + container and a node. The block sizes of Boost.MultiIndex's nodes are not public, and this way + none is repeated here. + */ + static costs measure_costs() noexcept { + constexpr std::size_t scratch_bytes = 2048; + alignas(16) std::array<std::byte, scratch_bytes> scratch{}; + heap* h = new (scratch.data()) heap(scratch.size(), sizeof(heap)); + costs c; + c.heap = measure_heap_costs(); + std::uint64_t free_memory = h->get_free_memory(); + void* block = h->allocate_aligned(sizeof(nodes_type), alignof(nodes_type)); + BOOST_ASSERT(block != nullptr); + c.container = std::exchange(free_memory, h->get_free_memory()) - free_memory; + auto* nodes = new (block) nodes_type(allocator<node_type>(h)); + c.header_node = std::exchange(free_memory, h->get_free_memory()) - free_memory; + const byte_string empty; + const scalar_type zero{}; + nodes->emplace(root_id, std::uint64_t{0}, index_group, std::uint64_t{0}, empty, + kind_t::null, repr::none, zero, empty); + c.node = std::exchange(free_memory, h->get_free_memory()) - free_memory; + nodes->~nodes_type(); + return c; + } + + // NOLINTEND(bugprone-exception-escape) + + /** + The node of the smallest id, which is the root, read through the two pointers that reach it, + the container's header node and the first node of the index by id, each first checked to lie + inside the image's `size` bytes; null when either does not, or when the tree has no node. + */ + [[nodiscard]] const node_type* first_by_id(std::uint64_t size) const noexcept { + const auto& ids = nodes_of()->template get<by_id>(); + const auto begin = reinterpret_cast<std::uintptr_t>(region_->data()); + const auto within = [begin, size](const auto* p) { + const auto at = reinterpret_cast<std::uintptr_t>(p); + constexpr std::uint64_t bytes = sizeof(*p); + return at >= begin + header_bytes && at % alignof(decltype(*p)) == 0 && bytes <= size && + at - begin <= size - bytes; + }; + // get_node gives an iterator's node without reading it, which no other member does. + const auto end = ids.end(); + if (!within(end.get_node())) { + return nullptr; + } + const auto first = ids.begin(); + if (first == end || !within(first.get_node())) { + return nullptr; + } + return &*first; + } + + /** The fewest bytes that hold a header and an empty heap. */ + static std::uint64_t smallest_image() noexcept { + return header_bytes + heap::get_min_size(sizeof(heap)); + } + + /** `a + b`, or the largest value when that overflows. */ + static std::uint64_t saturated_sum(std::uint64_t a, std::uint64_t b) noexcept { + return a > std::numeric_limits<std::uint64_t>::max() - b + ? std::numeric_limits<std::uint64_t>::max() + : a + b; + } + + /** The bytes as a `std::string_view`, as the index by key holds keys. */ + static std::string_view as_chars(std::span<const std::byte> bytes) noexcept { + return {reinterpret_cast<const char*>(bytes.data()), bytes.size()}; + } + + /** Eight bytes of a scalar, from `at`. */ + static std::uint64_t word(const scalar_type& s, std::size_t at) noexcept { + return load_little(s.data() + at, 8); + } + + /** Writes eight bytes of a scalar, from `at`. */ + static void set_word(scalar_type& s, std::size_t at, std::uint64_t value) noexcept { + store_little(value, s.data() + at, 8); + } + + /** Whether `n` is a node of kind `k`. */ + static bool is_kind(const node_type* n, kind_t k) noexcept { + return n != nullptr && n->kind == k; + } + + /** The node of `id` in `nodes`, or null. */ + static const node_type* find_in(const nodes_type& nodes, std::uint64_t id) noexcept { + const auto& ids = nodes.template get<by_id>(); + const auto it = ids.find(id); + return it == ids.end() ? nullptr : &*it; + } + + /** + A key in UTF-8 as the index @ref by_key looks it up: itself under `utf8`, which stores keys + so, else a @ref utf8_lookup. + */ + static auto lookup_key(std::string_view utf8) noexcept { + if constexpr (utf16_text) { + return utf8_lookup{utf8}; + } else { + return utf8; + } + } + + /** + The child of `object` whose key is `key`, in the traits' encoding as a `std::string_view`, or + in UTF-8 as a @ref utf8_lookup; or null. + */ + template <class Key> + static const node_type* member_in(const nodes_type& nodes, std::uint64_t object, + const Key& key) noexcept { + const auto& keys = nodes.template get<by_key>(); + const auto it = keys.find(std::make_tuple(object, key)); + return it == keys.end() ? nullptr : &*it; + } + + /** The element `index` of `array`, or null. */ + static const node_type* element_in(const nodes_type& nodes, std::uint64_t array, + std::uint64_t index) noexcept { + const auto& order = nodes.template get<by_order>(); + const auto it = order.find(std::make_tuple(array, index_group, index)); + return it == order.end() ? nullptr : &*it; + } + + /** The first child of `parent` in `index`, or null. */ + template <class Index> + static const node_type* first_of(const Index& index, std::uint64_t parent) noexcept { + const auto it = index.lower_bound(std::make_tuple(parent)); + return it == index.end() || it->parent != parent ? nullptr : &*it; + } + + /** The node after `child` in `index`, when it has the same parent, or null. */ + template <class Index> + static const node_type* next_of(const Index& index, const node_type& child) noexcept { + auto it = index.iterator_to(child); + ++it; + return it == index.end() || it->parent != child.parent ? nullptr : &*it; + } + + /** The container of the attached image, or null when the tree is attached to nothing. */ + [[nodiscard]] nodes_type* nodes_of() const noexcept { + if (region_ == nullptr || region_->data() == nullptr) { + return nullptr; + } + std::uint64_t offset = 0; + std::memcpy(&offset, region_->data() + offsetof(image_header, container), sizeof offset); + return std::launder(reinterpret_cast<nodes_type*>(region_->data() + offset)); + } + + /** The header of the attached image. */ + [[nodiscard]] image_header read_header() const noexcept { + image_header header{}; + std::memcpy(&header, region_->data(), sizeof header); + return header; + } + +private: + template <class, class> + friend class tree; + + /** The bytes of the image it reads, or null when it is attached to nothing. */ + region_bytes* region_ = nullptr; +}; + +/** + The tree of a document, a light handle on a region: it holds no pointer into the image, so it + stays valid when the region grows and its bytes move. + + Every operation that changes the tree either completes or changes nothing, and returns + @ref errc::capacity when there is no room, in the image or, with exceptions, in the allocator. + Keys are given in UTF-8; with `utf16` the tree writes them as UTF-16 into the image when it stores + them and compares them unit by unit when it looks them up, and a key that is not UTF-8 finds + nothing. + + @tparam Traits The traits. + @tparam Allocator The allocator of the region, which grows an owned image and, rebound, holds all + an operation stages before it changes anything, and compaction's walk. +*/ +template <class Traits, class Allocator> +class tree : public tree_view<Traits> { + /** The reading half. */ + using view = tree_view<Traits>; + + using typename view::costs; + using typename view::kind_t; + using typename view::node_type; + using typename view::nodes_type; + using typename view::scalar_type; + using view::as_chars; + using view::element_in; + using view::find_in; + using view::first_by_id; + using view::is_kind; + using view::key_count_at; + using view::length_at; + using view::lookup_key; + using view::measure_costs; + using view::member_in; + using view::next_insertion_at; + using view::nodes_of; + using view::read_header; + using view::saturated_sum; + using view::set_word; + using view::smallest_image; + using view::sorted_keys; + using view::utf16_text; + using view::word; + +public: + /** The region of this tree's allocator. */ + using region_type = basic_region<Allocator>; + + using view::count; + using view::element; + using view::find; + using view::first_child; + using view::member; + using view::member_stored; + using view::next_sibling; + + // Formatting allocates nothing but in the image, after its probe; an allocation there that + // fails, a bug of the document's, which the image's allocator reports by + // boost::throw_exception, ends the program. + // NOLINTBEGIN(bugprone-exception-escape) + /** + Formats a region that holds an empty heap: the header, the container, a root holding `null`. + */ + static result<tree> format(region_type& r) noexcept { + if (r.data() == nullptr || r.size() < smallest_image()) { + return errc::capacity; + } + // The container's block, the header node its constructor allocates, and the root. + const std::array<std::uint64_t, 3> sizes{ + sizeof(nodes_type), + node_probe_bytes<Traits>, + node_probe_bytes<Traits>, + }; + while (!probe(heap_of(r), sizes)) { + if (!r.grow(grown_size(r, sizes[0] + sizes[1] + sizes[2]))) { + return errc::capacity; + } + } + heap& h = heap_of(r); + void* block = h.allocate_aligned(sizeof(nodes_type), alignof(nodes_type)); + if (block == nullptr) { + boost::throw_exception(std::bad_alloc()); + } + std::memset(block, 0, sizeof(nodes_type)); + // The container is the heap's first block, where attach requires it. + BOOST_ASSERT(std::cmp_equal(static_cast<std::byte*>(block) - r.data(), container_offset)); + auto* nodes = new (block) nodes_type(allocator<node_type>(&h)); + const byte_string empty; + const scalar_type zero{}; + nodes->emplace(root_id, std::uint64_t{0}, index_group, std::uint64_t{0}, empty, + kind_t::null, repr::none, zero, empty); + + image_header header{}; + header.magic = image_magic; + header.version = format_version; + header.byte_order = byte_order_mark; + header.reserved_4 = 0; + header.layout = layout_tag<Traits>(); + header.size = r.size(); + header.container = container_offset; + header.next_id = root_id + 1; + std::memcpy(r.data(), &header, sizeof header); + tree t; + t.region_ = &r; + return t; + } + + // NOLINTEND(bugprone-exception-escape) + + /** + Attaches to an image already in a region: checks its header, its heap's sanity, and that the + pointers it follows to the root lie inside the image. + */ + static result<tree> attach(region_type& r) noexcept { + // Fewer bytes than a header and a heap would have the heap's check read past them. + if (r.data() == nullptr || r.size() < smallest_image() || + reinterpret_cast<std::uintptr_t>(r.data()) % 16 != 0) { + return errc::not_a_document; + } + // A seal is checked by whoever opens the image, before it attaches. + const std::span<const std::byte> bytes(r.data(), static_cast<std::size_t>(r.size())); + if (const auto checked = check_image(bytes, layout_tag<Traits>(), verify::none); + !checked.has_value()) { + return checked.error(); + } + image_header header{}; + std::memcpy(&header, r.data(), sizeof header); + if (header.container != container_offset || + header.size < container_offset + sizeof(nodes_type) || header.next_id <= root_id) { + return errc::not_a_document; + } + heap& h = heap_of(r); + if (h.get_size() > header.size - header_bytes || !h.check_sanity()) { + return errc::not_a_document; + } + tree t; + t.region_ = &r; + const node_type* root = t.first_by_id(header.size); + if (root == nullptr || root->id != root_id || root->parent != 0) { + return errc::not_a_document; + } + return t; + } + + /** A tree attached to nothing, which reads as nothing and changes nothing. */ + tree() noexcept = default; + + /** Attaches the tree to `r`, the same image after the region that held it was moved. */ + void rebind(region_type& r) noexcept { this->region_ = &r; } + + /** The region it is attached to. */ + [[nodiscard]] region_type& storage() const noexcept { + return static_cast<region_type&>(*this->region_); + } + + /** The allocator of its region, which holds what an operation stages. */ + [[nodiscard]] Allocator get_allocator() const noexcept { return storage().get_allocator(); } + + // An operation stages in the allocator, which with exceptions makes its std::bad_alloc + // errc::capacity before anything changes; an allocation in the image that fails after its + // probe passed, a bug of the document's, which the image's allocator reports by + // boost::throw_exception, ends the program. + // NOLINTBEGIN(bugprone-exception-escape) + /** + Replaces the value of node `id` with `v`, its children erased after the new value is in place. + */ + result<void> assign(std::uint64_t id, const item<Traits>& v) noexcept { + const nodes_type* nodes = nodes_of(); + const node_type* target = nodes == nullptr ? nullptr : find_in(*nodes, id); + if (target == nullptr) { + return errc::type; } - const std::uint64_t length = word(a->scalar, length_at); - if (at > length || remove > length - at) { - return errc::range; + change c = start_change(); + return write( + c, + [&]() -> result<void> { + add_existing(c, *target, v, id == root_id); + return read_values(c); + }, + [] {}); + } + + /** + Sets the member `key`: an existing one is assigned and keeps its place, a new one takes the + policy's place; returns its id. + */ + result<std::uint64_t> set_member(std::uint64_t object, std::string_view key, + const item<Traits>& v) noexcept { + const nodes_type* nodes = nodes_of(); + const node_type* o = nodes == nullptr ? nullptr : find_in(*nodes, object); + if (!is_kind(o, kind_t::object)) { + return errc::type; + } + if (!valid_utf8(key)) { + return errc::type; + } + if (const node_type* existing = member_in(*nodes, object, lookup_key(key))) { + const std::uint64_t id = existing->id; + if (const auto done = assign(id, v); !done.has_value()) { + return done.error(); + } + return id; + } + scalar_type counts = o->scalar; + std::uint64_t next = word(counts, next_insertion_at); + std::uint64_t id = 0; + change c = start_change(); + if (const auto done = write( + c, + [&]() -> result<void> { + id = add_member(c, object, key, next, v); + return read_values(c); + }, + [] {}); + !done.has_value()) { + return done.error(); + } + set_word(counts, next_insertion_at, next); + set_word(counts, key_count_at, word(counts, key_count_at) + 1); + set_scalar(object, counts); + return id; + } + + /** Sets each entry's member in order, as one operation: `Object.assign`. */ + result<void> set_members(std::uint64_t object, + std::span<const literal_entry<Traits>> members) noexcept { + const nodes_type* nodes = nodes_of(); + const node_type* o = nodes == nullptr ? nullptr : find_in(*nodes, object); + if (!is_kind(o, kind_t::object)) { + return errc::type; } + scalar_type counts = o->scalar; + std::uint64_t next = word(counts, next_insertion_at); + std::uint64_t added = 0; change c = start_change(); - for (std::uint64_t i = 0; i < remove; ++i) { - c.doomed.push_back(element_in(*nodes_of(), array, at + i)->id); + if (const auto done = write( + c, + [&]() -> result<void> { + if (const auto placed = place_members(c, object, members, next, added, true); + !placed.has_value()) { + return placed; + } + return read_values(c); + }, + [] {}); + !done.has_value()) { + return done; + } + set_word(counts, next_insertion_at, next); + set_word(counts, key_count_at, word(counts, key_count_at) + added); + set_scalar(object, counts); + return {}; + } + + /** + Erases the member `key` and its subtree; whether it was there. It allocates nothing and + cannot run out of room. + */ + result<bool> erase_member(std::uint64_t object, std::string_view key) noexcept { + const node_type* o = find(object); + if (!is_kind(o, kind_t::object)) { + return errc::type; + } + const node_type* m = member(object, key); + if (m == nullptr) { + return false; + } + erase_child(*o, m->id); + return true; + } + + /** + Erases the member of `object` whose node is `id`, and its subtree: the erasure of a member + found by walking, with no key to look up. It allocates nothing and cannot run out of room. + + @return Whether `id` is a member of `object`; @ref errc::type when `object` is no object. + */ + result<bool> erase_member_by_id(std::uint64_t object, std::uint64_t id) noexcept { + const node_type* o = find(object); + if (!is_kind(o, kind_t::object)) { + return errc::type; + } + const node_type* m = find(id); + if (m == nullptr || m->parent != object) { + return false; + } + erase_child(*o, id); + return true; + } + + /** + Sets the element `index`: assigned when it exists, else the array filled with `null` up to it + and `v` appended, as one operation. + */ + result<void> set_element(std::uint64_t array, std::uint64_t index, + const item<Traits>& v) noexcept { + const node_type* a = find(array); + if (!is_kind(a, kind_t::array)) { + return errc::type; + } + const std::uint64_t length = word(a->scalar, length_at); + if (index < length) { + return assign(element_in(*nodes_of(), array, index)->id, v); + } + return append(array, length, index - length, &v); + } + + /** Inserts `v` before the element `at`, the later elements renumbered. */ + result<void> insert_elements(std::uint64_t array, std::uint64_t at, + std::span<const item<Traits>> v) noexcept { + return splice(array, at, 0, v); + } + + /** + Erases `n` elements from `at` and their subtrees, the later elements renumbered. It allocates + nothing and cannot run out of room. + */ + result<void> erase_elements(std::uint64_t array, std::uint64_t at, std::uint64_t n) noexcept { + return splice(array, at, n, {}); + } + + /** + Erases `remove` elements from `at` and inserts `v` there, as one operation; with nothing to + insert, an erasure, which allocates nothing and cannot run out of room. + */ + result<void> splice(std::uint64_t array, std::uint64_t at, std::uint64_t remove, + std::span<const item<Traits>> v) noexcept { + const node_type* a = find(array); + if (!is_kind(a, kind_t::array)) { + return errc::type; } - for (std::size_t i = 0; i < v.size(); ++i) { - add_element(c, array, at + i, &v[i]); + const std::uint64_t length = word(a->scalar, length_at); + if (at > length || remove > length - at) { + return errc::range; } - if (const auto read = read_values(c); !read.has_value()) { - return read; + if (v.empty()) { + erase_range(array, length, at, remove); + return {}; } const std::uint64_t added = v.size(); + change c = start_change(); + const auto stage = [&]() -> result<void> { + for (std::uint64_t i = 0; i < remove; ++i) { + c.doomed.push_back(element_in(*nodes_of(), array, at + i)->id); + } + for (std::size_t i = 0; i < v.size(); ++i) { + add_element(c, array, at + i, &v[i]); + } + return read_values(c); + }; // The removed elements have left the index group: the later ones move into their place. - auto done = write(c, [&] { + const auto arrange = [&] { if (added > remove) { for (std::uint64_t o = length; o > at + remove; --o) { renumber(array, o - 1, o - 1 + (added - remove)); @@ -789,8 +1207,8 @@ class tree { renumber(array, o, o - (remove - added)); } } - }); - if (!done.has_value()) { + }; + if (const auto done = write(c, stage, arrange); !done.has_value()) { return done; } set_length_word(array, length - remove + added); @@ -844,14 +1262,14 @@ class tree { if (nodes_of() == nullptr) { return errc::type; } - if (!region_->is_owned()) { + if (!storage().is_owned()) { return {}; } - heap_of(*region_).shrink_to_fit(); - const std::uint64_t size = header_bytes + heap_of(*region_).get_size(); - if (!region_->shrink_to(size)) { + heap_of(storage()).shrink_to_fit(); + const std::uint64_t size = header_bytes + heap_of(storage()).get_size(); + if (!storage().shrink_to(size)) { // The heap takes its end back, so that it ends where the region does. - heap_of(*region_).grow(region_->size() - size); + heap_of(storage()).grow(storage().size() - size); return errc::capacity; } sync_header(read_header().next_id); @@ -866,52 +1284,36 @@ class tree { if (nodes_of() == nullptr) { return errc::type; } - if (bytes <= region_->size()) { + if (bytes <= storage().size()) { return {}; } - if (!region_->grow(bytes)) { + if (!storage().grow(bytes)) { return errc::capacity; } sync_header(read_header().next_id); return {}; } - /** - The exact size of the image @ref compact_to builds from this tree: the header, the heap's own - bytes, the container's two blocks, and for each node its block and those of its key and text. - - It reads every node and allocates nothing; 0 when the tree is attached to nothing. - */ - [[nodiscard]] std::uint64_t compact_bytes() const noexcept { - const nodes_type* nodes = nodes_of(); - if (nodes == nullptr) { - return 0; - } - const costs c = measure_costs(); - std::uint64_t total = header_bytes + c.heap.overhead + c.container + c.header_node; - for (const node_type& n : nodes->template get<by_id>()) { - total = saturated_sum(total, c.node); - total = saturated_sum(total, c.heap.block(n.key.size)); - total = saturated_sum(total, c.heap.block(n.text.size)); - } - return total; - } - - // The walk keeps its stack on the process heap, whose exhaustion ends the program, as the - // library tolerates. + // The walk's stack is in the allocator of `to`, whose std::bad_alloc is errc::capacity with + // exceptions; an allocation in the image that fails after the heap was found to hold it, a bug + // of the document's, which the image's allocator reports by boost::throw_exception, ends the + // program. // NOLINTBEGIN(bugprone-exception-escape) /** Builds into `to` a copy of `from` in document order: ids from the first, insertion numbers from 0, and for each node its key, its text, then the node, each block right after the last. `to` is a fresh region of exactly `bytes`, @ref compact_bytes of `from`, over a heap that holds - nothing, so that its blocks fill it, with no hole and no free block. + nothing, so that its blocks fill it, with no hole and no free block. The walk keeps its stack + in the allocator of `to`, rebound; `from` is never changed. @return The tree over `to`; @ref errc::type when `from` is attached to nothing, - @ref errc::capacity when `to` is not of `bytes` bytes. + @ref errc::capacity when `to` is not of `bytes` bytes, or, with exceptions, when the allocator + has no room for the walk's stack, `to` then holding part of the copy and no header. */ - static result<tree> compact_to(region& to, const tree& from, std::uint64_t bytes) noexcept { - const nodes_type* from_nodes = from.nodes_of(); + static result<tree> compact_to(region_type& to, const view& from, + std::uint64_t bytes) noexcept { + const nodes_type* from_nodes = from.nodes(); const node_type* root = from_nodes == nullptr ? nullptr : find_in(*from_nodes, root_id); if (root == nullptr) { return errc::type; @@ -925,119 +1327,43 @@ class tree { // taken only when it is there, whatever the sizes say: a wrong figure is an error value. if (h.get_free_memory() < c.heap.slack + c.container + c.header_node) { return errc::capacity; - } - void* block = h.allocate_aligned(sizeof(nodes_type), alignof(nodes_type)); - BOOST_ASSERT(block != nullptr); - std::memset(block, 0, sizeof(nodes_type)); - // The container is the heap's first block, where attach requires it. - BOOST_ASSERT(std::cmp_equal(static_cast<std::byte*>(block) - to.data(), container_offset)); - auto* nodes = new (block) nodes_type(allocator<node_type>(&h)); - - compaction copier{from, c, h, nodes}; - if (!copier.copy_tree(*root)) { - return errc::capacity; - } - BOOST_ASSERT(h.get_free_memory() == c.heap.slack); - - image_header header{}; - header.magic = image_magic; - header.version = format_version; - header.byte_order = byte_order_mark; - header.reserved_4 = 0; - header.layout = layout_tag<Traits>(); - header.size = to.size(); - header.container = container_offset; - header.next_id = copier.next_id; - std::memcpy(to.data(), &header, sizeof header); - tree t; - t.region_ = &to; - return t; - } - - // NOLINTEND(bugprone-exception-escape) - - /** - The container of the nodes, for what walks its indices itself, both ways or by a bound; null - when the tree is attached to nothing. - */ - [[nodiscard]] const container<Traits>* nodes() const noexcept { return nodes_of(); } - -private: - /** - What a compact image's blocks take, measured once per call: the heap's, the container's, the - container's header node and a node. - */ - struct costs { - /** The heap's own. */ - heap_costs heap; - - /** The block of the container itself. */ - std::uint64_t container = 0; - - /** The block of the container's header node, which its constructor takes. */ - std::uint64_t header_node = 0; - - /** The block of each node. */ - std::uint64_t node = 0; - }; - - // The scratch heap is sized for what is built in it, so no allocation fails; were one to, the - // allocator would report it by boost::throw_exception, as the library tolerates. - // NOLINTBEGIN(bugprone-exception-escape) - /** - Measures @ref costs in a scratch heap on the stack, by building in it what a tree does: a - container and a node. The block sizes of Boost.MultiIndex's nodes are not public, and this way - none is repeated here. - */ - static costs measure_costs() noexcept { - constexpr std::size_t scratch_bytes = 2048; - alignas(16) std::array<std::byte, scratch_bytes> scratch{}; - heap* h = new (scratch.data()) heap(scratch.size(), sizeof(heap)); - costs c; - c.heap = measure_heap_costs(); - std::uint64_t free_memory = h->get_free_memory(); - void* block = h->allocate_aligned(sizeof(nodes_type), alignof(nodes_type)); - BOOST_ASSERT(block != nullptr); - c.container = std::exchange(free_memory, h->get_free_memory()) - free_memory; - auto* nodes = new (block) nodes_type(allocator<node_type>(h)); - c.header_node = std::exchange(free_memory, h->get_free_memory()) - free_memory; - const byte_string empty; - const scalar_type zero{}; - nodes->emplace(root_id, std::uint64_t{0}, index_group, std::uint64_t{0}, empty, - kind_t::null, repr::none, zero, empty); - c.node = std::exchange(free_memory, h->get_free_memory()) - free_memory; - nodes->~nodes_type(); - return c; - } - - // NOLINTEND(bugprone-exception-escape) - - /** The node of this tree. */ - using node_type = node<Traits>; - - /** The container of this tree's nodes. */ - using nodes_type = container<Traits>; - - /** A node's scalar. */ - using scalar_type = std::array<std::byte, scalar_bytes<Traits>>; - - /** The kinds of values, which a node's member `kind` hides inside it. */ - using kind_t = webcpp::document::kind; + } + void* block = h.allocate_aligned(sizeof(nodes_type), alignof(nodes_type)); + BOOST_ASSERT(block != nullptr); + std::memset(block, 0, sizeof(nodes_type)); + // The container is the heap's first block, where attach requires it. + BOOST_ASSERT(std::cmp_equal(static_cast<std::byte*>(block) - to.data(), container_offset)); + auto* nodes = new (block) nodes_type(allocator<node_type>(&h)); - /** Whether keys and strings are stored as UTF-16 code units. */ - static constexpr bool utf16_text = std::same_as<typename Traits::string, utf16>; + compaction copier{from, c, h, nodes, to.get_allocator()}; + if (!copier.copy_tree(*root)) { + return errc::capacity; + } + BOOST_ASSERT(h.get_free_memory() == c.heap.slack); - /** Whether objects walk their members by key. */ - static constexpr bool sorted_keys = std::same_as<typename Traits::object, sorted>; + image_header header{}; + header.magic = image_magic; + header.version = format_version; + header.byte_order = byte_order_mark; + header.reserved_4 = 0; + header.layout = layout_tag<Traits>(); + header.size = to.size(); + header.container = container_offset; + header.next_id = copier.next_id; + std::memcpy(to.data(), &header, sizeof header); + tree t; + t.region_ = &to; + return t; + } - /** Where an array's length is in its scalar. */ - static constexpr std::size_t length_at = 0; + // NOLINTEND(bugprone-exception-escape) - /** Where an object's next insertion number is in its scalar. */ - static constexpr std::size_t next_insertion_at = 0; +private: + /** Where the scalar of a node @ref erase_subtree lists holds the id of the next one. */ + static constexpr std::size_t next_listed_at = 0; - /** Where an object's key count is in its scalar. */ - static constexpr std::size_t key_count_at = 8; + /** Where the scalar of a node @ref erase_subtree lists holds the id of the one before. */ + static constexpr std::size_t previous_listed_at = 8; /** The group a node of `group` takes while an operation sets it aside, erased or renumbered: no @@ -1047,8 +1373,10 @@ class tree { return static_cast<std::uint8_t>(group + 2); } - // The walk keeps its stack on the process heap, whose exhaustion ends the program, as the - // library tolerates. + // The walk's stack is in the allocator, whose std::bad_alloc is a failed copy with + // exceptions; an allocation in the image that fails after the heap was found to hold it, a bug + // of the document's, which the image's allocator reports by boost::throw_exception, ends the + // program. // NOLINTBEGIN(bugprone-exception-escape) /** What @ref compact_to builds a compact image with: the source tree, the costs of its blocks, @@ -1056,7 +1384,7 @@ class tree { */ struct compaction { /** The tree copied from. */ - const tree& from; + const view& from; /** What the blocks of the image take. */ const costs& c; @@ -1067,6 +1395,9 @@ class tree { /** The image's container. */ nodes_type* nodes; + /** The allocator of the walk's stack. */ + Allocator alloc; + /** The id the next node copied takes. */ std::uint64_t next_id = root_id; @@ -1142,14 +1473,30 @@ class tree { return true; } - /** Copies `root` and everything under it in document order, on a stack of its own. */ + /** The walk's stack, in the allocator. */ + using stack_type = std::vector<frame, rebound<Allocator, frame>>; + + /** Pushes `f` on the walk's stack; false when the allocator has no room for it. */ + [[nodiscard]] static bool push(stack_type& stack, const frame& f) noexcept { + return staging([&]() -> result<void> { + stack.push_back(f); + return {}; + }) + .has_value(); + } + + /** + Copies `root` and everything under it in document order, on a stack of its own; false + when the heap or the allocator has no room. + */ [[nodiscard]] bool copy_tree(const node_type& root) noexcept { if (!copy(root, 0, index_group, 0)) { return false; } - std::vector<frame> stack; - if (const node_type* first = from.first_child(root_id)) { - stack.push_back({first, root_id, 0}); + stack_type stack{rebound<Allocator, frame>(alloc)}; + if (const node_type* first = from.first_child(root_id); + first != nullptr && !push(stack, {first, root_id, 0})) { + return false; } while (!stack.empty()) { frame& top = stack.back(); @@ -1166,8 +1513,9 @@ class tree { ordinal)) { return false; } - if (const node_type* first = from.first_child(child.id)) { - stack.push_back({first, id, 0}); + if (const node_type* first = from.first_child(child.id); + first != nullptr && !push(stack, {first, id, 0})) { + return false; } } return true; @@ -1191,10 +1539,17 @@ class tree { std::uint64_t ordinal = 0; /** - Its key in the traits' encoding; nothing for a node already there, which keeps its own. + Its key, in the traits' encoding, or in UTF-8 when `utf8_key`; nothing for a node already + there, which keeps its own. */ std::span<const std::byte> key; + /** + Whether `key` is UTF-8 that the allocate phase writes into the image as the traits' + UTF-16, so that no copy of it is transcoded first. + */ + bool utf8_key = false; + /** Its kind. */ kind_t kind = kind_t::null; @@ -1209,6 +1564,12 @@ class tree { /** Whether the node is already there and only its value is replaced. */ bool existing = false; + + /** The key's string in the image, which the allocate phase makes for a new node. */ + byte_string made_key; + + /** The text's string in the image, which the allocate phase makes. */ + byte_string made_text; }; /** A value still to be read into a staged node: an item, or a node of a tree to copy. */ @@ -1220,7 +1581,7 @@ class tree { const item<Traits>* value = nullptr; /** The tree of the node to copy. */ - const tree* from = nullptr; + const view* from = nullptr; /** The id of the node to copy. */ std::uint64_t from_id = 0; @@ -1229,22 +1590,44 @@ class tree { bool may_be_undefined = false; }; - /** What an operation writes, gathered before it changes anything. */ + /** A list of `T` in the region's allocator, rebound. */ + template <class T> + using list = std::vector<T, rebound<Allocator, T>>; + + /** + What an operation writes, gathered before it changes anything, in the region's allocator: + the room phase allocates all of it, so that the others allocate only in the image. + */ struct change { + /** An empty change, its lists in `alloc`, which allocates nothing yet. */ + explicit change(const Allocator& alloc) noexcept + : nodes(rebound<Allocator, staged>(alloc)), + doomed(rebound<Allocator, std::uint64_t>(alloc)), + work(rebound<Allocator, pending>(alloc)), + sizes(rebound<Allocator, std::uint64_t>(alloc)), + copies(rebound<Allocator, std::byte>(alloc)) {} + /** The nodes it writes, in the order their blocks are probed and allocated. */ - std::vector<staged> nodes; + list<staged> nodes; - /** The subtrees it erases once the new nodes are in place. */ - std::vector<std::uint64_t> doomed; + /** The roots of the subtrees it erases once the new nodes are in place. */ + list<std::uint64_t> doomed; /** Values still to be read into staged nodes. */ - std::vector<pending> work; + list<pending> work; + + /** The sizes of the blocks it allocates in the image, in the order it allocates them. */ + list<std::uint64_t> sizes; - /** Keys transcoded to UTF-16. */ - std::vector<std::vector<char16_t>> keys16; + /** The sum of `sizes`, or the largest value when that overflows. */ + std::uint64_t total = 0; + + /** Whether the blocks fit in the image; the room phase grows it until they do. */ + bool fits = false; - /** Copies of what pointed into the image, taken before it moves. */ - std::vector<std::vector<std::byte>> copies; + /** The bytes of what its keys and strings viewed inside the image, before the image grew. + */ + list<std::byte> copies; /** The id the change's first new node takes. */ std::uint64_t next_id = 0; @@ -1253,139 +1636,53 @@ class tree { std::uint64_t created = 0; }; + /** An entry of a literal by its key: what @ref place_members sorts. */ + struct keyed { + /** The key, in UTF-8. */ + std::string_view key; + + /** The entry's place among the literal's, or the largest value once it is placed. */ + std::size_t entry = 0; + }; + + // A list's std::length_error cannot escape: no list a change keeps reaches its max_size + // before its allocator runs out, each holding less per node than the node's block in an image + // that fits in memory, and the copies of views are checked against it. + // NOLINTBEGIN(bugprone-exception-escape) /** - The node of the smallest id, which is the root, read through the two pointers that reach it, - the container's header node and the first node of the index by id, each first checked to lie - inside the image's `size` bytes; null when either does not, or when the tree has no node. + Runs `stage`, which allocates in the allocator what an operation needs before it changes + anything, and returns its result: with exceptions, the allocator's failure + (@ref unless_allocation_fails) is @ref errc::capacity, nothing having changed; without them, + an allocator that fails ends the program, as it does itself. */ - [[nodiscard]] const node_type* first_by_id(std::uint64_t size) const noexcept { - const auto& ids = nodes_of()->template get<by_id>(); - const auto begin = reinterpret_cast<std::uintptr_t>(region_->data()); - const auto within = [begin, size](const auto* p) { - const auto at = reinterpret_cast<std::uintptr_t>(p); - constexpr std::uint64_t bytes = sizeof(*p); - return at >= begin + header_bytes && at % alignof(decltype(*p)) == 0 && bytes <= size && - at - begin <= size - bytes; - }; - // get_node gives an iterator's node without reading it, which no other member does. - const auto end = ids.end(); - if (!within(end.get_node())) { - return nullptr; - } - const auto first = ids.begin(); - if (first == end || !within(first.get_node())) { - return nullptr; - } - return &*first; - } - - /** The fewest bytes that hold a header and an empty heap. */ - static std::uint64_t smallest_image() noexcept { - return header_bytes + heap::get_min_size(sizeof(heap)); + template <class Stage> + static result<void> staging(Stage&& stage) noexcept { + return unless_allocation_fails(std::forward<Stage>(stage), + [] { return result<void>(errc::capacity); }); } - /** `a + b`, or the largest value when that overflows. */ - static std::uint64_t saturated_sum(std::uint64_t a, std::uint64_t b) noexcept { - return a > std::numeric_limits<std::uint64_t>::max() - b - ? std::numeric_limits<std::uint64_t>::max() - : a + b; - } + // NOLINTEND(bugprone-exception-escape) /** The size a region grows to for blocks of `total` bytes: its size and twice the blocks. */ - static std::uint64_t grown_size(const region& r, std::uint64_t total) noexcept { + static std::uint64_t grown_size(const region_bytes& r, std::uint64_t total) noexcept { return saturated_sum(r.size(), saturated_sum(total, total)); } - /** The bytes as a `std::string_view`, as the index by key holds keys. */ - static std::string_view as_chars(std::span<const std::byte> bytes) noexcept { - return {reinterpret_cast<const char*>(bytes.data()), bytes.size()}; - } - - /** Eight bytes of a scalar, from `at`. */ - static std::uint64_t word(const scalar_type& s, std::size_t at) noexcept { - return load_little(s.data() + at, 8); - } - - /** Writes eight bytes of a scalar, from `at`. */ - static void set_word(scalar_type& s, std::size_t at, std::uint64_t value) noexcept { - store_little(value, s.data() + at, 8); - } - - /** Whether `n` is a node of kind `k`. */ - static bool is_kind(const node_type* n, kind_t k) noexcept { - return n != nullptr && n->kind == k; - } - - /** The node of `id` in `nodes`, or null. */ - static const node_type* find_in(const nodes_type& nodes, std::uint64_t id) noexcept { - const auto& ids = nodes.template get<by_id>(); - const auto it = ids.find(id); - return it == ids.end() ? nullptr : &*it; - } - - /** The child of `object` whose key is `key`, in the traits' encoding, or null. */ - static const node_type* member_in(const nodes_type& nodes, std::uint64_t object, - std::string_view key) noexcept { - const auto& keys = nodes.template get<by_key>(); - const auto it = keys.find(std::make_tuple(object, key)); - return it == keys.end() ? nullptr : &*it; - } - - /** The element `index` of `array`, or null. */ - static const node_type* element_in(const nodes_type& nodes, std::uint64_t array, - std::uint64_t index) noexcept { - const auto& order = nodes.template get<by_order>(); - const auto it = order.find(std::make_tuple(array, index_group, index)); - return it == order.end() ? nullptr : &*it; - } - - /** The first child of `parent` in `index`, or null. */ - template <class Index> - static const node_type* first_of(const Index& index, std::uint64_t parent) noexcept { - const auto it = index.lower_bound(std::make_tuple(parent)); - return it == index.end() || it->parent != parent ? nullptr : &*it; - } - - /** The node after `child` in `index`, when it has the same parent, or null. */ - template <class Index> - static const node_type* next_of(const Index& index, const node_type& child) noexcept { - auto it = index.iterator_to(child); - ++it; - return it == index.end() || it->parent != child.parent ? nullptr : &*it; - } - - /** The container of the attached image, or null when the tree is attached to nothing. */ - [[nodiscard]] nodes_type* nodes_of() const noexcept { - if (region_ == nullptr || region_->data() == nullptr) { - return nullptr; - } - std::uint64_t offset = 0; - std::memcpy(&offset, region_->data() + offsetof(image_header, container), sizeof offset); - return std::launder(reinterpret_cast<nodes_type*>(region_->data() + offset)); - } - - /** The header of the attached image. */ - [[nodiscard]] image_header read_header() const noexcept { - image_header header{}; - std::memcpy(&header, region_->data(), sizeof header); - return header; - } - /** Writes the region's size and the next id into the header, and clears its seal: every change to the tree ends here, so a changed image is never sealed. */ void sync_header(std::uint64_t next_id) noexcept { image_header header = read_header(); - header.size = region_->size(); + header.size = storage().size(); header.next_id = next_id; header.seal = 0; - std::memcpy(region_->data(), &header, sizeof header); + std::memcpy(storage().data(), &header, sizeof header); } - /** An empty change, its new nodes numbered from the header's next id. */ + /** An empty change in the region's allocator, its new nodes numbered from the next id. */ [[nodiscard]] change start_change() const noexcept { - change c; + change c(get_allocator()); c.next_id = read_header().next_id; return c; } @@ -1393,21 +1690,12 @@ class tree { /** The id of the change's next new node. */ static std::uint64_t take_id(change& c) noexcept { return c.next_id + c.created++; } - /** - A key, valid UTF-8, in the traits' encoding, held by the change when transcoded; or nothing. - */ - static std::optional<std::span<const std::byte>> encode_key(change& c, std::string_view utf8) { - if (!valid_utf8(utf8)) { - return std::nullopt; - } - if constexpr (utf16_text) { - std::vector<char16_t>& units = - c.keys16.emplace_back(static_cast<std::size_t>(utf16_length(utf8))); - to_utf16(utf8, units.data()); - return std::as_bytes(std::span(units)); - } else { - return std::as_bytes(std::span(utf8.data(), utf8.size())); + /** The size of a staged node's key as the image holds it. */ + static std::uint64_t stored_key_bytes(const staged& n) noexcept { + if (n.utf8_key) { + return utf16_length(as_chars(n.key)) * sizeof(char16_t); } + return n.key.size(); } /** The group and ordinal of a new member by the object policy; `next` advances when taken. */ @@ -1445,15 +1733,18 @@ class tree { } } - /** Stages a new member of `object` holding `v`; its id. */ + /** + Stages a new member of `object` at the key `utf8_key`, valid UTF-8, holding `v`; its id. The + key is written into the image in the traits' encoding when the node's blocks are allocated. + */ static std::uint64_t add_member(change& c, std::uint64_t object, std::string_view utf8_key, - std::span<const std::byte> stored_key, std::uint64_t& next, - const item<Traits>& v) { + std::uint64_t& next, const item<Traits>& v) { staged n; n.id = take_id(c); n.parent = object; std::tie(n.group, n.ordinal) = member_place(utf8_key, n.id, next); - n.key = stored_key; + n.key = std::as_bytes(std::span(utf8_key.data(), utf8_key.size())); + n.utf8_key = utf16_text; c.nodes.push_back(n); c.work.push_back({c.nodes.size() - 1, &v, nullptr, 0, false}); return n.id; @@ -1482,29 +1773,33 @@ class tree { std::span<const literal_entry<Traits>> entries, std::uint64_t& next, std::uint64_t& added, bool assign_existing) const { constexpr std::size_t placed = std::numeric_limits<std::size_t>::max(); - std::map<std::string_view, std::size_t> last; + // Sorted by key, then by place, the entries of a key are a run whose first place is where + // its member goes and whose last entry holds its value. + list<keyed> runs{rebound<Allocator, keyed>(get_allocator())}; + runs.reserve(entries.size()); for (std::size_t i = 0; i < entries.size(); ++i) { if (!valid_utf8(entries[i].key)) { return errc::type; } - last.insert_or_assign(entries[i].key, i); + runs.push_back({entries[i].key, i}); } + std::ranges::sort(runs, [](const keyed& a, const keyed& b) noexcept { + return a.key != b.key ? a.key < b.key : a.entry < b.entry; + }); for (const literal_entry<Traits>& entry : entries) { - const auto it = last.find(entry.key); - if (it->second == placed) { + const auto run = + std::ranges::equal_range(runs, entry.key, std::ranges::less{}, &keyed::key); + if (run.front().entry == placed) { continue; } - const item<Traits>& value = entries[std::exchange(it->second, placed)].value; - const auto stored = encode_key(c, entry.key); - if (!stored.has_value()) { - return errc::type; - } + const item<Traits>& value = entries[run.back().entry].value; + run.front().entry = placed; const node_type* existing = - assign_existing ? member_in(*nodes_of(), object, as_chars(*stored)) : nullptr; + assign_existing ? member_in(*nodes_of(), object, lookup_key(entry.key)) : nullptr; if (existing != nullptr) { add_existing(c, *existing, value, false); } else { - add_member(c, object, entry.key, *stored, next, value); + add_member(c, object, entry.key, next, value); ++added; } } @@ -1572,9 +1867,9 @@ class tree { } /** Reads the node `id` of `from` into the staged node `slot`, its children into new nodes. */ - result<void> read_copy(change& c, std::size_t slot, const tree* from, std::uint64_t id, + result<void> read_copy(change& c, std::size_t slot, const view* from, std::uint64_t id, bool may_be_undefined) const { - const nodes_type* source_nodes = from == nullptr ? nullptr : from->nodes_of(); + const nodes_type* source_nodes = from == nullptr ? nullptr : from->nodes(); const node_type* source_node = source_nodes == nullptr ? nullptr : find_in(*source_nodes, id); if (source_node == nullptr || @@ -1605,39 +1900,60 @@ class tree { /** Copies what the change's keys and strings view inside the image, before the image moves: a - value of this tree, or a key or text a caller read from it. + value of this tree, or a key or text a caller read from it; all of them into one buffer, + allocated once. @ref errc::capacity when they are more bytes than a buffer holds. */ - void own_views(change& c) const { - const std::byte* first = region_->data(); - const std::byte* last = first + region_->size(); + result<void> own_views(change& c) const { + const std::byte* first = storage().data(); + const std::byte* last = first + storage().size(); const std::less<> before; + const auto inside = [&](std::span<const std::byte> view) { + return !view.empty() && before(view.data(), last) && + before(first, view.data() + view.size()); + }; + std::uint64_t bytes = 0; + for (const staged& n : c.nodes) { + bytes = saturated_sum(bytes, inside(n.key) ? n.key.size() : 0); + bytes = saturated_sum(bytes, inside(n.text) ? n.text.size() : 0); + } + if (bytes > c.copies.max_size()) { + return errc::capacity; + } + // Reserved whole, the buffer never moves while views are taken into it. + c.copies.reserve(static_cast<std::size_t>(bytes)); const auto own = [&](std::span<const std::byte>& view) { - if (view.empty() || !before(view.data(), last) || - !before(first, view.data() + view.size())) { + if (!inside(view)) { return; } - view = c.copies.emplace_back(view.begin(), view.end()); + const std::size_t at = c.copies.size(); + c.copies.insert(c.copies.end(), view.begin(), view.end()); + view = std::span<const std::byte>(c.copies).subspan(at, view.size()); }; for (staged& n : c.nodes) { own(n.key); own(n.text); } + return {}; } /** - Finds room for the change's blocks, its strings then its nodes, growing an owned region while - they do not fit; changes nothing but the region's size when there is no room. + Lists, in the allocator, what the change's later phases need, so that they allocate only in + the image: the sizes of the blocks to allocate, the strings then the nodes; and when the blocks + do not fit an owned image, which must then grow, copies of what the change views inside it. */ - result<void> find_room(change& c) { - std::vector<std::uint64_t> sizes; - std::uint64_t total = 0; - const auto add = [&](std::uint64_t size) { - sizes.push_back(size); - total = saturated_sum(total, size); + result<void> plan(change& c) const { + std::size_t count = 0; + for (const staged& n : c.nodes) { + count += n.existing ? 1 : 3; + } + c.sizes.reserve(count); + const auto add = [&c](std::uint64_t size) { + c.sizes.push_back(size); + c.total = saturated_sum(c.total, size); }; for (const staged& n : c.nodes) { if (!n.existing) { - add(n.key.size()); + add(stored_key_bytes(n)); } add(n.text.size()); } @@ -1646,19 +1962,24 @@ class tree { add(node_probe_bytes<Traits>); } } - bool owned = false; - while (!probe(heap_of(*region_), sizes)) { - if (!region_->is_owned()) { - return errc::capacity; - } - if (!owned) { - own_views(c); - owned = true; - } - if (!region_->grow(grown_size(*region_, total))) { + c.fits = probe(heap_of(storage()), c.sizes); + if (!c.fits && storage().is_owned()) { + return own_views(c); + } + return {}; + } + + /** + Finds room for the change's blocks, growing an owned region while they do not fit; changes + nothing but the region's size when there is no room, and allocates nothing outside it. + */ + result<void> find_room(change& c) noexcept { + while (!c.fits) { + if (!storage().is_owned() || !storage().grow(grown_size(storage(), c.total))) { return errc::capacity; } sync_header(c.next_id); + c.fits = probe(heap_of(storage()), c.sizes); } return {}; } @@ -1674,53 +1995,85 @@ class tree { } /** - Writes a change in its three phases: the room found, the strings then the nodes allocated, then - what allocates nothing: the doomed set aside, `arrange`, the values replaced, the doomed - erased. + The key of a new staged node, which the probe has found room for: its bytes, or its UTF-8 + written straight into its block as UTF-16. + */ + static byte_string make_key(heap& h, const staged& n) { + if (!n.utf8_key) { + return make_probed(h, n.key); + } + const std::string_view utf8 = as_chars(n.key); + const std::uint64_t bytes = utf16_length(utf8) * sizeof(char16_t); + if (bytes == 0) { + return byte_string{}; + } + void* block = h.allocate(bytes); + if (block == nullptr) { + // The probe has found its room: a failure here is the document's bug. + boost::throw_exception(std::bad_alloc()); + } + // A block of the heap is 16-aligned, so it holds char16_t's. + to_utf16(utf8, static_cast<char16_t*>(block)); + byte_string made; + made.data = static_cast<std::byte*>(block); + made.size = bytes; + return made; + } + + /** + Writes a change in its three phases. Room: `stage` gathers it, @ref plan lists the rest of + what it allocates outside the image, all before anything changes, and the image grows until + its blocks fit. Allocate: the strings, then the nodes. Arrange, which allocates nothing: the + doomed set aside, `arrange`, the values replaced, the doomed erased. */ - template <class Arrange> - result<void> write(change& c, Arrange&& arrange) { + template <class Stage, class Arrange> + result<void> write(change& c, Stage&& stage, Arrange&& arrange) { + if (const auto planned = staging([&]() -> result<void> { + if (const auto gathered = std::forward<Stage>(stage)(); !gathered.has_value()) { + return gathered; + } + return plan(c); + }); + !planned.has_value()) { + return planned; + } if (const auto room = find_room(c); !room.has_value()) { return room; } - heap& h = heap_of(*region_); - std::vector<std::array<byte_string, 2>> made(c.nodes.size()); - for (std::size_t i = 0; i < c.nodes.size(); ++i) { - if (!c.nodes[i].existing) { - made[i][0] = make_probed(h, c.nodes[i].key); + heap& h = heap_of(storage()); + for (staged& n : c.nodes) { + if (!n.existing) { + n.made_key = make_key(h, n); } - made[i][1] = make_probed(h, c.nodes[i].text); + n.made_text = make_probed(h, n.text); } - set_aside_doomed(c.doomed); + set_aside_doomed(c); std::forward<Arrange>(arrange)(); nodes_type& nodes = *nodes_of(); - for (std::size_t i = 0; i < c.nodes.size(); ++i) { - const staged& n = c.nodes[i]; + for (const staged& n : c.nodes) { if (!n.existing) { [[maybe_unused]] const bool inserted = nodes - .emplace(n.id, n.parent, n.group, n.ordinal, made[i][0], n.kind, n.number, - n.scalar, made[i][1]) + .emplace(n.id, n.parent, n.group, n.ordinal, n.made_key, n.kind, n.number, + n.scalar, n.made_text) .second; BOOST_ASSERT(inserted); } } - for (std::size_t i = 0; i < c.nodes.size(); ++i) { - if (c.nodes[i].existing) { - replace_value(c.nodes[i], made[i][1]); + for (const staged& n : c.nodes) { + if (n.existing) { + replace_value(n, n.made_text); } } - for (const std::uint64_t id : c.doomed) { - erase_subtree(id); - } + erase_doomed(c); sync_header(c.next_id + c.created); return {}; } - /** Moves the doomed nodes out of their groups, so that new nodes may take their places. */ - void set_aside_doomed(const std::vector<std::uint64_t>& doomed) noexcept { + /** Moves the doomed roots out of their groups, so that new nodes may take their places. */ + void set_aside_doomed(const change& c) noexcept { auto& ids = nodes_of()->template get<by_id>(); - for (const std::uint64_t id : doomed) { + for (const std::uint64_t id : c.doomed) { ids.modify(ids.find(id), [](node_type& n) noexcept { n.group = set_aside(n.group); }); } } @@ -1736,7 +2089,7 @@ class tree { n.scalar = value.scalar; n.text = text; }); - free_string(heap_of(*region_), old); + free_string(heap_of(storage()), old); } /** Moves the element `from` of `array` to the ordinal `to`, which no element holds. */ @@ -1759,32 +2112,102 @@ class tree { set_scalar(array, s); } - /** Erases a node and its subtree, children first, each one's strings zeroed and freed. */ - void erase_subtree(std::uint64_t id) { + /** Erases the member `id` of the object `o` and its subtree, its key count lowered by one. */ + void erase_child(const node_type& o, std::uint64_t id) noexcept { + scalar_type counts = o.scalar; + const std::uint64_t object = o.id; + erase_subtree(id); + set_word(counts, key_count_at, word(counts, key_count_at) - 1); + set_scalar(object, counts); + sync_header(read_header().next_id); + } + + /** + Erases `n` elements of `array`, of `length`, from `at`, as a splice that inserts nothing does + it: the elements set aside, the later ones moved into their places, then each one's subtree + erased, found in the group it was set aside to. + */ + void erase_range(std::uint64_t array, std::uint64_t length, std::uint64_t at, + std::uint64_t n) noexcept { + auto& order = nodes_of()->template get<by_order>(); + for (std::uint64_t i = 0; i < n; ++i) { + order.modify(order.find(std::make_tuple(array, index_group, at + i)), + [](node_type& e) noexcept { e.group = set_aside(e.group); }); + } + for (std::uint64_t o = at + n; o < length; ++o) { + renumber(array, o, o - n); + } + for (std::uint64_t i = 0; i < n; ++i) { + erase_subtree(order.find(std::make_tuple(array, set_aside(index_group), at + i))->id); + } + sync_header(read_header().next_id); + set_length_word(array, length - n); + } + + /** Erases the change's doomed subtrees, in the order their roots were staged. */ + void erase_doomed(const change& c) noexcept { + for (const std::uint64_t id : c.doomed) { + erase_subtree(id); + } + } + + /** + Erases a node and its subtree, children first, each node's strings zeroed and freed, and + allocates nothing: an erasure needs no room and cannot fail. + + The nodes are listed breadth first through their own scalars, which no index reads and which + die with them, each holding the id of the node after it and of the one before; the list is + then erased from its end. Each scalar is written by a `modify` that changes no key, so no + index moves a node, and the allocator zeroes the scalar with its node's block. + */ + void erase_subtree(std::uint64_t id) noexcept { nodes_type& nodes = *nodes_of(); - const auto& order = nodes.template get<by_order>(); - // Each node's children are listed after it, so the list read backwards is children first. - std::vector<std::uint64_t> subtree{id}; - std::size_t listed = 0; - while (listed < subtree.size()) { - const std::uint64_t parent = subtree[listed++]; + auto& ids = nodes.template get<by_id>(); + auto& order = nodes.template get<by_order>(); + // A node joins the list at its end, after `previous`, and the node there before it is + // followed by it. + const auto listed_last = [](std::uint64_t previous) noexcept { + return [previous](node_type& n) noexcept { + set_word(n.scalar, next_listed_at, 0); + set_word(n.scalar, previous_listed_at, previous); + }; + }; + const auto followed_by = [](std::uint64_t next) noexcept { + return [next](node_type& n) noexcept { set_word(n.scalar, next_listed_at, next); }; + }; + const node_type* last = &*ids.find(id); + ids.modify(ids.iterator_to(*last), listed_last(0)); + for (const node_type* listed = last; listed != nullptr; + listed = listed_after(*listed, next_listed_at)) { + const std::uint64_t parent = listed->id; for (auto it = order.lower_bound(std::make_tuple(parent)); it != order.end() && it->parent == parent; ++it) { - subtree.push_back(it->id); + order.modify(it, listed_last(last->id)); + ids.modify(ids.iterator_to(*last), followed_by(it->id)); + last = &*it; } } - auto& ids = nodes.template get<by_id>(); - heap& h = heap_of(*region_); - for (const std::uint64_t victim : std::views::reverse(subtree)) { - const auto found = ids.find(victim); - byte_string key = found->key; - byte_string text = found->text; - ids.erase(found); + heap& h = heap_of(storage()); + for (const node_type* victim = last; victim != nullptr;) { + const node_type* before = listed_after(*victim, previous_listed_at); + byte_string key = victim->key; + byte_string text = victim->text; + ids.erase(ids.iterator_to(*victim)); free_string(h, key); free_string(h, text); + victim = before; } } + /** + The node whose id the scalar of `n`, listed by @ref erase_subtree, holds at `at`, or null at + an end of the list. + */ + [[nodiscard]] const node_type* listed_after(const node_type& n, std::size_t at) const noexcept { + const std::uint64_t id = word(n.scalar, at); + return id == 0 ? nullptr : find_in(*nodes_of(), id); + } + /** Appends `fill` elements holding `null` to an array of `length`, then one holding `*last` when it is not null, as one operation. @@ -1792,27 +2215,25 @@ class tree { result<void> append(std::uint64_t array, std::uint64_t length, std::uint64_t fill, const item<Traits>* last) { // More nodes than the region could ever hold is no room, before a change takes memory. - if (fill >= region_->max_bytes() / node_probe_bytes<Traits>) { + if (fill >= storage().max_bytes() / node_probe_bytes<Traits>) { return errc::capacity; } change c = start_change(); - for (std::uint64_t i = 0; i < fill; ++i) { - add_element(c, array, length + i, nullptr); - } - if (last != nullptr) { - add_element(c, array, length + fill, last); - } - if (const auto read = read_values(c); !read.has_value()) { - return read; - } - if (const auto done = write(c, [] {}); !done.has_value()) { + const auto stage = [&]() -> result<void> { + for (std::uint64_t i = 0; i < fill; ++i) { + add_element(c, array, length + i, nullptr); + } + if (last != nullptr) { + add_element(c, array, length + fill, last); + } + return read_values(c); + }; + if (const auto done = write(c, stage, [] {}); !done.has_value()) { return done; } set_length_word(array, length + fill + (last != nullptr ? 1 : 0)); return {}; } - - region* region_ = nullptr; }; } // namespace webcpp::document::detail diff --git a/include/webcpp/document/detail/value_array.hpp b/include/webcpp/document/detail/value_array.hpp index c53cacb..669ba61 100644 --- a/include/webcpp/document/detail/value_array.hpp +++ b/include/webcpp/document/detail/value_array.hpp @@ -17,6 +17,8 @@ #include <webcpp/document/value.hpp> +#include <boost/config.hpp> + #include <array> #include <concepts> #include <cstddef> @@ -66,8 +68,8 @@ constexpr std::uint64_t splice_count(std::int64_t count, std::uint64_t start, /** The tree and node a copy source reads. */ template <class Traits> struct source_read { - /** The tree. */ - const tree<Traits>* from = nullptr; + /** The tree, of a document of any allocator. */ + const tree_view<Traits>* from = nullptr; /** The node, or null when the source reads `undefined`. */ const node<Traits>* n = nullptr; @@ -76,7 +78,7 @@ struct source_read { /** Where a document's value is read: its tree and its root; @ref errc::type when moved from. */ template <class Traits, class Storage> result<source_read<Traits>> read_source(const basic_document<Traits, Storage>& d) noexcept { - const tree<Traits>* t = access::tree_of(d); + const tree_view<Traits>* t = access::tree_of(d); if (t == nullptr) { return errc::type; } @@ -93,9 +95,9 @@ result<source_read<Traits>> read_source(const basic_const_value<Traits, Storage> Makes `out` the item of a value an array method stores: a C++ value prepared, or a deep copy of a source's value, `null` for one that reads `undefined`, as `[undefined]` is written. */ -template <class Traits, class T> +template <class Traits, class Allocator, class T> requires settable<Traits, T> -result<void> prepare_element(const T& v, prepared<Traits>& out) noexcept { +result<void> prepare_element(const T& v, prepared<Traits, Allocator>& out) noexcept { if constexpr (copy_source<Traits, T>) { const auto s = read_source(v); if (!s.has_value()) { @@ -111,12 +113,24 @@ result<void> prepare_element(const T& v, prepared<Traits>& out) noexcept { } } +/** `sizeof...(I)` prepared values, each holding its buffers in `alloc`. */ +template <class Traits, class Allocator, std::size_t... I> +std::array<prepared<Traits, Allocator>, sizeof...(I)> prepared_values( + const Allocator& alloc, std::index_sequence<I...> /*indices*/) noexcept { + if constexpr (sizeof...(I) == 0) { + return {}; + } else { + // Each element is made in its place: a prepared value is not copied. + return {{(static_cast<void>(I), prepared<Traits, Allocator>(alloc))...}}; + } +} + /** Prepares each value into `held` and its item into `items`, in order: the first failure stops it. The items point into `held`, which must outlive them. */ -template <class Traits, class... T, std::size_t... I> -result<void> prepare_elements(std::array<prepared<Traits>, sizeof...(T)>& held, +template <class Traits, class Allocator, class... T, std::size_t... I> +result<void> prepare_elements(std::array<prepared<Traits, Allocator>, sizeof...(T)>& held, std::array<item<Traits>, sizeof...(T)>& items, std::index_sequence<I...> /*indices*/, const T&... v) noexcept { if constexpr (sizeof...(T) != 0) { @@ -131,10 +145,11 @@ result<void> prepare_elements(std::array<prepared<Traits>, sizeof...(T)>& held, return {}; } -/** A new owned document whose value is `v`, read before the call returns. */ -template <class Traits> -result<basic_document<Traits, owned>> owned_holding(const item<Traits>& v) noexcept { - auto made = basic_document<Traits, owned>::create(); +/** A new owned document in `alloc` whose value is `v`, read before the call returns. */ +template <class Traits, class Allocator> +result<basic_document<Traits, basic_owned<Allocator>>> owned_holding( + const item<Traits>& v, const Allocator& alloc) noexcept { + auto made = basic_document<Traits, basic_owned<Allocator>>::create(alloc); if (!made.has_value()) { return made.error(); } @@ -154,14 +169,10 @@ item<Traits> array_of(std::span<const literal_entry<Traits>> entries) noexcept { return a; } -// The entries are staged on the process heap, whose exhaustion ends the program, as the library -// tolerates. -// NOLINTBEGIN(bugprone-exception-escape) - /** Appends to `out` an entry copying each of the `n` elements of `array` in `from`, from `at`. */ -template <class Traits> -void copy_elements(const tree<Traits>& from, std::uint64_t array, std::uint64_t at, std::uint64_t n, - std::vector<literal_entry<Traits>>& out) { +template <class Traits, class Entries> +void copy_elements(const tree_view<Traits>& from, std::uint64_t array, std::uint64_t at, + std::uint64_t n, Entries& out) { const node<Traits>* e = n == 0 ? nullptr : from.element(array, at); for (std::uint64_t i = 0; i < n && e != nullptr; ++i, e = from.next_sibling(*e)) { literal_entry<Traits>& entry = out.emplace_back(); @@ -177,12 +188,11 @@ void copy_elements(const tree<Traits>& from, std::uint64_t array, std::uint64_t The document holds the array of the copies, or, when `single`, the one element, or `undefined` when there is none: `pop` and `shift`. */ -template <class Traits> -result<basic_document<Traits, owned>> splice_elements(tree<Traits>& t, std::uint64_t array, - std::uint64_t at, std::uint64_t n, - std::span<const item<Traits>> items, - bool single) noexcept { - result<basic_document<Traits, owned>> removed = errc::type; +template <class Traits, class Allocator> +result<basic_document<Traits, basic_owned<Allocator>>> splice_elements( + tree<Traits, Allocator>& t, std::uint64_t array, std::uint64_t at, std::uint64_t n, + std::span<const item<Traits>> items, bool single) noexcept { + result<basic_document<Traits, basic_owned<Allocator>>> removed = errc::type; if (single) { // With nothing to remove, it holds undefined, which JavaScript's pop of [] returns. item<Traits> one = empty_item<Traits>(webcpp::document::kind::undefined); @@ -190,12 +200,15 @@ result<basic_document<Traits, owned>> splice_elements(tree<Traits>& t, std::uint one.from = &t; one.from_id = t.element(array, at)->id; } - removed = owned_holding(one); + removed = owned_holding(one, t.get_allocator()); } else { - std::vector<literal_entry<Traits>> entries; - entries.reserve(static_cast<std::size_t>(n)); - copy_elements(t, array, at, n, entries); - removed = owned_holding(array_of<Traits>(entries)); + removed = bad_alloc_as_capacity([&] { + std::vector<literal_entry<Traits>, rebound<Allocator, literal_entry<Traits>>> entries( + rebound<Allocator, literal_entry<Traits>>(t.get_allocator())); + entries.reserve(static_cast<std::size_t>(n)); + copy_elements<Traits>(t, array, at, n, entries); + return owned_holding(array_of<Traits>(entries), t.get_allocator()); + }); } if (!removed.has_value()) { return removed; @@ -208,14 +221,20 @@ result<basic_document<Traits, owned>> splice_elements(tree<Traits>& t, std::uint /** The entries of `concat`'s array, and the prepared values they point into: this array's elements, - then each argument, an array's elements or the value. + then each argument, an array's elements or the value, all in the document's allocator. */ -template <class Traits> +template <class Traits, class Allocator> class concatenation { public: + /** No entry yet, each to be held in `alloc`. */ + explicit concatenation(const Allocator& alloc) noexcept + : alloc_(alloc), + held_(rebound<Allocator, prepared<Traits, Allocator>>(alloc)), + entries_(rebound<Allocator, literal_entry<Traits>>(alloc)) {} + /** Appends a copy of each element of `array` in `from`. */ - void add_elements(const tree<Traits>& from, std::uint64_t array) { - copy_elements(from, array, 0, from.count(array), entries_); + void add_elements(const tree_view<Traits>& from, std::uint64_t array) { + copy_elements<Traits>(from, array, 0, from.count(array), entries_); } /** Appends an argument: an array's elements, spread, or the value. */ @@ -272,7 +291,7 @@ class concatenation { /** Appends one value. */ template <class T> result<void> add_value(const T& v) { - prepared<Traits>& p = held_.emplace_back(); + prepared<Traits, Allocator>& p = held_.emplace_back(alloc_); if (const auto made = prepare_element(v, p); !made.has_value()) { return made; } @@ -280,16 +299,17 @@ class concatenation { return {}; } + /** The allocator of the prepared values' buffers. */ + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS Allocator alloc_; + // A prepared value moved keeps what its item points at, so the vector may grow. /** The prepared values the entries point into. */ - std::vector<prepared<Traits>> held_; + std::vector<prepared<Traits, Allocator>, rebound<Allocator, prepared<Traits, Allocator>>> held_; /** The array's entries, in order. */ - std::vector<literal_entry<Traits>> entries_; + std::vector<literal_entry<Traits>, rebound<Allocator, literal_entry<Traits>>> entries_; }; -// NOLINTEND(bugprone-exception-escape) - } // namespace webcpp::document::detail namespace webcpp::document { @@ -323,54 +343,57 @@ basic_value<Traits, Storage> basic_value<Traits, Storage>::at(std::int64_t index return this->template element_handle<basic_value>(k); } -// The copies' entries are staged on the process heap, whose exhaustion ends the program, as the -// library tolerates. -// NOLINTBEGIN(bugprone-exception-escape) - template <class Traits, class Storage> -result<basic_document<Traits, owned>> basic_const_value<Traits, Storage>::slice( +result<basic_document<Traits, detail::owned_of<Storage>>> basic_const_value<Traits, Storage>::slice( std::int64_t start, std::int64_t stop) const noexcept { const std::uint64_t id = id_of(webcpp::document::kind::array); if (id == 0) { return errc::type; } - const detail::tree<Traits>& t = *tree_ptr(); + const auto& t = *tree_ptr(); const std::uint64_t length = t.count(id); const std::uint64_t first = detail::relative_index(start, length); const std::uint64_t last = detail::relative_index(stop, length); - std::vector<detail::literal_entry<Traits>> entries; - if (last > first) { - entries.reserve(static_cast<std::size_t>(last - first)); - detail::copy_elements(t, id, first, last - first, entries); - } - return detail::owned_holding(detail::array_of<Traits>(entries)); + return detail::bad_alloc_as_capacity([&] { + std::vector<detail::literal_entry<Traits>, + detail::rebound<allocator_type, detail::literal_entry<Traits>>> + entries( + detail::rebound<allocator_type, detail::literal_entry<Traits>>(t.get_allocator())); + if (last > first) { + entries.reserve(static_cast<std::size_t>(last - first)); + detail::copy_elements<Traits>(t, id, first, last - first, entries); + } + return detail::owned_holding(detail::array_of<Traits>(entries), t.get_allocator()); + }); } template <class Traits, class Storage> template <class... T> -result<basic_document<Traits, owned>> basic_const_value<Traits, Storage>::concat( - const T&... v) const noexcept +result<basic_document<Traits, detail::owned_of<Storage>>> +basic_const_value<Traits, Storage>::concat(const T&... v) const noexcept requires(detail::settable<Traits, T> && ...) { const std::uint64_t id = id_of(webcpp::document::kind::array); if (id == 0) { return errc::type; } - detail::concatenation<Traits> c; - c.add_elements(*tree_ptr(), id); - if constexpr (sizeof...(T) != 0) { - result<void> added; - // The fold stops at the first argument that fails. - static_cast<void>(((added = c.add(v), added.has_value()) && ...)); - if (!added.has_value()) { - return added.error(); - } - } - return detail::owned_holding(detail::array_of<Traits>(c.entries())); + return detail::bad_alloc_as_capacity( + [&]() -> result<basic_document<Traits, detail::owned_of<Storage>>> { + detail::concatenation<Traits, allocator_type> c(tree_ptr()->get_allocator()); + c.add_elements(*tree_ptr(), id); + if constexpr (sizeof...(T) != 0) { + result<void> added; + // The fold stops at the first argument that fails. + static_cast<void>(((added = c.add(v), added.has_value()) && ...)); + if (!added.has_value()) { + return added.error(); + } + } + return detail::owned_holding(detail::array_of<Traits>(c.entries()), + tree_ptr()->get_allocator()); + }); } -// NOLINTEND(bugprone-exception-escape) - template <class Traits, class Storage> template <class... T> result<std::uint64_t> basic_value<Traits, Storage>::push(const T&... v) noexcept @@ -380,14 +403,15 @@ result<std::uint64_t> basic_value<Traits, Storage>::push(const T&... v) noexcept if (id == 0) { return errc::type; } - std::array<detail::prepared<Traits>, sizeof...(T)> held{}; + auto* t = writable_tree(); + auto held = + detail::prepared_values<Traits>(t->get_allocator(), std::index_sequence_for<T...>()); std::array<detail::item<Traits>, sizeof...(T)> items{}; if (const auto made = detail::prepare_elements(held, items, std::index_sequence_for<T...>(), v...); !made.has_value()) { return made.error(); } - detail::tree<Traits>* t = writable_tree(); if (const auto done = t->insert_elements(id, t->count(id), items); !done.has_value()) { return done.error(); } @@ -395,24 +419,26 @@ result<std::uint64_t> basic_value<Traits, Storage>::push(const T&... v) noexcept } template <class Traits, class Storage> -result<basic_document<Traits, owned>> basic_value<Traits, Storage>::pop() noexcept { +result<basic_document<Traits, detail::owned_of<Storage>>> +basic_value<Traits, Storage>::pop() noexcept { const std::uint64_t id = this->id_of(webcpp::document::kind::array); if (id == 0) { return errc::type; } - detail::tree<Traits>* t = writable_tree(); + auto* t = writable_tree(); const std::uint64_t length = t->count(id); return detail::splice_elements<Traits>(*t, id, length == 0 ? 0 : length - 1, length == 0 ? 0 : 1, {}, true); } template <class Traits, class Storage> -result<basic_document<Traits, owned>> basic_value<Traits, Storage>::shift() noexcept { +result<basic_document<Traits, detail::owned_of<Storage>>> +basic_value<Traits, Storage>::shift() noexcept { const std::uint64_t id = this->id_of(webcpp::document::kind::array); if (id == 0) { return errc::type; } - detail::tree<Traits>* t = writable_tree(); + auto* t = writable_tree(); return detail::splice_elements<Traits>(*t, id, 0, t->count(id) == 0 ? 0 : 1, {}, true); } @@ -425,14 +451,15 @@ result<std::uint64_t> basic_value<Traits, Storage>::unshift(const T&... v) noexc if (id == 0) { return errc::type; } - std::array<detail::prepared<Traits>, sizeof...(T)> held{}; + auto* t = writable_tree(); + auto held = + detail::prepared_values<Traits>(t->get_allocator(), std::index_sequence_for<T...>()); std::array<detail::item<Traits>, sizeof...(T)> items{}; if (const auto made = detail::prepare_elements(held, items, std::index_sequence_for<T...>(), v...); !made.has_value()) { return made.error(); } - detail::tree<Traits>* t = writable_tree(); if (const auto done = t->insert_elements(id, 0, items); !done.has_value()) { return done.error(); } @@ -441,23 +468,23 @@ result<std::uint64_t> basic_value<Traits, Storage>::unshift(const T&... v) noexc template <class Traits, class Storage> template <class... T> -result<basic_document<Traits, owned>> basic_value<Traits, Storage>::splice(std::int64_t start, - std::int64_t count, - const T&... v) noexcept +result<basic_document<Traits, detail::owned_of<Storage>>> basic_value<Traits, Storage>::splice( + std::int64_t start, std::int64_t count, const T&... v) noexcept requires(detail::settable<Traits, T> && ...) { const std::uint64_t id = this->id_of(webcpp::document::kind::array); if (id == 0) { return errc::type; } - std::array<detail::prepared<Traits>, sizeof...(T)> held{}; + auto* t = writable_tree(); + auto held = + detail::prepared_values<Traits>(t->get_allocator(), std::index_sequence_for<T...>()); std::array<detail::item<Traits>, sizeof...(T)> items{}; if (const auto made = detail::prepare_elements(held, items, std::index_sequence_for<T...>(), v...); !made.has_value()) { return made.error(); } - detail::tree<Traits>* t = writable_tree(); const std::uint64_t length = t->count(id); const std::uint64_t at = detail::relative_index(start, length); return detail::splice_elements<Traits>(*t, id, at, detail::splice_count(count, at, length), @@ -465,13 +492,13 @@ result<basic_document<Traits, owned>> basic_value<Traits, Storage>::splice(std:: } template <class Traits, class Storage> -result<basic_document<Traits, owned>> basic_value<Traits, Storage>::splice( +result<basic_document<Traits, detail::owned_of<Storage>>> basic_value<Traits, Storage>::splice( std::int64_t start) noexcept { const std::uint64_t id = this->id_of(webcpp::document::kind::array); if (id == 0) { return errc::type; } - detail::tree<Traits>* t = writable_tree(); + auto* t = writable_tree(); const std::uint64_t length = t->count(id); const std::uint64_t at = detail::relative_index(start, length); return detail::splice_elements<Traits>(*t, id, at, length - at, {}, false); diff --git a/include/webcpp/document/detail/value_sugar.hpp b/include/webcpp/document/detail/value_sugar.hpp index 5e4c17a..fcfe5d8 100644 --- a/include/webcpp/document/detail/value_sugar.hpp +++ b/include/webcpp/document/detail/value_sugar.hpp @@ -26,6 +26,7 @@ #include <webcpp/document/errors.hpp> #include <concepts> +#include <memory> #include <string_view> #include <type_traits> #include <utility> @@ -49,13 +50,26 @@ T value_or_raise(result<T>&& made) { template <class Traits, class Storage> basic_document<Traits, Storage>::basic_document() - requires detail::exceptions_enabled<Traits> && std::same_as<Storage, owned> + requires detail::exceptions_enabled<Traits> && detail::owned_storage<Storage> : basic_document(detail::value_or_raise(create())) {} +template <class Traits, class Storage> +basic_document<Traits, Storage>::basic_document(const allocator_type& alloc) + requires detail::exceptions_enabled<Traits> && detail::owned_storage<Storage> + : basic_document(detail::value_or_raise(create(alloc))) {} + template <class Traits, class Storage> basic_document<Traits, Storage>::basic_document(const basic_document& other) - requires detail::exceptions_enabled<Traits> && std::same_as<Storage, owned> - : basic_document(detail::value_or_raise(other.clone())) {} + requires detail::exceptions_enabled<Traits> && detail::owned_storage<Storage> + : basic_document(detail::value_or_raise( + other.clone(std::allocator_traits<allocator_type>::select_on_container_copy_construction( + other.get_allocator())))) {} + +template <class Traits, class Storage> +basic_document<Traits, Storage>::basic_document(const basic_document& other, + const allocator_type& alloc) + requires detail::exceptions_enabled<Traits> && detail::owned_storage<Storage> + : basic_document(detail::value_or_raise(other.clone(alloc))) {} template <class Traits, class Storage> template <class T> diff --git a/include/webcpp/document/detail/writer.hpp b/include/webcpp/document/detail/writer.hpp index 6489949..277d400 100644 --- a/include/webcpp/document/detail/writer.hpp +++ b/include/webcpp/document/detail/writer.hpp @@ -9,6 +9,11 @@ of its own rather than recursion, and writes what ECMA-262's SerializeJSONObject, SerializeJSONArray and QuoteJSONString write, to an output that `stringify` keeps whole and `stringify_to` hands to a sink in chunks. + + Its working state, the stack and the piece `stringify_to` holds back, has room of its own for a + value nested @ref first_frames deep and a piece of @ref first_piece_room bytes, and allocates + only past them, in the allocator it is given, rebound: the string's for `stringify`, the + document's for `stringify_to`. That and its output are all it allocates. */ #ifndef WEBCPP_DOCUMENT_DETAIL_WRITER_HPP @@ -16,12 +21,16 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/detail/allocation.hpp> #include <webcpp/document/detail/tree.hpp> -#include <webcpp/document/detail/utf.hpp> #include <webcpp/document/errors.hpp> #include <webcpp/document/number.hpp> +#include <webcpp/document/quote.hpp> +#include <webcpp/document/storage.hpp> #include <webcpp/document/traits.hpp> +#include <boost/config.hpp> + #include <algorithm> #include <array> #include <concepts> @@ -29,10 +38,13 @@ #include <cstdint> #include <functional> #include <limits> +#include <new> +#include <optional> #include <span> #include <string> #include <string_view> #include <type_traits> +#include <utility> #include <vector> namespace webcpp::document::detail { @@ -40,6 +52,20 @@ namespace webcpp::document::detail { /** The most spaces of one level: `JSON.stringify` clamps its third argument to 10. */ inline constexpr std::uint32_t max_indent = 10; +/** + The frames the writer's stack holds in room of its own, 16 bytes each: a value nested 16 deep is + written with no allocation of its stack. The frames past them are allocated, room for 16 at + first and twice the room each time it is full. +*/ +inline constexpr std::size_t first_frames = 16; + +/** + The bytes of the room of its own the piece `stringify_to` holds back takes, the default chunk's: + a chunk of 4096 bytes or fewer allocates no piece. A larger chunk's piece, once it holds more, + is allocated at twice this room, then twice its room each time it is full, up to the chunk. +*/ +inline constexpr std::size_t first_piece_room = 4096; + /** A sink of `stringify_to`: a callable taking `std::string_view` and returning `void` or `result<void>`. @@ -57,50 +83,85 @@ concept output = requires(Out& out, std::string_view text) { { out.put(text) } -> std::same_as<result<void>>; }; +/** + Runs `allocate`, which allocates through the writer's allocator: with exceptions, the allocator's + failure (@ref unless_allocation_fails) is @ref errc::capacity; without, an allocator that fails + ends the program, as it does itself. +*/ +template <class Allocate> +result<void> allocating(Allocate&& allocate) { + return unless_allocation_fails( + [&]() -> result<void> { + std::forward<Allocate>(allocate)(); + return {}; + }, + [] { return result<void>(errc::capacity); }); +} + /** The output of `stringify`: the text appended to a string. */ class string_output { public: /** An output that appends to `text`, which outlives it. */ explicit string_output(std::string& text) noexcept : text_(&text) {} - /** Appends `text`; the standard library's `std::bad_alloc` is its only failure. */ + /** Appends `text`; the string's `std::bad_alloc` propagates, the output's only failure. */ result<void> put(std::string_view text) { text_->append(text); return {}; } private: + /** The string appended to. */ std::string* text_; }; -/** The output of `stringify_to`: the text handed to a sink in pieces of at most `chunk` bytes. */ -template <class Sink> +/** + The output of `stringify_to`: the text handed to a sink in pieces of at most `chunk` bytes, the + piece it holds back until it is full in room of its own of @ref first_piece_room bytes, or, for a + larger chunk, in `Allocator`, rebound, once it holds more. + + Tip: the larger room's string of bytes is made only when the piece first outgrows its own room, so + that a piece that keeps to it makes no standard container: a standard library may allocate for + one when it is made, as the MSVC STL's checked iterators allocate a proxy for each. +*/ +template <class Sink, class Allocator> class chunked_output { public: - /** An output to `sink`, which outlives it, in pieces of at most `chunk` bytes, at least 1. */ - chunked_output(Sink& sink, std::uint64_t chunk) + /** + An output to `sink`, which outlives it, in pieces of at most `chunk` bytes, at least 1, a + piece larger than its own room held back in `alloc`. + */ + chunked_output(Sink& sink, std::uint64_t chunk, const Allocator& alloc) noexcept // A chunk of 0 would never hand anything over; one past the address space is all of it. : sink_(&sink), chunk_(static_cast<std::size_t>( - std::clamp<std::uint64_t>(chunk, 1, std::numeric_limits<std::size_t>::max()))) {} + std::clamp<std::uint64_t>(chunk, 1, std::numeric_limits<std::size_t>::max()))), + alloc_(alloc) {} - /** Takes `text`, handing the sink each full piece; the sink's failure is returned. */ + /** + Takes `text`, handing the sink each full piece; the sink's failure is returned, and with + exceptions @ref errc::capacity when the allocator has no room for the piece held back. + */ result<void> put(std::string_view text) { while (!text.empty()) { // A full piece of the text itself is handed over without a copy. - if (pending_.empty() && text.size() >= chunk_) { + if (held_ == 0 && text.size() >= chunk_) { if (const result<void> handed = hand(text.substr(0, chunk_)); !handed) { return handed; } text.remove_prefix(chunk_); continue; } - const std::size_t taken = std::min(chunk_ - pending_.size(), text.size()); - pending_.append(text.substr(0, taken)); + const std::size_t taken = std::min(chunk_ - held_, text.size()); + if (const result<void> room = make_room(held_ + taken); !room) { + return room; + } + std::ranges::copy(text.substr(0, taken), piece() + held_); + held_ += taken; text.remove_prefix(taken); - if (pending_.size() == chunk_) { - const result<void> handed = hand(pending_); - pending_.clear(); + if (held_ == chunk_) { + const result<void> handed = hand({piece(), held_}); + held_ = 0; if (!handed) { return handed; } @@ -111,15 +172,26 @@ class chunked_output { /** Hands the sink what is left; the sink's failure is returned. */ result<void> flush() { - if (pending_.empty()) { + if (held_ == 0) { return {}; } - const result<void> handed = hand(pending_); - pending_.clear(); + const result<void> handed = hand({piece(), held_}); + held_ = 0; return handed; } private: + /** The allocator of a piece larger than its own room. */ + using piece_allocator = rebound<Allocator, char>; + + /** The room of a piece larger than its own. */ + using piece_room = std::vector<char, piece_allocator>; + + /** The first byte of the piece held back: in its own room, or in the larger one. */ + [[nodiscard]] char* piece() noexcept { + return larger_.has_value() ? larger_->data() : own_.data(); + } + /** Hands one piece to the sink, a sink returning `void` succeeding. */ result<void> hand(std::string_view piece) { if constexpr (std::same_as<std::invoke_result_t<Sink&, std::string_view>, void>) { @@ -130,28 +202,151 @@ class chunked_output { } } + /** + Makes room in the piece for `size` bytes, at most the chunk, before it takes them: past its + own room, twice that room, then twice the room each time, up to the chunk, the piece held + moved into it, so that each growth is one allocation. + */ + result<void> make_room(std::size_t size) { + const std::size_t room = larger_.has_value() ? larger_->size() : own_.size(); + if (size <= room) { + return {}; + } + std::size_t grown = room; + while (grown < size) { + grown = grown > chunk_ / 2 ? chunk_ : 2 * grown; + } + piece_room larger(alloc_); + if (const result<void> made = allocating([&larger, grown] { larger.resize(grown); }); + !made) { + return made; + } + std::ranges::copy(std::string_view(piece(), held_), larger.data()); + if (!larger_.has_value()) { + larger_.emplace(alloc_); + } + larger_->swap(larger); + return {}; + } + + /** The sink, used in place. */ Sink* sink_; + + /** The largest piece. */ std::size_t chunk_; - std::string pending_; + + /** How many bytes of the text the piece holds, fewer than a chunk. */ + std::size_t held_ = 0; + + /** The piece's room of its own. */ + std::array<char, first_piece_room> own_{}; + + /** The allocator of a piece larger than its own room. */ + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS piece_allocator alloc_; + + /** The piece's room once it holds more than its own, none until then. */ + std::optional<piece_room> larger_; +}; + +/** + The writer's stack: room of its own for @ref first_frames frames, and the deeper ones in + `Allocator`, rebound, room for @ref first_frames at first and twice the room each time it is + full. + + Tip: the list of the deeper frames is made with the first of them, so that a stack that keeps to + its own room makes no standard container: a standard library may allocate for one when it is + made, as the MSVC STL's checked iterators allocate a proxy for each. +*/ +template <class Frame, class Allocator> +class frame_stack { +public: + /** An empty stack, its deeper frames in `alloc`. */ + explicit frame_stack(const Allocator& alloc) noexcept : alloc_(alloc) {} + + /** How many frames it holds. */ + [[nodiscard]] std::size_t size() const noexcept { return size_; } + + /** Whether it holds none. */ + [[nodiscard]] bool empty() const noexcept { return size_ == 0; } + + /** The innermost frame; the stack holds one. */ + [[nodiscard]] Frame& back() noexcept { + return size_ > first_frames && deeper_.has_value() ? deeper_->back() : own_[size_ - 1]; + } + + /** Removes the innermost frame; the stack holds one. */ + void pop_back() noexcept { + if (size_ > first_frames && deeper_.has_value()) { + deeper_->pop_back(); + } + --size_; + } + + /** + Pushes `f`, room made first; with exceptions, @ref errc::capacity when the allocator has no + room, the stack as it was. + */ + result<void> push(const Frame& f) { + if (size_ < first_frames) { + own_[size_++] = f; + return {}; + } + if (!deeper_.has_value()) { + deeper_.emplace(alloc_); + } + frames& deeper = *deeper_; + if (deeper.size() == deeper.capacity()) { + const std::size_t room = deeper.capacity() == 0 ? first_frames : 2 * deeper.capacity(); + if (const result<void> made = allocating([&deeper, room] { deeper.reserve(room); }); + !made) { + return made; + } + } + // There is room: it does not allocate. + deeper.push_back(f); + ++size_; + return {}; + } + +private: + /** A list of frames, in the allocator. */ + using frames = std::vector<Frame, rebound<Allocator, Frame>>; + + /** The outermost frames. */ + std::array<Frame, first_frames> own_{}; + + /** The allocator of the frames past them. */ + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS rebound<Allocator, Frame> alloc_; + + /** The frames past them, innermost last; none until the first of them. */ + std::optional<frames> deeper_; + + /** How many frames it holds. */ + std::size_t size_ = 0; }; /** The walk of @ref write_json over one subtree, which keeps the containers it is inside on a stack - of its own: depth is not bounded by the API, and a recursion would be bounded by the thread's - stack. + of its own, @ref frame_stack, the frames past its own room in `Allocator`, rebound: depth is not + bounded by the API, and a recursion would be bounded by the thread's stack. Tip: the stack holds ids, never nodes, and each step finds its node again, so that nothing the walk holds points into the image across a call of the output. */ -template <class Traits, class Out> +template <class Traits, class Out, class Allocator> class json_writer { public: - /** A walk of `t` writing to `out` with `indent` spaces a level, already clamped. */ - json_writer(const tree<Traits>& t, std::uint32_t indent, Out& out) noexcept - : tree_(&t), indent_(indent), out_(&out) {} + /** + A walk of `t` writing to `out` with `indent` spaces a level, already clamped, its stack in + `alloc`. + */ + json_writer(const tree_view<Traits>& t, std::uint32_t indent, Out& out, + const Allocator& alloc) noexcept + : tree_(&t), indent_(indent), out_(&out), stack_(alloc) {} /** - Writes the subtree of `root`, a node that is not `undefined`; the output's failure ends it. + Writes the subtree of `root`, a node that is not `undefined`; the output's failure ends it, + and with exceptions @ref errc::capacity when the allocator has no room for the stack. */ result<void> run(const node<Traits>& root) { write_value(root); @@ -227,15 +422,34 @@ class json_writer { } } - /** Opens a container: `[]` or `{}` when it is empty, else its opener and a frame. */ + /** + Opens a container: `[]` or `{}` when it is empty, else its frame, then its opener, so that a + stack with no room writes nothing of it. + */ void open(const node<Traits>& n, bool object) { + if (!status_) { + return; + } const node<Traits>* first = tree_->first_child(n.id); if (first == nullptr) { put(object ? "{}" : "[]"); return; } - put(object ? "{" : "["); - stack_.push_back(frame{.next = first->id, .object = object, .first = true}); + if (push(frame{.next = first->id, .object = object, .first = true})) { + put(object ? "{" : "["); + } + } + + /** + Pushes a frame, room made first; with exceptions, an allocator with no room stops the writing + with @ref errc::capacity. + */ + bool push(const frame& f) { + if (const result<void> pushed = stack_.push(f); !pushed) { + status_ = pushed; + return false; + } + return true; } /** Writes a number as JavaScript's Number::toString writes the traits' `number`. */ @@ -336,88 +550,15 @@ class json_writer { } /** - QuoteJSONString of UTF-8 text, valid as the document holds it: the runs that need no escape - are written as they are. + QuoteJSONString of a key or a string: UTF-8, valid as the document holds it, or UTF-16. */ - void quote(std::string_view text) { - put("\""); - std::size_t run = 0; - for (std::size_t i = 0; i < text.size() && status_; ++i) { - const auto unit = static_cast<unsigned char>(text[i]); - if (unit >= 0x20 && unit != '"' && unit != '\\') { - continue; - } - put(text.substr(run, i - run)); - escape_into(unit); - run = i + 1; - } - put(text.substr(run)); - put("\""); - } - - /** - QuoteJSONString of UTF-16 text: transcoded to UTF-8 through a buffer, and a lone surrogate - written as `\\u` and its four lowercase hex digits, as JavaScript writes it since ES2019. - */ - void quote(std::u16string_view units) { - // The longest a unit or a pair becomes: six characters, the escape of a lone surrogate. - constexpr std::size_t longest = 6; - std::array<char, 256> buffer{}; - std::size_t used = 0; - put("\""); - for (std::size_t i = 0; i < units.size() && status_; ++i) { - if (buffer.size() - used < longest) { - put({buffer.data(), used}); - used = 0; - } - const char16_t unit = units[i]; - const bool pair = - high_surrogate(unit) && i + 1 < units.size() && low_surrogate(units[i + 1]); - if (pair) { - used += static_cast<std::size_t>(to_utf8(units.substr(i, 2), buffer.data() + used)); - ++i; - } else if (high_surrogate(unit) || low_surrogate(unit)) { - used += unicode_escape(unit, buffer.data() + used); - } else if (unit >= 0x80) { - used += static_cast<std::size_t>(to_utf8(units.substr(i, 1), buffer.data() + used)); - } else if (unit >= 0x20 && unit != u'"' && unit != u'\\') { - buffer[used++] = static_cast<char>(unit); - } else { - put({buffer.data(), used}); - used = 0; - escape_into(unit); - } - } - put({buffer.data(), used}); - put("\""); - } - - /** Writes the escape of a unit below 0x20, `"` or `\\`. */ - void escape_into(std::uint32_t unit) { - switch (unit) { - case '"': put("\\\""); return; - case '\\': put("\\\\"); return; - case '\b': put("\\b"); return; - case '\f': put("\\f"); return; - case '\n': put("\\n"); return; - case '\r': put("\\r"); return; - case '\t': put("\\t"); return; - default: break; - } - std::array<char, 6> text{}; - put({text.data(), unicode_escape(unit, text.data())}); - } - - /** Writes `\\u` and the four lowercase hex digits of `unit` at `out`, and returns 6. */ - static std::size_t unicode_escape(std::uint32_t unit, char* out) noexcept { - constexpr std::string_view hex = "0123456789abcdef"; - out[0] = '\\'; - out[1] = 'u'; - out[2] = hex[(unit >> 12U) & 0xfU]; - out[3] = hex[(unit >> 8U) & 0xfU]; - out[4] = hex[(unit >> 4U) & 0xfU]; - out[5] = hex[unit & 0xfU]; - return 6; + template <class Text> + void quote(Text text) { + const auto pass = [this](std::string_view piece) { + put(piece); + return status_.has_value(); + }; + quote_json(text, pass); } /** Writes a line break and the spaces of `level` levels; nothing when writing compactly. */ @@ -444,25 +585,35 @@ class json_writer { status_ = out_->put(text); } - const tree<Traits>* tree_; + /** The tree read. */ + const tree_view<Traits>* tree_; + + /** The spaces of a level, already clamped. */ std::uint32_t indent_; + + /** The output written to. */ Out* out_; - std::vector<frame> stack_; + + /** The containers the walk is inside, the innermost last. */ + frame_stack<frame, Allocator> stack_; + + /** The first failure, which stops the writing, or success. */ result<void> status_{}; }; /** Writes the subtree of `root` as `JSON.stringify(value, null, indent)` does, `indent` clamped to - @ref max_indent; a null `root`, `undefined`, writes nothing. + @ref max_indent, the frames of its stack past its own room in `alloc`, rebound; a null `root`, + `undefined`, writes nothing. */ -template <class Traits, class Out> +template <class Traits, class Out, class Allocator> requires output<Out> -result<void> write_json(const tree<Traits>& t, const node<Traits>* root, std::uint32_t indent, - Out& out) { +result<void> write_json(const tree_view<Traits>& t, const node<Traits>* root, std::uint32_t indent, + Out& out, const Allocator& alloc) { if (root == nullptr || root->kind == webcpp::document::kind::undefined) { return {}; } - json_writer<Traits, Out> writer(t, std::min(indent, max_indent), out); + json_writer<Traits, Out, Allocator> writer(t, std::min(indent, max_indent), out, alloc); return writer.run(*root); } diff --git a/include/webcpp/document/document.hpp b/include/webcpp/document/document.hpp index 73d27b9..57a3976 100644 --- a/include/webcpp/document/document.hpp +++ b/include/webcpp/document/document.hpp @@ -20,35 +20,24 @@ #include <webcpp/document/errors.hpp> #include <webcpp/document/image.hpp> #include <webcpp/document/kind.hpp> +#include <webcpp/document/storage.hpp> #include <webcpp/document/traits.hpp> +#include <boost/throw_exception.hpp> + #include <algorithm> #include <concepts> #include <cstddef> #include <cstdint> #include <cstring> +#include <memory> +#include <new> #include <span> #include <string> #include <string_view> namespace webcpp::document { -/** - The storage of a document that owns its image: a buffer of its own, 16-aligned, which grows, - twice the size each time, up to its `max_bytes`. - - @see "Images", in the guide. -*/ -struct owned {}; - -/** - The storage of a document whose image is a buffer its user owns, such as a browser's memory: when - it is full, an operation returns @ref errc::capacity and changes nothing. - - @see "Images", in the guide. -*/ -struct external {}; - /** The largest image an owned document grows to unless told otherwise: 1 GiB. */ inline constexpr std::uint64_t default_max_bytes = std::uint64_t{1} << 30U; @@ -64,6 +53,22 @@ inline constexpr std::uint64_t default_max_bytes = std::uint64_t{1} << 30U; template <class Traits = default_traits> result<basic_document<Traits, external>> format(std::span<std::byte> buffer) noexcept; +/** + Formats a buffer as a new, empty document, holding `null`, whose operations keep their working + state in `alloc`. + + @tparam Traits The traits. + @tparam Allocator An allocator of `std::byte`. + @param buffer The buffer, 16-aligned, which the document uses in place and its user keeps alive. + @param alloc The allocator of the working state of the document's operations. + @return The document; @ref errc::capacity when the buffer is too small for an empty document or + is not 16-aligned. + @see "Allocators", in the guide. +*/ +template <class Traits = default_traits, detail::byte_allocator Allocator> +result<basic_document<Traits, basic_external<Allocator>>> format(std::span<std::byte> buffer, + const Allocator& alloc) noexcept; + /** Opens the image already in a buffer, in place. @@ -83,6 +88,22 @@ template <class Traits = default_traits> result<basic_document<Traits, external>> open(std::span<std::byte> buffer, verify check = verify::seal) noexcept; +/** + Opens the image already in a buffer, in place, as @ref open does, the working state of the + document's operations in `alloc`. + + @tparam Traits The traits the image was written with. + @tparam Allocator An allocator of `std::byte`. + @param buffer The buffer, which the document uses in place and its user keeps alive. + @param alloc The allocator of the working state of the document's operations. + @param check Whether a sealed image's bytes are checked against its seal. + @return The document; the errors of @ref open. + @see "Allocators", in the guide. +*/ +template <class Traits = default_traits, detail::byte_allocator Allocator> +result<basic_document<Traits, basic_external<Allocator>>> open( + std::span<std::byte> buffer, const Allocator& alloc, verify check = verify::seal) noexcept; + /** Copies an image into a new owned document. @@ -102,6 +123,24 @@ result<basic_document<Traits, owned>> from_image(std::span<const std::byte> byte std::uint64_t max_bytes = default_max_bytes, verify check = verify::seal) noexcept; +/** + Copies an image into a new owned document allocated through `alloc`, as @ref from_image does. + + @tparam Traits The traits the image was written with. + @tparam Allocator An allocator of `std::byte`. + @param bytes The image, at any address. + @param alloc The allocator of the copy and of the working state of its operations. + @param max_bytes The size the copy may grow to. + @param check Whether a sealed image's bytes are checked against its seal. + @return The document; the errors of @ref from_image, and @ref errc::capacity when `alloc` has no + room for the copy. + @see "Allocators", in the guide. +*/ +template <class Traits = default_traits, detail::byte_allocator Allocator> +result<basic_document<Traits, basic_owned<Allocator>>> from_image( + std::span<const std::byte> bytes, const Allocator& alloc, + std::uint64_t max_bytes = default_max_bytes, verify check = verify::seal) noexcept; + /** A JSON document: one value, in one relocatable image. @@ -110,39 +149,83 @@ result<basic_document<Traits, owned>> from_image(std::span<const std::byte> byte document is moved cheaply; moving it, or destroying it, invalidates its handles, as a container's iterators would be. It is copied only with exceptions, or by @ref clone. + It is allocator-aware as the standard containers are: its storage's allocator allocates, grows and + frees an owned image and, rebound, holds the working state of its operations; a move takes the + allocator, a move assignment between allocators that are not equal and do not propagate copies + the image, and the copy constructor asks `select_on_container_copy_construction`. + @tparam Traits The traits: the stored types, the encoding, the bytes policy and the key order. - @tparam Storage @ref owned or @ref external. + @tparam Storage @ref basic_owned or @ref basic_external of an allocator of `std::byte`: @ref owned + and @ref external in the standard allocator, `pmr::owned` and `pmr::external` in a + `std::pmr::memory_resource`. @see "Handles", in the guide. @see "Images", in the guide. + @see "Allocators", in the guide. */ template <class Traits, class Storage> class basic_document { static_assert(document_traits<Traits>, "the traits do not satisfy document_traits"); - static_assert(std::same_as<Storage, owned> || std::same_as<Storage, external>, - "a document's storage is owned or external"); + static_assert(detail::storage<Storage>, + "a document's storage is basic_owned or basic_external of an allocator of " + "std::byte"); public: + /** The allocator of the image, when owned, and of the working state of the operations. */ + using allocator_type = Storage::allocator_type; + /** - Makes a new owned document, holding `null`. + Makes a new owned document, holding `null`, in a default-constructed allocator. @param max_bytes The size its image may grow to; past it an operation returns @ref errc::capacity. @return The document; @ref errc::capacity when even an empty one does not fit `max_bytes`. */ static result<basic_document> create(std::uint64_t max_bytes = default_max_bytes) noexcept - requires std::same_as<Storage, owned> + requires detail::owned_storage<Storage> { - auto made = detail::region::owned(std::min(first_bytes, max_bytes / 16 * 16), max_bytes); + return create(allocator_type(), max_bytes); + } + + /** + Makes a new owned document, holding `null`, allocated through `alloc`. + + @param alloc The allocator of the image and of the working state of the operations. + @param max_bytes The size its image may grow to; past it an operation returns + @ref errc::capacity. + @return The document; @ref errc::capacity when even an empty one does not fit `max_bytes`, or + `alloc` has no room for it. + @see "Allocators", in the guide. + */ + static result<basic_document> create(const allocator_type& alloc, + std::uint64_t max_bytes = default_max_bytes) noexcept + requires detail::owned_storage<Storage> + { + auto made = + region_type::owned(std::min(first_bytes, max_bytes / 16 * 16), max_bytes, alloc); if (!made.has_value()) { return made.error(); } - if (const auto formatted = detail::tree<Traits>::format(made.unsafe_value()); - !formatted.has_value()) { + if (const auto formatted = tree_type::format(made.unsafe_value()); !formatted.has_value()) { return formatted.error(); } return basic_document(std::move(made.unsafe_value())); } + /** + A document that holds nothing, as a moved-from document does: it has no image, allocates + nothing and cannot fail, so a library can hand one out where it has no document to give. + + Its root reads `undefined`, it writes no text, @ref image is empty, a change and @ref clone + return @ref errc::type, and a move assignment gives it an image. + + @param alloc The allocator it keeps, as a moved-from document keeps its own. + @return The document. + @see "Allocators", in the guide. + */ + static basic_document nothing(const allocator_type& alloc = allocator_type()) noexcept { + return basic_document(region_type(alloc)); + } + /** Makes a new owned document, holding `null`, as @ref create does, throwing on failure; only with exceptions. @@ -151,20 +234,45 @@ class basic_document { @see "The sugar that throws", in the guide. */ basic_document() - requires detail::exceptions_enabled<Traits> && std::same_as<Storage, owned>; + requires detail::exceptions_enabled<Traits> && detail::owned_storage<Storage>; + + /** + Makes a new owned document, holding `null`, allocated through `alloc`, as @ref create does, + throwing on failure; only with exceptions. + + @param alloc The allocator of the image and of the working state of the operations. + @throws capacity_error When even an empty document does not fit. + @see "The sugar that throws", in the guide. + */ + explicit basic_document(const allocator_type& alloc) + requires detail::exceptions_enabled<Traits> && detail::owned_storage<Storage>; /** - Copies a document's image into a new owned document, as @ref clone does, throwing on failure; - only with exceptions. + Copies a document's image into a new owned document, in the allocator that + `select_on_container_copy_construction` gives for `other`'s, throwing on failure; only with + exceptions. @param other The document. @throws capacity_error When the copy does not fit. */ basic_document(const basic_document& other) - requires detail::exceptions_enabled<Traits> && std::same_as<Storage, owned>; + requires detail::exceptions_enabled<Traits> && detail::owned_storage<Storage>; + + /** + Copies a document's image into a new owned document allocated through `alloc`, as + @ref clone does, throwing on failure; only with exceptions. + + @param other The document. + @param alloc The allocator of the copy. + @throws capacity_error When the copy does not fit. + @see "Allocators", in the guide. + */ + basic_document(const basic_document& other, const allocator_type& alloc) + requires detail::exceptions_enabled<Traits> && detail::owned_storage<Storage>; /** - Takes the image of `other`, whose handles become invalid; `other` holds nothing after it. + Takes the image and the allocator of `other`, whose handles become invalid; `other` holds + nothing after it. @param other The document. */ @@ -174,16 +282,37 @@ class basic_document { } /** - Takes the image of `other`, freeing this document's own; the handles of both become invalid. + Takes the image of `other`, freeing this document's own; the handles of both become invalid, + and `other` holds nothing after it. + + The allocator is taken when it propagates on a move assignment. When it does not, and the two + are not equal, an owned image is copied into this document's allocator, one copy of its bytes, + and `other`'s freed; an external image, which no allocator holds, is taken as it is. @param other The document. @return This document. + @throws std::bad_alloc When an owned image is copied and this document's allocator has no room + for it, through `boost::throw_exception`, as a failure that cannot be returned: never for + allocators that propagate or are always equal, the standard one among them, nor for an + external document, whose image no allocator holds, for which it is `noexcept`. + @see "Allocators", in the guide. */ - basic_document& operator=(basic_document&& other) noexcept { - if (this != &other) { - region_ = std::move(other.region_); - tree_.rebind(region_); + // It is noexcept for allocators that propagate or are always equal and for an external + // document, none of which takes the copy, the one path that throws. + // NOLINTNEXTLINE(bugprone-exception-escape) + basic_document& operator=(basic_document&& other) noexcept(moves_cheaply || + detail::external_storage<Storage>) { + if (this == &other) { + return *this; } + if constexpr (!moves_cheaply && detail::owned_storage<Storage>) { + if (region_.get_allocator() != other.region_.get_allocator()) { + take_by_copy(other); + return *this; + } + } + region_ = std::move(other.region_); + tree_.rebind(region_); return *this; } @@ -194,7 +323,15 @@ class basic_document { ~basic_document() = default; /** - Copies the image into a new owned document, as `structuredClone` would. + The allocator of the image, when owned, and of the working state of the operations. + + @return A copy of it. + */ + [[nodiscard]] allocator_type get_allocator() const noexcept { return region_.get_allocator(); } + + /** + Copies the image into a new owned document, as `structuredClone` would, in this document's + allocator. The copy keeps a seal, its bytes being the image's; the seal is not checked, the image being this document's own. @@ -202,15 +339,25 @@ class basic_document { @return The copy, equal and independent; @ref errc::capacity when it does not fit, and @ref errc::type for a moved-from document, which has no image. */ - [[nodiscard]] result<basic_document<Traits, owned>> clone() const noexcept { + [[nodiscard]] result<basic_document<Traits, detail::owned_of<Storage>>> clone() const noexcept { + return clone(get_allocator()); + } + + /** + Copies the image into a new owned document allocated through `alloc`, as `structuredClone` + would. + + @param alloc The allocator of the copy and of the working state of its operations. + @return The copy, equal and independent; @ref errc::capacity when it does not fit, or `alloc` + has no room for it, and @ref errc::type for a moved-from document, which has no image. + @see "Allocators", in the guide. + */ + [[nodiscard]] result<basic_document<Traits, detail::owned_of<Storage>>> clone( + const allocator_type& alloc) const noexcept { if (region_.data() == nullptr) { return errc::type; } - // A copy keeps an owned image's limit; an external image's grows as a new document would. - const std::uint64_t limit = std::same_as<Storage, owned> - ? region_.max_bytes() - : std::max(default_max_bytes, region_.size()); - return from_image<Traits>(image(), limit, verify::none); + return from_image<Traits>(image(), alloc, copy_limit(), verify::none); } /** @@ -316,7 +463,7 @@ class basic_document { @return Success; @ref errc::capacity when the smaller buffer cannot be allocated. */ result<void> shrink_to_fit() noexcept - requires std::same_as<Storage, owned> + requires detail::owned_storage<Storage> { return tree_.shrink_to_fit(); } @@ -338,17 +485,17 @@ class basic_document { @see "Images", in the guide. */ result<void> compact() noexcept - requires std::same_as<Storage, owned> + requires detail::owned_storage<Storage> { if (region_.data() == nullptr) { return errc::type; } const std::uint64_t bytes = tree_.compact_bytes(); - auto made = detail::region::owned(bytes, region_.max_bytes()); + auto made = region_type::owned(bytes, region_.max_bytes(), region_.get_allocator()); if (!made.has_value()) { return made.error(); } - if (const auto built = detail::tree<Traits>::compact_to(made.unsafe_value(), tree_, bytes); + if (const auto built = tree_type::compact_to(made.unsafe_value(), tree_, bytes); !built.has_value()) { return built.error(); } @@ -366,12 +513,13 @@ class basic_document { @param buffer The buffer, 16-aligned, of at least @ref compact_size bytes, which the returned document uses in place and its user keeps alive; it must not overlap this document's image. - @return The document, over the buffer's first @ref compact_size bytes; @ref errc::capacity - when the buffer is smaller or is not 16-aligned, writing nothing; @ref errc::type for a - moved-from document and for a buffer that overlaps the image. + @return The document, over the buffer's first @ref compact_size bytes, its working state in + this document's allocator; @ref errc::capacity when the buffer is smaller or is not + 16-aligned, writing nothing; @ref errc::type for a moved-from document and for a buffer that + overlaps the image. @see "Images", in the guide. */ - [[nodiscard]] result<basic_document<Traits, external>> compact_into( + [[nodiscard]] result<basic_document<Traits, basic_external<allocator_type>>> compact_into( std::span<std::byte> buffer) const noexcept; /** @@ -453,21 +601,87 @@ class basic_document { friend class detail::handler; friend struct detail::access; + /** The region of the storage's allocator. */ + using region_type = detail::basic_region<allocator_type>; + + /** The tree of the storage's allocator. */ + using tree_type = detail::tree<Traits, allocator_type>; + + /** The allocator's traits. */ + using alloc_traits = std::allocator_traits<allocator_type>; + + /** + Whether a move assignment only takes the other image: the allocator propagates on a move, or + two of them are always equal. + */ + static constexpr bool moves_cheaply = + alloc_traits::propagate_on_container_move_assignment::value || + alloc_traits::is_always_equal::value; + /** The size of a new owned document's first buffer, which grows as its content needs. */ static constexpr std::uint64_t first_bytes = 4096; /** The document of a region whose tree was formatted or attached, the tree rebound to it. */ - explicit basic_document(detail::region r) noexcept : region_(std::move(r)) { + explicit basic_document(region_type r) noexcept : region_(std::move(r)) { tree_.rebind(region_); } - detail::region region_; - detail::tree<Traits> tree_; + /** The limit of a copy: an owned image's own; an external image's grows as a new one would. */ + [[nodiscard]] std::uint64_t copy_limit() const noexcept { + return detail::owned_storage<Storage> ? region_.max_bytes() + : std::max(default_max_bytes, region_.size()); + } + + /** + Copies the owned image of `other`, of an allocator that is not equal and does not propagate, + into this document's allocator, and frees `other`'s; a moved-from `other` leaves this + document holding nothing. + */ + void take_by_copy(basic_document& other) { + if (other.region_.data() == nullptr) { + region_ = region_type(region_.get_allocator()); + tree_.rebind(region_); + return; + } + auto copied = region_type::owned_copy(other.image(), other.region_.max_bytes(), + region_.get_allocator()); + if (!copied.has_value()) { + boost::throw_exception(std::bad_alloc()); + } + region_ = std::move(copied.unsafe_value()); + tree_.rebind(region_); + other.region_ = region_type(other.region_.get_allocator()); + } + + region_type region_; + tree_type tree_; }; /** A document of the default traits, owned: exact numbers, UTF-8, JavaScript's key order. */ using document = basic_document<>; +namespace pmr { + +/** + A document that owns its image, which a `std::pmr::memory_resource` holds with the working state + of its operations. + + @tparam Traits The traits. + @see "Allocators", in the guide. +*/ +template <class Traits = default_traits> +using basic_document = webcpp::document::basic_document<Traits, owned>; + +/** + A document of the default traits whose image and working state a `std::pmr::memory_resource` + holds. + + @see "Allocators", in the guide. +*/ +using document = basic_document<>; + +} // namespace pmr + namespace detail { /** @@ -475,7 +689,7 @@ namespace detail { `value.hpp` defines after this header: `Access` defers its lookup to where a call is instantiated. */ template <class Traits, class Storage, class Access = access> -basic_document<Traits, Storage> adopt(region r) noexcept { +basic_document<Traits, Storage> adopt(basic_region<typename Storage::allocator_type> r) noexcept { return Access::template make_document<Traits, Storage>(std::move(r)); } @@ -483,19 +697,32 @@ basic_document<Traits, Storage> adopt(region r) noexcept { template <class Traits> result<basic_document<Traits, external>> format(std::span<std::byte> buffer) noexcept { - auto made = detail::region::external_empty(buffer); + return format<Traits>(buffer, std::allocator<std::byte>()); +} + +template <class Traits, detail::byte_allocator Allocator> +result<basic_document<Traits, basic_external<Allocator>>> format(std::span<std::byte> buffer, + const Allocator& alloc) noexcept { + auto made = detail::basic_region<Allocator>::external_empty(buffer, alloc); if (!made.has_value()) { return made.error(); } - if (const auto formatted = detail::tree<Traits>::format(made.unsafe_value()); + if (const auto formatted = detail::tree<Traits, Allocator>::format(made.unsafe_value()); !formatted.has_value()) { return formatted.error(); } - return detail::adopt<Traits, external>(std::move(made.unsafe_value())); + return detail::adopt<Traits, basic_external<Allocator>>(std::move(made.unsafe_value())); } template <class Traits> result<basic_document<Traits, external>> open(std::span<std::byte> buffer, verify check) noexcept { + return open<Traits>(buffer, std::allocator<std::byte>(), check); +} + +template <class Traits, detail::byte_allocator Allocator> +result<basic_document<Traits, basic_external<Allocator>>> open(std::span<std::byte> buffer, + const Allocator& alloc, + verify check) noexcept { if (reinterpret_cast<std::uintptr_t>(buffer.data()) % 16 != 0) { return errc::not_a_document; } @@ -506,38 +733,46 @@ result<basic_document<Traits, external>> open(std::span<std::byte> buffer, verif image_header header{}; std::memcpy(&header, buffer.data(), sizeof header); // The image is what its header states, which a larger buffer may hold. - detail::region r = - detail::region::external(buffer.first(static_cast<std::size_t>(header.size))); - if (const auto attached = detail::tree<Traits>::attach(r); !attached.has_value()) { + auto r = detail::basic_region<Allocator>::external( + buffer.first(static_cast<std::size_t>(header.size)), alloc); + if (const auto attached = detail::tree<Traits, Allocator>::attach(r); !attached.has_value()) { return attached.error(); } - return detail::adopt<Traits, external>(std::move(r)); + return detail::adopt<Traits, basic_external<Allocator>>(std::move(r)); } template <class Traits> result<basic_document<Traits, owned>> from_image(std::span<const std::byte> bytes, std::uint64_t max_bytes, verify check) noexcept { + return from_image<Traits>(bytes, std::allocator<std::byte>(), max_bytes, check); +} + +template <class Traits, detail::byte_allocator Allocator> +result<basic_document<Traits, basic_owned<Allocator>>> from_image(std::span<const std::byte> bytes, + const Allocator& alloc, + std::uint64_t max_bytes, + verify check) noexcept { if (const auto checked = check_image(bytes, detail::layout_tag<Traits>(), check); !checked.has_value()) { return checked.error(); } image_header header{}; std::memcpy(&header, bytes.data(), sizeof header); - auto made = - detail::region::owned_copy(bytes.first(static_cast<std::size_t>(header.size)), max_bytes); + auto made = detail::basic_region<Allocator>::owned_copy( + bytes.first(static_cast<std::size_t>(header.size)), max_bytes, alloc); if (!made.has_value()) { return made.error(); } - if (const auto attached = detail::tree<Traits>::attach(made.unsafe_value()); + if (const auto attached = detail::tree<Traits, Allocator>::attach(made.unsafe_value()); !attached.has_value()) { return attached.error(); } - return detail::adopt<Traits, owned>(std::move(made.unsafe_value())); + return detail::adopt<Traits, basic_owned<Allocator>>(std::move(made.unsafe_value())); } template <class Traits, class Storage> -result<basic_document<Traits, external>> basic_document<Traits, Storage>::compact_into( - std::span<std::byte> buffer) const noexcept { +result<basic_document<Traits, basic_external<typename Storage::allocator_type>>> +basic_document<Traits, Storage>::compact_into(std::span<std::byte> buffer) const noexcept { if (region_.data() == nullptr) { return errc::type; } @@ -550,16 +785,17 @@ result<basic_document<Traits, external>> basic_document<Traits, Storage>::compac if (bytes > buffer.size()) { return errc::capacity; } - auto made = detail::region::external_empty(buffer.first(static_cast<std::size_t>(bytes))); + auto made = region_type::external_empty(buffer.first(static_cast<std::size_t>(bytes)), + region_.get_allocator()); if (!made.has_value()) { return made.error(); } - if (const auto built = detail::tree<Traits>::compact_to(made.unsafe_value(), tree_, bytes); + if (const auto built = tree_type::compact_to(made.unsafe_value(), tree_, bytes); !built.has_value()) { return built.error(); } std::memset(buffer.data() + bytes, 0, buffer.size() - static_cast<std::size_t>(bytes)); - return detail::adopt<Traits, external>(std::move(made.unsafe_value())); + return detail::adopt<Traits, basic_external<allocator_type>>(std::move(made.unsafe_value())); } } // namespace webcpp::document diff --git a/include/webcpp/document/parse.hpp b/include/webcpp/document/parse.hpp index 061ab54..075f23a 100644 --- a/include/webcpp/document/parse.hpp +++ b/include/webcpp/document/parse.hpp @@ -70,20 +70,46 @@ struct parse_options { @param text The text. @param o The limits and the revivers. @return The document; @ref errc::syntax for malformed text, @ref errc::range for a number the - traits' `number` refuses, @ref errc::capacity past a limit. + traits' `number` refuses, @ref errc::capacity past a limit or, with exceptions, when memory runs + out. @see "Parsing", in the guide. */ template <class Traits = default_traits> -// The parser ends the program where the process heap, which holds its frames and pending text, -// runs out, as the library tolerates; with no selector, nothing else of it throws. +// Nothing escapes: with exceptions the parser makes an allocator with no room errc::capacity, and +// with no selector no callback throws, though the analysis sees a callback's exception rethrown. // NOLINTNEXTLINE(bugprone-exception-escape) result<basic_document<Traits, owned>> parse(std::string_view text, const parse_options& o = {}) noexcept { basic_parser<Traits, owned> p(o); - if (const result<void> written = p.write(text); !written.has_value()) { - return written.error(); - } - return p.finish(); + return p.finish_with(text); +} + +/** + `JSON.parse(text)`: reads JSON text into a new owned document allocated through `alloc`, as + @ref parse does. + + The document's image and the parse's working state are allocated through `alloc`; a text given + whole, as here, leaves Boost.JSON's parser no state to suspend, so nothing else allocates. With + exceptions, an allocator that has no room is @ref errc::capacity; without them it ends the + program, as the allocator itself does. + + @tparam Traits The traits of the document. + @tparam Allocator An allocator of `std::byte`. + @param text The text. + @param o The limits and the revivers. + @param alloc The allocator of the document and of the parse's working state. + @return The document; the errors of @ref parse, and @ref errc::capacity when `alloc` has no room. + @see "Allocators", in the guide. +*/ +template <class Traits = default_traits, detail::byte_allocator Allocator> +// Nothing escapes: with exceptions the parser makes an allocator with no room errc::capacity, and +// with no selector no callback throws, though the analysis sees a callback's exception rethrown. +// NOLINTNEXTLINE(bugprone-exception-escape) +result<basic_document<Traits, basic_owned<Allocator>>> parse(std::string_view text, + const parse_options& o, + const Allocator& alloc) noexcept { + basic_parser<Traits, basic_owned<Allocator>> p(o, alloc); + return p.finish_with(text); } /** @@ -96,17 +122,42 @@ result<basic_document<Traits, owned>> parse(std::string_view text, @return The document; the errors of @ref parse, and @ref errc::capacity when the buffer is full. */ template <class Traits = default_traits> -// The parser ends the program where the process heap, which holds its frames and pending text, -// runs out, as the library tolerates; with no selector, nothing else of it throws. +// Nothing escapes: with exceptions the parser makes an allocator with no room errc::capacity, and +// with no selector no callback throws, though the analysis sees a callback's exception rethrown. // NOLINTNEXTLINE(bugprone-exception-escape) result<basic_document<Traits, external>> parse_into(std::span<std::byte> buffer, std::string_view text, const parse_options& o = {}) noexcept { basic_parser<Traits, external> p(buffer, o); - if (const result<void> written = p.write(text); !written.has_value()) { - return written.error(); - } - return p.finish(); + return p.finish_with(text); +} + +/** + Reads JSON text into a new document in a buffer its user owns, as @ref parse_into does, the + parse's working state and the document's allocated through `alloc`. + + Nothing else allocates, as with @ref parse. With exceptions, an allocator that has no room is + @ref errc::capacity; without them it ends the program, as the allocator itself does. + + @tparam Traits The traits of the document. + @tparam Allocator An allocator of `std::byte`. + @param buffer The buffer, 16-aligned, which the document uses in place. + @param text The text. + @param o The limits and the revivers. + @param alloc The allocator of the working state of the parse and of the document's operations. + @return The document; the errors of @ref parse_into, and @ref errc::capacity when `alloc` has no + room. + @see "Allocators", in the guide. +*/ +template <class Traits = default_traits, detail::byte_allocator Allocator> +// Nothing escapes: with exceptions the parser makes an allocator with no room errc::capacity, and +// with no selector no callback throws, though the analysis sees a callback's exception rethrown. +// NOLINTNEXTLINE(bugprone-exception-escape) +result<basic_document<Traits, basic_external<Allocator>>> parse_into( + std::span<std::byte> buffer, std::string_view text, const parse_options& o, + const Allocator& alloc) noexcept { + basic_parser<Traits, basic_external<Allocator>> p(buffer, o, alloc); + return p.finish_with(text); } /** @@ -118,7 +169,7 @@ result<basic_document<Traits, external>> parse_into(std::span<std::byte> buffer, @return The document. @throws syntax_error For malformed text, with the byte offset where it was found. @throws range_error For a number the traits' `number` refuses. - @throws capacity_error Past a limit. + @throws capacity_error Past a limit, or when memory runs out. @see "The sugar that throws", in the guide. */ template <class Traits = default_traits> @@ -131,10 +182,7 @@ template <class Traits> requires detail::exceptions_enabled<Traits> basic_document<Traits, owned> parse_or_throw(std::string_view text, const parse_options& o) { basic_parser<Traits, owned> p(o); - if (const result<void> written = p.write(text); !written.has_value()) { - detail::raise(written.error(), p.offset()); - } - result<basic_document<Traits, owned>> made = p.finish(); + result<basic_document<Traits, owned>> made = p.finish_with(text); if (!made.has_value()) { detail::raise(made.error(), p.offset()); } diff --git a/include/webcpp/document/parser.hpp b/include/webcpp/document/parser.hpp index ee25035..53a1101 100644 --- a/include/webcpp/document/parser.hpp +++ b/include/webcpp/document/parser.hpp @@ -14,6 +14,7 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/detail/allocation.hpp> #include <webcpp/document/detail/fwd.hpp> #include <webcpp/document/detail/selector.hpp> #include <webcpp/document/document.hpp> @@ -21,6 +22,7 @@ #include <webcpp/document/parse.hpp> #include <webcpp/document/value.hpp> +#include <boost/config.hpp> #include <boost/json/basic_parser_impl.hpp> #include <boost/json/error.hpp> #include <boost/system/error_code.hpp> @@ -31,6 +33,7 @@ #include <cstdint> #include <functional> #include <limits> +#include <memory> #include <optional> #include <span> #include <string> @@ -41,6 +44,7 @@ #ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS #include <exception> +#include <new> #endif namespace webcpp::document { @@ -143,11 +147,185 @@ concept selector_callback = std::same_as<std::invoke_result_t<F&, basic_const_value<Traits, Storage>, path_view>, result<void>>); -/** A selector and its callback, as `on` or `observe` registered it. */ +/** + A selector's callback, its type erased as `std::function` erases it, its object allocated through + the parser's allocator, rebound, which `std::function` cannot take. + + Its object is the callable a selector was given, decayed, made by `make`; the callback is moved, + never copied, and calls it as `std::function` does, its `void` made success. +*/ +template <class Traits, class Storage> +class delivery { +public: + /** The allocator of the parser, which holds the callable. */ + using allocator_type = Storage::allocator_type; + + /** The read-only handle a callback is given. */ + using handle = basic_const_value<Traits, Storage>; + + /** + A callback holding `f`, decayed, in storage allocated through `alloc`; what the allocator or + the callable's constructor throws propagates, and the storage goes back to `alloc`. + */ + template <class F> + requires selector_callback<std::decay_t<F>, Traits, Storage> + static delivery make(F&& f, const allocator_type& alloc) { + using held = std::decay_t<F>; + using held_allocator = rebound<allocator_type, held>; + using held_traits = std::allocator_traits<held_allocator>; + held_allocator a(alloc); + storage_for<held> storage(a); + held_traits::construct(a, storage.get(), std::forward<F>(f)); + storage.release(); + // A callable that is a function pointer makes its storage a pointer to a pointer. + return delivery(static_cast<void*>(storage.get()), &operations_of<held>, alloc); + } + + /** Takes the callable of `other`, which holds none after it. */ + delivery(delivery&& other) noexcept + : object_(std::exchange(other.object_, nullptr)), ops_(other.ops_), alloc_(other.alloc_) {} + + /** A callback is not copied: it owns its callable. */ + delivery(const delivery&) = delete; + + /** A callback is not copied: it owns its callable. */ + delivery& operator=(const delivery&) = delete; + + /** A callback is not assigned: a polymorphic allocator, which it may hold, is not. */ + delivery& operator=(delivery&&) = delete; + + /** Destroys the callable and gives its storage back to the allocator. */ + ~delivery() { + if (object_ != nullptr) { + ops_->destroy(object_, alloc_); + } + } + + /** + Calls the callable with a value and its path, as `std::function` would: with a copy of the + handle, its `void` made success; what it throws propagates. + */ + result<void> operator()(const handle& v, path_view where) { + return ops_->call(object_, v, where); + } + +private: + /** + What a callable of one type does: be called, and be destroyed with its storage. + + Tip: each member has an initializer, else MSVC 14.3 and 14.5 warn (C4268, an error under /WX) + that `operations_of`, which sets every member, is filled with zeros; it is not, and the + callback it builds is called and destroyed as it should be. + */ + struct operations { + /** Calls the callable at `object` with a value and its path. */ + result<void> (*call)(void* object, const handle& v, path_view where) = nullptr; + + /** Destroys the callable at `object` and gives its storage back to `alloc`. */ + void (*destroy)(void* object, const allocator_type& alloc) noexcept = nullptr; + }; + + /** + Storage for one callable of type `T`, allocated through an allocator, which goes back to it + unless it is released once the callable is built in it. + */ + template <class T> + class storage_for { + public: + /** The allocator's traits, rebound to `T`. */ + using traits = std::allocator_traits<rebound<allocator_type, T>>; + + /** Storage for one `T` from `allocator`, which outlives it; what the allocator throws. */ + explicit storage_for(rebound<allocator_type, T>& allocator) + : allocator_(&allocator), place_(traits::allocate(allocator, 1)) {} + + /** The storage is the one being made: it is not copied. */ + storage_for(const storage_for&) = delete; + + /** The storage is the one being made: it is not copied. */ + storage_for& operator=(const storage_for&) = delete; + + /** The storage is the one being made: it is not moved. */ + storage_for(storage_for&&) = delete; + + /** The storage is the one being made: it is not moved. */ + storage_for& operator=(storage_for&&) = delete; + + /** Gives the storage back unless it was released. */ + ~storage_for() { + if (!released_) { + traits::deallocate(*allocator_, place_, 1); + } + } + + /** The storage's address. */ + [[nodiscard]] T* get() const noexcept { return std::to_address(place_); } + + /** Keeps the storage, which the callable built in it now owns. */ + void release() noexcept { released_ = true; } + + private: + /** The allocator. */ + rebound<allocator_type, T>* allocator_; + + /** The storage. */ + traits::pointer place_; + + /** Whether the storage is kept. */ + bool released_ = false; + }; + + /** + Calls the callable of type `F` at `object` with a copy of the handle, as `std::function` + passes its argument, so that a callable taking the handle by value or as an rvalue is called + as one taking a const reference is; its `void` made success. + */ + template <class F> + static result<void> call_as(void* object, const handle& v, path_view where) { + F& f = *static_cast<F*>(object); + if constexpr (std::same_as<std::invoke_result_t<F&, handle, path_view>, void>) { + std::invoke(f, handle(v), where); + return {}; + } else { + return std::invoke(f, handle(v), where); + } + } + + /** Destroys the callable of type `F` at `object` and gives its storage back to `alloc`. */ + template <class F> + static void destroy_as(void* object, const allocator_type& alloc) noexcept { + using held_allocator = rebound<allocator_type, F>; + using held_traits = std::allocator_traits<held_allocator>; + held_allocator a(alloc); + F* const f = static_cast<F*>(object); + const auto place = std::pointer_traits<typename held_traits::pointer>::pointer_to(*f); + held_traits::destroy(a, f); + held_traits::deallocate(a, place, 1); + } + + /** The operations of a callable of type `F`. */ + template <class F> + static constexpr operations operations_of{.call = &call_as<F>, .destroy = &destroy_as<F>}; + + /** A callback of the callable at `object`, built, whose operations are `ops`. */ + delivery(void* object, const operations* ops, const allocator_type& alloc) noexcept + : object_(object), ops_(ops), alloc_(alloc) {} + + /** The callable, in storage of the allocator; null once moved from. */ + void* object_; + + /** What the callable does. */ + const operations* ops_; + + /** The allocator of the callable's storage. */ + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS allocator_type alloc_; +}; + +/** A selector and its callback, as `on` or `observe` registered it, in the parser's allocator. */ template <class Traits, class Storage> struct subscription { /** The places it matches. */ - selector where; + basic_selector<typename Storage::allocator_type> where; /** Whether the value is dropped after its delivery, as `on` asks, or kept, as `observe` does. @@ -155,7 +333,7 @@ struct subscription { bool take = false; /** The callback, its `void` made success. */ - std::function<result<void>(basic_const_value<Traits, Storage>, path_view)> deliver; + delivery<Traits, Storage> deliver; }; } // namespace detail @@ -169,31 +347,56 @@ struct subscription { its own, since its input is the network's; an exception a callback throws propagates from `write` or `finish`, and leaves the parser failed: every later call throws it again, until @ref reset. + Its working state, the handler's frames, path and pending text, the selectors and their + callbacks, is allocated through the document's allocator, rebound. With exceptions, an allocator + that has no room is @ref errc::capacity, and fails the parser; without them it ends the program, + as the allocator itself does. A text given whole to @ref finish_with never suspends Boost.JSON's + parser, and allocates nothing else. A text fed in chunks by @ref write suspends it at each + chunk's end, and Boost.JSON keeps its suspension stack in the global heap, which no allocator + reaches: one allocation at the first suspension, and one more at each suspension deeper than + every earlier one, the last kept until the parser is destroyed, across @ref reset. + @tparam Traits The traits of the document. - @tparam Storage @ref owned, or @ref external to build it in a buffer of its user's. + @tparam Storage @ref basic_owned or @ref basic_external of an allocator of `std::byte`: @ref owned + and `pmr::owned`, or @ref external and `pmr::external` to build it in a buffer of its user's. The + allocator holds an owned document's image and the parser's working state. @see "Parsing", in the guide. */ template <class Traits, class Storage> class basic_parser { public: + /** The allocator of the document and of the parser's working state. */ + using allocator_type = Storage::allocator_type; + /** A parser of an owned document. @param o The limits and the revivers. + @param alloc The allocator of the document it makes and of its own working state. */ - explicit basic_parser(const parse_options& o = {}) noexcept - requires std::same_as<Storage, owned> - : options_(o), json_(json_options(o), *this) {} + explicit basic_parser(const parse_options& o = parse_options(), + const allocator_type& alloc = allocator_type()) noexcept + requires detail::owned_storage<Storage> + : options_(o), + alloc_(alloc), + subscriptions_(subscriptions_allocator(alloc)), + json_(json_options(o), *this) {} /** A parser of a document in a buffer its user owns, formatted when the text begins. @param buffer The buffer, 16-aligned, which outlives the parser and its document. @param o The limits and the revivers. + @param alloc The allocator of the document's working state and of the parser's own. */ - explicit basic_parser(std::span<std::byte> buffer, const parse_options& o = {}) noexcept - requires std::same_as<Storage, external> - : options_(o), buffer_(buffer), json_(json_options(o), *this) {} + explicit basic_parser(std::span<std::byte> buffer, const parse_options& o = parse_options(), + const allocator_type& alloc = allocator_type()) noexcept + requires detail::external_storage<Storage> + : options_(o), + alloc_(alloc), + buffer_(buffer), + subscriptions_(subscriptions_allocator(alloc)), + json_(json_options(o), *this) {} /** A parser is not copied: its handler and its document refer to it. */ basic_parser(const basic_parser&) = delete; @@ -215,8 +418,8 @@ class basic_parser { @param chunk The chunk: any split of the text, down to one byte. @return Success; @ref errc::syntax for malformed text, a second text after the first included, - @ref errc::range for a number the traits refuse, @ref errc::capacity past a limit, or the - error a callback returned. + @ref errc::range for a number the traits refuse, @ref errc::capacity past a limit or, with + exceptions, when the allocator has no room, or the error a callback returned. */ result<void> write(std::string_view chunk) { if (!failure_.has_value()) { @@ -234,7 +437,7 @@ class basic_parser { return {}; } boost::system::error_code ec; - const std::size_t used = json_.write_some(true, chunk.data(), chunk.size(), ec); + const std::size_t used = feed(true, chunk, ec); // Boost.JSON stops where a second text begins, without an error, and its next call would // begin that text as a new document. if (!ec && used < chunk.size()) { @@ -251,17 +454,41 @@ class basic_parser { @return The document; the errors of @ref write, and @ref errc::syntax for text that ends early. */ - result<basic_document<Traits, Storage>> finish() { + result<basic_document<Traits, Storage>> finish() { return finish_with(std::string_view()); } + + /** + Feeds the last chunk of the text, ends the text and returns the document, without the values + `on` took: what @ref write of `last` then @ref finish return. + + Boost.JSON's parser is told that no text follows, so that it never suspends: a text given + whole, to a parser that was given none before, allocates nothing outside the allocator, where + @ref write would have Boost.JSON allocate its suspension stack. After it the parser takes no + more text, which is @ref errc::syntax, until @ref reset. + + @param last The last chunk: the whole text, or what follows the chunks @ref write took. + @return The document; the errors of @ref write, and @ref errc::syntax for text that ends + early. + */ + result<basic_document<Traits, Storage>> finish_with(std::string_view last) { if (!failure_.has_value()) { return failed().error(); } if (ended_) { return end_again().error(); } + if (last.size() > options_.max_bytes - given_) { + failure_ = errc::capacity; + return failure_.error(); + } + given_ += last.size(); // No more text, as Boost.JSON's own stream_parser ends one. boost::system::error_code ec; - static_cast<void>(json_.write_some(false, nullptr, 0, ec)); - if (const result<void> settled = settle(ec, 0); !settled.has_value()) { + const std::size_t used = feed(false, last, ec); + // A second text after the first, which write finds the same way. + if (!ec && used < last.size()) { + ec = boost::json::error::extra_data; + } + if (const result<void> settled = settle(ec, used); !settled.has_value()) { return settled.error(); } ended_ = true; @@ -309,11 +536,14 @@ class basic_parser { completes when its token ends, an array or object when it closes; a value inside another that also matches is delivered first. + The selector and the callback, decayed, are held in the allocator. + @tparam F A callable taking a read-only handle and a @ref path_view, returning `void` or `result<void>`. @param selector The selector. @param f The callback. - @return Success; @ref errc::type for a malformed selector. + @return Success; @ref errc::type for a malformed selector, and with exceptions + @ref errc::capacity when the allocator has no room, the parser then unchanged. @see "Selectors", in the guide. */ template <class F> @@ -330,7 +560,8 @@ class basic_parser { `result<void>`. @param selector The selector, as @ref on takes it. @param f The callback. - @return Success; @ref errc::type for a malformed selector. + @return Success; @ref errc::type for a malformed selector, and with exceptions + @ref errc::capacity when the allocator has no room, the parser then unchanged. @see "Selectors", in the guide. */ template <class F> @@ -366,7 +597,7 @@ class basic_parser { return failure_.error(); } boost::system::error_code ec; - const std::size_t used = json_.write_some(true, fed.data(), fed.size(), ec); + const std::size_t used = feed(true, fed, ec); given_ += used; if (const result<void> settled = settle(ec, used); !settled.has_value()) { return settled.error(); @@ -390,6 +621,25 @@ class basic_parser { return made; } + /** + Feeds Boost.JSON's parser a chunk, `more` telling whether text follows; returns how many bytes + it used. + + With exceptions, an allocation that fails, of the handler in the allocator or of Boost.JSON's + suspension stack, propagates out of Boost.JSON's parser, which lets its handler throw and + fails itself: `std::bad_alloc`, a type derived from it, or Boost.Interprocess's `bad_alloc`. + It is @ref errc::capacity, which fails the parser until @ref reset. + */ + std::size_t feed(bool more, std::string_view chunk, boost::system::error_code& ec) { + return detail::unless_allocation_fails( + [&] { return json_.write_some(more, chunk.data(), chunk.size(), ec); }, + [&]() -> std::size_t { + failure_ = errc::capacity; + ec = failure_.error(); + return 0; + }); + } + /** Boost.JSON's options: numbers left as text, and the depth limit. */ static boost::json::parse_options json_options(const parse_options& o) noexcept { boost::json::parse_options made; @@ -441,37 +691,46 @@ class basic_parser { return failure_; } - /** Adds a subscription, its callback's `void` made success. */ + /** A subscription of this parser. */ + using subscription_type = detail::subscription<Traits, Storage>; + + /** The allocator of the subscriptions. */ + using subscriptions_allocator = detail::rebound<allocator_type, subscription_type>; + + /** + Adds a subscription, its selector and its callback in the allocator; with exceptions, an + allocator with no room is @ref errc::capacity, and adds nothing. + */ template <class F> result<void> subscribe(std::string_view text, F&& f, bool take) { - result<detail::selector> parsed = detail::selector::parse(text); + return detail::unless_allocation_fails([&] { return add(text, std::forward<F>(f), take); }, + [] { return result<void>(errc::capacity); }); + } + + /** + Adds a subscription, made whole before it is added, so that what fails to allocate leaves + the subscriptions as they were. + */ + template <class F> + result<void> add(std::string_view text, F&& f, bool take) { + result<detail::basic_selector<allocator_type>> parsed = + detail::basic_selector<allocator_type>::parse(text, alloc_); if (!parsed.has_value()) { return parsed.error(); } - using callback = std::decay_t<F>; - detail::subscription<Traits, Storage> added; - added.where = std::move(parsed).unsafe_value(); - added.take = take; - if constexpr (std::same_as<std::invoke_result_t< - callback&, basic_const_value<Traits, Storage>, path_view>, - void>) { - added.deliver = [g = callback(std::forward<F>(f))]( - const basic_const_value<Traits, Storage>& v, - path_view where) mutable -> result<void> { - g(v, where); - return {}; - }; - } else { - added.deliver = callback(std::forward<F>(f)); - } - subscriptions_.push_back(std::move(added)); + subscriptions_.push_back(subscription_type{ + .where = std::move(parsed).unsafe_value(), + .take = take, + .deliver = detail::delivery<Traits, Storage>::make(std::forward<F>(f), alloc_), + }); return {}; } parse_options options_; + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS allocator_type alloc_; std::span<std::byte> buffer_; std::optional<basic_document<Traits, Storage>> document_; - std::vector<detail::subscription<Traits, Storage>> subscriptions_; + std::vector<subscription_type, subscriptions_allocator> subscriptions_; boost::json::basic_parser<detail::handler<Traits, Storage>> json_; result<void> failure_; boost::system::error_code cause_; @@ -486,6 +745,18 @@ class basic_parser { /** The streaming parser of a @ref document. */ using parser = basic_parser<>; +namespace pmr { + +/** + The streaming parser of a `pmr::document`, its working state in the document's + `std::pmr::memory_resource`. + + @see "Allocators", in the guide. +*/ +using parser = webcpp::document::basic_parser<default_traits, owned>; + +} // namespace pmr + } // namespace webcpp::document #include <webcpp/document/detail/handler.hpp> diff --git a/include/webcpp/document/quote.hpp b/include/webcpp/document/quote.hpp new file mode 100644 index 0000000..fb68c3e --- /dev/null +++ b/include/webcpp/document/quote.hpp @@ -0,0 +1,192 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + `JSON.stringify` of a string alone: a string written as a JSON string literal, appended to a + string of the caller's, with the escapes `stringify` writes, without a document. +*/ + +#ifndef WEBCPP_DOCUMENT_QUOTE_HPP +#define WEBCPP_DOCUMENT_QUOTE_HPP + +#include <webcpp/document/config.hpp> + +#include <webcpp/document/detail/utf.hpp> +#include <webcpp/document/errors.hpp> + +#include <array> +#include <cstddef> +#include <cstdint> +#include <string_view> + +namespace webcpp::document { + +namespace detail { + +/** An output of @ref quote, a string that `append(data, size)` appends to. */ +template <class Out> +concept appendable = + requires(Out& out, const char* data, std::size_t size) { out.append(data, size); }; + +/** Writes `\\u` and the four lowercase hex digits of `unit` at `out`, and returns 6. */ +inline std::size_t unicode_escape(std::uint32_t unit, char* out) noexcept { + constexpr std::string_view hex = "0123456789abcdef"; + out[0] = '\\'; + out[1] = 'u'; + out[2] = hex[(unit >> 12U) & 0xfU]; + out[3] = hex[(unit >> 8U) & 0xfU]; + out[4] = hex[(unit >> 4U) & 0xfU]; + out[5] = hex[unit & 0xfU]; + return 6; +} + +/** Hands `put` the escape of a unit below 0x20, `"` or `\\`, and returns what `put` returned. */ +template <class Put> +bool escape_into(std::uint32_t unit, Put& put) { + switch (unit) { + case '"': return put("\\\""); + case '\\': return put("\\\\"); + case '\b': return put("\\b"); + case '\f': return put("\\f"); + case '\n': return put("\\n"); + case '\r': return put("\\r"); + case '\t': return put("\\t"); + default: break; + } + std::array<char, 6> text{}; + return put(std::string_view(text.data(), unicode_escape(unit, text.data()))); +} + +/** + QuoteJSONString of valid UTF-8 text, handed to `put` in pieces: the runs that need no escape are + handed as they are. + + Tip: `put` takes a `std::string_view` and returns whether the writing goes on; the first false + stops it, and is returned. +*/ +template <class Put> +bool quote_json(std::string_view text, Put& put) { + if (!put("\"")) { + return false; + } + std::size_t run = 0; + for (std::size_t i = 0; i < text.size(); ++i) { + const auto unit = static_cast<unsigned char>(text[i]); + if (unit >= 0x20 && unit != '"' && unit != '\\') { + continue; + } + if (!put(text.substr(run, i - run)) || !escape_into(unit, put)) { + return false; + } + run = i + 1; + } + return put(text.substr(run)) && put("\""); +} + +/** + QuoteJSONString of UTF-16 text, handed to `put` in pieces: transcoded to UTF-8 through a buffer, + and a lone surrogate written as `\\u` and its four lowercase hex digits, as JavaScript writes it + since ES2019. +*/ +template <class Put> +bool quote_json(std::u16string_view units, Put& put) { + // The longest a unit or a pair becomes: six characters, the escape of a lone surrogate. + constexpr std::size_t longest = 6; + std::array<char, 256> buffer{}; + std::size_t used = 0; + if (!put("\"")) { + return false; + } + for (std::size_t i = 0; i < units.size(); ++i) { + if (buffer.size() - used < longest) { + if (!put(std::string_view(buffer.data(), used))) { + return false; + } + used = 0; + } + const char16_t unit = units[i]; + const bool pair = + high_surrogate(unit) && i + 1 < units.size() && low_surrogate(units[i + 1]); + if (pair) { + used += static_cast<std::size_t>(to_utf8(units.substr(i, 2), buffer.data() + used)); + ++i; + } else if (high_surrogate(unit) || low_surrogate(unit)) { + used += unicode_escape(unit, buffer.data() + used); + } else if (unit >= 0x80) { + used += static_cast<std::size_t>(to_utf8(units.substr(i, 1), buffer.data() + used)); + } else if (unit >= 0x20 && unit != u'"' && unit != u'\\') { + buffer[used++] = static_cast<char>(unit); + } else { + if (!put(std::string_view(buffer.data(), used)) || !escape_into(unit, put)) { + return false; + } + used = 0; + } + } + return put(std::string_view(buffer.data(), used)) && put("\""); +} + +} // namespace detail + +/** + `JSON.stringify(s)` of a string `s`: appends UTF-8 text to `out` as a JSON string literal, its + quotes included. + + The bytes are the ones @ref stringify writes of the same string: `"` and `\\` escaped with a + backslash, `\\b`, `\\f`, `\\n`, `\\r` and `\\t` for their controls, `\\u` and four lowercase hex + digits for every other unit below U+0020, and everything else as it is, U+007F and U+2028 + included. It allocates only through `out`, so that a JSON text can be written field by field into + a string of the caller's allocator, a `std::pmr::string` among them. + + @tparam Out The output: `std::string`, `std::pmr::string`, or any type with + `append(const char*, std::size_t)`. + @param utf8 The text, in UTF-8. + @param out The string the literal is appended to. + @return Success; @ref errc::type when `utf8` is not valid UTF-8, which no JavaScript string is, + with `out` unchanged. An allocation failure of `out` propagates as `out` reports it. + @see "Writing JSON", in the guide. +*/ +template <class Out> + requires detail::appendable<Out> +result<void> quote(std::string_view utf8, Out& out) { + if (!detail::valid_utf8(utf8)) { + return errc::type; + } + const auto put = [&out](std::string_view text) { + out.append(text.data(), text.size()); + return true; + }; + detail::quote_json(utf8, put); + return {}; +} + +/** + `JSON.stringify(s)` of a string `s`: appends UTF-16 text to `out` as a JSON string literal, its + quotes included, in UTF-8. + + It writes what the UTF-8 overload writes of the same characters, and a lone surrogate, which a + JavaScript string may hold, as `\\u` and its four lowercase hex digits, as JavaScript writes it + since ES2019 and as @ref stringify writes it under `js_traits`. + + @tparam Out The output: `std::string`, `std::pmr::string`, or any type with + `append(const char*, std::size_t)`. + @param utf16 The text, in UTF-16 code units, any sequence of them. + @param out The string the literal is appended to; the only thing that allocates. + @see "Writing JSON", in the guide. +*/ +template <class Out> + requires detail::appendable<Out> +void quote(std::u16string_view utf16, Out& out) { + const auto put = [&out](std::string_view text) { + out.append(text.data(), text.size()); + return true; + }; + detail::quote_json(utf16, put); +} + +} // namespace webcpp::document + +#endif // WEBCPP_DOCUMENT_QUOTE_HPP diff --git a/include/webcpp/document/storage.hpp b/include/webcpp/document/storage.hpp new file mode 100644 index 0000000..4a4a4b7 --- /dev/null +++ b/include/webcpp/document/storage.hpp @@ -0,0 +1,165 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The storage of a document, its second template parameter: where its image lives, owned and + growing or in a buffer its user owns, and the allocator of everything it allocates. +*/ + +#ifndef WEBCPP_DOCUMENT_STORAGE_HPP +#define WEBCPP_DOCUMENT_STORAGE_HPP + +#include <webcpp/document/config.hpp> + +#include <concepts> +#include <cstddef> +#include <memory> +#include <memory_resource> + +namespace webcpp::document { + +/** + The storage of a document that owns its image: a buffer of its own, 16-aligned, which grows, + twice the size each time, up to its `max_bytes`, allocated, grown and freed through `Allocator`. + + The same allocator, rebound, holds what the document's operations need while they run: the + records a change stages, the stacks of a deep copy and of a compaction, the parser's frames, + path, pending text and selectors, the writer's stack and the piece it holds back past their own + room, a missing member's key, the buffers a value is prepared in, and the keys `Object.assign` + takes. A move takes the allocator with the image, + and a move assignment between allocators that are not equal and do not propagate copies the image + into the target's allocator. + + The image is allocated as blocks of 16 bytes, 16-aligned, and the allocator rebound to them must + give them that alignment: a buffer it gives at another alignment is given back, and the operation + returns @ref errc::capacity. With exceptions, an allocator that has no room throws + `std::bad_alloc`, a type derived from it, or Boost.Interprocess's `bad_alloc`, and the operation + returns @ref errc::capacity; anything else it throws ends the program. + + @tparam Allocator An allocator of `std::byte`; `std::allocator<std::byte>` by default, whose + documents are those of @ref owned. + @see "Images", in the guide. + @see "Allocators", in the guide. +*/ +template <class Allocator = std::allocator<std::byte>> +struct basic_owned { + /** The allocator of the image and of the working state. */ + using allocator_type = Allocator; +}; + +/** + The storage of a document whose image is a buffer its user owns, such as a browser's memory: when + it is full, an operation returns @ref errc::capacity and changes nothing. + + The image never grows, and `Allocator` holds only the working state of the document's operations, + as @ref basic_owned lists it. With exceptions, an allocator that has no room throws + `std::bad_alloc`, a type derived from it, or Boost.Interprocess's `bad_alloc`, and the operation + returns @ref errc::capacity; anything else it throws ends the program. + + @tparam Allocator An allocator of `std::byte`; `std::allocator<std::byte>` by default, whose + documents are those of @ref external. + @see "Images", in the guide. + @see "Allocators", in the guide. +*/ +template <class Allocator = std::allocator<std::byte>> +struct basic_external { + /** The allocator of the working state. */ + using allocator_type = Allocator; +}; + +/** + The storage of a document that owns its image, in the standard allocator. + + @see "Images", in the guide. +*/ +using owned = basic_owned<>; + +/** + The storage of a document whose image is a buffer its user owns, its working state in the + standard allocator. + + @see "Images", in the guide. +*/ +using external = basic_external<>; + +/** The storages of documents whose memory is a `std::pmr::memory_resource`. */ +namespace pmr { + +/** + The storage of a document that owns its image, which a `std::pmr::memory_resource` holds with + the working state of its operations. + + @see "Allocators", in the guide. +*/ +using owned = basic_owned<std::pmr::polymorphic_allocator<std::byte>>; + +/** + The storage of a document whose image is a buffer its user owns, the working state of its + operations in a `std::pmr::memory_resource`. + + @see "Allocators", in the guide. +*/ +using external = basic_external<std::pmr::polymorphic_allocator<std::byte>>; + +} // namespace pmr + +namespace detail { + +/** + Whether `A` is an allocator of `std::byte`, which a document's storage takes: its `value_type` is + checked before `std::allocator_traits` is named, which would not compile for a type that is no + allocator, so that a call whose argument is no allocator chooses another overload. +*/ +template <class A> +concept byte_allocator = + requires { typename A::value_type; } && std::same_as<typename A::value_type, std::byte> && + requires(A& a, std::size_t n) { a.allocate(n); } && std::copy_constructible<A> && + std::equality_comparable<A>; + +/** Whether `S` is @ref basic_owned of an allocator. */ +template <class S> +inline constexpr bool is_owned = false; + +/** Whether `S` is @ref basic_owned of an allocator: it is. */ +template <class A> +inline constexpr bool is_owned<basic_owned<A>> = true; + +/** Whether `S` is @ref basic_external of an allocator. */ +template <class S> +inline constexpr bool is_external = false; + +/** Whether `S` is @ref basic_external of an allocator: it is. */ +template <class A> +inline constexpr bool is_external<basic_external<A>> = true; + +/** A storage that owns its image: @ref basic_owned of an allocator of `std::byte`. */ +template <class S> +concept owned_storage = is_owned<S> && byte_allocator<typename S::allocator_type>; + +/** A storage over a buffer its user owns: @ref basic_external of an allocator of `std::byte`. */ +template <class S> +concept external_storage = is_external<S> && byte_allocator<typename S::allocator_type>; + +/** A document's storage, owned or external. */ +template <class S> +concept storage = owned_storage<S> || external_storage<S>; + +/** + The owned storage of the same allocator as `S`: the storage of the documents an operation on a + document of `S` makes, a copy, a `pop` or a `slice`. +*/ +template <class S> +using owned_of = basic_owned<typename S::allocator_type>; + +/** The allocator `A` gives for objects of `T`. */ +template <class A, class T> +using rebound = std::allocator_traits<A>::template rebind_alloc<T>; + +} // namespace detail + +} // namespace webcpp::document + +#endif // WEBCPP_DOCUMENT_STORAGE_HPP diff --git a/include/webcpp/document/stringify.hpp b/include/webcpp/document/stringify.hpp index 99bce15..63f484c 100644 --- a/include/webcpp/document/stringify.hpp +++ b/include/webcpp/document/stringify.hpp @@ -18,7 +18,10 @@ #include <webcpp/document/errors.hpp> #include <webcpp/document/value.hpp> +#include <boost/throw_exception.hpp> + #include <cstdint> +#include <new> #include <string> #include <string_view> #include <type_traits> @@ -38,24 +41,35 @@ inline constexpr std::uint64_t default_chunk = 4096; numbers are written as JavaScript writes them; a date as Date.prototype.toJSON writes it; bytes by the traits' bytes policy. + The text is a `std::string`, the program's value in the standard allocator whatever the + document's, and the writer's stack is in the same allocator: `stringify` asks the document's + allocator for nothing. The stack holds a frame of 16 bytes for each container the writer is + inside, the first 16 in room of its own and the deeper ones allocated, room for 16 at first and + twice the room each time it is full, and freed when it returns. + @tparam Traits The document's traits. @tparam Storage The document's storage. @param v The value. @param indent The spaces of each level, clamped to 10; 0 writes compactly. @return The text; empty when the value is `undefined`, since `JSON.stringify(undefined)` returns - no text. The standard library's `std::bad_alloc` is its only failure. + no text. + @throws std::bad_alloc When the standard allocator has no room for the text or the stack; without + exceptions, the standard allocator's failure ends the program, as it does itself. @see "Writing JSON", in the guide. */ template <class Traits, class Storage> std::string stringify(basic_const_value<Traits, Storage> v, std::uint32_t indent = 0) { std::string text; - const detail::tree<Traits>* t = detail::access::tree_of(v); + const auto* t = detail::access::tree_of(v); if (t == nullptr) { return text; } detail::string_output out(text); - // A string output fails only by throwing std::bad_alloc: its result is always a success. - (void)detail::write_json(*t, detail::access::node_of(v), indent, out); + // The stack is in the text's allocator. A string output fails only by throwing: a failure + // returned is the stack's, with exceptions, which the text a std::string returns cannot carry. + if (!detail::write_json(*t, detail::access::node_of(v), indent, out, text.get_allocator())) { + boost::throw_exception(std::bad_alloc()); + } return text; } @@ -69,6 +83,7 @@ std::string stringify(basic_const_value<Traits, Storage> v, std::uint32_t indent @param d The document. @param indent The spaces of each level, clamped to 10; 0 writes compactly. @return The text, as @ref stringify of its root writes it. + @throws std::bad_alloc As @ref stringify of its root throws it. */ template <class Traits, class Storage> std::string stringify(const basic_document<Traits, Storage>& d, std::uint32_t indent = 0) { @@ -80,6 +95,15 @@ std::string stringify(const basic_document<Traits, Storage>& d, std::uint32_t in /** Writes a value as @ref stringify does, in pieces of at most `chunk` bytes, to a sink. + Its working state has room of its own, and it allocates only past it, in the document's + allocator, rebound, freed when it returns: its stack holds a frame of 16 bytes for each container + it is inside, the first 16 in its own room and the deeper ones allocated, room for 16 at first + and twice the room each time it is full; and the piece it holds back until it is full has 4096 + bytes of its own room, so that a chunk of at most 4096 bytes allocates none, while a larger + chunk's piece, once it holds more, is allocated at 8192 bytes, then twice its room, up to + `chunk`, each time it is full. A value nested 16 deep or less, written in chunks of at most 4096 + bytes, asks the document's allocator for nothing. What the sink allocates is the program's own. + @tparam Traits The document's traits. @tparam Storage The document's storage. @tparam Sink A callable taking `std::string_view` and returning `void` or `result<void>`. @@ -87,22 +111,27 @@ std::string stringify(const basic_document<Traits, Storage>& d, std::uint32_t in @param sink The sink. @param indent The spaces of each level, clamped to 10; 0 writes compactly. @param chunk The largest piece, at least 1. - @return Success, or the first failure the sink returned, which stops the writing; an exception - the sink throws propagates. The document is unchanged either way. + @return Success, or the first failure the sink returned, which stops the writing; with + exceptions, @ref errc::capacity when the document's allocator has no room for the stack or the + piece, which stops it too, the sink not called again. An exception the sink throws propagates. + The document is unchanged either way; without exceptions, an allocator that fails ends the + program, as it does itself. @see "Writing JSON", in the guide. */ template <class Traits, class Storage, class Sink> requires detail::sink<std::remove_reference_t<Sink>> result<void> stringify_to(basic_const_value<Traits, Storage> v, Sink&& sink, std::uint32_t indent = 0, std::uint64_t chunk = default_chunk) { - const detail::tree<Traits>* t = detail::access::tree_of(v); + const auto* t = detail::access::tree_of(v); if (t == nullptr) { return {}; } + const typename Storage::allocator_type alloc = t->get_allocator(); // The sink is called through a reference: it is used in place, never forwarded or copied. - detail::chunked_output<std::remove_reference_t<Sink>> out(sink, chunk); + detail::chunked_output<std::remove_reference_t<Sink>, typename Storage::allocator_type> out( + sink, chunk, alloc); if (const result<void> written = - detail::write_json(*t, detail::access::node_of(v), indent, out); + detail::write_json(*t, detail::access::node_of(v), indent, out, alloc); !written) { return written; } @@ -121,7 +150,8 @@ result<void> stringify_to(basic_const_value<Traits, Storage> v, Sink&& sink, @param sink The sink. @param indent The spaces of each level, clamped to 10; 0 writes compactly. @param chunk The largest piece, at least 1. - @return Success, or the first failure the sink returned. + @return Success, the first failure the sink returned, or with exceptions @ref errc::capacity, as + @ref stringify_to of its root returns them. */ template <class Traits, class Storage, class Sink> requires detail::sink<std::remove_reference_t<Sink>> diff --git a/include/webcpp/document/traits.hpp b/include/webcpp/document/traits.hpp index ab114ce..ea9cb81 100644 --- a/include/webcpp/document/traits.hpp +++ b/include/webcpp/document/traits.hpp @@ -1122,7 +1122,11 @@ inline void write_base64(std::span<const std::byte> in, char* out, bool url) noe } } -/** Reads base64 text into `out`, which has room for it, and returns the size read. */ +/** + Reads base64 text into `out`, which has room for it, and returns the size read; with a null + `out`, it only checks the text and counts the bytes it holds, so that their room is sized before + it is allocated. +*/ inline result<std::uint64_t> read_base64(std::string_view text, std::byte* out, bool url) noexcept { // Base64 is padded to a multiple of four characters with at most two '='; base64url has no // padding, and a length of 4n + 1 leaves no whole byte. @@ -1150,7 +1154,10 @@ inline result<std::uint64_t> read_base64(std::string_view text, std::byte* out, pending_bits += 6; if (pending_bits >= 8) { pending_bits -= 8; - out[written++] = static_cast<std::byte>((pending >> pending_bits) & 0xffU); + if (out != nullptr) { + out[written] = static_cast<std::byte>((pending >> pending_bits) & 0xffU); + } + ++written; pending &= (1U << pending_bits) - 1; } } diff --git a/include/webcpp/document/value.hpp b/include/webcpp/document/value.hpp index 1036343..6caa68d 100644 --- a/include/webcpp/document/value.hpp +++ b/include/webcpp/document/value.hpp @@ -29,11 +29,15 @@ #include <webcpp/document/literal.hpp> #include <webcpp/document/traits.hpp> +#include <array> +#include <charconv> #include <concepts> #include <cstddef> #include <cstdint> #include <iterator> #include <limits> +#include <optional> +#include <span> #include <string> #include <string_view> #include <type_traits> @@ -191,23 +195,154 @@ class WEBCPP_DOCUMENT_NO_DANGLING children { std::uint64_t parent_ = 0; }; +/** A missing member's key, in UTF-8, in the document's allocator `A`, rebound. */ +template <class A> +using key_string = std::basic_string<char, std::char_traits<char>, rebound<A, char>>; + +/** + `key` held in `alloc`, or nothing when, with exceptions, `alloc` has no room for it: a handle that + could not hold its key reads `undefined` and fails a change with @ref errc::capacity. +*/ +template <class A> +std::optional<key_string<A>> hold_key(std::string_view key, const A& alloc) noexcept { + auto held = bad_alloc_as_capacity([&]() -> result<key_string<A>> { + return key_string<A>(key.data(), key.size(), rebound<A, char>(alloc)); + }); + if (!held.has_value()) { + return std::nullopt; + } + return std::optional<key_string<A>>(std::move(held.unsafe_value())); +} + +/** A copy of a held key in its own allocator, as @ref hold_key holds it; nothing for none. */ +template <class String> +std::optional<String> copy_key(const std::optional<String>& key) noexcept { + if (!key.has_value()) { + return std::nullopt; + } + return hold_key(std::string_view(*key), key->get_allocator()); +} + +/** The decimal digits of an array's index, as `Object.assign` keys an element: on the stack. */ +struct index_key { + /** The digits, in the first `size` places. */ + std::array<char, std::numeric_limits<std::uint64_t>::digits10 + 1> digits{}; + + /** How many digits there are. */ + std::size_t size = 0; + + /** The digits of `index`. */ + explicit index_key(std::uint64_t index) noexcept + : size(static_cast<std::size_t>( + std::to_chars(digits.data(), digits.data() + digits.size(), index).ptr - + digits.data())) {} + + /** The digits, valid while this object lives. */ + [[nodiscard]] std::string_view view() const noexcept { return {digits.data(), size}; } +}; + +/** + The members `Object.assign` sets from a source's children, in the target document's allocator: + the keys in UTF-8, all in one buffer, and an entry per child that copies its value. + + The keys are copied, not views of the source: the tree may move the source's image while it finds + its room, when the source is the target's document. +*/ +template <class Traits, class Allocator> +class assigned_members { +public: + /** + Stages the children of the node `parent` of `from`, each keyed by its index when `elements`; + only the allocator's `std::bad_alloc` can leave it. + */ + assigned_members(const tree_view<Traits>& from, const node<Traits>& parent, bool elements, + const Allocator& alloc) + : keys_(rebound<Allocator, char>(alloc)), + entries_(rebound<Allocator, literal_entry<Traits>>(alloc)) { + std::size_t count = 0; + std::size_t bytes = 0; + for (const node<Traits>* c = from.first_child(parent.id); c != nullptr; + c = from.next_sibling(*c)) { + ++count; + bytes += elements ? index_key(c->ordinal).size : key_size(*c); + } + // Sized once, so that no key moves after an entry points at it. + keys_.resize(bytes); + entries_.resize(count); + std::size_t at = 0; + std::size_t i = 0; + for (const node<Traits>* c = from.first_child(parent.id); c != nullptr; + c = from.next_sibling(*c), ++i) { + const std::size_t size = elements ? write_index(c->ordinal, at) : write_key(*c, at); + entries_[i].key = std::string_view(keys_.data() + at, size); + entries_[i].value.from = &from; + entries_[i].value.from_id = c->id; + at += size; + } + } + + /** The entries, valid while this object lives. */ + [[nodiscard]] std::span<const literal_entry<Traits>> entries() const noexcept { + return entries_; + } + +private: + /** Whether keys are stored as UTF-16 code units. */ + static constexpr bool utf16_text = std::same_as<typename Traits::string, utf16>; + + /** The size of the UTF-8 of the key of `n`. */ + static std::size_t key_size(const node<Traits>& n) noexcept { + if constexpr (utf16_text) { + return static_cast<std::size_t>(utf8_size(n.key.units())); + } else { + return n.key.chars().size(); + } + } + + /** Writes the digits of `index` at `at` of the keys; their count. */ + std::size_t write_index(std::uint64_t index, std::size_t at) noexcept { + const index_key key(index); + std::ranges::copy(key.view(), keys_.begin() + static_cast<std::ptrdiff_t>(at)); + return key.size; + } + + /** Writes the UTF-8 of the key of `n` at `at` of the keys; its size. */ + std::size_t write_key(const node<Traits>& n, std::size_t at) noexcept { + if constexpr (utf16_text) { + return static_cast<std::size_t>(to_utf8(n.key.units(), keys_.data() + at)); + } else { + std::ranges::copy(n.key.chars(), keys_.begin() + static_cast<std::ptrdiff_t>(at)); + return n.key.chars().size(); + } + } + + /** The keys, one after another. */ + std::vector<char, rebound<Allocator, char>> keys_; + + /** The entries, in the source's order. */ + std::vector<literal_entry<Traits>, rebound<Allocator, literal_entry<Traits>>> entries_; +}; + /** What the library's other parts reach inside documents and handles: their tree and their node. */ struct access { /** The tree of a document, or null when it was moved from. */ template <class Traits, class Storage> - static tree<Traits>* tree_of(basic_document<Traits, Storage>& d) noexcept { + static tree<Traits, typename Storage::allocator_type>* tree_of( + basic_document<Traits, Storage>& d) noexcept { return d.region_.data() == nullptr ? nullptr : &d.tree_; } /** The tree of a document, or null when it was moved from. */ template <class Traits, class Storage> - static const tree<Traits>* tree_of(const basic_document<Traits, Storage>& d) noexcept { + static const tree<Traits, typename Storage::allocator_type>* tree_of( + const basic_document<Traits, Storage>& d) noexcept { return d.region_.data() == nullptr ? nullptr : &d.tree_; } /** The tree of a handle's document, or null when it names nothing. */ template <class Traits, class Storage> - static const tree<Traits>* tree_of(const basic_const_value<Traits, Storage>& v) noexcept { + static const tree<Traits, typename Storage::allocator_type>* tree_of( + const basic_const_value<Traits, Storage>& v) noexcept { return v.tree_ptr(); } @@ -232,7 +367,8 @@ struct access { /** The document of a region whose tree was formatted or attached, the tree rebound to it. */ template <class Traits, class Storage> - static basic_document<Traits, Storage> make_document(region r) noexcept { + static basic_document<Traits, Storage> make_document( + basic_region<typename Storage::allocator_type> r) noexcept { return basic_document<Traits, Storage>(std::move(r)); } }; @@ -248,6 +384,11 @@ struct access { the document grows and its image moves; it reads `undefined` once its node is erased, and is invalid once its document is moved from or destroyed. + A handle of a missing member holds its key, in the document's allocator, so making or copying one + of a long key allocates there; with exceptions, a key the allocator has no room for is not held, + and the handle reads `undefined` and fails a change with @ref errc::capacity. Any other handle + allocates nothing. + @tparam Traits The document's traits. @tparam Storage The document's storage. @see "Handles", in the guide. @@ -382,7 +523,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { [[nodiscard]] result<T> get() const noexcept requires detail::readable<Traits, T> { - const detail::tree<Traits>* t = tree_ptr(); + const auto* t = tree_ptr(); if (t == nullptr) { return errc::type; } @@ -562,7 +703,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { @return A new owned document holding the array of the copies; @ref errc::type for any other kind, @ref errc::capacity when it does not fit. */ - [[nodiscard]] result<basic_document<Traits, owned>> slice( + [[nodiscard]] result<basic_document<Traits, detail::owned_of<Storage>>> slice( std::int64_t start = 0, std::int64_t stop = std::numeric_limits<std::int64_t>::max()) const noexcept; @@ -575,7 +716,8 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { @ref errc::capacity when it does not fit. */ template <class... T> - [[nodiscard]] result<basic_document<Traits, owned>> concat(const T&... v) const noexcept + [[nodiscard]] result<basic_document<Traits, detail::owned_of<Storage>>> concat( + const T&... v) const noexcept requires(detail::settable<Traits, T> && ...); /** @@ -636,13 +778,69 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { return equals(a, b); } + /** + A handle of the same place; a missing member's key is copied in the allocator of the + document, not in the one `select_on_container_copy_construction` gives. + + @param other The handle. + */ + basic_const_value(const basic_const_value& other) noexcept + : doc_(other.doc_), + id_(other.id_), + index_(other.index_), + key_(detail::copy_key(other.key_)), + place_(other.place_) {} + + /** + A handle of the same place, which takes a missing member's key. + + @param other The handle. + */ + basic_const_value(basic_const_value&& other) noexcept = default; + + /** + Makes this a handle of the place of `other`, a missing member's key copied in the allocator of + `other`'s document. + + @param other The handle. + @return This handle. + */ + basic_const_value& operator=(const basic_const_value& other) noexcept { + if (this != &other) { + assign(other, detail::copy_key(other.key_)); + } + return *this; + } + + /** + Makes this a handle of the place of `other`, taking a missing member's key. + + @param other The handle. + @return This handle. + */ + basic_const_value& operator=(basic_const_value&& other) noexcept { + if (this != &other) { + assign(other, std::move(other.key_)); + } + return *this; + } + + /** Gives back a missing member's key. */ + ~basic_const_value() = default; + private: - // A missing member's key is held on the process heap, whose exhaustion ends the program, as - // the library tolerates. - // NOLINTBEGIN(bugprone-exception-escape) + /** The allocator of the document's working state. */ + using allocator_type = Storage::allocator_type; + + /** A missing member's key, held in the document's allocator. */ + using key_type = detail::key_string<allocator_type>; + /** A handle of `doc` at the place `where`: the node or container `id`, and a missing element's - `index` or member's `key`. + `index` or member's `key`, held in the document's allocator. + + With exceptions, a key the allocator has no room for is not held: the handle reads + `undefined`, and a change through it fails with @ref errc::capacity. */ basic_const_value(basic_document<Traits, Storage>* doc, detail::place where, std::uint64_t id, std::uint64_t index, std::string_view key) noexcept @@ -650,19 +848,34 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { : doc_(where == detail::place::nothing ? nullptr : doc), id_(where == detail::place::nothing ? 0 : id), index_(where == detail::place::element ? index : 0), - key_(where == detail::place::member ? key : std::string_view()), + key_(where == detail::place::member && doc_ != nullptr + ? detail::hold_key(key, doc_->get_allocator()) + : std::nullopt), place_(doc_ == nullptr ? detail::place::nothing : where) {} - // NOLINTEND(bugprone-exception-escape) + /** Takes the place of `other`, with `key` its key held for this handle. */ + void assign(const basic_const_value& other, std::optional<key_type>&& key) noexcept { + // Emptied first, the key is made anew from `key` with its allocator, not assigned into + // this one's. + key_.reset(); + if (key.has_value()) { + key_.emplace(std::move(*key)); + } + doc_ = other.doc_; + id_ = other.id_; + index_ = other.index_; + place_ = other.place_; + } /** The tree of the handle's document, or null when it names nothing or the document none. */ - [[nodiscard]] const detail::tree<Traits>* tree_ptr() const noexcept { + [[nodiscard]] const detail::tree<Traits, typename Storage::allocator_type>* tree_ptr() + const noexcept { return doc_ == nullptr ? nullptr : detail::access::tree_of(std::as_const(*doc_)); } /** The node the handle names now, or null when it reads `undefined`. */ [[nodiscard]] const detail::node<Traits>* resolve() const noexcept { - const detail::tree<Traits>* t = tree_ptr(); + const auto* t = tree_ptr(); if (t == nullptr) { return nullptr; } @@ -670,7 +883,9 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { const detail::node<Traits>* n = nullptr; switch (place_) { case detail::place::node: n = t->find(id_); break; - case detail::place::member: n = t->member(id_, key_); break; + case detail::place::member: + n = key_.has_value() ? t->member(id_, std::string_view(*key_)) : nullptr; + break; case detail::place::element: n = t->element(id_, index_); break; case detail::place::nothing: break; } @@ -729,8 +944,11 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { /** A missing element's index. */ std::uint64_t index_ = 0; - /** A missing member's key, in UTF-8. */ - std::string key_; + /** + A missing member's key, in UTF-8, in the document's allocator; none for another place, and + none for a missing member whose key the allocator had no room for. + */ + std::optional<key_type> key_; /** What the handle names. */ detail::place place_ = detail::place::nothing; @@ -856,7 +1074,9 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, @ref date_ms (within JavaScript's range, else @ref errc::range); `nullptr` or @ref null; the literals @ref object and @ref array; a handle or a document of the same traits, copied deeply; and @ref undefined, which erases a member, stores `null` in an element and makes a root hold - `undefined`. Numbers are stored by value. + `undefined`. Numbers are stored by value. A change this place cannot take is refused before + the value is prepared, so that a refusal allocates nothing and comes before the value's own + errors. @tparam T The value's type. @param v The value. @@ -880,11 +1100,17 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, return store_undefined(); } // The tree reads the source before it changes anything, so it may be this tree. - detail::prepared<Traits> p; - p.copy_of(*from, n->id); - return store(p.value()); + detail::item<Traits> copy; + copy.from = from; + copy.from_id = n->id; + return store(copy); } else { - detail::prepared<Traits> p; + // A change this place cannot take is refused before the value is prepared, so that a + // refusal allocates nothing. + if (const result<void> refused = refusal(); !refused.has_value()) { + return refused; + } + detail::prepared<Traits, allocator_type> p(this->doc_->get_allocator()); if (const auto made = detail::prepare(v, p); !made.has_value()) { return made; } @@ -906,9 +1132,6 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, return writable_tree()->erase_member(n->id, key); } - // The source's keys and ids are staged on the process heap, whose exhaustion ends the program, - // as the library tolerates. - // NOLINTBEGIN(bugprone-exception-escape) /** `Object.assign(v, source)`: sets each member of `source` here, in its order, as one operation. @@ -933,27 +1156,15 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, if (!elements && s->kind != webcpp::document::kind::object) { return errc::type; } - const detail::tree<Traits>& from = *source.tree_ptr(); - // The keys are owned here, in UTF-8, before an entry points at one: the tree may move the - // source's image while it finds its room, when the source is this document. - std::vector<std::string> keys; - std::vector<std::uint64_t> ids; - for (const detail::node<Traits>* c = from.first_child(s->id); c != nullptr; - c = from.next_sibling(*c)) { - keys.push_back(elements ? std::to_string(c->ordinal) : utf8_key(*c)); - ids.push_back(c->id); - } - std::vector<detail::literal_entry<Traits>> entries(keys.size()); - for (std::size_t i = 0; i < keys.size(); ++i) { - entries[i].key = keys[i]; - entries[i].value.from = &from; - entries[i].value.from_id = ids[i]; - } - return writable_tree()->set_members(target->id, entries); + const detail::tree_view<Traits>& from = *source.tree_ptr(); + auto* t = writable_tree(); + return detail::bad_alloc_as_capacity([&]() -> result<void> { + const detail::assigned_members<Traits, allocator_type> members(from, *s, elements, + t->get_allocator()); + return t->set_members(target->id, members.entries()); + }); } - // NOLINTEND(bugprone-exception-escape) - /** `Array.prototype.push`: appends each value. @@ -972,7 +1183,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, @return A new owned document holding it, or holding `undefined` when the array is empty; @ref errc::type for any other kind. */ - [[nodiscard]] result<basic_document<Traits, owned>> pop() noexcept; + [[nodiscard]] result<basic_document<Traits, detail::owned_of<Storage>>> pop() noexcept; /** `Array.prototype.shift`: removes the first element. @@ -980,7 +1191,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, @return A new owned document holding it, or holding `undefined` when the array is empty; @ref errc::type for any other kind. */ - [[nodiscard]] result<basic_document<Traits, owned>> shift() noexcept; + [[nodiscard]] result<basic_document<Traits, detail::owned_of<Storage>>> shift() noexcept; /** `Array.prototype.unshift`: inserts each value at the front, in order. @@ -1009,9 +1220,8 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, @see "Arrays", in the guide. */ template <class... T> - [[nodiscard]] result<basic_document<Traits, owned>> splice(std::int64_t start, - std::int64_t count, - const T&... v) noexcept + [[nodiscard]] result<basic_document<Traits, detail::owned_of<Storage>>> splice( + std::int64_t start, std::int64_t count, const T&... v) noexcept requires(detail::settable<Traits, T> && ...); /** @@ -1021,7 +1231,8 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, @return A new owned document holding the array of the removed elements; @ref errc::type for any other kind. */ - [[nodiscard]] result<basic_document<Traits, owned>> splice(std::int64_t start) noexcept; + [[nodiscard]] result<basic_document<Traits, detail::owned_of<Storage>>> splice( + std::int64_t start) noexcept; /** `Array.prototype.reverse`: reverses the elements in place. @@ -1075,21 +1286,25 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, friend class basic_const_value; friend struct detail::access; + /** The allocator of the document's working state. */ + using allocator_type = Storage::allocator_type; + /** A handle of `doc` at the place `where`, as the read-only handle's. */ basic_value(basic_document<Traits, Storage>* doc, detail::place where, std::uint64_t id, std::uint64_t index, std::string_view key) noexcept : basic_const_value<Traits, Storage>(doc, where, id, index, key) {} /** The tree of the handle's document, to write; null when it names nothing. */ - [[nodiscard]] detail::tree<Traits>* writable_tree() const noexcept { + [[nodiscard]] detail::tree<Traits, typename Storage::allocator_type>* writable_tree() + const noexcept { return this->doc_ == nullptr ? nullptr : detail::access::tree_of(*this->doc_); } /** Where a deep copy of a document reads: its tree and its root; none when moved from. */ template <class S> - static result<std::pair<const detail::tree<Traits>*, const detail::node<Traits>*>> copy_from( - const basic_document<Traits, S>& d) noexcept { - const detail::tree<Traits>* t = detail::access::tree_of(d); + static result<std::pair<const detail::tree_view<Traits>*, const detail::node<Traits>*>> + copy_from(const basic_document<Traits, S>& d) noexcept { + const detail::tree_view<Traits>* t = detail::access::tree_of(d); if (t == nullptr) { return errc::type; } @@ -1098,33 +1313,64 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, /** Where a deep copy of a handle's value reads: its tree and its node, null for undefined. */ template <class S> - static result<std::pair<const detail::tree<Traits>*, const detail::node<Traits>*>> copy_from( - const basic_const_value<Traits, S>& v) noexcept { + static result<std::pair<const detail::tree_view<Traits>*, const detail::node<Traits>*>> + copy_from(const basic_const_value<Traits, S>& v) noexcept { return std::pair(detail::access::tree_of(v), detail::access::node_of(v)); } - /** A key of `n`, in UTF-8: what the tree's operations take. */ - static std::string utf8_key(const detail::node<Traits>& n) { - if constexpr (std::same_as<typename Traits::string, utf16>) { - const std::u16string_view units = n.key.units(); - std::string out(static_cast<std::size_t>(detail::utf8_size(units)), '\0'); - detail::to_utf8(units, out.data()); - return out; - } else { - return std::string(n.key.chars()); + /** + Why a change of this place is refused before anything is prepared for it: @ref errc::type for + a handle of nothing, a document that holds nothing, a node no longer there, a missing member + of what is no object or of a key that is not UTF-8, and a missing element of what is no array; + @ref errc::capacity for a missing member whose key found no room. Success otherwise. + */ + [[nodiscard]] result<void> refusal() const noexcept { + const auto* t = writable_tree(); + if (t == nullptr) { + return errc::type; } + const auto is = [t](std::uint64_t id, webcpp::document::kind k) { + const detail::node<Traits>* n = t->find(id); + return n != nullptr && n->kind == k; + }; + switch (this->place_) { + case detail::place::node: + if (t->find(this->id_) == nullptr) { + return errc::type; + } + return {}; + case detail::place::member: + if (!this->key_.has_value()) { + return errc::capacity; + } + if (!is(this->id_, webcpp::document::kind::object) || + !detail::valid_utf8(std::string_view(*this->key_))) { + return errc::type; + } + return {}; + case detail::place::element: + if (!is(this->id_, webcpp::document::kind::array)) { + return errc::type; + } + return {}; + case detail::place::nothing: break; + } + return errc::type; } /** Stores an item at this place: the node replaced, or the member or element created. */ result<void> store(const detail::item<Traits>& v) noexcept { - detail::tree<Traits>* t = writable_tree(); + auto* t = writable_tree(); if (t == nullptr) { return errc::type; } switch (this->place_) { case detail::place::node: return t->assign(this->id_, v); case detail::place::member: { - const auto set = t->set_member(this->id_, this->key_, v); + if (!this->key_.has_value()) { + return errc::capacity; + } + const auto set = t->set_member(this->id_, std::string_view(*this->key_), v); if (!set.has_value()) { return set.error(); } @@ -1136,22 +1382,22 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, return errc::type; } - // A member's key is turned into UTF-8 on the process heap, whose exhaustion ends the program, - // as the library tolerates. - // NOLINTBEGIN(bugprone-exception-escape) /** Stores `undefined` at this place: a member erased, an element `null`, a root holding `undefined`. */ result<void> store_undefined() noexcept { - detail::tree<Traits>* t = writable_tree(); + auto* t = writable_tree(); if (t == nullptr) { return errc::type; } switch (this->place_) { case detail::place::node: break; case detail::place::member: { - const auto erased = t->erase_member(this->id_, this->key_); + if (!this->key_.has_value()) { + return errc::capacity; + } + const auto erased = t->erase_member(this->id_, std::string_view(*this->key_)); if (!erased.has_value()) { return erased.error(); } @@ -1174,14 +1420,13 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, parent->kind == webcpp::document::kind::array) { return t->assign(this->id_, detail::empty_item<Traits>(webcpp::document::kind::null)); } - const auto erased = t->erase_member(n->parent, utf8_key(*n)); + // By its id: nothing is looked up by key, transcoded or allocated, and nothing can fail. + const auto erased = t->erase_member_by_id(n->parent, n->id); if (!erased.has_value()) { return erased.error(); } return {}; } - - // NOLINTEND(bugprone-exception-escape) }; /** A handle of a @ref document, reading and writing. */ @@ -1190,6 +1435,24 @@ using value = basic_value<>; /** A handle of a @ref document, read only. */ using const_value = basic_const_value<>; +namespace pmr { + +/** + A handle of a `pmr::document`, reading and writing. + + @see "Allocators", in the guide. +*/ +using value = webcpp::document::basic_value<default_traits, owned>; + +/** + A handle of a `pmr::document`, read only. + + @see "Allocators", in the guide. +*/ +using const_value = webcpp::document::basic_const_value<default_traits, owned>; + +} // namespace pmr + // The members below make handles, which are complete only here. template <class Traits, class Storage> @@ -1230,16 +1493,14 @@ basic_const_value<Traits, Storage> basic_document<Traits, Storage>::operator[]( namespace detail { -// A handle of a node holds no key, so copying one allocates nothing; were it to, the process heap's -// exhaustion would end the program, as the library tolerates. -// NOLINTBEGIN(bugprone-exception-escape) template <class Traits, class Storage, children_of Kind> auto children_iterator<Traits, Storage, Kind>::operator*() const noexcept -> value_type { if constexpr (Kind == children_of::values) { return basic_const_value<Traits, Storage>(doc_, place::node, child_, 0, {}); } else { // A key is a view of the image, valid until the document's next change. - const tree<Traits>* t = doc_ == nullptr ? nullptr : access::tree_of(std::as_const(*doc_)); + const tree_view<Traits>* t = + doc_ == nullptr ? nullptr : access::tree_of(std::as_const(*doc_)); const node<Traits>* n = t == nullptr ? nullptr : t->find(child_); text_view_t<Traits> key; if (n != nullptr) { @@ -1258,12 +1519,10 @@ auto children_iterator<Traits, Storage, Kind>::operator*() const noexcept -> val } } -// NOLINTEND(bugprone-exception-escape) - template <class Traits, class Storage, children_of Kind> children_iterator<Traits, Storage, Kind>& children_iterator<Traits, Storage, Kind>::operator++() noexcept { - const tree<Traits>* t = doc_ == nullptr ? nullptr : access::tree_of(std::as_const(*doc_)); + const tree_view<Traits>* t = doc_ == nullptr ? nullptr : access::tree_of(std::as_const(*doc_)); const node<Traits>* n = t == nullptr ? nullptr : t->find(child_); const node<Traits>* next = n == nullptr ? nullptr : t->next_sibling(*n); child_ = next == nullptr ? 0 : next->id; @@ -1273,7 +1532,7 @@ children_iterator<Traits, Storage, Kind>::operator++() noexcept { template <class Traits, class Storage, children_of Kind> children_iterator<Traits, Storage, Kind> children<Traits, Storage, Kind>::begin() const noexcept { // The root's parent is 0: the children of 0 are those of nothing, not the root. - const tree<Traits>* t = + const tree_view<Traits>* t = doc_ == nullptr || parent_ == 0 ? nullptr : access::tree_of(std::as_const(*doc_)); const node<Traits>* first = t == nullptr ? nullptr : t->first_child(parent_); return {doc_, first == nullptr ? 0 : first->id}; diff --git a/test/Jamfile b/test/Jamfile index a830500..1328cb4 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -68,6 +68,9 @@ webcpp.run image : image_test.cpp ; # grow there. webcpp.run stringify : stringify_test.cpp : <toolset>emscripten:<linkflags>-sALLOW_MEMORY_GROWTH ; +# quote, a string alone as JSON.stringify quotes it, into the caller's string, +# which alone allocates. +webcpp.run quote : quote_test.cpp ; # parse, whole or in chunks, as JSON.parse reads; and the parse that throws. A # 64 MB string, an object of 100,000 keys and 800 KB of zeros outgrow # Emscripten's initial 16 MB, so its memory may grow. @@ -123,6 +126,24 @@ webcpp.run shared : shared_test.cpp ; webcpp.run shared_interprocess : shared_test.cpp : <exception-handling>on <define>WEBCPP_TEST_DOCUMENT_INTERPROCESS : native ; +# A document's allocator: the image created, grown, copied and moved in a +# resource, between resources and in an allocator of the program's own, with no +# call of the global operator new, which counting.cpp counts; and an allocator +# with no room, errc::capacity. +webcpp.run allocator : allocator_test.cpp counting.cpp ; +# The working state of a document's operations in its allocator, with no call +# of the global operator new: the tree's changes, the handles' and the +# conversions', the parser's and the writer's. Their arenas of several MB +# outgrow Emscripten's initial 16 MB, so its memory may grow. +webcpp.run allocator_tree : allocator_tree_test.cpp counting.cpp + : <toolset>emscripten:<linkflags>-sALLOW_MEMORY_GROWTH ; +webcpp.run allocator_values : allocator_values_test.cpp counting.cpp + : <toolset>emscripten:<linkflags>-sALLOW_MEMORY_GROWTH ; +webcpp.run allocator_parse : allocator_parse_test.cpp counting.cpp + : <toolset>emscripten:<linkflags>-sALLOW_MEMORY_GROWTH ; +webcpp.run allocator_stringify : allocator_stringify_test.cpp counting.cpp + : <toolset>emscripten:<linkflags>-sALLOW_MEMORY_GROWTH ; + # Compact images: equal content gives equal bytes, the exact size, a caller's # buffer. webcpp.run compact : compact_test.cpp ; diff --git a/test/allocator_parse_test.cpp b/test/allocator_parse_test.cpp new file mode 100644 index 0000000..cdacfaa --- /dev/null +++ b/test/allocator_parse_test.cpp @@ -0,0 +1,854 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The parser's working state in the document's allocator. A text given whole, to parse, to +// parse_into or to a parser's finish, with selectors or without, under both traits and with the +// revivers, makes no call of the global operator new, and the resource gets back all it gave. A +// text fed in chunks calls it only for Boost.JSON's suspension stack, exactly as often as that +// stack's rule says. finish_with(text) is write(text) then finish(), its errors, offsets and causes +// included. With exceptions, an allocator that runs out at any step is errc::capacity, with no +// document, and a selector it cannot hold is not added. + +#include <webcpp/document.hpp> + +#include <boost/core/lightweight_test.hpp> + +#include "counting.hpp" +#include "parse_corpus.hpp" +#include "require.hpp" + +#include <algorithm> +#include <array> +#include <cstddef> +#include <cstdint> +#include <iostream> +#include <memory> +#include <memory_resource> +#include <string> +#include <string_view> +#include <type_traits> +#include <vector> + +namespace wd = webcpp::document; + +namespace { + +using webcpp::test::arena; +using webcpp::test::global_count; +using webcpp::test::require; + +constexpr std::size_t mebibyte = std::size_t{1} << 20U; + +/** A parser of the traits `Traits` whose working state is in a memory resource. */ +template <class Traits> +using pmr_parser = wd::basic_parser<Traits, wd::pmr::owned>; + +/** Whether two documents' images are the same bytes; it allocates nothing. */ +template <class A, class B> +bool same_image(const A& a, const B& b) noexcept { + return std::ranges::equal(a.image(), b.image()); +} + +/** Text as JSON writes it, and as a parse reads it. */ +struct text_pair { + /** The text in JSON, escapes among its characters. */ + std::string json; + + /** The text it reads as, in UTF-8. */ + std::string read; +}; + +/** + A key or a string of more than 100 bytes, longer than any small-string buffer, whose JSON holds + every kind of escape and raw multi-byte characters; `tag` tells keys of one object apart. +*/ +text_pair long_text(char tag) { + text_pair made; + for (std::size_t i = 0; i < 4; ++i) { + made.json += tag; + made.json += R"( quote \" backslash \\ newline \n tab \t e é smile 😀 )"; + made.json += "raw \xc3\xa9\xe2\x82\xac "; + made.read += tag; + made.read += " quote \" backslash \\ newline \n tab \t e \xc3\xa9 smile \xf0\x9f\x98\x80 "; + made.read += "raw \xc3\xa9\xe2\x82\xac "; + } + return made; +} + +/** The selector of a member of the root by its key, as read: its `'` and `\` escaped. */ +std::string member_selector(std::string_view key) { + std::string selector = "$['"; + for (const char c : key) { + if (c == '\'' || c == '\\') { + selector += '\\'; + } + selector += c; + } + selector += "']"; + return selector; +} + +/** Arrays and objects in turn, `depth` of them, around a number: `[{"k":[{"k":...1...}]}]`. */ +std::string nested(std::size_t depth) { + std::string open; + std::string close; + for (std::size_t i = 0; i < depth; ++i) { + if (i % 2 == 0) { + open += '['; + close.insert(close.begin(), ']'); + } else { + open += R"({"k":)"; + close.insert(close.begin(), '}'); + } + } + return open + "1" + close; +} + +/** Base64 text of `count` bytes, a multiple of three, which revive_bytes turns into bytes. */ +std::string base64_of(std::size_t count) { + // Every three bytes "foo" are "Zm9v". + std::string text; + for (std::size_t i = 0; i < count / 3; ++i) { + text += "Zm9v"; + } + return text; +} + +/** An object of the shape JSON.stringify gives a Uint8Array of `count` bytes. */ +std::string javascript_bytes_of(std::size_t count) { + std::string text = "{"; + for (std::size_t i = 0; i < count; ++i) { + text += i == 0 ? "\"" : ",\""; + text += std::to_string(i); + text += "\":"; + text += std::to_string(i % 256); + } + text += '}'; + return text; +} + +/** A text to parse, with the options it is parsed with, and its name for a failure's message. */ +struct sample { + /** What the text holds. */ + std::string name; + + /** The text. */ + std::string text; + + /** The options. */ + wd::parse_options options; +}; + +/** The options with dates revived. */ +wd::parse_options reviving_dates() { + wd::parse_options o; + o.revive_dates = true; + return o; +} + +/** The options with bytes revived. */ +wd::parse_options reviving_bytes() { + wd::parse_options o; + o.revive_bytes = true; + return o; +} + +/** The texts every parse of a whole text reads, under both traits. */ +std::vector<sample> samples() { + const text_pair key = long_text('k'); + const text_pair other = long_text('o'); + const text_pair value = long_text('v'); + std::vector<sample> made; + made.push_back({ + .name = "an object", + .text = R"({"name":"document","list":[1,2.5,"three",[true,null]],"x":{}})", + .options = wd::parse_options(), + }); + made.push_back({ + .name = "arrays", + .text = R"([[],[{}],[1,[2,[3,[4]]]],"",0,[true,false,null]])", + .options = wd::parse_options(), + }); + made.push_back({ + .name = "nesting 50 deep", + .text = nested(50), + .options = wd::parse_options(), + }); + made.push_back({ + .name = "numbers", + .text = "[0,-0,1,-1,1.5,-2.25e-3,1e400,123456789012345678," + "-9223372036854775808,9223372036854775808,0.1," + "12345678901234567890123456789012]", + .options = wd::parse_options(), + }); + made.push_back({ + .name = "long strings and keys", + .text = R"({")" + key.json + R"(":")" + value.json + R"(",")" + other.json + R"(":[")" + + value.json + R"(",{")" + key.json + R"(":1}],")" + key.json + R"(":"replaced"})", + .options = wd::parse_options(), + }); + made.push_back({ + .name = "dates revived", + .text = R"(["2026-10-12T03:04:05.678Z","2026-10-12",)" + R"({"when":"1970-01-01T00:00:00.000Z"}])", + .options = reviving_dates(), + }); + made.push_back({ + .name = "bytes revived", + .text = R"(["Zm9v","Zm9v!",")" + base64_of(150) + R"(",{"0":1}])", + .options = reviving_bytes(), + }); + made.push_back({ + .name = "javascript bytes revived", + .text = R"({"u":{"0":102,"1":111,"2":111},"gap":{"0":1,"2":2},"big":{"0":256},)" + R"("s":"Zm9v","long":)" + + javascript_bytes_of(120) + "}", + .options = reviving_bytes(), + }); + return made; +} + +/** Names the sample a failed check was about, outside any counted region. */ +void name_on_failure(bool held, const sample& s) { + if (!held) { + std::cerr << " in the sample: " << s.name << '\n'; + } +} + +/** A buffer of an external document, 16-aligned, made before anything is counted. */ +struct block { + /** The bytes. */ + alignas(16) std::array<std::byte, std::size_t{512} * 1024> bytes; +}; + +// parse of a whole text in a resource calls no global operator new: the image and every byte of +// the parse's working state come from the resource, which gets all of it back once the document +// is gone; and the image is the one the default storage makes. +template <class Traits> +void parse_calls_no_global_new(const sample& s) { + const auto reference = wd::parse<Traits>(s.text, s.options); + require(BOOST_TEST(reference.has_value())); + arena a(16 * mebibyte); + bool held = true; + std::uint64_t news = 0; + { + const global_count global; + { + const auto made = wd::parse<Traits>(s.text, s.options, a.allocator()); + held = BOOST_TEST(made.has_value()) && BOOST_TEST(same_image(*made, *reference)); + } + news = global.news(); + } + held = BOOST_TEST_EQ(news, 0U) && held; + held = BOOST_TEST_GT(a.resource().allocations(), 0U) && held; + name_on_failure(BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U) && held, s); +} + +// parse_into of a whole text calls no global operator new: its working state comes from the +// resource, which gets all of it back. +template <class Traits> +void parse_into_calls_no_global_new(const sample& s) { + const auto buffers = std::make_unique<std::array<block, 2>>(); + const auto reference = wd::parse_into<Traits>((*buffers)[0].bytes, s.text, s.options); + require(BOOST_TEST(reference.has_value())); + arena a(16 * mebibyte); + bool held = true; + std::uint64_t news = 0; + { + const global_count global; + { + const auto made = + wd::parse_into<Traits>((*buffers)[1].bytes, s.text, s.options, a.allocator()); + held = BOOST_TEST(made.has_value()) && BOOST_TEST(same_image(*made, *reference)); + } + news = global.news(); + } + held = BOOST_TEST_EQ(news, 0U) && held; + name_on_failure(BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U) && held, s); +} + +/** The selectors a parser registers, in the order it registers them. */ +enum selector_index : std::uint8_t { items, meta, deep, members, long_member, selector_count }; + +/** What the selectors of a parser were given, counted without allocating. */ +struct tally { + /** The deliveries to each selector. */ + std::array<std::uint64_t, selector_count> deliveries{}; + + /** The deliveries whose path or value was not the one expected. */ + std::uint64_t wrong = 0; + + friend bool operator==(const tally&, const tally&) = default; +}; + +/** The text the selectors read, and what they select, made before anything is counted. */ +struct selected { + /** The text. */ + std::string text; + + /** The long key, read. */ + std::string key; + + /** The selector of the root's member of the long key. */ + std::string long_member; + + /** The selector of the deep value under the long key. */ + std::string deep; +}; + +/** The text the selectors read: metadata, items, and a long key holding a deep value. */ +selected selected_text() { + const text_pair key = long_text('k'); + const text_pair value = long_text('v'); + selected made; + made.text = R"({"meta":{"n":2,")" + key.json + R"(":")" + value.json + + R"("},"items":[{"id":0,")" + key.json + R"(":[1,2]},{"id":1},{"id":2}],")" + + key.json + R"(":{"deep":[[[7]]],"s":")" + value.json + R"("}})"; + made.key = key.read; + made.long_member = member_selector(key.read); + made.deep = made.long_member + ".deep[0][0][*]"; + return made; +} + +/** Counts the one value the deep selector delivers, at the end of a path through the long key. */ +template <class Value> +void count_deep(tally& t, const selected& s, const Value& v, wd::path_view where) { + ++t.deliveries[deep]; + if (where.size() != 5 || where.key(0) != s.key || where.key(1) != "deep" || + where.index(4) != 0 || v.value_or(std::int64_t{0}) != 7) { + ++t.wrong; + } +} + +/** + Registers selectors of every kind on `p`, which count what they are given in `t`: `on` and + `observe`, callbacks returning `void` and `result<void>`, selectors with a long key; returns + which were added. +*/ +template <class Parser> +std::array<bool, selector_count> subscribe(Parser& p, tally& t, const selected& s) { + std::array<bool, selector_count> added{}; + added[items] = + p.on("$.items[*]", [&t](const auto& v, wd::path_view where) { + if (where.size() != 2 || where.key(0) != "items" || + v["id"].value_or(std::int64_t{-1}) != static_cast<std::int64_t>(where.index(1))) { + ++t.wrong; + } + ++t.deliveries[items]; + }).has_value(); + added[meta] = p.observe("$.meta", [&t](const auto& v, wd::path_view) -> wd::result<void> { + if (v["n"].value_or(std::int64_t{0}) != 2) { + ++t.wrong; + } + ++t.deliveries[meta]; + return {}; + }).has_value(); + added[deep] = p.observe(s.deep, [&t, &s](const auto& v, wd::path_view where) { + count_deep(t, s, v, where); + }).has_value(); + added[members] = p.observe("$.*.*", [&t](const auto&, wd::path_view) { + ++t.deliveries[members]; + }).has_value(); + added[long_member] = p.observe(s.long_member, [&t, &s](const auto&, wd::path_view where) { + if (where.key(0) != s.key) { + ++t.wrong; + } + ++t.deliveries[long_member]; + }).has_value(); + return added; +} + +/** Whether every selector was added. */ +bool all_added(const std::array<bool, selector_count>& added) noexcept { + return std::ranges::all_of(added, [](bool b) { return b; }); +} + +/** What the selectors are given while a parser of the default storage reads the selected text. */ +template <class Traits> +tally selected_tally() { + const selected s = selected_text(); + tally t; + wd::basic_parser<Traits> p; + require(BOOST_TEST(all_added(subscribe(p, t, s)))); + require(BOOST_TEST(p.finish_with(s.text).has_value())); + // The items, taken; the metadata; the deep value; the members of meta and of the long key's + // object; the long key's object. + BOOST_TEST((t == tally{.deliveries = {3, 1, 1, 4, 1}, .wrong = 0})); + return t; +} + +// A pmr parser registers selectors and is given a whole text by finish_with(text): registration, +// parsing and deliveries call no global operator new; the selectors, their callbacks, the path and +// its long keys are in the resource, which gets all of it back. +template <class Traits> +void selectors_call_no_global_new() { + const selected s = selected_text(); + const tally expected = selected_tally<Traits>(); + tally reference_tally; + wd::basic_parser<Traits> reference_parser; + require(BOOST_TEST(all_added(subscribe(reference_parser, reference_tally, s)))); + const auto reference = reference_parser.finish_with(s.text); + require(BOOST_TEST(reference.has_value())); + + arena a(16 * mebibyte); + tally t; + std::uint64_t news = 0; + { + const global_count global; + { + pmr_parser<Traits> p({}, a.allocator()); + BOOST_TEST(all_added(subscribe(p, t, s))); + const auto made = p.finish_with(s.text); + BOOST_TEST(made.has_value() && same_image(*made, *reference)); + } + news = global.news(); + } + BOOST_TEST_EQ(news, 0U); + BOOST_TEST(t == expected); + BOOST_TEST_GT(a.resource().allocations(), 0U); + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +/** + How many times Boost.JSON allocates its suspension stack, in the global heap, while a parser is + written `text` in chunks of `size` bytes. + + Boost.JSON's parser suspends at the end of each chunk, and reserves its stack for the depth it + suspends at whenever the stack it holds is smaller: so once at the first suspension, then at each + suspension deeper than all before it. Its depth is that of the arrays and objects open at the + chunk's end, a bracket inside a string being none. +*/ +std::uint64_t stack_allocations(std::string_view text, std::size_t size) { + std::uint64_t allocations = 0; + std::int64_t deepest = -1; + std::int64_t depth = 0; + bool quoted = false; + bool escaped = false; + for (std::size_t i = 0; i < text.size(); ++i) { + const char c = text[i]; + if (escaped) { + escaped = false; + } else if (quoted) { + escaped = c == '\\'; + quoted = c != '"'; + } else if (c == '"') { + quoted = true; + } else if (c == '[' || c == '{') { + ++depth; + } else if (c == ']' || c == '}') { + --depth; + } + const bool chunk_ends = (i + 1) % size == 0 || i + 1 == text.size(); + if (chunk_ends && depth > deepest) { + ++allocations; + deepest = depth; + } + } + return allocations; +} + +/** + Writes `text` to `p` in chunks of `size` bytes, then finishes it; returns whether every write + succeeded and the document it finished with is `reference`. +*/ +template <class Parser, class Document> +bool write_in_chunks(Parser& p, std::string_view text, std::size_t size, + const Document& reference) { + for (std::size_t at = 0; at < text.size(); at += size) { + if (!p.write(text.substr(at, size)).has_value()) { + return false; + } + } + const auto made = p.finish(); + return made.has_value() && same_image(*made, reference); +} + +/** + Feeds `text` in chunks of 1, 7 and 64 bytes to a parser in a resource, with the selectors or + without, and checks that it calls the global operator new exactly as often as Boost.JSON's + suspension stack is reserved, frees each of those but the last at the next and the last with the + parser, and has everything else in the resource, which gets all of it back; the selectors are + given what they are given for the whole text. +*/ +template <class Traits> +void chunks_call_only_the_stack(std::string_view text, bool selectors) { + const selected s = selected_text(); + tally reference_tally; + wd::basic_parser<Traits> reference_parser; + if (selectors) { + require(BOOST_TEST(all_added(subscribe(reference_parser, reference_tally, s)))); + } + const auto reference = reference_parser.finish_with(text); + require(BOOST_TEST(reference.has_value())); + for (const std::size_t size : {std::size_t{1}, std::size_t{7}, std::size_t{64}}) { + const std::uint64_t expected = stack_allocations(text, size); + arena a(64 * mebibyte); + tally t; + std::uint64_t news = 0; + std::uint64_t deletes_while_parsing = 0; + std::uint64_t deletes = 0; + { + const global_count global; + { + pmr_parser<Traits> p({}, a.allocator()); + if (selectors) { + BOOST_TEST(all_added(subscribe(p, t, s))); + } + BOOST_TEST(write_in_chunks(p, text, size, *reference)); + deletes_while_parsing = global.deletes(); + } + news = global.news(); + deletes = global.deletes(); + } + BOOST_TEST_EQ(news, expected); + BOOST_TEST_EQ(deletes_while_parsing, expected - 1); + BOOST_TEST_EQ(deletes, expected); + BOOST_TEST(t == reference_tally); + BOOST_TEST_GT(a.resource().allocations(), 0U); + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); + } +} + +// The rule of the stack, on the text nested 50 deep, 101 bytes: in chunks of 1 byte the parser +// suspends at a new depth 50 times; in chunks of 7 at depths 7, 14, ..., 49 before the text turns +// back; in chunks of 64 once, at depth 37. A text of one level in chunks of 1 byte: once; brackets +// in strings count for nothing. +void the_stack_rule() { + const std::string deep = std::string(50, '[') + "1" + std::string(50, ']'); + BOOST_TEST_EQ(stack_allocations(deep, 1), 50U); + BOOST_TEST_EQ(stack_allocations(deep, 7), 7U); + BOOST_TEST_EQ(stack_allocations(deep, 64), 1U); + BOOST_TEST_EQ(stack_allocations("[1,2,3]", 1), 1U); + // A raw string that holds a quote and a backslash stays out of the macro's arguments: MSVC 14.3 + // splits them without reading it as one, and its escape then stands outside any literal. + constexpr std::string_view quoted_brackets = R"(["[[[",{"a":"]\"]"}])"; + BOOST_TEST_EQ(stack_allocations(quoted_brackets, 1), 2U); + chunks_call_only_the_stack<wd::default_traits>(deep, false); +} + +/** + Checks that `finish_with(text)` gives what `write(text)` then `finish()` give: the same document or + error, offset and cause, and the same answer to a later call. +*/ +template <class Traits> +void finish_is_write_then_finish(std::string_view text, const wd::parse_options& o) { + wd::basic_parser<Traits> whole(o); + const auto at_once = whole.finish_with(text); + wd::basic_parser<Traits> split(o); + const wd::result<void> written = split.write(text); + const auto in_two = written.has_value() + ? split.finish() + : wd::result<wd::basic_document<Traits>>(written.error()); + bool held = BOOST_TEST_EQ(at_once.has_value(), in_two.has_value()); + if (held && at_once.has_value()) { + held = BOOST_TEST(same_image(*at_once, *in_two)); + } else if (held) { + held = BOOST_TEST(at_once.error() == in_two.error()); + } + held = BOOST_TEST_EQ(whole.offset(), split.offset()) && held; + held = BOOST_TEST(whole.cause() == split.cause()) && held; + held = BOOST_TEST(whole.write("1").error() == split.write("1").error()) && held; + if (!held) { + std::cerr << " in the text: " << text << '\n'; + } +} + +// finish_with(text) is write(text) then finish(), for every prefix of every text of the corpus, +// which makes every error of a text that ends early, and for texts that fail otherwise: malformed, +// a second text, a number past the traits, past the depth, past the bytes. +template <class Traits> +void finish_is_write_then_finish() { + for (const std::string& text : webcpp::test::parse_corpus()) { + for (std::size_t length = 0; length <= text.size(); ++length) { + finish_is_write_then_finish<Traits>(std::string_view(text).substr(0, length), {}); + } + } + for (const std::string_view text : { + "[1,]", + "[1,2", + "1 2", + R"({"a":1}{"b":2})", + "1x", + "[1] ]", + "", + " ", + "nul", + "tru", + R"("\ud800")", + R"(["\u12)", + "[1e999999999999]", + "12345678901234567890123456789012345", + "-", + "[-]", + "{\"a\"", + "{\"a\":", + "[1,2,3,456]", + "[[[[[1]]]]]", + }) { + finish_is_write_then_finish<Traits>(text, {}); + } + wd::parse_options limited; + limited.max_bytes = 10; + limited.max_depth = 4; + for (const std::string_view text : + {"[1,2,3,45]", "[1,2,3,456]", "[[[[1]]]]", "[[[[[1]]]]]", "[[[[1]]]] ", "[1,2,3,4] x"}) { + finish_is_write_then_finish<Traits>(text, limited); + } +} + +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + +/** An allocator of `resource`. */ +std::pmr::polymorphic_allocator<std::byte> allocator_of(std::pmr::memory_resource& resource) { + return {&resource}; +} + +/** More allocations than any parse here makes. */ +constexpr std::uint64_t plenty = std::uint64_t{1} << 40U; + +// A parse whose allocator runs out at any allocation is errc::capacity, with no document and +// every block given back; given room for every allocation it parses the text, refusing none. +template <class Traits> +void parse_runs_out(const sample& s) { + const auto reference = wd::parse<Traits>(s.text, s.options); + require(BOOST_TEST(reference.has_value())); + std::uint64_t failed = 0; + for (std::uint64_t budget = 0;; ++budget) { + webcpp::test::failing_resource failing(std::pmr::new_delete_resource(), budget); + bool parsed = false; + bool held = true; + { + const auto made = wd::parse<Traits>(s.text, s.options, allocator_of(failing)); + if (made.has_value()) { + parsed = true; + held = BOOST_TEST(same_image(*made, *reference)); + held = BOOST_TEST_EQ(failing.refusals(), 0U) && held; + } else { + ++failed; + held = BOOST_TEST(made.error() == wd::errc::capacity); + held = BOOST_TEST_GT(failing.refusals(), 0U) && held; + } + } + name_on_failure(BOOST_TEST_EQ(failing.bytes_in_use(), 0U) && held, s); + if (parsed) { + break; + } + } + name_on_failure(BOOST_TEST_GT(failed, 0U), s); +} + +// parse_into whose allocator runs out at any allocation is errc::capacity, with no document and +// every block given back. +template <class Traits> +void parse_into_runs_out(const sample& s) { + const auto buffers = std::make_unique<std::array<block, 2>>(); + const auto reference = wd::parse_into<Traits>((*buffers)[0].bytes, s.text, s.options); + require(BOOST_TEST(reference.has_value())); + std::uint64_t failed = 0; + for (std::uint64_t budget = 0;; ++budget) { + webcpp::test::failing_resource failing(std::pmr::new_delete_resource(), budget); + bool parsed = false; + bool held = true; + { + const auto made = wd::parse_into<Traits>((*buffers)[1].bytes, s.text, s.options, + allocator_of(failing)); + if (made.has_value()) { + parsed = true; + held = BOOST_TEST(same_image(*made, *reference)); + } else { + ++failed; + held = BOOST_TEST(made.error() == wd::errc::capacity); + } + } + name_on_failure(BOOST_TEST_EQ(failing.bytes_in_use(), 0U) && held, s); + if (parsed) { + break; + } + } + name_on_failure(BOOST_TEST_GT(failed, 0U), s); +} + +/** + Checks a parser whose registrations ran out: given room again, it reads the text, and each + selector it added is given what it is given when all are, the others nothing. +*/ +template <class Parser> +void refused_selectors_were_not_added(Parser& p, webcpp::test::failing_resource& failing, + const std::array<bool, selector_count>& added, const tally& t, + const tally& expected, std::string_view text) { + failing.allow(plenty); + BOOST_TEST(p.finish_with(text).has_value()); + for (std::size_t i = 0; i < selector_count; ++i) { + BOOST_TEST_EQ(t.deliveries[i], added[i] ? expected.deliveries[i] : 0U); + } + BOOST_TEST_EQ(t.wrong, 0U); +} + +/** + Checks a parser whose allocator ran out while it read a text: it failed with errc::capacity and + stays failed, whatever it is given, until it is reset. +*/ +template <class Parser> +void a_parser_that_ran_out_stays_failed(Parser& p, webcpp::test::failing_resource& failing) { + BOOST_TEST(p.write("").error() == wd::errc::capacity); + BOOST_TEST(p.finish().error() == wd::errc::capacity); + BOOST_TEST_GT(failing.refusals(), 0U); + failing.allow(plenty); + BOOST_TEST(p.write(" ").error() == wd::errc::capacity); + BOOST_TEST(p.finish_with("[1]").error() == wd::errc::capacity); + p.reset(); + BOOST_TEST(p.finish_with("[1]").has_value()); +} + +// A parser whose allocator runs out while it registers its selectors returns errc::capacity and +// adds nothing. Once they are registered, a parser whose allocator runs out while it reads the +// text, whole or in chunks of 7 bytes, is errc::capacity, and stays failed until reset. +template <class Traits> +void parser_runs_out(bool in_chunks) { + const selected s = selected_text(); + const tally expected = selected_tally<Traits>(); + tally reference_tally; + wd::basic_parser<Traits> reference_parser; + require(BOOST_TEST(all_added(subscribe(reference_parser, reference_tally, s)))); + const auto reference = reference_parser.finish_with(s.text); + require(BOOST_TEST(reference.has_value())); + std::uint64_t failed = 0; + for (std::uint64_t budget = 0;; ++budget) { + webcpp::test::failing_resource failing(std::pmr::new_delete_resource(), budget); + bool parsed = false; + { + tally t; + pmr_parser<Traits> p({}, allocator_of(failing)); + const std::array<bool, selector_count> added = subscribe(p, t, s); + if (!all_added(added)) { + ++failed; + refused_selectors_were_not_added(p, failing, added, t, expected, s.text); + } else if (in_chunks ? write_in_chunks(p, s.text, 7, *reference) + : p.finish_with(s.text).has_value()) { + parsed = true; + BOOST_TEST(t == expected); + BOOST_TEST_EQ(failing.refusals(), 0U); + } else { + ++failed; + a_parser_that_ran_out_stays_failed(p, failing); + } + } + BOOST_TEST_EQ(failing.bytes_in_use(), 0U); + if (parsed) { + break; + } + } + BOOST_TEST_GT(failed, 0U); +} + +// A parse runs out at every allocation of each sample under both traits, and a parser at every +// allocation of its selectors and of its text, whole and in chunks. +void running_out() { + for (const sample& s : samples()) { + parse_runs_out<wd::default_traits>(s); + parse_runs_out<wd::js_traits>(s); + parse_into_runs_out<wd::default_traits>(s); + parse_into_runs_out<wd::js_traits>(s); + } + parser_runs_out<wd::default_traits>(false); + parser_runs_out<wd::js_traits>(false); + parser_runs_out<wd::default_traits>(true); + parser_runs_out<wd::js_traits>(true); +} + +#endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS + +// finish is the parser's member as it was published, whose address is taken without a cast; the +// last chunk is finish_with's. +static_assert( + std::is_same_v<decltype(&wd::parser::finish), wd::result<wd::document> (wd::parser::*)()>); + +/** The allocations of a parse of `text` in an arena, with `revive_bytes` or without. */ +template <class Traits> +std::uint64_t parse_allocations(std::string_view text, bool revive_bytes) { + arena a(16 * mebibyte); + wd::parse_options o; + o.revive_bytes = revive_bytes; + const auto made = wd::parse<Traits>(text, o, a.allocator()); + require(BOOST_TEST(made.has_value())); + return a.resource().allocations(); +} + +// A parse allocates what a value needs only once it needs it: reviving bytes, text that is not +// base64 and objects of another shape than a Uint8Array's take no buffer, so that a parse that +// revives bytes allocates as often as one that does not; and the parser's prepared value keeps its +// buffers, so that strings transcoded to UTF-16 one after another allocate as often as the longest +// grows, not once each. +void allocations_when_needed() { + std::string strings = "["; + std::string objects = "["; + for (std::size_t i = 0; i < 64; ++i) { + strings += std::string(i == 0 ? "" : ",") + R"("not base64, )" + std::string(i, 'x') + '"'; + objects += std::string(i == 0 ? "" : ",") + R"({"a":1,"0":2})"; + } + strings += ']'; + objects += ']'; + BOOST_TEST_EQ(parse_allocations<wd::default_traits>(strings, true), + parse_allocations<wd::default_traits>(strings, false)); + BOOST_TEST_EQ(parse_allocations<wd::js_traits>(objects, true), + parse_allocations<wd::js_traits>(objects, false)); + + arena a(mebibyte); + wd::detail::prepared<wd::js_traits, std::pmr::polymorphic_allocator<std::byte>> p( + a.allocator()); + const std::string longest(200, 'u'); + BOOST_TEST(wd::detail::prepare_string(longest, false, false, p).has_value()); + const std::uint64_t first = a.resource().allocations(); + BOOST_TEST_GT(first, 0U); + for (std::size_t size = 0; size <= longest.size(); size += 10) { + BOOST_TEST( + wd::detail::prepare_string(std::string_view(longest).substr(0, size), false, false, p) + .has_value()); + BOOST_TEST(p.value().text.size() == size * sizeof(char16_t)); + } + BOOST_TEST_EQ(a.resource().allocations(), first); + + wd::detail::prepared<wd::default_traits, std::pmr::polymorphic_allocator<std::byte>> b( + a.allocator()); + const std::uint64_t before = a.resource().allocations(); + BOOST_TEST(wd::detail::prepare_string("not base64!", false, true, b).has_value()); + BOOST_TEST(b.value().kind == wd::kind::string); + BOOST_TEST_EQ(a.resource().allocations(), before); + BOOST_TEST(wd::detail::prepare_string("aGVsbG8=", false, true, b).has_value()); + BOOST_TEST(b.value().kind == wd::kind::bytes); + BOOST_TEST_EQ(b.value().text.size(), 5U); + const std::uint64_t decoded = a.resource().allocations(); + BOOST_TEST(wd::detail::prepare_string("d29ybGQ=", false, true, b).has_value()); + BOOST_TEST_EQ(b.value().text.size(), 5U); + BOOST_TEST_EQ(a.resource().allocations(), decoded); +} + +} // namespace + +int main() { + const std::vector<sample> texts = samples(); + for (const sample& s : texts) { + parse_calls_no_global_new<wd::default_traits>(s); + parse_calls_no_global_new<wd::js_traits>(s); + parse_into_calls_no_global_new<wd::default_traits>(s); + parse_into_calls_no_global_new<wd::js_traits>(s); + } + selectors_call_no_global_new<wd::default_traits>(); + selectors_call_no_global_new<wd::js_traits>(); + const selected s = selected_text(); + chunks_call_only_the_stack<wd::default_traits>(s.text, true); + chunks_call_only_the_stack<wd::js_traits>(s.text, true); + chunks_call_only_the_stack<wd::default_traits>(texts[2].text, false); + chunks_call_only_the_stack<wd::js_traits>(texts[4].text, false); + the_stack_rule(); + finish_is_write_then_finish<wd::default_traits>(); + finish_is_write_then_finish<wd::js_traits>(); + allocations_when_needed(); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + running_out(); +#endif + return boost::report_errors(); +} diff --git a/test/allocator_stringify_test.cpp b/test/allocator_stringify_test.cpp new file mode 100644 index 0000000..697b5ae --- /dev/null +++ b/test/allocator_stringify_test.cpp @@ -0,0 +1,675 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The writer's working state past its own room in the document's allocator: stringify_to of a +// pmr::document, of a pmr document under js_traits and of an external pmr document under +// base64url, into a std::pmr::string on the document's own arena, at every indent and chunk, a +// document nested 10,000 levels deep among them, makes no call of the global operator new and +// gives back to the arena all it took; the writer allocates the frames of its stack past the 16 of +// its own room and a piece larger than its own 4,096 bytes alone, as often as their rooms double, +// so that a dozen small texts written in the example's 64 KiB arena take none of it; stringify asks +// the document's allocator for nothing, and calls the global operator new exactly as often as its +// std::string grows and its stack's deeper frames need; quote allocates through its output alone; +// and, with exceptions, a resource that fails at any step is errc::capacity for stringify_to, the +// sink not called again, its text a prefix and the document unchanged, while a sink's own +// std::bad_alloc propagates. + +#include <webcpp/document.hpp> + +#include <boost/core/lightweight_test.hpp> + +#include "counting.hpp" +#include "require.hpp" + +#include <algorithm> +#include <array> +#include <chrono> +#include <concepts> +#include <cstddef> +#include <cstdint> +#include <memory> +#include <memory_resource> +#include <new> +#include <optional> +#include <span> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +namespace wd = webcpp::document; + +namespace { + +using webcpp::test::arena; +using webcpp::test::global_count; +using webcpp::test::require; + +constexpr std::size_t mebibyte = std::size_t{1} << 20U; + +/** + What an arena holds besides a document's image: a monotonic arena never reuses what it took, so + it holds the writer's stacks, about 512 KB for the deepest document, and the texts' strings, as + they grew, of every case written in it. +*/ +constexpr std::size_t working_room = std::size_t{16} << 20U; + +/** The levels of the deepest document: arrays and objects in turn, the innermost empty. */ +constexpr std::size_t depth = 10'000; + +/** The frames the writer's stack holds at once for it: every level but the innermost, empty. */ +constexpr std::uint64_t deep_frames = depth - 1; + +/** The arrays nested under the sample's "deep" member, the innermost empty. */ +constexpr std::size_t sample_levels = 40; + +/** The frames the writer's stack holds at once for the sample: its root and the arrays but one. */ +constexpr std::uint64_t sample_frames = 1 + sample_levels - 1; + +/** The default traits, but bytes written as base64url. */ +struct url_traits : wd::default_traits { + /** RFC 4648 section 5, no padding. */ + using bytes = wd::base64url; +}; + +/** A block of an external document's buffer, which is 16-aligned. */ +struct alignas(16) block { + /** Its bytes. */ + std::array<std::byte, 16> bytes{}; +}; + +/** + Every escape QuoteJSONString writes and characters of two, three and four bytes in UTF-8, U+2028 + among them: 20 bytes. +*/ +constexpr std::string_view escaped_run = + "x\"\\\b\f\n\r\t\x01\x1f/" + "\xc3\xa9" + "\xe2\x80\xa8" + "\xf0\x9f\x98\x80"; + +/** `count` copies of `run`. */ +std::string repeated(std::string_view run, std::size_t count) { + std::string text; + for (std::size_t i = 0; i < count; ++i) { + text += run; + } + return text; +} + +/** An empty document of `Traits`, in the standard allocator. */ +template <class Traits> +wd::basic_document<Traits> make_document() { + auto made = wd::basic_document<Traits>::create(); + require(BOOST_TEST(made.has_value())); + return std::move(*made); +} + +/** + Sets `levels` containers from `top` down, each the only element or member of the one before: + arrays, or with `alternate` arrays at even levels and objects of the key "k" at odd ones; the + innermost is empty. +*/ +template <class Traits> +void nest(wd::basic_value<Traits> top, std::size_t levels, bool alternate) { + // A handle cannot be assigned without exceptions: the next one is constructed in place. + std::optional<wd::basic_value<Traits>> at; + at.emplace(std::move(top)); + for (std::size_t level = 0; level < levels; ++level) { + const bool object = alternate && level % 2 == 1; + require(BOOST_TEST((object ? at->set(wd::object()) : at->set(wd::array())).has_value())); + if (level + 1 < levels) { + wd::basic_value<Traits> child = object ? (*at)["k"] : (*at)[std::uint64_t{0}]; + at.emplace(std::move(child)); + } + } +} + +/** A document of `Traits` nested @ref depth levels deep, built in the standard allocator. */ +template <class Traits> +wd::basic_document<Traits> nested() { + wd::basic_document<Traits> doc = make_document<Traits>(); + nest(doc.root(), depth, true); + return doc; +} + +/** + A document of `Traits` that holds what the writer writes: a key of 120 bytes and strings with + escapes and characters past ASCII, a run of 10,000 bytes, numbers, dates, 301 bytes, empty + containers, arrays nested @ref sample_levels deep, and under UTF-16 lone surrogates. +*/ +template <class Traits> +wd::basic_document<Traits> sample() { + wd::basic_document<Traits> doc = make_document<Traits>(); + require(BOOST_TEST(doc.root().set(wd::object()).has_value())); + const std::string key = repeated(escaped_run, 6); + const std::string text = repeated(escaped_run, 15); + const std::string run(10000, 'z'); + std::vector<std::byte> bytes(301); + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast<std::byte>((i * 7) % 256); + } + using std::chrono::milliseconds; + require(BOOST_TEST(doc[key].set(std::string_view(text)).has_value())); + require(BOOST_TEST(doc["run"].set(std::string_view(run)).has_value())); + require(BOOST_TEST(doc["date"].set(wd::date_ms{milliseconds{1791774245678}}).has_value())); + require(BOOST_TEST(doc["early"].set(wd::date_ms{milliseconds{-62198755200000}}).has_value())); + require(BOOST_TEST(doc["bytes"].set(std::span<const std::byte>(bytes)).has_value())); + require(BOOST_TEST(doc["list"] + .set(wd::array{1, -1, std::int64_t{1234567890123}, true, nullptr, + "three", wd::literal(wd::array()), wd::object()}) + .has_value())); + nest(doc["deep"], sample_levels, false); + if constexpr (std::same_as<typename Traits::string, wd::utf16>) { + // A lone low surrogate, a lone high one, a pair, and a high one before a control. + const std::u16string lone{u'a', 0xDC00, 0xD800, u'b', 0xD83D, 0xDE00, 0xD83D, u'\n'}; + require(BOOST_TEST(doc["lone"].set(std::u16string_view(lone)).has_value())); + } + return doc; +} + +/** What `stringify` writes of `source` at each of `indents`. */ +template <class Document> +std::vector<std::string> texts_of(const Document& source, std::span<const std::uint32_t> indents) { + std::vector<std::string> texts; + for (const std::uint32_t indent : indents) { + texts.push_back(wd::stringify(source, indent)); + } + return texts; +} + +/** Whether two documents' images are the same bytes; it allocates nothing. */ +template <class A, class B> +bool same_image(const A& a, const B& b) noexcept { + return std::ranges::equal(a.image(), b.image()); +} + +/** A copy of `source` that owns its image, in `resource`. */ +template <class Traits> +wd::pmr::basic_document<Traits> owned_copy(const wd::basic_document<Traits>& source, + std::pmr::memory_resource* resource) { + auto made = wd::from_image<Traits>(source.image(), + std::pmr::polymorphic_allocator<std::byte>(resource)); + require(BOOST_TEST(made.has_value())); + return std::move(*made); +} + +/** A buffer of 16-aligned blocks holding a copy of `source`'s image. */ +template <class Traits> +std::vector<block> buffer_of(const wd::basic_document<Traits>& source) { + std::vector<block> buffer((source.image().size() / sizeof(block)) + 1); + std::ranges::copy(source.image(), std::as_writable_bytes(std::span(buffer)).begin()); + return buffer; +} + +/** An external document over `buffer`, the working state of its operations in `resource`. */ +template <class Traits> +wd::basic_document<Traits, wd::pmr::external> external_copy(std::vector<block>& buffer, + std::pmr::memory_resource* resource) { + auto opened = wd::open<Traits>(std::as_writable_bytes(std::span(buffer)), + std::pmr::polymorphic_allocator<std::byte>(resource)); + require(BOOST_TEST(opened.has_value())); + return std::move(*opened); +} + +/** + The allocations of the writer's stack to hold `frames` frames at once: 16 in its own room, then, + past them, room for 16 frames first and twice the room each time it is full. +*/ +constexpr std::uint64_t stack_allocations(std::uint64_t frames) { + const std::uint64_t deeper = frames > 16 ? frames - 16 : 0; + std::uint64_t count = 0; + for (std::uint64_t room = 0; room < deeper; room = room == 0 ? 16 : 2 * room) { + ++count; + } + return count; +} + +/** + The allocations of the piece `stringify_to` holds back, for a text of `size` bytes written in + pieces smaller than any room: none while it fits its own room of 4096 bytes, then twice that + room, then twice the room, up to `chunk`, each time it is full. +*/ +constexpr std::uint64_t piece_allocations(std::uint64_t chunk, std::uint64_t size) { + const std::uint64_t most = std::min(chunk, size); + std::uint64_t count = 0; + for (std::uint64_t room = 4096; room < most; room = std::min(chunk, 2 * room)) { + ++count; + } + return count; +} + +/** An output of the writer that records the size of each piece it is handed. */ +class piece_recorder { +public: + /** A recorder that appends to `sizes`, which outlives it. */ + explicit piece_recorder(std::vector<std::size_t>& sizes) noexcept : sizes_(&sizes) {} + + /** Records the size of `text`. */ + wd::result<void> put(std::string_view text) { + sizes_->push_back(text.size()); + return {}; + } + +private: + /** The sizes, in the order the pieces came. */ + std::vector<std::size_t>* sizes_; +}; + +/** + stringify_to of `doc`, a copy of `source` whose allocator is `a`'s, into a std::pmr::string on `a` + too, at each of `indents` and in pieces of 1, 7 and 4096 bytes: no call of the global operator + new, the text of `expected` at that indent, every byte the writer and the string took given back, + and the document unchanged. +*/ +template <class Document, class Source> +void writes_in_its_arena(const Document& doc, const Source& source, arena& a, + std::span<const std::uint32_t> indents, + const std::vector<std::string>& expected) { + const std::uint64_t held = a.resource().bytes_in_use(); + for (std::size_t i = 0; i < indents.size(); ++i) { + for (const std::uint64_t chunk : {1U, 7U, 4096U}) { + { + // Its growth is the arena's too: nothing is reserved. + std::pmr::string out(&a.resource()); + const global_count global; + const wd::result<void> written = wd::stringify_to( + doc, [&out](std::string_view piece) { out.append(piece); }, indents[i], chunk); + const std::uint64_t news = global.news(); + BOOST_TEST_EQ(news, 0U); + BOOST_TEST(written.has_value()); + BOOST_TEST(std::string_view(out) == expected[i]); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), held); + BOOST_TEST(same_image(doc, source)); + } + } +} + +/** @ref writes_in_its_arena for a copy of `source` that owns its image in an arena. */ +template <class Traits> +void owned_in_arena(const wd::basic_document<Traits>& source, + std::span<const std::uint32_t> indents) { + const std::vector<std::string> expected = texts_of(source, indents); + arena a(source.image().size() + working_room); + { + const wd::pmr::basic_document<Traits> doc = owned_copy(source, &a.resource()); + BOOST_TEST(doc.get_allocator().resource() == &a.resource()); + writes_in_its_arena(doc, source, a, indents, expected); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +/** @ref writes_in_its_arena for an external copy of `source`, its working state in an arena. */ +template <class Traits> +void external_in_arena(const wd::basic_document<Traits>& source, + std::span<const std::uint32_t> indents) { + const std::vector<std::string> expected = texts_of(source, indents); + std::vector<block> buffer = buffer_of(source); + arena a(working_room); + { + const auto doc = external_copy<Traits>(buffer, &a.resource()); + BOOST_TEST(doc.get_allocator().resource() == &a.resource()); + writes_in_its_arena(doc, source, a, indents, expected); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// stringify_to into a std::pmr::string on the document's own arena makes no call of the global +// operator new, for a pmr::document, a pmr document under js_traits and an external pmr document +// under base64url: the sample at indents 0, 2 and 10, and the document nested 10,000 levels deep +// compactly, since its indentation grows with the square of its depth (100 MB at an indent of 2). +void stringify_to_calls_no_global_new() { + const std::array<std::uint32_t, 3> indents{0, 2, 10}; + const std::array<std::uint32_t, 1> compact{0}; + owned_in_arena(sample<wd::default_traits>(), indents); + owned_in_arena(sample<wd::js_traits>(), indents); + external_in_arena(sample<url_traits>(), indents); + owned_in_arena(nested<wd::default_traits>(), compact); + owned_in_arena(nested<wd::js_traits>(), compact); + external_in_arena(nested<url_traits>(), compact); +} + +/** + stringify_to of `doc`, whose allocator is `docs`', into a std::pmr::string on `outs`, compactly, in + pieces of `chunk` bytes: the document's resource makes the allocations of a stack of `frames` + frames and of the piece held back, and takes back every one. +*/ +template <class Document> +void allocates_its_stack_and_piece(const Document& doc, arena& docs, arena& outs, + const std::string& expected, std::uint64_t frames, + std::uint64_t chunk) { + const std::uint64_t held = docs.resource().bytes_in_use(); + const std::uint64_t made = docs.resource().allocations(); + const std::uint64_t freed = docs.resource().deallocations(); + { + std::pmr::string out(&outs.resource()); + const global_count global; + const wd::result<void> written = + wd::stringify_to(doc, [&out](std::string_view piece) { out.append(piece); }, 0, chunk); + const std::uint64_t news = global.news(); + BOOST_TEST_EQ(news, 0U); + BOOST_TEST(written.has_value()); + BOOST_TEST(std::string_view(out) == expected); + } + const std::uint64_t allocations = + stack_allocations(frames) + piece_allocations(chunk, expected.size()); + BOOST_TEST_EQ(docs.resource().allocations() - made, allocations); + BOOST_TEST_EQ(docs.resource().deallocations() - freed, allocations); + BOOST_TEST_EQ(docs.resource().bytes_in_use(), held); +} + +// The writer allocates, in the document's resource, the frames of its stack past its own room and +// a piece larger than its own alone, as often as their rooms double, and takes back all of it; the +// output's string, on another arena, holds all else. The deep text, about 40,000 bytes, fills +// pieces of 32,768 bytes and a piece of 65,536 bytes only in part; its pieces of 4096 bytes or +// fewer are held in the piece's own room. +void the_writer_allocates_its_stack_and_piece() { + { + const wd::document source = nested<wd::default_traits>(); + const std::string expected = wd::stringify(source); + BOOST_TEST_GT(expected.size(), 32768U); + BOOST_TEST_LT(expected.size(), 65536U); + arena docs(source.image().size() + working_room); + arena outs(working_room); + const wd::pmr::document doc = owned_copy(source, &docs.resource()); + for (const std::uint64_t chunk : {1U, 7U, 4096U, 32768U, 65536U}) { + allocates_its_stack_and_piece(doc, docs, outs, expected, deep_frames, chunk); + } + } + { + const auto source = nested<wd::js_traits>(); + const std::string expected = wd::stringify(source); + std::vector<block> buffer = buffer_of(source); + arena docs(working_room); + arena outs(working_room); + const auto doc = external_copy<wd::js_traits>(buffer, &docs.resource()); + allocates_its_stack_and_piece(doc, docs, outs, expected, deep_frames, 4096); + } + { + // The run of 10,000 bytes reaches the sink without a piece larger than its own room. + const auto source = sample<wd::js_traits>(); + const std::string expected = wd::stringify(source); + arena docs(source.image().size() + working_room); + arena outs(working_room); + const auto doc = owned_copy(source, &docs.resource()); + for (const std::uint64_t chunk : {1U, 7U, 4096U}) { + allocates_its_stack_and_piece(doc, docs, outs, expected, sample_frames, chunk); + } + } +} + +/** + stringify of a copy of `source` in an arena, at each of `indents`, calls the global operator new + and operator delete exactly as often as a std::string that appends the writer's pieces of the same + text does, made in the same count, and as the stack of `frames` frames needs: its frames past its + own room, and what the standard library allocates for the list that holds them (counting.hpp's + bookkeeping); the arena makes no allocation. +*/ +template <class Traits> +void calls_new_for_its_string_alone(const wd::basic_document<Traits>& source, std::uint64_t frames, + std::span<const std::uint32_t> indents) { + arena a(source.image().size() + working_room); + const wd::pmr::basic_document<Traits> doc = owned_copy(source, &a.resource()); + const std::uint64_t held = a.resource().bytes_in_use(); + for (const std::uint32_t indent : indents) { + const std::string expected = wd::stringify(source, indent); + std::vector<std::size_t> sizes; + piece_recorder recorder(sizes); + BOOST_TEST(wd::detail::write_json(*wd::detail::access::tree_of(source), + wd::detail::access::node_of(source.root()), indent, + recorder, std::allocator<std::byte>()) + .has_value()); + std::uint64_t reference_news = 0; + std::uint64_t reference_deletes = 0; + { + // Made in the count, as stringify's string is: what a standard library allocates for a + // string itself is counted on both sides. + const global_count global; + std::string reference; + std::size_t at = 0; + for (const std::size_t size : sizes) { + reference.append(std::string_view(expected).substr(at, size)); + at += size; + } + reference_news = global.news(); + reference_deletes = global.deletes(); + BOOST_TEST(reference == expected); + } + BOOST_TEST_GT(reference_news, 0U); + const std::uint64_t deeper = stack_allocations(frames); + const std::uint64_t stack = deeper == 0 ? 0 : deeper + webcpp::test::bookkeeping().blocks; + const std::uint64_t made = a.resource().allocations(); + { + const global_count global; + const std::string text = wd::stringify(doc, indent); + const std::uint64_t news = global.news(); + const std::uint64_t deletes = global.deletes(); + BOOST_TEST_EQ(news, reference_news + stack); + BOOST_TEST_EQ(deletes, reference_deletes + stack); + BOOST_TEST(text == expected); + } + BOOST_TEST_EQ(a.resource().allocations(), made); + BOOST_TEST_EQ(a.resource().bytes_in_use(), held); + } +} + +// stringify returns a std::string, the program's value in the standard allocator, and keeps its +// stack in the same allocator: it calls the global operator new for that string and the stack's +// deeper frames alone, and asks the document's resource for nothing. +void stringify_calls_new_for_its_string_alone() { + const std::array<std::uint32_t, 3> indents{0, 2, 10}; + const std::array<std::uint32_t, 1> compact{0}; + calls_new_for_its_string_alone(sample<wd::default_traits>(), sample_frames, indents); + calls_new_for_its_string_alone(sample<wd::js_traits>(), sample_frames, indents); + calls_new_for_its_string_alone(nested<wd::default_traits>(), deep_frames, compact); +} + +// A dozen small texts written by stringify_to in a 64 KiB arena, the example's, take nothing of it: +// the stack and the piece fit their own room, and make no list a standard library would allocate +// for (counting.hpp's bookkeeping), and the arena holds the document alone, which stays as it was. +void small_texts_take_nothing() { + arena a(std::size_t{64} * 1024); + auto made = wd::parse(R"({"user":"Ada","langs":["Analytical","Note G"],"draft":true})", + wd::parse_options(), a.allocator()); + require(BOOST_TEST(made.has_value())); + const std::uint64_t allocations = a.resource().all_allocations(); + const std::uint64_t held = a.resource().bytes_in_use(); + for (std::size_t call = 0; call < 12; ++call) { + std::string out; + BOOST_TEST(wd::stringify_to(*made, [&out](std::string_view piece) { + out.append(piece); + }).has_value()); + BOOST_TEST_EQ(out, R"({"user":"Ada","langs":["Analytical","Note G"],"draft":true})"); + } + BOOST_TEST_EQ(a.resource().all_allocations(), allocations); + BOOST_TEST_EQ(a.resource().bytes_in_use(), held); +} + +// quote appends to a std::pmr::string on an arena, UTF-8 and UTF-16, long texts with escapes, +// characters past ASCII and lone surrogates, with no call of the global operator new; text that is +// not UTF-8 changes nothing. +void quote_allocates_through_its_output() { + const std::string utf8 = repeated(escaped_run, 50); + std::u16string utf16; + for (std::size_t i = 0; i < 100; ++i) { + utf16 += u"x\"\\\b\n\x01/\u00e9\u2028"; + // A pair, then a lone low surrogate, then a high one the next round's text follows. + utf16 += std::u16string{0xD83D, 0xDE00, 0xDC00, 0xD800}; + } + std::string expected; + require(BOOST_TEST(wd::quote(std::string_view(utf8), expected).has_value())); + wd::quote(std::u16string_view(utf16), expected); + constexpr std::string_view invalid = "\xc3"; + arena a(mebibyte); + { + std::pmr::string out(&a.resource()); + const global_count global; + const wd::result<void> quoted = wd::quote(std::string_view(utf8), out); + wd::quote(std::u16string_view(utf16), out); + const wd::result<void> refused = wd::quote(invalid, out); + const std::uint64_t news = global.news(); + BOOST_TEST_EQ(news, 0U); + BOOST_TEST(quoted.has_value()); + BOOST_TEST(refused.error() == wd::errc::type); + BOOST_TEST(std::string_view(out) == expected); + BOOST_TEST_GT(a.resource().allocations(), 0U); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + +/** + stringify_to of `doc`, whose working state `failing` holds, with every budget from 0 until it + succeeds: each step that fails is errc::capacity, with the sink not called after the refusal, its + text a prefix of the whole, the document `source`'s image and the resource back where it was; and + as many steps fail as the writer allocates. +*/ +template <class Document, class Source> +void capacity_at_every_step(const Document& doc, const Source& source, + webcpp::test::failing_resource& failing, std::uint32_t indent, + std::uint64_t chunk, std::uint64_t allocations) { + const std::string expected = wd::stringify(source, indent); + const std::uint64_t held = failing.bytes_in_use(); + const std::uint64_t refused = failing.refusals(); + std::uint64_t budget = 0; + for (;; ++budget) { + failing.allow(budget); + std::string out; + std::uint64_t late = 0; + const std::uint64_t before = failing.refusals(); + const wd::result<void> written = wd::stringify_to( + doc, + [&out, &late, &failing, before](std::string_view piece) { + late += failing.refusals() == before ? 0 : 1; + out += piece; + }, + indent, chunk); + BOOST_TEST_EQ(late, 0U); + BOOST_TEST(same_image(doc, source)); + BOOST_TEST_EQ(failing.bytes_in_use(), held); + if (written.has_value()) { + BOOST_TEST(out == expected); + break; + } + BOOST_TEST(written.error() == wd::errc::capacity); + BOOST_TEST(std::string_view(expected).starts_with(out)); + // A writer that kept failing would never end the loop. + if (!BOOST_TEST_LT(budget, allocations)) { + break; + } + } + BOOST_TEST_EQ(budget, allocations); + BOOST_TEST_EQ(failing.refusals() - refused, allocations); +} + +/** + stringify of `doc`, whose working state `failing` holds, with a budget of 0: it asks the resource + for nothing, so it writes the whole text, refused nothing. +*/ +template <class Document, class Source> +void stringify_asks_nothing(const Document& doc, const Source& source, + webcpp::test::failing_resource& failing, std::uint32_t indent) { + const std::uint64_t refused = failing.refusals(); + failing.allow(0); + const std::string text = wd::stringify(doc, indent); + BOOST_TEST(text == wd::stringify(source, indent)); + BOOST_TEST_EQ(failing.refusals(), refused); +} + +// A sink's own std::bad_alloc is the program's: it propagates, as anything a sink throws does, and +// is not taken for the writer's errc::capacity; the writer gives back what it took. +void a_sinks_bad_alloc_propagates() { + const wd::document source = nested<wd::default_traits>(); + arena a(source.image().size() + working_room); + const wd::pmr::document doc = owned_copy(source, &a.resource()); + const std::uint64_t held = a.resource().bytes_in_use(); + std::size_t calls = 0; + bool thrown = false; + try { + (void)wd::stringify_to( + doc, + [&calls](std::string_view) { + if (++calls == 2) { + throw std::bad_alloc(); + } + }, + 0, 7); + } catch (const std::bad_alloc&) { + thrown = true; + } + BOOST_TEST(thrown); + BOOST_TEST_EQ(calls, 2U); + BOOST_TEST_EQ(a.resource().bytes_in_use(), held); + BOOST_TEST(same_image(doc, source)); +} + +/** As many allocations as a test may need, for a document's image and its copies. */ +constexpr std::uint64_t unlimited = std::uint64_t{1} << 40U; + +// With exceptions, a resource that has no room for the writer's stack or piece, at any step, makes +// stringify_to errc::capacity, and changes nothing, while stringify, which asks it for nothing, +// writes: for the document nested 10,000 levels deep, owned under the default traits and js_traits +// and external under base64url, and for the sample with an indent. +void a_resource_with_no_room() { + webcpp::test::failing_resource failing(std::pmr::new_delete_resource(), unlimited); + { + const wd::document source = nested<wd::default_traits>(); + const std::uint64_t size = wd::stringify(source).size(); + const wd::pmr::document doc = owned_copy(source, &failing); + for (const std::uint64_t chunk : {1U, 4096U, 32768U}) { + capacity_at_every_step(doc, source, failing, 0, chunk, + stack_allocations(deep_frames) + piece_allocations(chunk, size)); + } + stringify_asks_nothing(doc, source, failing, 0); + failing.allow(unlimited); + } + { + const auto source = nested<wd::js_traits>(); + const std::uint64_t size = wd::stringify(source).size(); + const auto doc = owned_copy(source, &failing); + capacity_at_every_step(doc, source, failing, 0, 4096, + stack_allocations(deep_frames) + piece_allocations(4096, size)); + failing.allow(unlimited); + } + { + const auto source = nested<url_traits>(); + const std::uint64_t size = wd::stringify(source).size(); + std::vector<block> buffer = buffer_of(source); + const auto doc = external_copy<url_traits>(buffer, &failing); + capacity_at_every_step(doc, source, failing, 0, 4096, + stack_allocations(deep_frames) + piece_allocations(4096, size)); + failing.allow(unlimited); + } + { + const auto source = sample<wd::js_traits>(); + const std::uint64_t size = wd::stringify(source, 2).size(); + const auto doc = owned_copy(source, &failing); + capacity_at_every_step(doc, source, failing, 2, 4096, + stack_allocations(sample_frames) + piece_allocations(4096, size)); + stringify_asks_nothing(doc, source, failing, 2); + failing.allow(unlimited); + } + BOOST_TEST_EQ(failing.bytes_in_use(), 0U); +} + +#endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS + +} // namespace + +int main() { + stringify_to_calls_no_global_new(); + the_writer_allocates_its_stack_and_piece(); + stringify_calls_new_for_its_string_alone(); + small_texts_take_nothing(); + quote_allocates_through_its_output(); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + a_resource_with_no_room(); + a_sinks_bad_alloc_propagates(); +#endif + return boost::report_errors(); +} diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp new file mode 100644 index 0000000..04afbfa --- /dev/null +++ b/test/allocator_test.cpp @@ -0,0 +1,983 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A document's allocator holds its image: created, grown several times, shrunk, copied into another +// resource, moved, and move-assigned across resources, a pmr::document makes no call of the global +// operator new, and gives back to its resource all it took; the image is the same bytes in any +// allocator; any allocator of std::byte works, a stateful one of the program's own among them; an +// external document carries its allocator for its working state; and, with exceptions, an +// allocator that has no room is errc::capacity with nothing changed. + +#include <webcpp/document.hpp> + +#include <boost/core/lightweight_test.hpp> + +#include "counting.hpp" +#include "require.hpp" + +#include <algorithm> +#include <array> +#include <concepts> +#include <cstddef> +#include <cstdint> +#include <memory> +#include <memory_resource> +#include <new> +#include <span> +#include <string> +#include <string_view> +#include <type_traits> +#include <utility> +#include <vector> + +namespace wd = webcpp::document; + +namespace { + +using webcpp::test::arena; +using webcpp::test::global_count; +using webcpp::test::require; + +constexpr std::size_t mebibyte = std::size_t{1} << 20U; + +/** What a stateful allocator of the test's own counts. */ +struct allocator_counts { + /** The allocations it made. */ + std::uint64_t allocations = 0; + + /** The deallocations it made. */ + std::uint64_t deallocations = 0; +}; + +/** + An allocator of the program's own, stateful and neither standard nor polymorphic: it counts + through a pointer and allocates with the aligned global operator new, so that any allocator is + shown to give the image its 16-byte alignment through the rebind. +*/ +template <class T> +class tallying_allocator { +public: + /** The type allocated. */ + using value_type = T; + + /** An allocator that counts in `counts`, which outlives it. */ + explicit tallying_allocator(allocator_counts* counts) noexcept : counts_(counts) {} + + // The Allocator requirements construct a rebound allocator from this one, `A a(b)`, and ask no + // conversion; this one converts implicitly, as std::allocator does, and explicit_allocator + // below does not. + /** The same allocator for another type. */ + template <class U> + // NOLINTNEXTLINE(misc-explicit-constructor) + tallying_allocator(const tallying_allocator<U>& other) noexcept : counts_(other.counts()) {} + + /** Room for `n` objects of `T`, aligned for `T`. */ + T* allocate(std::size_t n) { + ++counts_->allocations; + return static_cast<T*>(::operator new(n * sizeof(T), std::align_val_t{alignof(T)})); + } + + /** Gives back what @ref allocate made. */ + void deallocate(T* p, std::size_t /*n*/) noexcept { + ++counts_->deallocations; + ::operator delete(p, std::align_val_t{alignof(T)}); + } + + /** The counts. */ + [[nodiscard]] allocator_counts* counts() const noexcept { return counts_; } + + /** Whether two allocators count in the same place. */ + template <class U> + friend bool operator==(const tallying_allocator& a, const tallying_allocator<U>& b) noexcept { + return a.counts_ == b.counts(); + } + +private: + allocator_counts* counts_; +}; + +/** + How an allocator of the test's own propagates: on a move assignment, and whether two of them are + always equal. +*/ +enum class propagation : std::uint8_t { + /** Neither: a move assignment between two that differ copies the image. */ + none, + + /** It propagates on a move assignment. */ + on_move, + + /** Two of them are always equal, whatever they count in. */ + always_equal, +}; + +/** + A stateful allocator of the program's own, neither standard nor polymorphic, whose rebinding + constructor is explicit, as the Allocator requirements allow: a rebound allocator is constructed + from it, `A a(b)`, never converted to. It counts through a pointer, and `How` says how it + propagates. +*/ +template <class T, propagation How = propagation::none> +class explicit_allocator { +public: + /** The type allocated. */ + using value_type = T; + + /** Whether it propagates on a move assignment. */ + using propagate_on_container_move_assignment = std::bool_constant<How == propagation::on_move>; + + /** Whether two of them are always equal. */ + using is_always_equal = std::bool_constant<How == propagation::always_equal>; + + /** The same allocator for another type. */ + template <class U> + struct rebind { + /** The allocator of `U`. */ + using other = explicit_allocator<U, How>; + }; + + /** An allocator that counts in `counts`, which outlives it. */ + explicit explicit_allocator(allocator_counts* counts) noexcept : counts_(counts) {} + + /** The same allocator for another type, constructed from it and never converted to. */ + template <class U> + explicit explicit_allocator(const explicit_allocator<U, How>& other) noexcept + : counts_(other.counts()) {} + + /** Room for `n` objects of `T`, aligned for `T`. */ + T* allocate(std::size_t n) { + ++counts_->allocations; + return static_cast<T*>(::operator new(n * sizeof(T), std::align_val_t{alignof(T)})); + } + + /** Gives back what @ref allocate made. */ + void deallocate(T* p, std::size_t /*n*/) noexcept { + ++counts_->deallocations; + ::operator delete(p, std::align_val_t{alignof(T)}); + } + + /** The counts. */ + [[nodiscard]] allocator_counts* counts() const noexcept { return counts_; } + + /** Whether two allocators count in the same place, or are always equal. */ + template <class U> + friend bool operator==(const explicit_allocator& a, + const explicit_allocator<U, How>& b) noexcept { + return How == propagation::always_equal || a.counts_ == b.counts(); + } + +private: + allocator_counts* counts_; +}; + +/** A document of `Traits` whose storage owns its image in an @ref explicit_allocator. */ +template <class Traits, propagation How = propagation::none> +using explicit_document = + wd::basic_document<Traits, wd::basic_owned<explicit_allocator<std::byte, How>>>; + +/** What an allocator of @ref aligning_allocator does: its counts, and whether it under-aligns. */ +struct alignment_control { + /** The allocations it made. */ + std::uint64_t allocations = 0; + + /** The deallocations it made. */ + std::uint64_t deallocations = 0; + + /** Whether each block it hands out is 8 bytes past a 16-aligned address. */ + bool under_align = false; +}; + +/** + An allocator that, when told to, aligns every block to 8 bytes and never to 16, whatever the type + asks, as an allocator that ignores an over-aligned request may: a block of the image, alignas(16), + is over-aligned wherever std::max_align_t's alignment is 8, as on arm64 macOS and on MSVC. +*/ +template <class T> +class aligning_allocator { +public: + /** The type allocated. */ + using value_type = T; + + /** An allocator that does as `control` says and counts there; `control` outlives it. */ + explicit aligning_allocator(alignment_control* control) noexcept : control_(control) {} + + // Implicit, as std::allocator's conversion is: the Allocator requirements ask only `A a(b)`. + /** The same allocator for another type. */ + template <class U> + // NOLINTNEXTLINE(misc-explicit-constructor) + aligning_allocator(const aligning_allocator<U>& other) noexcept : control_(other.control()) {} + + /** Room for `n` objects of `T`, 16-aligned or, when told to, 8 bytes past it. */ + T* allocate(std::size_t n) { + ++control_->allocations; + auto* block = + static_cast<std::byte*>(::operator new((n * sizeof(T)) + 16, std::align_val_t{16})); + return reinterpret_cast<T*>(block + offset()); + } + + /** Gives back what @ref allocate made. */ + void deallocate(T* p, std::size_t /*n*/) noexcept { + ++control_->deallocations; + // A block is given back from the 16-aligned address it was made at. + auto* block = reinterpret_cast<std::byte*>(p); + const std::size_t past = reinterpret_cast<std::uintptr_t>(block) % 16; + ::operator delete(block - past, std::align_val_t{16}); + } + + /** What it does and counts. */ + [[nodiscard]] alignment_control* control() const noexcept { return control_; } + + /** Whether two allocators do as the same control says. */ + template <class U> + friend bool operator==(const aligning_allocator& a, const aligning_allocator<U>& b) noexcept { + return a.control_ == b.control(); + } + +private: + /** The bytes past a 16-aligned address it hands out. */ + [[nodiscard]] std::size_t offset() const noexcept { return control_->under_align ? 8 : 0; } + + alignment_control* control_; +}; + +/** The tag a @ref tagging_allocator's pointers carry, which an address alone does not give. */ +constexpr std::uint64_t pointer_tag = 0x5ea1; + +/** + A pointer that is not a plain one, as an allocator of a segment of shared memory may hand out: + an address and a tag, which a pointer rebuilt from the address alone does not carry. +*/ +template <class T> +class tagged_pointer { +public: + /** The type pointed to. */ + using element_type = T; + + /** A difference of pointers. */ + using difference_type = std::ptrdiff_t; + + /** A null pointer. */ + tagged_pointer() noexcept = default; + + // A null pointer converts to it implicitly, as the NullablePointer requirements ask. + /** A null pointer. */ + // NOLINTNEXTLINE(misc-explicit-constructor) + tagged_pointer(std::nullptr_t /*null*/) noexcept {} + + /** The pointer to `address` that carries `tag`. */ + tagged_pointer(T* address, std::uint64_t tag) noexcept : address_(address), tag_(tag) {} + + /** What `std::pointer_traits` rebuilds from an object alone: its address, with no tag. */ + template <class U = T> + static tagged_pointer pointer_to(U& object) noexcept { + return tagged_pointer(std::addressof(object), 0); + } + + /** The address. */ + T* operator->() const noexcept { return address_; } + + /** Whether it is not null. */ + explicit operator bool() const noexcept { return address_ != nullptr; } + + /** The tag. */ + [[nodiscard]] std::uint64_t tag() const noexcept { return tag_; } + + /** Whether two pointers have the same address and tag. */ + friend bool operator==(const tagged_pointer& a, const tagged_pointer& b) noexcept = default; + +private: + T* address_ = nullptr; + std::uint64_t tag_ = 0; +}; + +/** What a @ref tagging_allocator counts. */ +struct tag_counts { + /** The allocations it made. */ + std::uint64_t allocations = 0; + + /** The deallocations it made. */ + std::uint64_t deallocations = 0; + + /** The deallocations given a pointer without the tag it handed out. */ + std::uint64_t untagged = 0; +}; + +/** + An allocator whose pointer to the image's blocks is a @ref tagged_pointer, and to anything else a + plain one: it counts a block given back through a pointer that lost its tag. +*/ +template <class T> +class tagging_allocator { +public: + /** Whether its pointer is tagged: for the image's blocks. */ + static constexpr bool tagged = std::same_as<T, wd::detail::image_block>; + + /** The type allocated. */ + using value_type = T; + + /** Its pointer. */ + using pointer = std::conditional_t<tagged, tagged_pointer<T>, T*>; + + /** An allocator that counts in `counts`, which outlives it. */ + explicit tagging_allocator(tag_counts* counts) noexcept : counts_(counts) {} + + // Implicit, as std::allocator's conversion is: the Allocator requirements ask only `A a(b)`. + /** The same allocator for another type. */ + template <class U> + // NOLINTNEXTLINE(misc-explicit-constructor) + tagging_allocator(const tagging_allocator<U>& other) noexcept : counts_(other.counts()) {} + + /** Room for `n` objects of `T`, aligned for `T`. */ + pointer allocate(std::size_t n) { + ++counts_->allocations; + auto* p = static_cast<T*>(::operator new(n * sizeof(T), std::align_val_t{alignof(T)})); + if constexpr (tagged) { + return pointer(p, pointer_tag); + } else { + return p; + } + } + + /** Gives back what @ref allocate made, counting a pointer that lost its tag. */ + void deallocate(pointer p, std::size_t /*n*/) noexcept { + ++counts_->deallocations; + if constexpr (tagged) { + counts_->untagged += p.tag() == pointer_tag ? 0 : 1; + ::operator delete(p.operator->(), std::align_val_t{alignof(T)}); + } else { + ::operator delete(p, std::align_val_t{alignof(T)}); + } + } + + /** The counts. */ + [[nodiscard]] tag_counts* counts() const noexcept { return counts_; } + + /** Whether two allocators count in the same place. */ + template <class U> + friend bool operator==(const tagging_allocator& a, const tagging_allocator<U>& b) noexcept { + return a.counts_ == b.counts(); + } + +private: + tag_counts* counts_; +}; + +/** The bytes of `d`'s image, copied. */ +template <class Document> +std::vector<std::byte> bytes_of(const Document& d) { + const std::span<const std::byte> image = d.image(); + return {image.begin(), image.end()}; +} + +/** Whether two documents' images are the same bytes; it allocates nothing. */ +template <class A, class B> +bool same_image(const A& a, const B& b) noexcept { + return std::ranges::equal(a.image(), b.image()); +} + +/** A document of the default storage holding an object, an array and strings, parsed. */ +wd::document sample() { + auto parsed = wd::parse(R"({"name":"document","list":[1,2.5,"three",[true,null]],"x":{}})"); + require(BOOST_TEST(parsed.has_value())); + return std::move(*parsed); +} + +// A pmr::document is created, grown three times and shrunk in its resource, with no call of the +// global operator new, and gives back all it took when destroyed; every block the resource gave it +// was asked with the alignment of 16. +void image_in_resource() { + arena a(4 * mebibyte); + const global_count global; + { + auto made = wd::pmr::document::create(a.allocator()); + require(BOOST_TEST(made.has_value())); + wd::pmr::document d = std::move(*made); + BOOST_TEST(d.get_allocator().resource() == &a.resource()); + BOOST_TEST_EQ(d.capacity(), 4096U); + BOOST_TEST(d.reserve(16384).has_value()); + BOOST_TEST(d.reserve(65536).has_value()); + BOOST_TEST(d.reserve(262144).has_value()); + BOOST_TEST_EQ(d.capacity(), 262144U); + BOOST_TEST(d.shrink_to_fit().has_value()); + BOOST_TEST_LT(d.capacity(), 4096U); + // Created, grown three times and shrunk: five buffers, the last one held. + BOOST_TEST_EQ(a.resource().allocations(), 5U); + BOOST_TEST_EQ(a.resource().deallocations(), 4U); + } + BOOST_TEST_EQ(global.news(), 0U); + BOOST_TEST_EQ(global.deletes(), 0U); + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); + BOOST_TEST_EQ(a.resource().largest_alignment(), 16U); +} + +// The default storage is unchanged: create calls the global operator new once, for its image, and +// an image is the same bytes whatever allocated it. +void default_storage_unchanged() { + { + const global_count global; + const auto made = wd::document::create(); + require(BOOST_TEST(made.has_value())); + BOOST_TEST_EQ(global.news(), 1U); + } + const wd::document source = sample(); + arena a(mebibyte); + auto copy = wd::from_image(source.image(), a.allocator()); + require(BOOST_TEST(copy.has_value())); + BOOST_TEST(same_image(*copy, source)); +} + +// A move takes the image and the allocator; the document moved from holds nothing. +void move_takes_allocator() { + arena a(mebibyte); + const wd::document source = sample(); + auto made = wd::from_image(source.image(), a.allocator()); + require(BOOST_TEST(made.has_value())); + const global_count global; + wd::pmr::document moved(std::move(*made)); + BOOST_TEST(moved.get_allocator().resource() == &a.resource()); + BOOST_TEST(made->image().empty()); + BOOST_TEST(same_image(moved, source)); + const wd::pmr::document again(std::move(moved)); + BOOST_TEST(same_image(again, source)); + BOOST_TEST_EQ(global.news(), 0U); +} + +// A move assignment between resources copies the image into the target's resource, one copy of +// its bytes, and frees the source's in its own; between equal resources it takes the image. +void move_assign_across_resources() { + arena a(mebibyte); + arena b(mebibyte); + const wd::document source = sample(); + auto in_a = wd::pmr::document::create(a.allocator()); + auto in_b = wd::from_image(source.image(), b.allocator()); + require(BOOST_TEST(in_a.has_value() && in_b.has_value())); + const std::uint64_t a_before = a.resource().allocations(); + const global_count global; + *in_a = std::move(*in_b); + BOOST_TEST_EQ(global.news(), 0U); + BOOST_TEST(in_a->get_allocator().resource() == &a.resource()); + BOOST_TEST(same_image(*in_a, source)); + BOOST_TEST(in_b->image().empty()); + BOOST_TEST_EQ(a.resource().allocations(), a_before + 1); + BOOST_TEST_EQ(b.resource().bytes_in_use(), 0U); + + // Between documents of one resource, the image itself is taken. + auto other = wd::pmr::document::create(a.allocator()); + require(BOOST_TEST(other.has_value())); + const std::uint64_t a_taken = a.resource().allocations(); + *other = std::move(*in_a); + BOOST_TEST_EQ(a.resource().allocations(), a_taken); + BOOST_TEST(same_image(*other, source)); + + // A document moved from, assigned to one of another resource, leaves it holding nothing. + *in_b = std::move(*in_a); + BOOST_TEST(in_b->image().empty()); + BOOST_TEST(in_b->get_allocator().resource() == &b.resource()); +} + +// clone copies into the document's own resource, clone(alloc) into another's, and from_image into +// any allocator's. +void clone_into_resources() { + arena a(mebibyte); + arena b(mebibyte); + const wd::document source = sample(); + auto in_a = wd::from_image(source.image(), a.allocator()); + require(BOOST_TEST(in_a.has_value())); + const global_count global; + auto same = in_a->clone(); + auto other = in_a->clone(b.allocator()); + require(BOOST_TEST(same.has_value() && other.has_value())); + BOOST_TEST_EQ(global.news(), 0U); + BOOST_TEST(same->get_allocator().resource() == &a.resource()); + BOOST_TEST(other->get_allocator().resource() == &b.resource()); + BOOST_TEST(same_image(*same, source)); + BOOST_TEST(same_image(*other, source)); +} + +// An external document carries the allocator of its working state: format, open, compact_into and +// clone keep it, and none of them calls the global operator new. +void external_carries_allocator() { + arena a(mebibyte); + const wd::document source = sample(); + alignas(16) std::array<std::byte, 8192> buffer{}; + alignas(16) std::array<std::byte, 8192> compacted{}; + std::copy(source.image().begin(), source.image().end(), buffer.begin()); + const global_count global; + auto opened = wd::open(std::span(buffer), a.allocator()); + require(BOOST_TEST(opened.has_value())); + BOOST_TEST(opened->get_allocator().resource() == &a.resource()); + BOOST_TEST(same_image(*opened, source)); + auto packed = opened->compact_into(compacted); + require(BOOST_TEST(packed.has_value())); + BOOST_TEST(packed->get_allocator().resource() == &a.resource()); + auto owned = opened->clone(); + require(BOOST_TEST(owned.has_value())); + BOOST_TEST(owned->get_allocator().resource() == &a.resource()); + alignas(16) std::array<std::byte, 4096> empty{}; + auto formatted = wd::format(std::span(empty), a.allocator()); + require(BOOST_TEST(formatted.has_value())); + BOOST_TEST(formatted->root().is_null()); + BOOST_TEST_EQ(global.news(), 0U); +} + +// Any allocator of std::byte works: one of the program's own, stateful, rebound to the image's +// blocks, allocates and frees the image, and copies keep it. +void any_allocator() { + allocator_counts counts; + using storage = wd::basic_owned<tallying_allocator<std::byte>>; + using document = wd::basic_document<wd::default_traits, storage>; + const tallying_allocator<std::byte> alloc(&counts); + { + auto made = document::create(alloc); + require(BOOST_TEST(made.has_value())); + BOOST_TEST(made->reserve(65536).has_value()); + const wd::document source = sample(); + auto copy = wd::from_image(source.image(), alloc); + require(BOOST_TEST(copy.has_value())); + BOOST_TEST(copy->get_allocator() == alloc); + BOOST_TEST(same_image(*copy, source)); + } + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 3U); +} + +// A move assignment is noexcept where it never copies: for the standard allocator, for an external +// document whatever its allocator, and for an allocator that propagates or is always equal; an +// owned document of polymorphic allocators, which may differ, may copy and throw. +static_assert(std::is_nothrow_move_assignable_v<wd::document>); +static_assert( + std::is_nothrow_move_assignable_v<wd::basic_document<wd::default_traits, wd::external>>); +static_assert( + std::is_nothrow_move_assignable_v<wd::basic_document<wd::default_traits, wd::pmr::external>>); +static_assert(std::is_nothrow_move_assignable_v< + explicit_document<wd::default_traits, propagation::always_equal>>); +static_assert( + std::is_nothrow_move_assignable_v<explicit_document<wd::default_traits, propagation::on_move>>); +static_assert(!std::is_nothrow_move_assignable_v<wd::pmr::document>); +static_assert(!std::is_nothrow_move_assignable_v<explicit_document<wd::default_traits>>); + +// An allocator that propagates on a move assignment is taken with the image: the target's own image +// is given back to its own allocator, nothing is copied, and the target allocates in the source's +// allocator from then on. +void propagating_allocator() { + allocator_counts target_counts; + allocator_counts source_counts; + using document = explicit_document<wd::default_traits, propagation::on_move>; + using allocator = explicit_allocator<std::byte, propagation::on_move>; + auto target = document::create(allocator(&target_counts)); + auto source = document::create(allocator(&source_counts)); + require(BOOST_TEST(target.has_value() && source.has_value())); + BOOST_TEST(source->root().set(wd::object{{"name", "document"}}).has_value()); + const std::byte* image = source->image().data(); + const std::uint64_t made = source_counts.allocations; + *target = std::move(*source); + BOOST_TEST(target->image().data() == image); + BOOST_TEST(target->get_allocator().counts() == &source_counts); + BOOST_TEST_EQ(source_counts.allocations, made); + BOOST_TEST_EQ(target_counts.allocations, target_counts.deallocations); + BOOST_TEST(target->reserve(65536).has_value()); + BOOST_TEST_EQ(source_counts.allocations, made + 1); + BOOST_TEST((*target)["name"].get<std::string_view>().value() == "document"); +} + +// An allocator whose instances are always equal, though each counts in its own place, lets a move +// assignment take the image as it is, with no copy; what it allocated is given back through the +// target's, which equals it. +void always_equal_allocator() { + allocator_counts target_counts; + allocator_counts source_counts; + { + using document = explicit_document<wd::default_traits, propagation::always_equal>; + using allocator = explicit_allocator<std::byte, propagation::always_equal>; + auto target = document::create(allocator(&target_counts)); + auto source = document::create(allocator(&source_counts)); + require(BOOST_TEST(target.has_value() && source.has_value())); + const std::byte* image = source->image().data(); + const std::uint64_t made = target_counts.allocations + source_counts.allocations; + *target = std::move(*source); + BOOST_TEST(target->image().data() == image); + BOOST_TEST(target->get_allocator().counts() == &target_counts); + BOOST_TEST_EQ(target_counts.allocations + source_counts.allocations, made); + } + BOOST_TEST_EQ(target_counts.allocations + source_counts.allocations, + target_counts.deallocations + source_counts.deallocations); +} + +// A stateful allocator of the program's own, neither standard nor polymorphic, whose rebinding +// constructor is explicit, holds the image and every operation's working state, under both traits: +// a parse whole and in chunks with a selector, the changes through handles, a missing member's key +// and its copy, Object.assign, the array methods, compaction, a copy, and stringify_to of a value +// deeper than its stack's own room in chunks larger than its piece's. It is given back all it gave. +template <class Traits> +void explicit_rebinding() { + allocator_counts counts; + const explicit_allocator<std::byte> alloc(&counts); + using parser = wd::basic_parser<Traits, wd::basic_owned<explicit_allocator<std::byte>>>; + const std::string key(120, 'k'); + const std::string text(120, 't'); + const std::string json = R"({"list":[1,")" + text + R"(",{"x":true}],")" + key + R"(":)" + + std::string(40, '[') + std::string(40, ']') + "}"; + { + auto whole = wd::parse<Traits>(json, wd::parse_options(), alloc); + require(BOOST_TEST(whole.has_value())); + parser p(wd::parse_options(), alloc); + std::uint64_t seen = 0; + BOOST_TEST(p.on("$.list[*]", [&seen](const auto&, wd::path_view) { ++seen; }).has_value()); + for (std::size_t at = 0; at < json.size(); at += 7) { + BOOST_TEST(p.write(std::string_view(json).substr(at, 7)).has_value()); + } + const auto chunked = p.finish(); + require(BOOST_TEST(chunked.has_value())); + BOOST_TEST_EQ(seen, 3U); + auto& d = *whole; + const auto missing = d[std::string(150, 'm')]; + auto copy = missing; + BOOST_TEST(copy.set(wd::object{{key, text}, {"list", wd::array{1, text}}}).has_value()); + BOOST_TEST(d["o"].set(wd::object()).has_value()); + BOOST_TEST(d["o"].assign_from(d["list"]).has_value()); + BOOST_TEST(d["list"].push(text, d["o"]).has_value()); + const auto sliced = d["list"].slice(1); + const auto joined = d["list"].concat(d["list"], text); + const auto popped = d["list"].pop(); + const auto spliced = d["list"].splice(0, 1, text); + require(BOOST_TEST(sliced.has_value() && joined.has_value() && popped.has_value() && + spliced.has_value())); + BOOST_TEST(d.compact().has_value()); + auto cloned = d.clone(); + require(BOOST_TEST(cloned.has_value())); + BOOST_TEST(*cloned == d); + std::string out; + BOOST_TEST(wd::stringify_to( + d, [&out](std::string_view piece) { out.append(piece); }, 10, 1U << 20U) + .has_value()); + BOOST_TEST(out == wd::stringify(d, 10)); + BOOST_TEST_GT(out.size(), 8192U); + } + BOOST_TEST_GT(counts.allocations, 0U); + BOOST_TEST_EQ(counts.allocations, counts.deallocations); +} + +// An allocator that gives the image a block not aligned to 16 has it given back, and the operation +// is errc::capacity with nothing changed: a document that cannot be made, read from an image, +// grown, shrunk, compacted or copied; a heap at another alignment would put its first block where +// the tree does not look for it. The allocator is given back every block it made. +void under_aligned_image_is_capacity() { + using storage = wd::basic_owned<aligning_allocator<std::byte>>; + using document = wd::basic_document<wd::default_traits, storage>; + alignment_control control; + const aligning_allocator<std::byte> alloc(&control); + const wd::document source = sample(); + { + control.under_align = true; + BOOST_TEST(document::create(alloc).error() == wd::errc::capacity); + BOOST_TEST(wd::from_image(source.image(), alloc).error() == wd::errc::capacity); + BOOST_TEST_EQ(control.allocations, 2U); + BOOST_TEST_EQ(control.deallocations, 2U); + + control.under_align = false; + auto made = wd::from_image(source.image(), alloc); + require(BOOST_TEST(made.has_value())); + BOOST_TEST(made->reserve(16384).has_value()); + const std::vector<std::byte> before = bytes_of(*made); + control.under_align = true; + BOOST_TEST(made->reserve(65536).error() == wd::errc::capacity); + BOOST_TEST(made->shrink_to_fit().error() == wd::errc::capacity); + BOOST_TEST(made->compact().error() == wd::errc::capacity); + BOOST_TEST(made->clone().error() == wd::errc::capacity); + BOOST_TEST_EQ(made->capacity(), 16384U); + BOOST_TEST(bytes_of(*made) == before); + BOOST_TEST(made->root()["name"].set("changed").has_value()); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + // A move assignment between allocators that differ copies the image, and has no result to + // return the failure in: it throws std::bad_alloc and leaves both documents as they were. + alignment_control other_control; + auto target = document::create(aligning_allocator<std::byte>(&other_control)); + require(BOOST_TEST(target.has_value())); + other_control.under_align = true; + const std::vector<std::byte> target_before = bytes_of(*target); + const std::vector<std::byte> source_before = bytes_of(*made); + bool thrown = false; + try { + *target = std::move(*made); + } catch (const std::bad_alloc&) { + thrown = true; + } + BOOST_TEST(thrown); + BOOST_TEST(bytes_of(*target) == target_before); + BOOST_TEST(bytes_of(*made) == source_before); + other_control.under_align = false; +#endif + } + BOOST_TEST_EQ(control.allocations, control.deallocations); +} + +// An allocator whose pointer is not a plain one is given back the very pointers it handed out, tag +// and all: the image's pointer is kept as the allocator gave it, never rebuilt from an address, +// whether the image is made, grown, changed, shrunk, compacted, copied or moved. +void fancy_pointers_kept() { + tag_counts counts; + using storage = wd::basic_owned<tagging_allocator<std::byte>>; + using document = wd::basic_document<wd::default_traits, storage>; + const tagging_allocator<std::byte> alloc(&counts); + { + auto made = document::create(alloc); + require(BOOST_TEST(made.has_value())); + BOOST_TEST(made->reserve(65536).has_value()); + BOOST_TEST(made->root() + .set(wd::object{{"name", "document"}, {"list", wd::array{1, 2}}}) + .has_value()); + BOOST_TEST(made->shrink_to_fit().has_value()); + BOOST_TEST(made->compact().has_value()); + auto copy = made->clone(); + require(BOOST_TEST(copy.has_value())); + document moved(std::move(*made)); + *copy = std::move(moved); + BOOST_TEST(copy->root()["name"].get<std::string_view>().value() == "document"); + } + BOOST_TEST_GT(counts.allocations, 0U); + BOOST_TEST_EQ(counts.allocations, counts.deallocations); + BOOST_TEST_EQ(counts.untagged, 0U); +} + +// A document that holds nothing allocates nothing, in its allocator or the global heap, reads as a +// moved-from document does, refuses a change and a copy with errc::type, and takes an image by a +// move assignment. +template <class Storage> +void holding_nothing() { + using document = wd::basic_document<wd::default_traits, Storage>; + arena a(mebibyte); + const wd::document source = sample(); + // Literals hold their values in the standard allocator: made before anything is counted. + const wd::object members{{"key", wd::array{1, "text"}}}; + const wd::array elements{1, 2}; + const global_count global; + document none = document::nothing(a.allocator()); + BOOST_TEST(none.get_allocator().resource() == &a.resource()); + BOOST_TEST(none.root().is_undefined()); + BOOST_TEST(none.image().empty()); + BOOST_TEST_EQ(none.capacity(), 0U); + auto root = none.root(); + BOOST_TEST(root.set(1).error() == wd::errc::type); + BOOST_TEST(root.set(members).error() == wd::errc::type); + BOOST_TEST(root["key"].set(elements).error() == wd::errc::type); + BOOST_TEST(none.clone().error() == wd::errc::type); + BOOST_TEST_EQ(global.news(), 0U); + BOOST_TEST_EQ(a.resource().allocations(), 0U); + if constexpr (wd::detail::owned_storage<Storage>) { + auto made = wd::from_image(source.image(), a.allocator()); + require(BOOST_TEST(made.has_value())); + none = std::move(*made); + BOOST_TEST(same_image(none, source)); + } +} + +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + +// The sugar's copy asks select_on_container_copy_construction, which gives a polymorphic +// allocator the default resource; the allocator-extended copy takes the one given. +void copies_select_allocator() { + arena a(mebibyte); + arena b(mebibyte); + const wd::document source = sample(); + auto made = wd::from_image(source.image(), a.allocator()); + require(BOOST_TEST(made.has_value())); + // The copy constructor itself is what is tested, hence a copy where a reference would read. + const wd::pmr::document copied(*made); // NOLINT(performance-unnecessary-copy-initialization) + BOOST_TEST(copied.get_allocator().resource() == std::pmr::get_default_resource()); + const wd::pmr::document placed(*made, b.allocator()); + BOOST_TEST(placed.get_allocator().resource() == &b.resource()); + BOOST_TEST(same_image(placed, source)); + const wd::pmr::document fresh(a.allocator()); + BOOST_TEST(fresh.get_allocator().resource() == &a.resource()); + BOOST_TEST(fresh.root().is_null()); +} + +// An allocator with no room is errc::capacity, and changes nothing: a document that cannot be made, +// grown, copied or read from an image; and a move assignment that cannot copy throws std::bad_alloc +// and leaves both documents as they were. +void full_allocator_is_capacity() { + const wd::document source = sample(); + { + arena tiny(1024); + BOOST_TEST(wd::pmr::document::create(tiny.allocator()).error() == wd::errc::capacity); + BOOST_TEST(wd::from_image(source.image(), tiny.allocator()).error() == wd::errc::capacity); + } + // Room for one empty document's 4,096 bytes and not for a second. + arena small(6144); + auto made = wd::pmr::document::create(small.allocator()); + require(BOOST_TEST(made.has_value())); + const std::vector<std::byte> before = bytes_of(*made); + BOOST_TEST(made->reserve(65536).error() == wd::errc::capacity); + BOOST_TEST_EQ(made->capacity(), 4096U); + BOOST_TEST(bytes_of(*made) == before); + BOOST_TEST(made->clone().error() == wd::errc::capacity); + BOOST_TEST(made->root().is_null()); + + arena large(mebibyte); + auto full = wd::from_image(source.image(), large.allocator()); + require(BOOST_TEST(full.has_value())); + bool thrown = false; + try { + *made = std::move(*full); + } catch (const std::bad_alloc&) { + thrown = true; + } + BOOST_TEST(thrown); + BOOST_TEST(bytes_of(*made) == before); + BOOST_TEST(same_image(*full, source)); +} + +/** The error of `made`; none when it holds a document. */ +template <class Document> +boost::system::error_code error_of(const wd::result<Document>& made) { + return made.has_value() ? boost::system::error_code() : made.error(); +} + +/** + Runs `op` over `failing`, which allows each budget from 0 until `op` succeeds: each failure must be + errc::capacity, and at least one budget must fail. +*/ +template <class Op> +void capacity_until_it_fits(webcpp::test::interprocess_failing_resource& failing, Op op) { + constexpr std::uint64_t unlimited = std::uint64_t{1} << 40U; + for (std::uint64_t budget = 0;; ++budget) { + failing.allow(budget); + const boost::system::error_code failed = op(); + failing.allow(unlimited); + if (!failed) { + BOOST_TEST_GT(budget, 0U); + return; + } + BOOST_TEST(failed == wd::errc::capacity); + // An operation that kept failing would never end the loop. + if (!BOOST_TEST_LT(budget, 10000U)) { + return; + } + } +} + +// An allocator of Boost.Interprocess fails with its own bad_alloc, which derives from +// std::exception alone: it is errc::capacity as std::bad_alloc is, at every allocation of the +// image, of a change's staging, of a prepared value, of a missing member's key, of the parser's +// working state and selectors, of the writer's, and of the array methods' copies. +void interprocess_failure_is_capacity() { + webcpp::test::interprocess_failing_resource failing(std::pmr::new_delete_resource(), 0); + const std::pmr::polymorphic_allocator<std::byte> alloc(&failing); + const std::string key(120, 'k'); + const std::string text(120, 't'); + const std::string json = R"({"list":[1,")" + text + R"(",[true]],")" + key + R"(":)" + + std::string(40, '[') + std::string(40, ']') + "}"; + const wd::object members{{key, text}, {"list", wd::array{1, text, wd::object{{key, true}}}}}; + const auto source = wd::parse(json); + require(BOOST_TEST(source.has_value())); + capacity_until_it_fits(failing, [&] { return error_of(wd::pmr::document::create(alloc)); }); + capacity_until_it_fits(failing, [&] { + auto d = wd::from_image(source->image(), alloc); + return d.has_value() ? d->reserve(1U << 20U).error() : d.error(); + }); + capacity_until_it_fits(failing, + [&] { return error_of(wd::parse(json, wd::parse_options(), alloc)); }); + capacity_until_it_fits(failing, [&]() -> boost::system::error_code { + wd::pmr::parser p(wd::parse_options(), alloc); + if (const auto added = p.on("$.list[*]", [](const auto&, wd::path_view) {}); !added) { + return added.error(); + } + for (std::size_t at = 0; at < json.size(); ++at) { + if (const auto written = p.write(std::string_view(json).substr(at, 1)); !written) { + return written.error(); + } + } + return error_of(p.finish()); + }); + capacity_until_it_fits(failing, [&]() -> boost::system::error_code { + auto d = wd::from_image(source->image(), alloc); + if (!d.has_value()) { + return d.error(); + } + if (const auto set = (*d)["o"].set(wd::object()); !set) { + return set.error(); + } + return (*d)["o"][key].set(members).error(); + }); + capacity_until_it_fits(failing, [&]() -> boost::system::error_code { + auto d = wd::from_image(source->image(), alloc); + if (!d.has_value()) { + return d.error(); + } + std::string out; + return wd::stringify_to( + *d, [&out](std::string_view piece) { out.append(piece); }, 10, 1U << 20U) + .error(); + }); + capacity_until_it_fits(failing, [&]() -> boost::system::error_code { + auto d = wd::from_image(source->image(), alloc); + if (!d.has_value()) { + return d.error(); + } + if (const auto copied = (*d)["list"].concat((*d)["list"], members); !copied) { + return copied.error(); + } + return d->compact().error(); + }); +} + +// A move assignment that cannot copy the image into an allocator of Boost.Interprocess, which +// fails with its own bad_alloc, throws std::bad_alloc and leaves the source as it was. +void interprocess_failure_throws_from_a_move() { + webcpp::test::interprocess_failing_resource failing(std::pmr::new_delete_resource(), 1); + const std::pmr::polymorphic_allocator<std::byte> alloc(&failing); + const auto source = wd::parse(R"({"name":"document","list":[1,2]})"); + require(BOOST_TEST(source.has_value())); + auto target = wd::pmr::document::create(alloc); + auto other = wd::from_image(source->image()); + require(BOOST_TEST(target.has_value() && other.has_value())); + wd::pmr::document from = wd::pmr::document::nothing(); + { + auto copied = wd::from_image(source->image(), std::pmr::polymorphic_allocator<std::byte>()); + require(BOOST_TEST(copied.has_value())); + from = std::move(*copied); + } + failing.allow(0); + bool thrown = false; + try { + *target = std::move(from); + } catch (const std::bad_alloc&) { + thrown = true; + } + failing.allow(std::uint64_t{1} << 40U); + BOOST_TEST(thrown); + // The assignment threw before it took anything: `from` is read as it was. + BOOST_TEST(same_image(from, *other)); // NOLINT(bugprone-use-after-move) +} + +#endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS + +} // namespace + +int main() { + image_in_resource(); + default_storage_unchanged(); + move_takes_allocator(); + move_assign_across_resources(); + clone_into_resources(); + external_carries_allocator(); + any_allocator(); + propagating_allocator(); + always_equal_allocator(); + explicit_rebinding<wd::default_traits>(); + explicit_rebinding<wd::js_traits>(); + under_aligned_image_is_capacity(); + fancy_pointers_kept(); + holding_nothing<wd::pmr::owned>(); + holding_nothing<wd::pmr::external>(); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + copies_select_allocator(); + full_allocator_is_capacity(); + interprocess_failure_is_capacity(); + interprocess_failure_throws_from_a_move(); +#endif + return boost::report_errors(); +} diff --git a/test/allocator_tree_test.cpp b/test/allocator_tree_test.cpp new file mode 100644 index 0000000..4129a1f --- /dev/null +++ b/test/allocator_tree_test.cpp @@ -0,0 +1,898 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The tree's working state in the document's allocator: what a change stages before it changes +// anything (its nodes, the values still to read, the sizes it probes, the subtrees it erases, a +// literal's keys, and the copies of what it views in an image that must move) and compaction's walk +// are allocated through the document's allocator, rebound, with no call of the global operator +// new, under the default traits and JavaScript's, and all of it is given back; a member is found by +// a key of any length with no allocation at all; and, with exceptions, an allocator that fails at +// any of an operation's allocations makes it errc::capacity with the document unchanged. + +#include <webcpp/document.hpp> + +#include <boost/core/lightweight_test.hpp> +#include <boost/hash2/fnv1a.hpp> + +#include "counting.hpp" +#include "require.hpp" + +#include <algorithm> +#include <array> +#include <concepts> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <limits> +#include <memory_resource> +#include <span> +#include <string> +#include <string_view> +#include <utility> +#include <vector> + +namespace wd = webcpp::document; +namespace detail = webcpp::document::detail; + +namespace { + +using webcpp::test::arena; +using webcpp::test::failing_resource; +using webcpp::test::global_count; +using webcpp::test::require; + +/** The allocator of every document and tree here: a memory resource's. */ +using pmr_allocator = std::pmr::polymorphic_allocator<std::byte>; + +/** The region of a tree in a memory resource. */ +using pmr_region = detail::basic_region<pmr_allocator>; + +/** A tree of `Traits` in a memory resource. */ +template <class Traits> +using pmr_tree = detail::tree<Traits, pmr_allocator>; + +constexpr std::size_t mebibyte = std::size_t{1} << 20U; + +/** The default traits, but every object's keys in order of their UTF-16 code units. */ +struct sorted_traits : wd::default_traits { + /** Keys sorted. */ + using object = wd::sorted; +}; + +/** JavaScript's traits, but every object's keys in the order they were inserted. */ +struct insertion_traits : wd::js_traits { + /** Keys in insertion order. */ + using object = wd::insertion_order; +}; + +/** + The size an image here may grow to. Named apart from the `max_bytes` parameter of the document's + `create`: a parameter of a class template's member that hides a global of its name makes MSVC + warn (C4459, an error under /WX) wherever it compiles that member. +*/ +constexpr std::uint64_t image_limit = std::uint64_t{64} << 20U; + +/** A string past any small-string buffer, which `set` stores without copying it. */ +constexpr std::string_view long_text = + "A string longer than the small buffer of any std::string, which the tree copies into the " + "image as it is given."; + +/** The same string in UTF-16, which `set` stores in a document of JavaScript's traits. */ +constexpr std::u16string_view long_text16 = + u"A string longer than the small buffer of any std::string, which the tree copies into the " + u"image as it is given."; + +static_assert(long_text.size() >= 100 && long_text16.size() == long_text.size()); + +/** The long string in the encoding of `Traits`, which `set` stores without copying it. */ +template <class Traits> +auto long_string_of() { + if constexpr (std::same_as<typename Traits::string, wd::utf16>) { + return long_text16; + } else { + return long_text; + } +} + +/** + A key in UTF-8 past 64 UTF-16 code units and any small-string buffer, ending with `n`: 12 times a + stem of 10 bytes and 7 units, one of its characters past U+FFFF. +*/ +std::string long_key(std::size_t n) { + std::string key; + for (int i = 0; i < 12; ++i) { + key += "cl\xC3\xA9-\xF0\x9F\x98\x80-"; + } + key += std::to_string(n); + return key; +} + +/** The value of a result that must hold one. */ +template <class T> +T take(wd::result<T> made) { + require(BOOST_TEST(made.has_value())); + return std::move(*made); +} + +/** Sets the value `i` of a run of values: an integer, a boolean, null or a long string. */ +template <class Traits, class Handle> +wd::result<void> set_value(Handle& h, std::size_t i) { + switch (i % 4) { + case 0: return h.set(static_cast<std::int64_t>(i)); + case 1: return h.set(i % 8 == 1); + case 2: return h.set(nullptr); + default: return h.set(long_string_of<Traits>()); + } +} + +// Members with long keys, set, assigned, found and erased, grow an image several times with no +// call of the global operator new: the tree stages each change in the document's resource, and +// gives it all back. +template <class Traits> +void members_in_resource() { + using document = wd::pmr::basic_document<Traits>; + constexpr std::size_t members = 240; + arena a(16 * mebibyte); + { + document d = take(document::create(a.allocator())); + require(BOOST_TEST(d.root().set(wd::object{}))); + // The keys, and the handles that name them, are made before anything is counted. + std::vector<std::string> keys; + keys.reserve(members); + for (std::size_t i = 0; i < members; ++i) { + keys.push_back(long_key(i)); + } + std::vector<decltype(d.root())> places; + places.reserve(members); + for (const std::string& key : keys) { + places.push_back(d.root()[key]); + } + const std::uint64_t first_capacity = d.capacity(); + const std::uint64_t taken = a.resource().allocations(); + { + const global_count global; + for (std::size_t i = 0; i < members; ++i) { + BOOST_TEST(set_value<Traits>(places[i], i).has_value()); + } + BOOST_TEST(places[0].set(true).has_value()); + BOOST_TEST(d.root().contains(keys[1])); + BOOST_TEST(places[2].set(wd::undefined).has_value()); + const auto erased = d.root().erase(keys[3]); + BOOST_TEST(erased.has_value() && *erased); + BOOST_TEST_EQ(global.news(), 0U); + } + BOOST_TEST_GT(a.resource().allocations(), taken); + // Grown from 4,096 bytes, at least doubling each time, four times or more. + BOOST_TEST_GE(d.capacity(), 16 * first_capacity); + BOOST_TEST_EQ(d.root().size(), members - 2); + BOOST_TEST(d.root()[keys[0]].is_boolean()); + BOOST_TEST(d.root()[keys[members - 1]].is_string()); + BOOST_TEST(!d.root().contains(keys[2])); + BOOST_TEST(!d.root().contains(keys[3])); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// The array methods stage their changes in the document's resource: push, unshift, splice, pop +// and shift, whose documents are the resource's too, reverse, and set_length, which appends and +// erases. +template <class Traits> +void arrays_in_resource() { + using document = wd::pmr::basic_document<Traits>; + arena a(16 * mebibyte); + { + document d = take(document::create(a.allocator())); + require(BOOST_TEST(d.root().set(wd::array{}))); + auto list = d.root(); + const auto text = long_string_of<Traits>(); + const std::uint64_t taken = a.resource().allocations(); + { + const global_count global; + for (std::int64_t i = 0; i < 50; ++i) { + BOOST_TEST(list.push(i, true, nullptr, text).has_value()); + } + BOOST_TEST(list.unshift(std::int64_t{-1}, text).has_value()); + BOOST_TEST(list.splice(1, 0, false, text).has_value()); + const auto last = list.pop(); + BOOST_TEST(last.has_value() && last->root().is_string()); + const auto first = list.shift(); + BOOST_TEST(first.has_value() && first->root().is_number()); + BOOST_TEST(list.reverse().has_value()); + BOOST_TEST(list.set_length(250).has_value()); + BOOST_TEST(list.set_length(10).has_value()); + BOOST_TEST_EQ(global.news(), 0U); + } + BOOST_TEST_GT(a.resource().allocations(), taken); + BOOST_TEST_EQ(d.root().size(), 10U); + // Reversed, the list starts with the last push's values, its string popped. + BOOST_TEST(d.root()[std::uint64_t{0}].is_null()); + BOOST_TEST(d.root()[std::uint64_t{1}].is_boolean()); + BOOST_TEST(d.root()[std::uint64_t{2}].is_number()); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +/** A JSON text of nested containers, strings and scalars, for deep copies and failures. */ +constexpr std::string_view sample_json = R"({ + "small": 1, + "nested": {"a": [1, 2, {"deep": [[["x", {"y": [true]}]]]}], "b": true, "c": "text"}, + "list": [1, "two", {"x": 1}, [1, 2, 3], null] +})"; + +/** The sample, with a long string at a long key, parsed into `alloc`. */ +template <class Traits> +wd::pmr::basic_document<Traits> sample(const pmr_allocator& alloc) { + auto d = take(wd::parse<Traits>(sample_json, wd::parse_options(), alloc)); + require(BOOST_TEST(d.root()[long_key(0)].set(long_string_of<Traits>()).has_value())); + return d; +} + +// A deep copy stages its nodes in the document's resource: of a document in another resource, +// and of the document's own value into an image that must grow first, whose views into the image +// are copied, in the resource, before it moves; and shrink_to_fit, reserve and compact make no +// call of the global operator new either. +template <class Traits> +void copies_in_resource() { + using document = wd::pmr::basic_document<Traits>; + arena a(16 * mebibyte); + arena b(4 * mebibyte); + { + const document source = sample<Traits>(b.allocator()); + document d = take(document::create(a.allocator())); + require(BOOST_TEST(d.root().set(wd::object{}))); + auto copy = d.root()["copy"]; + auto again = d.root()["again"]; + const std::uint64_t taken = a.resource().allocations(); + { + const global_count global; + BOOST_TEST(copy.set(source).has_value()); + BOOST_TEST(d.shrink_to_fit().has_value()); + const std::uint64_t full = d.capacity(); + BOOST_TEST(again.set(d.root()["copy"]).has_value()); + BOOST_TEST_GT(d.capacity(), full); + BOOST_TEST(d.root()["copy"].set(std::int64_t{1}).has_value()); + BOOST_TEST(d.reserve(2 * d.capacity()).has_value()); + BOOST_TEST(d.compact().has_value()); + BOOST_TEST_EQ(global.news(), 0U); + } + BOOST_TEST_GT(a.resource().allocations(), taken); + BOOST_TEST(d.root()["again"] == source.root()); + BOOST_TEST(d.root()["copy"].is_number()); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); + BOOST_TEST_EQ(b.resource().bytes_in_use(), 0U); +} + +/** An item holding the integer `v`. */ +template <class Traits> +detail::item<Traits> integer(std::int64_t v) { + detail::item<Traits> i; + i.kind = wd::kind::number; + i.number = detail::repr::integer; + i.store(v); + return i; +} + +/** An item holding `v`. */ +template <class Traits> +detail::item<Traits> boolean(bool v) { + detail::item<Traits> i; + i.kind = wd::kind::boolean; + i.store(v); + return i; +} + +/** An item holding the long string, in the traits' encoding. */ +template <class Traits> +detail::item<Traits> long_string() { + detail::item<Traits> i; + i.kind = wd::kind::string; + i.text = std::as_bytes(std::span(long_string_of<Traits>())); + return i; +} + +/** An item holding an empty container of `k`, or a literal one of `entries`, which outlive it. */ +template <class Traits> +detail::item<Traits> container(wd::kind k, + std::span<const detail::literal_entry<Traits>> entries = {}) { + detail::item<Traits> i; + i.kind = k; + i.entries = entries.empty() ? nullptr : entries.data(); + i.entry_count = entries.size(); + return i; +} + +/** An item that copies the node `id` of `from`, deeply. */ +template <class Traits> +detail::item<Traits> copy_of(const detail::tree_view<Traits>& from, std::uint64_t id) { + detail::item<Traits> i; + i.from = &from; + i.from_id = id; + return i; +} + +/** A tree in a region of its own, in a memory resource; it is not moved, its tree naming it. */ +template <class Traits> +struct pmr_fixture { + /** A new tree holding null, in `alloc`. */ + explicit pmr_fixture(const pmr_allocator& alloc) + : r(take(pmr_region::owned(4096, image_limit, alloc))), + t(take(pmr_tree<Traits>::format(r))) {} + + /** A tree over a copy of the image of `other`, in `alloc`. */ + pmr_fixture(const pmr_fixture& other, const pmr_allocator& alloc) + : r(take(pmr_region::owned_copy(other.image(), image_limit, alloc))), + t(take(pmr_tree<Traits>::attach(r))) {} + + pmr_fixture(const pmr_fixture&) = delete; + pmr_fixture& operator=(const pmr_fixture&) = delete; + pmr_fixture(pmr_fixture&&) = delete; + pmr_fixture& operator=(pmr_fixture&&) = delete; + ~pmr_fixture() = default; + + /** The image. */ + [[nodiscard]] std::span<const std::byte> image() const { + return {r.data(), static_cast<std::size_t>(r.size())}; + } + + /** The image's next id. */ + [[nodiscard]] std::uint64_t next_id() const { + wd::image_header header{}; + std::memcpy(&header, r.data(), sizeof header); + return header.next_id; + } + + /** The region. */ + pmr_region r; + + /** The tree over it. */ + pmr_tree<Traits> t; +}; + +/** The id of the member `key` of `object`, which must be there. */ +template <class Traits> +std::uint64_t id_of(const detail::tree_view<Traits>& t, std::uint64_t object, + std::string_view key) { + const detail::node<Traits>* n = t.member(object, key); + require(BOOST_TEST(n != nullptr)); + return n->id; +} + +/** + Builds in `t` the sample's shape: an object of a small member, a nested object, a list holding a + copy of it, and a long string at a long key; returns the ids of the nested object and the list. +*/ +template <class Traits> +std::pair<std::uint64_t, std::uint64_t> build_sample(pmr_tree<Traits>& t) { + const std::uint64_t root = detail::root_id; + require(BOOST_TEST(t.assign(root, container<Traits>(wd::kind::object)).has_value())); + require(BOOST_TEST(t.set_member(root, "small", integer<Traits>(1)).has_value())); + const std::uint64_t nested = + take(t.set_member(root, "nested", container<Traits>(wd::kind::object))); + const std::uint64_t inner = take(t.set_member(nested, "a", container<Traits>(wd::kind::array))); + for (std::uint64_t i = 0; i < 6; ++i) { + const auto value = + i % 2 == 0 ? long_string<Traits>() : integer<Traits>(static_cast<std::int64_t>(i)); + require(BOOST_TEST(t.set_element(inner, i, value).has_value())); + } + require(BOOST_TEST(t.set_member(nested, long_key(1), boolean<Traits>(true)).has_value())); + const std::uint64_t list = take(t.set_member(root, "list", container<Traits>(wd::kind::array))); + for (std::uint64_t i = 0; i < 5; ++i) { + require(BOOST_TEST( + t.set_element(list, i, integer<Traits>(static_cast<std::int64_t>(i))).has_value())); + } + require(BOOST_TEST(t.set_element(list, 2, copy_of<Traits>(t, nested)).has_value())); + require(BOOST_TEST(t.set_member(root, long_key(0), long_string<Traits>()).has_value())); + return {nested, list}; +} + +// The tree's own operations, which no handle or conversion takes part in, stage in the region's +// resource: members with long keys, whose UTF-16 the tree writes into the image itself, a +// literal's members, a repeated key keeping its first place and its last value, lookups by long +// keys, a splice that erases a subtree and copies one, and erasures. +template <class Traits> +void tree_operations_in_resource() { + using entry = detail::literal_entry<Traits>; + const std::uint64_t root = detail::root_id; + arena a(4 * mebibyte); + { + pmr_fixture<Traits> f(a.allocator()); + const auto [nested, list] = build_sample(f.t); + const std::array<std::string, 3> keys{long_key(10), long_key(11), long_key(12)}; + const std::string nested_key = long_key(1); + const std::string near_miss = keys[0] + "x"; + const std::string_view prefix = std::string_view(keys[0]).substr(0, keys[0].size() - 1); + const auto inner = std::to_array<entry>({ + {.key = keys[2], .value = integer<Traits>(7)}, + {.key = "x", .value = boolean<Traits>(true)}, + }); + const auto entries = std::to_array<entry>({ + {.key = "x", .value = integer<Traits>(1)}, + {.key = keys[1], .value = long_string<Traits>()}, + {.key = "x", .value = integer<Traits>(2)}, + {.key = "inner", .value = container<Traits>(wd::kind::object, inner)}, + {.key = keys[0], .value = integer<Traits>(3)}, + }); + const std::array<detail::item<Traits>, 2> inserted{ + copy_of<Traits>(f.t, nested), + long_string<Traits>(), + }; + const std::uint64_t taken = a.resource().allocations(); + std::uint64_t first = 0; + { + const global_count global; + const auto set = f.t.set_member(root, keys[0], long_string<Traits>()); + BOOST_TEST(set.has_value()); + first = set.has_value() ? *set : 0; + BOOST_TEST(f.t.set_members(root, entries).has_value()); + const detail::node<Traits>* found = f.t.member(root, keys[0]); + BOOST_TEST(found != nullptr && found->id == first); + BOOST_TEST(f.t.member(root, near_miss) == nullptr); + BOOST_TEST(f.t.member(root, prefix) == nullptr); + BOOST_TEST(f.t.member(nested, nested_key) != nullptr); + BOOST_TEST(f.t.splice(list, 1, 2, inserted).has_value()); + const auto erased = f.t.erase_member(root, keys[1]); + BOOST_TEST(erased.has_value() && *erased); + const auto gone = f.t.erase_member(root, "nested"); + BOOST_TEST(gone.has_value() && *gone); + BOOST_TEST_EQ(global.news(), 0U); + } + BOOST_TEST_GT(a.resource().allocations(), taken); + // "x" keeps the place of its first entry and the value of its last; the key set first is + // assigned in place. + const detail::node<Traits>* x = f.t.member(root, "x"); + require(BOOST_TEST(x != nullptr)); + BOOST_TEST_EQ(x->template load<std::int64_t>(), 2); + const detail::node<Traits>* assigned = f.t.member(root, keys[0]); + require(BOOST_TEST(assigned != nullptr)); + BOOST_TEST_EQ(assigned->id, first); + BOOST_TEST_EQ(assigned->template load<std::int64_t>(), 3); + if constexpr (std::same_as<typename Traits::object, wd::sorted>) { + // Sorted keys take their places by their bytes, UTF-8 and UTF-16 alike here. + std::string_view previous; + for (const detail::node<Traits>* n = f.t.first_child(root); n != nullptr; + n = f.t.next_sibling(*n)) { + BOOST_TEST(previous < n->key.chars()); + previous = n->key.chars(); + } + } else { + BOOST_TEST_EQ(f.t.next_sibling(*assigned)->id, x->id); + } + const std::uint64_t literal = id_of(f.t, root, "inner"); + BOOST_TEST_EQ(f.t.count(literal), 2U); + BOOST_TEST(f.t.member(literal, keys[2]) != nullptr); + BOOST_TEST_EQ(f.t.count(list), 5U); + BOOST_TEST(f.t.member(root, "nested") == nullptr); + BOOST_TEST(f.t.member(root, keys[1]) == nullptr); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// A key given in UTF-8 finds the member stored under it in UTF-16, by code units, among +// characters past U+FFFF and from U+E000 to U+FFFF, which UTF-8 orders otherwise, with no +// allocation; a key between two stored ones, or longer than one, finds nothing. +void lookups_by_utf8_keys() { + using traits = wd::js_traits; + const std::array<std::string_view, 6> letters{ + "a", // U+0061 + "\xC3\xA9", // U+00E9 + "\xEE\x80\x80", // U+E000, which UTF-16 orders after a surrogate pair, UTF-8 before + "\xEF\xBD\xA1", // U+FF61 + "\xF0\x9F\x98\x80", // U+1F600, a surrogate pair + "\xF4\x8F\xBF\xBF", // U+10FFFF, the last + }; + std::vector<std::string> keys; + for (const std::string_view x : letters) { + for (const std::string_view y : letters) { + for (const std::string_view z : letters) { + keys.push_back(std::string(x) + std::string(y) + std::string(z)); + } + } + } + const std::string longer = keys[8] + "a"; + arena a(4 * mebibyte); + { + pmr_fixture<traits> f(a.allocator()); + const std::uint64_t root = detail::root_id; + require(BOOST_TEST(f.t.assign(root, container<traits>(wd::kind::object)).has_value())); + // Every other key is stored, so that each one left out falls between two stored ones. + for (std::size_t i = 0; i < keys.size(); i += 2) { + require(BOOST_TEST( + f.t.set_member(root, keys[i], integer<traits>(static_cast<std::int64_t>(i))) + .has_value())); + } + const global_count global; + for (std::size_t i = 0; i < keys.size(); ++i) { + const detail::node<traits>* n = f.t.member(root, keys[i]); + if (i % 2 == 0) { + BOOST_TEST(n != nullptr && + n->template load<std::int64_t>() == static_cast<std::int64_t>(i)); + } else { + BOOST_TEST(n == nullptr); + } + } + BOOST_TEST(f.t.member(root, longer) == nullptr); + BOOST_TEST(f.t.member(root, "\xFF") == nullptr); + BOOST_TEST_EQ(global.news(), 0U); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +/** A budget that refuses nothing. */ +constexpr std::uint64_t unlimited = std::numeric_limits<std::uint64_t>::max(); + +/** Whether an erasure erased. */ +bool erased(const wd::result<bool>& r) { + return r.has_value() && *r; +} + +// An erasure needs no room: members erased by key and by id, elements erased and cut off, through +// the tree and through the handles, allocate nothing at all, so that a resource that refuses +// every allocation lets them all through. A refusal would end a build without exceptions as +// surely as it fails this one. +template <class Traits> +void erasures_allocate_nothing() { + const std::uint64_t root = detail::root_id; + failing_resource failing(std::pmr::new_delete_resource(), unlimited); + { + pmr_fixture<Traits> f{pmr_allocator(&failing)}; + const auto [nested, list] = build_sample(f.t); + const std::uint64_t small = id_of(f.t, root, "small"); + const std::uint64_t keyed = id_of(f.t, root, long_key(0)); + const std::uint64_t element = f.t.element(list, 0)->id; + auto d = sample<Traits>(pmr_allocator(&failing)); + const std::string key = long_key(0); + auto items = d.root()["list"]; + failing.allow(0); + { + const global_count global; + BOOST_TEST(erased(f.t.erase_member(root, "nested"))); + BOOST_TEST(!erased(f.t.erase_member(root, "absent"))); + BOOST_TEST(!erased(f.t.erase_member_by_id(root, element))); + BOOST_TEST(f.t.erase_member_by_id(list, element).error() == wd::errc::type); + BOOST_TEST(erased(f.t.erase_member_by_id(root, keyed))); + BOOST_TEST(f.t.erase_elements(list, 1, 2).has_value()); + BOOST_TEST(f.t.splice(list, 0, 1, {}).has_value()); + BOOST_TEST(f.t.set_length(list, 0).has_value()); + BOOST_TEST(erased(f.t.erase_member_by_id(root, list))); + BOOST_TEST(erased(f.t.erase_member_by_id(root, small))); + BOOST_TEST(erased(d.root().erase(key))); + BOOST_TEST(erased(d.root().erase("nested"))); + BOOST_TEST(items.set_length(1).has_value()); + BOOST_TEST_EQ(global.news(), 0U); + } + BOOST_TEST_EQ(failing.refusals(), 0U); + failing.allow(unlimited); + BOOST_TEST_EQ(f.t.count(root), 0U); + BOOST_TEST_EQ(f.t.node_count(), 1U); + BOOST_TEST_EQ(d.root().size(), 2U); + BOOST_TEST_EQ(d.root()["list"].size(), 1U); + } + BOOST_TEST_EQ(failing.bytes_in_use(), 0U); +} + +/** + Builds a tree of the sample's shape and an array of 16 objects, then erases from it, as members, + elements, a value assigned over a subtree and arrays cut off: the digests of the image, FNV-1a of + 64 bits, before the erasures and after each. +*/ +template <class Traits> +std::vector<std::uint64_t> erasure_digests(pmr_fixture<Traits>& f) { + const std::uint64_t root = detail::root_id; + const auto [nested, list] = build_sample(f.t); + const std::uint64_t many = + take(f.t.set_member(root, "many", container<Traits>(wd::kind::array))); + for (std::uint64_t i = 0; i < 16; ++i) { + require( + BOOST_TEST(f.t.set_element(many, i, container<Traits>(wd::kind::object)).has_value())); + const std::uint64_t e = f.t.element(many, i)->id; + const std::uint64_t x = take(f.t.set_member(e, "x", container<Traits>(wd::kind::array))); + const auto n = static_cast<std::int64_t>(i); + require(BOOST_TEST(f.t.set_element(x, 0, integer<Traits>(n)).has_value())); + require(BOOST_TEST(f.t.set_element(x, 1, long_string<Traits>()).has_value())); + require(BOOST_TEST(f.t.set_member(e, long_key(i), boolean<Traits>(true)).has_value())); + } + std::vector<std::uint64_t> digests; + const auto digest = [&] { + boost::hash2::fnv1a_64 h; + h.update(f.image().data(), f.image().size()); + digests.push_back(h.result()); + }; + const std::string key = long_key(0); + digest(); + require(BOOST_TEST(f.t.erase_member(root, "nested").has_value())); + digest(); + require(BOOST_TEST(f.t.erase_elements(list, 1, 2).has_value())); + digest(); + require(BOOST_TEST(f.t.splice(list, 0, 1, {}).has_value())); + digest(); + require(BOOST_TEST(f.t.set_element(many, 3, integer<Traits>(7)).has_value())); + digest(); + require(BOOST_TEST(f.t.set_length(many, 12).has_value())); + digest(); + require(BOOST_TEST(f.t.erase_elements(many, 2, 5).has_value())); + digest(); + require(BOOST_TEST(f.t.erase_member(root, key).has_value())); + digest(); + require(BOOST_TEST(f.t.set_length(list, 0).has_value())); + digest(); + require(BOOST_TEST(f.t.erase_elements(many, 0, 1).has_value())); + digest(); + require(BOOST_TEST(f.t.erase_member(root, "many").has_value())); + digest(); + return digests; +} + +// Erasures leave every byte of the image as the tree did when it listed each erased subtree in a +// vector, whose digests are pinned here: the order the nodes of a subtree are erased in decides +// the heap's free blocks and the indices' links, so a change of it changes them. +template <class Traits> +void erasures_keep_the_image(const std::array<std::uint64_t, 11>& pinned) { + pmr_fixture<Traits> f{pmr_allocator(std::pmr::new_delete_resource())}; + const std::vector<std::uint64_t> digests = erasure_digests(f); + BOOST_TEST_ALL_EQ(digests.begin(), digests.end(), pinned.begin(), pinned.end()); +} + +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + +/** + Whether two trees hold the same nodes, each with the same id, place, key and value, and the same + next id: what an operation that fails must leave as it was. It allocates nothing. +*/ +template <class Traits> +bool same_tree(const pmr_fixture<Traits>& a, const pmr_fixture<Traits>& b) { + const auto same_node = [](const detail::node<Traits>& x, const detail::node<Traits>& y) { + return x.id == y.id && x.parent == y.parent && x.group == y.group && + x.ordinal == y.ordinal && x.kind == y.kind && x.number == y.number && + x.scalar == y.scalar && std::ranges::equal(x.key.view(), y.key.view()) && + std::ranges::equal(x.text.view(), y.text.view()); + }; + return a.next_id() == b.next_id() && + std::ranges::equal(a.t.nodes()->template get<detail::by_id>(), + b.t.nodes()->template get<detail::by_id>(), same_node); +} + +/** More allocations than any operation here makes: a run that reaches it never succeeded. */ +constexpr std::uint64_t step_limit = 100000; + +/** + Runs `operation` on a copy of `source` in a resource that refuses every allocation past the first + `budget`, for each budget from 0 until it succeeds: each run that fails must be errc::capacity, + refused by the resource, with the copy still equal to `source`, and the one that succeeds must + leave it equal to what an unhindered run makes. `operation` takes the copy and a function that + starts the budget, which it calls once it has made its handles. Returns the budget it succeeded + with: how many allocations the operation makes. +*/ +template <class Traits, class Operation> +std::uint64_t fail_each_allocation(const wd::pmr::basic_document<Traits>& source, + Operation operation) { + failing_resource failing(std::pmr::new_delete_resource(), unlimited); + const pmr_allocator alloc(&failing); + std::uint64_t budget = 0; + { + auto expected = take(wd::from_image<Traits>(source.image(), alloc)); + require(BOOST_TEST(operation(expected, [] {}).has_value())); + for (; budget < step_limit; ++budget) { + failing.allow(unlimited); + auto copy = take(wd::from_image<Traits>(source.image(), alloc)); + const std::uint64_t refused = failing.refusals(); + const auto done = operation(copy, [&failing, budget] { failing.allow(budget); }); + failing.allow(unlimited); + if (done.has_value()) { + BOOST_TEST_EQ(failing.refusals(), refused); + BOOST_TEST(copy == expected); + break; + } + BOOST_TEST(done.error() == wd::errc::capacity); + BOOST_TEST_GT(failing.refusals(), refused); + BOOST_TEST(copy == source); + } + } + BOOST_TEST_LT(budget, step_limit); + BOOST_TEST_EQ(failing.bytes_in_use(), 0U); + return budget; +} + +/** + As @ref fail_each_allocation, on a copy of the tree of `source`, which `operation` takes alone: + each run that fails must leave the copy's nodes as they were. +*/ +template <class Traits, class Operation> +std::uint64_t fail_each_allocation_in_tree(const pmr_fixture<Traits>& source, Operation operation) { + failing_resource failing(std::pmr::new_delete_resource(), unlimited); + const pmr_allocator alloc(&failing); + std::uint64_t budget = 0; + { + pmr_fixture<Traits> expected(source, alloc); + require(BOOST_TEST(operation(expected.t).has_value())); + for (; budget < step_limit; ++budget) { + failing.allow(unlimited); + pmr_fixture<Traits> copy(source, alloc); + const std::uint64_t refused = failing.refusals(); + failing.allow(budget); + const auto done = operation(copy.t); + failing.allow(unlimited); + if (done.has_value()) { + BOOST_TEST_EQ(failing.refusals(), refused); + BOOST_TEST(same_tree(copy, expected)); + break; + } + BOOST_TEST(done.error() == wd::errc::capacity); + BOOST_TEST_GT(failing.refusals(), refused); + BOOST_TEST(same_tree(copy, source)); + } + } + BOOST_TEST_LT(budget, step_limit); + BOOST_TEST_EQ(failing.bytes_in_use(), 0U); + return budget; +} + +// Through the handles: a new member at a long key, a value assigned over a subtree, a deep copy +// of the document's own value, a push, a pop and a compaction each fail at every one of their +// allocations with errc::capacity and nothing changed; an erasure has no allocation to fail at. +template <class Traits> +void handles_fail_softly() { + const auto text = long_string_of<Traits>(); + const std::string key = long_key(5); + const wd::pmr::basic_document<Traits> source = + sample<Traits>(pmr_allocator(std::pmr::new_delete_resource())); + const std::uint64_t set_member = fail_each_allocation(source, [&](auto& d, auto start) { + auto place = d.root()[key]; + start(); + return place.set(text); + }); + BOOST_TEST_GT(set_member, 0U); + const std::uint64_t assign = fail_each_allocation(source, [](auto& d, auto start) { + auto place = d.root()["nested"]; + start(); + return place.set(std::int64_t{5}); + }); + BOOST_TEST_GT(assign, 0U); + const std::uint64_t copy = fail_each_allocation(source, [](auto& d, auto start) { + auto place = d.root()["copy"]; + const auto from = d.root()["nested"]; + start(); + return place.set(from); + }); + BOOST_TEST_GT(copy, 0U); + // An erasure allocates nothing: it succeeds with no allocation allowed. + const std::uint64_t erase = fail_each_allocation(source, [](auto& d, auto start) { + start(); + return d.root().erase("nested"); + }); + BOOST_TEST_EQ(erase, 0U); + const std::uint64_t push = fail_each_allocation(source, [&](auto& d, auto start) { + auto list = d.root()["list"]; + start(); + return list.push(std::int64_t{6}, text); + }); + BOOST_TEST_GT(push, 0U); + const std::uint64_t pop = fail_each_allocation(source, [](auto& d, auto start) { + auto list = d.root()["list"]; + start(); + return list.pop(); + }); + BOOST_TEST_GT(pop, 0U); + const std::uint64_t compact = fail_each_allocation(source, [](auto& d, auto start) { + start(); + return d.compact(); + }); + // The image's buffer, then the walk's stack, which the nesting grows several times. + BOOST_TEST_GT(compact, 3U); +} + +// The tree's own operations fail at every one of their allocations with errc::capacity and +// nothing changed: a member at a long key, a literal's members that assign one holding a subtree, +// and a splice that erases subtrees and copies one; erasures, by key, by id and of elements, have +// no allocation to fail at. +template <class Traits> +void tree_fails_softly() { + using entry = detail::literal_entry<Traits>; + const std::uint64_t root = detail::root_id; + pmr_fixture<Traits> source{pmr_allocator(std::pmr::new_delete_resource())}; + const auto [nested, list] = build_sample(source.t); + const std::array<std::string, 2> keys{long_key(20), long_key(21)}; + const auto inner = std::to_array<entry>({ + {.key = keys[1], .value = long_string<Traits>()}, + {.key = "y", .value = boolean<Traits>(false)}, + }); + const auto entries = std::to_array<entry>({ + {.key = keys[0], .value = integer<Traits>(1)}, + {.key = "nested", .value = long_string<Traits>()}, + {.key = keys[0], .value = container<Traits>(wd::kind::object, inner)}, + {.key = "z", .value = container<Traits>(wd::kind::array, inner)}, + {.key = "small", .value = boolean<Traits>(true)}, + }); + const std::uint64_t set_member = fail_each_allocation_in_tree( + source, [&](auto& t) { return t.set_member(root, keys[0], long_string<Traits>()); }); + BOOST_TEST_GT(set_member, 0U); + const std::uint64_t set_members = + fail_each_allocation_in_tree(source, [&](auto& t) { return t.set_members(root, entries); }); + BOOST_TEST_GT(set_members, set_member); + const std::uint64_t splice = fail_each_allocation_in_tree(source, [&](auto& t) { + const std::array<detail::item<Traits>, 2> items{ + copy_of<Traits>(t, nested), + long_string<Traits>(), + }; + return t.splice(list, 1, 3, items); + }); + BOOST_TEST_GT(splice, 0U); + // An erasure allocates nothing: it succeeds with no allocation allowed. + const std::uint64_t erase = fail_each_allocation_in_tree( + source, [&](auto& t) { return t.erase_member(root, "nested"); }); + BOOST_TEST_EQ(erase, 0U); + const std::uint64_t erase_by_id = fail_each_allocation_in_tree( + source, [&](auto& t) { return t.erase_member_by_id(root, nested); }); + BOOST_TEST_EQ(erase_by_id, 0U); + const std::uint64_t erase_elements = + fail_each_allocation_in_tree(source, [&](auto& t) { return t.erase_elements(list, 1, 3); }); + BOOST_TEST_EQ(erase_elements, 0U); +} + +#endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS + +} // namespace + +int main() { + members_in_resource<wd::default_traits>(); + members_in_resource<wd::js_traits>(); + arrays_in_resource<wd::default_traits>(); + arrays_in_resource<wd::js_traits>(); + copies_in_resource<wd::default_traits>(); + copies_in_resource<wd::js_traits>(); + tree_operations_in_resource<wd::default_traits>(); + tree_operations_in_resource<wd::js_traits>(); + members_in_resource<sorted_traits>(); + members_in_resource<insertion_traits>(); + arrays_in_resource<sorted_traits>(); + arrays_in_resource<insertion_traits>(); + copies_in_resource<sorted_traits>(); + copies_in_resource<insertion_traits>(); + tree_operations_in_resource<sorted_traits>(); + tree_operations_in_resource<insertion_traits>(); + lookups_by_utf8_keys(); + erasures_allocate_nothing<wd::default_traits>(); + erasures_allocate_nothing<wd::js_traits>(); + erasures_allocate_nothing<sorted_traits>(); + erasures_allocate_nothing<insertion_traits>(); + erasures_keep_the_image<wd::default_traits>({ + 0x38c76b4a395b0326, + 0x2c14970cfa6dc330, + 0x35ea097c472ac20c, + 0xa19a73e9032fd691, + 0x58bf4826b5bdea1c, + 0x1e6bf1349054d6b2, + 0x704f7f300d9124fc, + 0x8ba81cffbbc560cc, + 0x040a767c2a348e42, + 0x74fb654128b4b9dd, + 0xbdec20dae902004d, + }); + erasures_keep_the_image<wd::js_traits>({ + 0x850a39306007c1dc, + 0x961d2dd418e3b7be, + 0x946f2e49edf7876b, + 0x66f5808c528b7a0e, + 0x1963759dd134db47, + 0xbca805ce38c0d5f6, + 0xdbeb1136b36154e9, + 0xc30c77810664054e, + 0xeb9d9db5c1c49417, + 0xcce96cf5f1d6a0e4, + 0xc72fa788f772579e, + }); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + handles_fail_softly<wd::default_traits>(); + handles_fail_softly<wd::js_traits>(); + tree_fails_softly<wd::default_traits>(); + tree_fails_softly<wd::js_traits>(); + handles_fail_softly<sorted_traits>(); + handles_fail_softly<insertion_traits>(); + tree_fails_softly<sorted_traits>(); + tree_fails_softly<insertion_traits>(); +#endif + return boost::report_errors(); +} diff --git a/test/allocator_values_test.cpp b/test/allocator_values_test.cpp new file mode 100644 index 0000000..12d6185 --- /dev/null +++ b/test/allocator_values_test.cpp @@ -0,0 +1,759 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The handles' and the conversions' working state in the document's allocator: set of literals, +// the keys of missing members and their copies, erasure, Object.assign, deep equality, the array +// methods and the containers' views of a pmr document, of default_traits and of js_traits, and of +// an external one, make no call of the global operator new and give back to the resource all they +// took; the documents the array methods make are in the same resource; a change a place cannot +// take is refused first, with nothing allocated; and, with exceptions, an allocator that runs out +// at any step of set, push, concat, splice or Object.assign is errc::capacity with the document as +// it was, while an erasure asks the allocator for nothing and cannot run out of room. + +#include <webcpp/document.hpp> + +#include <boost/core/lightweight_test.hpp> + +#include "counting.hpp" +#include "require.hpp" + +#include <boost/decimal/decimal64_t.hpp> + +#include <array> +#include <chrono> +#include <cstddef> +#include <cstdint> +#include <limits> +#include <memory> +#include <memory_resource> +#include <optional> +#include <span> +#include <string> +#include <string_view> +#include <utility> + +namespace wd = webcpp::document; + +namespace { + +using webcpp::test::arena; +using webcpp::test::global_count; +using webcpp::test::require; + +constexpr std::size_t mebibyte = std::size_t{1} << 20U; + +/** A document of `Traits` whose image and working state are a memory resource's. */ +template <class Traits> +using pmr_document = wd::basic_document<Traits, wd::pmr::owned>; + +/** Text of 120 copies of `c` and an "é": longer than any small-string buffer, and not ASCII. */ +std::string long_text(char c) { + return std::string(120, c) + "\xC3\xA9"; +} + +/** The values the tests store, made before anything is counted: literals own their text. */ +struct sample_values { + /** A long key. */ + std::string key = long_text('k'); + + /** Another long key. */ + std::string other_key = long_text('o'); + + /** A long string. */ + std::string text = long_text('t'); + + /** An object literal, with long keys and strings at two depths. */ + wd::object members{ + {key, text}, + {"list", wd::array{1, text, wd::object{{key, true}}}}, + {"none", nullptr}, + }; + + /** An array literal, with a nested object and array. */ + wd::array elements{text, wd::object{{key, 2}}, wd::literal(wd::array{text, false})}; +}; + +/** A document of `Traits` parsed from `json` in the standard allocator. */ +template <class Traits> +wd::basic_document<Traits> parsed(std::string_view json) { + auto made = wd::parse<Traits>(json); + require(BOOST_TEST(made.has_value())); + return std::move(*made); +} + +/** The document `json` holds, in the arena `a`. */ +template <class Traits> +pmr_document<Traits> in_arena(arena& a, std::string_view json) { + const auto source = parsed<Traits>(json); + auto made = wd::from_image<Traits>(source.image(), a.allocator()); + require(BOOST_TEST(made.has_value())); + return std::move(*made); +} + +/** The documents a scenario's array methods made, kept in place, which allocates nothing. */ +template <class Owned> +struct kept_documents { + /** The documents, in the order made. */ + std::array<std::optional<Owned>, 8> documents{}; + + /** How many there are. */ + std::size_t count = 0; + + /** Keeps `made`, which must be a document. */ + void keep(wd::result<Owned>&& made) { + require(BOOST_TEST(made.has_value())); + require(BOOST_TEST_LT(count, documents.size())); + documents.at(count++).emplace(std::move(*made)); + } +}; + +/** Whether `a`'s and `b`'s values are written the same, compared outside any counting. */ +template <class A, class B> +void same_value(const A& a, const B& b) { + BOOST_TEST_EQ(a.root().stringify(), b.root().stringify()); +} + +// Set of literals, by a node, a missing member of a short and of a long key, and an element past +// the end, and a deep copy: under js_traits each string and key, given in UTF-8, is transcoded in +// the prepared value, which is the document's resource's. +template <class Document> +void set_scenario(Document& d, const sample_values& f) { + BOOST_TEST(d["a"].set(f.members).has_value()); + BOOST_TEST(d["new"].set(f.elements).has_value()); + BOOST_TEST(d["c"][f.key].set(f.text).has_value()); + BOOST_TEST(d["b"][4].set(f.members).has_value()); + BOOST_TEST(d["c"]["copy"].set(d["a"]).has_value()); +} + +template <class Traits> +void set_literals() { + arena a(16 * mebibyte); + const sample_values f; + constexpr std::string_view json = R"({"a":1,"b":[1,2],"c":{}})"; + auto reference = parsed<Traits>(json); + set_scenario(reference, f); + { + auto d = in_arena<Traits>(a, json); + const std::uint64_t before = a.resource().allocations(); + { + const global_count global; + set_scenario(d, f); + BOOST_TEST_EQ(global.news(), 0U); + } + BOOST_TEST_GT(a.resource().allocations(), before); + same_value(d, reference); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// A handle of a missing member holds its long key in the document's resource, and so do a copy of +// it and a handle assigned it, not in the default resource a pmr string's copy would ask; a move +// takes the key; a set through any of them creates the member the others then read. +template <class Traits> +void missing_member_handles() { + arena a(16 * mebibyte); + const sample_values f; + constexpr std::string_view json = R"({"o":{}})"; + auto reference = parsed<Traits>(json); + BOOST_TEST(reference["o"][f.key].set(f.members).has_value()); + { + auto d = in_arena<Traits>(a, json); + { + const global_count global; + const std::uint64_t start = a.resource().allocations(); + const auto missing = d["o"][f.key]; + BOOST_TEST(missing.is_undefined()); + BOOST_TEST_EQ(a.resource().allocations(), start + 1); + auto copy = missing; + BOOST_TEST_EQ(a.resource().allocations(), start + 2); + wd::basic_const_value<Traits, wd::pmr::owned> assigned; + assigned = copy; + BOOST_TEST_EQ(a.resource().allocations(), start + 3); + auto moved = std::move(copy); + BOOST_TEST_EQ(a.resource().allocations(), start + 3); + BOOST_TEST(moved.set(f.members).has_value()); + BOOST_TEST(missing.is_object()); + BOOST_TEST(assigned.is_object()); + BOOST_TEST(missing == assigned); + BOOST_TEST_EQ(global.news(), 0U); + } + same_value(d, reference); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// set(undefined) erases a member by its node, whose key under js_traits is UTF-16 in the image, and +// by a missing member's handle, before and after the member exists. +template <class Document> +void erase_scenario(Document& d, const sample_values& f) { + BOOST_TEST(d[f.key].set(wd::undefined).has_value()); + BOOST_TEST(d["short"].set(wd::undefined).has_value()); + BOOST_TEST(d["keep"][f.key].set(wd::undefined).has_value()); + auto missing = d[f.other_key]; + BOOST_TEST(missing.set(wd::undefined).has_value()); + BOOST_TEST(missing.set(1).has_value()); + BOOST_TEST(missing.is_number()); + BOOST_TEST(missing.set(wd::undefined).has_value()); + BOOST_TEST(missing.is_undefined()); +} + +template <class Traits> +void erase_through_undefined() { + arena a(16 * mebibyte); + const sample_values f; + const std::string json = + R"({")" + f.key + R"(":1,"short":2,"keep":{")" + f.key + R"(":3,"x":4}})"; + auto reference = parsed<Traits>(json); + erase_scenario(reference, f); + { + auto d = in_arena<Traits>(a, json); + { + const global_count global; + erase_scenario(d, f); + BOOST_TEST_EQ(global.news(), 0U); + } + same_value(d, reference); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// Object.assign from an object of long keys, from an array, whose keys are its indices, from this +// document's own members and from a document of the standard allocator. +template <class Document, class Other> +void assign_scenario(Document& d, const Other& other) { + BOOST_TEST(d["target"].assign_from(d["source"]).has_value()); + BOOST_TEST(d["target"].assign_from(d["list"]).has_value()); + BOOST_TEST(d["target"].assign_from(d["target"]["y"]).has_value()); + BOOST_TEST(d["target"].assign_from(other.root()).has_value()); +} + +template <class Traits> +void assign_members() { + arena a(16 * mebibyte); + const sample_values f; + const std::string json = R"({"target":{"x":1},"source":{")" + f.key + R"(":")" + f.text + + R"(","y":[1,2]},"list":[10,20,30,40,50,60,70,80,90,100,110,120]})"; + const auto other = parsed<Traits>(R"({")" + f.other_key + R"(":{"deep":[1]},"x":2})"); + auto reference = parsed<Traits>(json); + assign_scenario(reference, other); + { + auto d = in_arena<Traits>(a, json); + { + const global_count global; + assign_scenario(d, other); + BOOST_TEST_EQ(global.news(), 0U); + } + same_value(d, reference); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// == compares deep values, members in any order, with no stack: it allocates nothing at all, from +// the resource or the global heap, equal or not. +template <class Traits> +void deep_equality() { + arena a(16 * mebibyte); + const sample_values f; + const std::string member = R"(")" + f.key + R"(":")" + f.text + R"(")"; + const std::string x_json = + R"({"a":[1,{)" + member + R"(,"b":[true,null,[[]]]}],"c":{"d":{"e":2.5,"f":{}}},"g":""})"; + const std::string y_json = + R"({"g":"","c":{"d":{"f":{},"e":2.5}},"a":[1,{"b":[true,null,[[]]],)" + member + "}]}"; + const std::string deeper = + R"({"a":[1,{)" + member + R"(,"b":[true,null,[[0]]]}],"c":{"d":{"e":2.5,"f":{}}},"g":""})"; + const std::string renamed = + R"({"a":[1,{)" + member + R"(,"b":[true,null,[[]]]}],"c":{"d":{"e":2.5,"h":{}}},"g":""})"; + const std::string reordered = + R"({"a":[{)" + member + R"(,"b":[true,null,[[]]]},1],"c":{"d":{"e":2.5,"f":{}}},"g":""})"; + { + const auto x = in_arena<Traits>(a, x_json); + const auto y = in_arena<Traits>(a, y_json); + const auto z = in_arena<Traits>(a, deeper); + const auto w = in_arena<Traits>(a, renamed); + const auto v = in_arena<Traits>(a, reordered); + const std::uint64_t before = a.resource().allocations(); + const global_count global; + BOOST_TEST(x.root() == y.root()); + BOOST_TEST(y.root() == x.root()); + BOOST_TEST(x["a"][1] == y["a"][1]); + BOOST_TEST(x["c"]["d"] == y["c"]["d"]); + BOOST_TEST(!(x.root() == z.root())); + BOOST_TEST(!(z.root() == x.root())); + BOOST_TEST(!(x.root() == w.root())); + BOOST_TEST(!(x.root() == v.root())); + BOOST_TEST(!(x["a"] == x["c"])); + BOOST_TEST(x["missing"] == y["absent"]); + BOOST_TEST_EQ(global.news(), 0U); + BOOST_TEST_EQ(a.resource().allocations(), before); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// The array methods with literal arguments: push, unshift, concat (of literals and of the array +// itself), slice, pop, shift and splice; the documents they make are in the source's resource. +template <class Document, class Kept> +void array_scenario(Document& d, const sample_values& f, Kept& kept) { + auto list = d["list"]; + const auto pushed = list.push(f.members, f.elements, f.text); + BOOST_TEST(pushed.has_value() && *pushed == 8); + const auto unshifted = list.unshift(f.elements, f.key); + BOOST_TEST(unshifted.has_value() && *unshifted == 10); + kept.keep(list.concat(f.elements, f.members, f.text, d["list"])); + kept.keep(list.slice(1, 4)); + kept.keep(list.pop()); + kept.keep(list.shift()); + kept.keep(list.splice(1, 2, f.members, f.elements)); + kept.keep(list.splice(5)); +} + +template <class Traits> +void array_methods() { + arena a(16 * mebibyte); + const sample_values f; + constexpr std::string_view json = R"({"list":[1,2,3,4,5]})"; + auto reference = parsed<Traits>(json); + kept_documents<wd::basic_document<Traits>> expected; + array_scenario(reference, f, expected); + { + auto d = in_arena<Traits>(a, json); + kept_documents<pmr_document<Traits>> made; + { + const global_count global; + array_scenario(d, f, made); + BOOST_TEST_EQ(global.news(), 0U); + } + same_value(d, reference); + BOOST_TEST_EQ(made.count, expected.count); + for (std::size_t i = 0; i < made.count; ++i) { + const auto& document = made.documents.at(i); + const auto& wanted = expected.documents.at(i); + if (!document.has_value() || !wanted.has_value()) { + BOOST_ERROR("a document the array methods made is missing"); + continue; + } + BOOST_TEST(document->get_allocator().resource() == &a.resource()); + same_value(*document, *wanted); + } + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// The views' writing members: an object's insert, insert_or_assign, try_emplace, a deep copy, its +// bounds by key, erase by key and by iterator and clear; an array's push_back, emplace_back, +// insert, erase, resize and pop_back. +template <class Document> +void views_scenario(Document& d, const sample_values& f) { + auto o = d["o"].as_object(); + require(BOOST_TEST(o.has_value())); + BOOST_TEST(o->insert(f.key, f.members).has_value()); + BOOST_TEST(o->insert_or_assign("a", f.elements).has_value()); + BOOST_TEST(o->try_emplace(f.other_key, f.text).has_value()); + BOOST_TEST(o->insert("copy", d["l"]).has_value()); + const auto keys = o->by_key(); + // By UTF-16 code units: "a", "copy", the key of 'k's, the key of 'o's. + BOOST_TEST((*keys.lower_bound("b")).second == d["o"]["copy"]); + BOOST_TEST((*keys.lower_bound(f.key)).second == d["o"][f.key]); + BOOST_TEST((*keys.upper_bound(f.key)).second == d["o"][f.other_key]); + BOOST_TEST(keys.upper_bound(f.other_key) == keys.end()); + BOOST_TEST(o->erase(f.other_key).has_value()); + // In insertion order the key of 'k's is followed by "a". + BOOST_TEST(o->erase(o->find(f.key)) == o->find("a")); + auto p = d["p"].as_object(); + require(BOOST_TEST(p.has_value())); + p->clear(); + + auto l = d["l"].as_array(); + require(BOOST_TEST(l.has_value())); + BOOST_TEST(l->push_back(f.members).has_value()); + BOOST_TEST(l->emplace_back(f.elements).has_value()); + BOOST_TEST(l->insert(l->begin(), f.text).has_value()); + l->erase(l->begin()); + BOOST_TEST(l->resize(10).has_value()); + l->pop_back(); +} + +template <class Traits> +void view_members() { + arena a(16 * mebibyte); + const sample_values f; + const std::string json = + R"({"o":{},"l":[1,2],"p":{")" + f.key + R"(":1,")" + f.other_key + R"(":2,"z":3}})"; + auto reference = parsed<Traits>(json); + views_scenario(reference, f); + { + auto d = in_arena<Traits>(a, json); + { + const global_count global; + views_scenario(d, f); + BOOST_TEST_EQ(global.news(), 0U); + } + same_value(d, reference); + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// A document's const reads ask its resource for nothing, as a standard container's do, so that any +// number of threads may make them at once whatever the resource: a lookup by a key of any length, +// a missing member of a short key, get, ==, iteration, the views, image, compact_size, stringify, +// and stringify_to of a value nested 16 deep in chunks of 4096 bytes. A missing member of a long +// key is one of the reads that allocate: its handle holds the key, once. +template <class Traits> +void const_reads_ask_nothing() { + arena a(16 * mebibyte); + const sample_values f; + const std::string json = R"({"a":1,")" + f.key + R"(":")" + f.text + + R"(","list":[1,[2,{"x":3}]],"deep":)" + std::string(15, '[') + + std::string(15, ']') + "}"; + const auto d = in_arena<Traits>(a, json); + const auto other = in_arena<Traits>(a, json); + const std::string long_missing(200, 'm'); + std::string written; + const std::uint64_t before = a.resource().allocations(); + { + BOOST_TEST(d[f.key].is_string()); + BOOST_TEST_EQ(d["a"].template get<std::int64_t>().value(), 1); + BOOST_TEST(d["k"].is_undefined()); + BOOST_TEST(d == other); + std::uint64_t elements = 0; + for (const auto element : d["list"]) { + elements += element.is_undefined() ? 0 : 1; + } + BOOST_TEST_EQ(elements, 2U); + const auto o = d.root().as_object(); + require(BOOST_TEST(o.has_value())); + BOOST_TEST_EQ(o->size(), 4U); + BOOST_TEST(o->contains(f.key)); + BOOST_TEST(!d.image().empty()); + BOOST_TEST_GT(d.compact_size(), 0U); + BOOST_TEST_EQ(wd::stringify(d, 2), wd::stringify(other, 2)); + BOOST_TEST(wd::stringify_to( + d, [&written](std::string_view piece) { written.append(piece); }, 2) + .has_value()); + } + BOOST_TEST_EQ(a.resource().allocations(), before); + BOOST_TEST_EQ(written, parsed<Traits>(json).root().stringify(2)); + { + const auto missing = d[long_missing]; + BOOST_TEST(missing.is_undefined()); + BOOST_TEST_EQ(a.resource().allocations(), before + 1); + } +} + +// Under js_traits, a bound by key compares a UTF-8 key with the stored UTF-16 ones as it is +// transcoded: U+10000's high surrogate comes before U+E000, and a prefix before its extensions. +void bounds_by_utf16_units() { + arena a(mebibyte); + const std::string private_use = "\xEE\x80\x80"; + const std::string supplementary = "\xF0\x90\x80\x80"; + auto d = in_arena<wd::js_traits>( + a, R"({")" + private_use + R"(":1,")" + supplementary + R"(":2,"ab":3,"abc":4,"b":5})"); + const global_count global; + const auto o = d.root().as_object(); + require(BOOST_TEST(o.has_value())); + const auto keys = o->by_key(); + BOOST_TEST((*keys.lower_bound(supplementary)).second == d[supplementary]); + BOOST_TEST((*keys.upper_bound(supplementary)).second == d[private_use]); + BOOST_TEST((*keys.lower_bound(private_use)).second == d[private_use]); + BOOST_TEST(keys.upper_bound(private_use) == keys.end()); + BOOST_TEST((*keys.lower_bound("ab")).second == d["ab"]); + BOOST_TEST((*keys.upper_bound("ab")).second == d["abc"]); + BOOST_TEST((*keys.lower_bound("abb")).second == d["abc"]); + BOOST_TEST((*keys.lower_bound("abcd")).second == d["b"]); + BOOST_TEST((*keys.lower_bound("")).second == d["ab"]); + BOOST_TEST_EQ(global.news(), 0U); +} + +// An external document, formatted in a buffer, keeps its working state in its allocator: set of +// literals, a missing member's handle and its copy, push and concat, whose document is owned in +// the same resource. +template <class Document, class Kept> +void external_scenario(Document& d, const sample_values& f, Kept& kept) { + BOOST_TEST(d.root().set(f.members)); + const auto missing = d[f.other_key]; + auto copy = missing; + BOOST_TEST(copy.set(f.elements).has_value()); + BOOST_TEST(missing.is_array()); + const auto pushed = d["list"].push(f.text, f.members); + BOOST_TEST(pushed.has_value() && *pushed == 5); + kept.keep(d["list"].concat(f.elements)); +} + +/** The buffer of an external document, 16-aligned. */ +struct alignas(16) external_buffer { + /** Its bytes. */ + std::array<std::byte, 65536> bytes{}; +}; + +void external_document() { + arena a(16 * mebibyte); + const sample_values f; + auto reference = parsed<wd::default_traits>("null"); + kept_documents<wd::document> expected; + external_scenario(reference, f, expected); + // On the heap, before anything is counted: Emscripten's stack is 64 KiB. + const auto buffer = std::make_unique<external_buffer>(); + { + auto made = wd::format(std::span(buffer->bytes), a.allocator()); + require(BOOST_TEST(made.has_value())); + kept_documents<wd::pmr::document> kept; + { + const global_count global; + external_scenario(*made, f, kept); + BOOST_TEST_EQ(global.news(), 0U); + } + same_value(*made, reference); + BOOST_TEST_EQ(kept.count, 1U); + const auto& document = kept.documents[0]; + const auto& wanted = expected.documents[0]; + if (!document.has_value() || !wanted.has_value()) { + BOOST_ERROR("the document concat made is missing"); + } else { + BOOST_TEST(document->get_allocator().resource() == &a.resource()); + same_value(*document, *wanted); + } + } + BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); +} + +// A change a place cannot take is refused with errc::type before its value is prepared, ahead of +// the value's own errors, and allocates nothing, in the document's resource or the global heap: a +// handle of nothing, a missing member of what is no longer an object, a missing element of what is +// no longer an array, and a node erased since. +template <class Traits> +void refused_first() { + arena a(mebibyte); + const sample_values f; + auto d = in_arena<Traits>(a, R"({"a":1,"o":{},"l":[],"gone":2})"); + auto nothing = d["missing"]["x"]; + const auto member = d["o"]["new"]; + const auto element = d["l"][std::uint64_t{3}]; + const auto gone = d["gone"]; + BOOST_TEST(d["o"].set(1).has_value()); + BOOST_TEST(d["l"].set(2).has_value()); + const auto erased = d.root().erase("gone"); + BOOST_TEST(erased.has_value() && *erased); + const std::uint64_t before = a.resource().allocations(); + const global_count global; + BOOST_TEST(nothing.is_undefined()); + const wd::date_ms late{std::chrono::milliseconds{wd::detail::date_limit_ms + 1}}; + for (auto place : {nothing, member, element, gone}) { + BOOST_TEST( + place.set(std::numeric_limits<boost::decimal::decimal64_t>::infinity()).error() == + wd::errc::type); + BOOST_TEST(place.set(late).error() == wd::errc::type); + BOOST_TEST(place.set(std::string_view("\xFF")).error() == wd::errc::type); + BOOST_TEST(place.set(1).error() == wd::errc::type); + BOOST_TEST(place.set(f.text).error() == wd::errc::type); + BOOST_TEST(place.set(f.members).error() == wd::errc::type); + BOOST_TEST(place.set(f.elements).error() == wd::errc::type); + } + BOOST_TEST(nothing.set(d["a"]).error() == wd::errc::type); + BOOST_TEST(nothing.set(wd::undefined).error() == wd::errc::type); + BOOST_TEST_EQ(global.news(), 0U); + BOOST_TEST_EQ(a.resource().allocations(), before); + same_value(d, parsed<Traits>(R"({"a":1,"o":1,"l":2})")); +} + +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + +/** What a resource that is never to run out allows. */ +constexpr std::uint64_t unlimited = std::numeric_limits<std::uint64_t>::max(); + +/** + Runs `op` on a fresh copy of the document `json` in a resource that fails from its allocation + `budget` on, for each budget from 0 until `op` succeeds: each failure must be errc::capacity, the + resource's one refusal, with the document's content as it was and every byte the operation took + before the refusal given back, so that a leak on a path of failure fails. Returns how many budgets + failed. +*/ +template <class Traits, class Op> +std::uint64_t fails_softly(const std::string& json, Op op) { + arena a(16 * mebibyte); + const auto source = parsed<Traits>(json); + const std::string before = source.root().stringify(); + webcpp::test::failing_resource failing(&a.resource(), unlimited); + const std::pmr::polymorphic_allocator<std::byte> alloc(&failing); + std::uint64_t failures = 0; + for (std::uint64_t budget = 0; budget < 1000; ++budget) { + failing.allow(unlimited); + auto d = wd::from_image<Traits>(source.image(), alloc); + require(BOOST_TEST(d.has_value())); + const std::uint64_t held = failing.bytes_in_use(); + const std::uint64_t refused = failing.refusals(); + failing.allow(budget); + const boost::system::error_code done = op(*d); + failing.allow(unlimited); + if (!done) { + BOOST_TEST_EQ(failing.refusals(), refused); + BOOST_TEST_GT(failures, 0U); + return failures; + } + BOOST_TEST(done == wd::errc::capacity); + BOOST_TEST_EQ(failing.refusals(), refused + 1); + BOOST_TEST_EQ(failing.bytes_in_use(), held); + BOOST_TEST_EQ(d->root().stringify(), before); + ++failures; + } + BOOST_TEST(false); + return failures; +} + +/** + Runs `op`, an erasure, on the document `json` in a resource that refuses every allocation: it must + succeed, change the document, and ask the resource for nothing. +*/ +template <class Traits, class Op> +void never_fails(const std::string& json, Op op) { + arena a(16 * mebibyte); + const auto source = parsed<Traits>(json); + const std::string before = source.root().stringify(); + webcpp::test::failing_resource failing(&a.resource(), unlimited); + auto d = wd::from_image<Traits>(source.image(), std::pmr::polymorphic_allocator<>(&failing)); + require(BOOST_TEST(d.has_value())); + failing.allow(0); + BOOST_TEST(!op(*d)); + BOOST_TEST_EQ(failing.refusals(), 0U); + failing.allow(unlimited); + BOOST_TEST_NE(d->root().stringify(), before); +} + +/** The error of `made`; none when it holds a document in `resource`. */ +template <class Document> +boost::system::error_code error_of(const wd::result<Document>& made, + const std::pmr::memory_resource* resource) { + if (!made.has_value()) { + return made.error(); + } + BOOST_TEST(made->get_allocator().resource() == resource); + return {}; +} + +// A handle of a missing member whose long key the resource had no room for reads undefined, and +// a change through it or a copy of it is errc::capacity, with nothing changed; a short key fits +// the string's own buffer, so its handle needs no allocation. +template <class Traits> +void unheld_key() { + arena a(16 * mebibyte); + const sample_values f; + const auto source = parsed<Traits>(R"({"o":{}})"); + webcpp::test::failing_resource failing(&a.resource(), unlimited); + auto made = wd::from_image<Traits>(source.image(), std::pmr::polymorphic_allocator<>(&failing)); + require(BOOST_TEST(made.has_value())); + auto& d = *made; + failing.allow(0); + auto missing = d["o"][f.key]; + auto small = d["o"]["k"]; + failing.allow(unlimited); + BOOST_TEST_EQ(failing.refusals(), 1U); + BOOST_TEST(missing.is_undefined()); + BOOST_TEST(missing.set(f.members).error() == wd::errc::capacity); + BOOST_TEST(missing.set(wd::undefined).error() == wd::errc::capacity); + auto copy = missing; + BOOST_TEST(copy.set(1).error() == wd::errc::capacity); + BOOST_TEST_EQ(d["o"].size(), 0U); + BOOST_TEST(small.set(1).has_value()); + BOOST_TEST_EQ(d["o"].size(), 1U); +} + +template <class Traits> +void failures_change_nothing() { + const sample_values f; + const std::string json = + R"({"a":1,"list":[1,2,3,4],"o":{")" + f.key + R"(":{"deep":[1,2]},"x":1}})"; + // A set through a node, and through a missing member's handle made while the resource fails. + fails_softly<Traits>(json, [&](auto& d) { return d["a"].set(f.members).error(); }); + fails_softly<Traits>(json, [&](auto& d) { return d[f.key].set(f.members).error(); }); + fails_softly<Traits>(json, [&](auto& d) { return d["list"].push(f.elements, f.text).error(); }); + fails_softly<Traits>(json, [&](auto& d) { + return error_of(d["list"].concat(f.elements, f.members, f.text), + d.get_allocator().resource()); + }); + fails_softly<Traits>(json, [&](auto& d) { + return error_of(d["list"].splice(1, 2, f.members, f.elements), + d.get_allocator().resource()); + }); + fails_softly<Traits>(json, [&](auto& d) { return d["o"].assign_from(d["list"]).error(); }); + // set(undefined) of an element stores null in its place, a change, not an erasure. + fails_softly<Traits>(json, [&](auto& d) { return d["list"][1].set(wd::undefined).error(); }); +} + +// Erasures ask the allocator for nothing, so they succeed with none to give: set(undefined) of a +// member of a long key, delete by key, each of the views' erasures and a truncation. +template <class Traits> +void erasures_never_fail() { + const sample_values f; + const std::string json = + R"({"a":1,"list":[1,[2,{"x":3}],3,4],"o":{")" + f.key + R"(":{"deep":[1,2]},"x":1}})"; + const boost::system::error_code none; + never_fails<Traits>(json, [&](auto& d) { return d["o"][f.key].set(wd::undefined).error(); }); + never_fails<Traits>(json, [&](auto& d) { return d["o"].erase(f.key).error(); }); + never_fails<Traits>(json, [&](auto& d) { + const auto o = d["o"].as_object(); + const auto next = o->erase(o->find(f.key)); + BOOST_TEST(next == o->find("x")); + return none; + }); + never_fails<Traits>(json, [&](auto& d) { + d["o"].as_object()->clear(); + return none; + }); + never_fails<Traits>(json, [&](auto& d) { + const auto l = d["list"].as_array(); + const auto next = l->erase(l->begin()); + BOOST_TEST(next == l->begin()); + return none; + }); + never_fails<Traits>(json, [&](auto& d) { + const auto l = d["list"].as_array(); + BOOST_TEST(l->erase(std::next(l->begin()), l->end()) == l->end()); + return none; + }); + never_fails<Traits>(json, [&](auto& d) { + d["list"].as_array()->pop_back(); + return none; + }); + never_fails<Traits>(json, [&](auto& d) { + d["list"].as_array()->clear(); + return none; + }); + never_fails<Traits>(json, [&](auto& d) { return d["list"].as_array()->resize(1).error(); }); +} + +#endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS + +} // namespace + +int main() { + set_literals<wd::default_traits>(); + set_literals<wd::js_traits>(); + missing_member_handles<wd::default_traits>(); + missing_member_handles<wd::js_traits>(); + erase_through_undefined<wd::default_traits>(); + erase_through_undefined<wd::js_traits>(); + assign_members<wd::default_traits>(); + assign_members<wd::js_traits>(); + deep_equality<wd::default_traits>(); + deep_equality<wd::js_traits>(); + array_methods<wd::default_traits>(); + array_methods<wd::js_traits>(); + view_members<wd::default_traits>(); + view_members<wd::js_traits>(); + const_reads_ask_nothing<wd::default_traits>(); + const_reads_ask_nothing<wd::js_traits>(); + bounds_by_utf16_units(); + external_document(); + refused_first<wd::default_traits>(); + refused_first<wd::js_traits>(); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + failures_change_nothing<wd::default_traits>(); + failures_change_nothing<wd::js_traits>(); + erasures_never_fail<wd::default_traits>(); + erasures_never_fail<wd::js_traits>(); + unheld_key<wd::default_traits>(); + unheld_key<wd::js_traits>(); +#endif + return boost::report_errors(); +} diff --git a/test/counting.cpp b/test/counting.cpp new file mode 100644 index 0000000..85a8399 --- /dev/null +++ b/test/counting.cpp @@ -0,0 +1,247 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The replacements of the global operator new and operator delete that counting.hpp's counts read, +// for the program that links this file alone: every form a program calls directly, the array and +// the nothrow forms included, each counted once, however the standard library implements one form +// through another; and the measure of what a standard container allocates for itself. + +#include "counting.hpp" + +#include <boost/config.hpp> + +#include <algorithm> +#include <array> +#include <cstddef> +#include <cstdint> +#include <cstdlib> +#include <memory_resource> +#include <new> +#include <vector> + +#ifdef _MSC_VER +#include <malloc.h> +#endif + +namespace { + +// What the replacements below counted. They are mutable global state, which no library holds: +// this program's own instrument, the one place where the replaced operator new can record what it +// sees. +std::uint64_t news = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) +std::uint64_t deletes = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) + +// Memory of `size` bytes, or null. +void* plain_memory(std::size_t size) noexcept { + ++news; + return std::malloc(size == 0 ? 1 : size); +} + +// Memory of `size` bytes aligned to `alignment`, or null; the UCRT of MSVC has no aligned_alloc, +// and memory from its _aligned_malloc is given back with _aligned_free. The aligned operator new +// takes any power of two, as an allocator of char asks 1; aligned_alloc may refuse one below the +// fundamental alignment, as macOS's does, so that one is asked at least that. +void* aligned_memory(std::size_t size, std::align_val_t alignment) noexcept { + ++news; + const std::size_t align = + std::max(static_cast<std::size_t>(alignment), alignof(std::max_align_t)); + const std::size_t rounded = size == 0 ? align : (size + align - 1) / align * align; +#ifdef _MSC_VER + return _aligned_malloc(rounded, align); +#else + return std::aligned_alloc(align, rounded); +#endif +} + +// Gives back what plain_memory took. +void free_plain(void* memory) noexcept { + if (memory != nullptr) { + ++deletes; + } + std::free(memory); +} + +// Gives back what aligned_memory took. +void free_aligned(void* memory) noexcept { + if (memory != nullptr) { + ++deletes; + } +#ifdef _MSC_VER + _aligned_free(memory); +#else + std::free(memory); +#endif +} + +// A failure of a form that throws: a test built without exceptions has no std::bad_alloc to throw, +// and none of these tests runs out of the global heap. +void* or_abort(void* memory) noexcept { + if (memory == nullptr) { + std::abort(); + } + return memory; +} + +// A resource that records the blocks it is asked for, with the size and the alignment of the last, +// and takes them from `upstream`. +class recording_resource final : public std::pmr::memory_resource { +public: + explicit recording_resource(std::pmr::memory_resource* upstream) noexcept + : upstream_(upstream) {} + + [[nodiscard]] webcpp::test::container_bookkeeping recorded() const noexcept { + return recorded_; + } + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++recorded_.blocks; + recorded_.bytes = bytes; + recorded_.alignment = alignment; + return upstream_->allocate(bytes, alignment); + } + + void do_deallocate(void* memory, std::size_t bytes, std::size_t alignment) override { + upstream_->deallocate(memory, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } + + std::pmr::memory_resource* upstream_; + webcpp::test::container_bookkeeping recorded_; +}; + +// What an empty std::pmr::vector allocates when it is made, in a buffer on the stack, so that the +// measure reaches no heap and no resource a test counts. +webcpp::test::container_bookkeeping measure() { + alignas(std::max_align_t) std::array<std::byte, 256> room{}; + std::pmr::monotonic_buffer_resource buffer(room.data(), room.size(), + std::pmr::null_memory_resource()); + recording_resource recorder(&buffer); + { + const std::pmr::vector<std::byte> empty(&recorder); + } + return recorder.recorded(); +} + +} // namespace + +namespace webcpp::test { + +std::uint64_t global_news() noexcept { + return news; +} + +std::uint64_t global_deletes() noexcept { + return deletes; +} + +const container_bookkeeping& bookkeeping() { + static const container_bookkeeping measured = measure(); + return measured; +} + +bool is_bookkeeping(std::size_t bytes, std::size_t alignment) { + const container_bookkeeping& b = bookkeeping(); + return b.blocks != 0 && bytes == b.bytes && alignment == b.alignment; +} + +} // namespace webcpp::test + +// The standard library declares these with parameter names reserved to the implementation, hence +// the exemption. None is ever inlined: GCC, seeing the malloc or the free inside one, would pair it +// with the other's call and warn of a mismatch. +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name) + +BOOST_NOINLINE void* operator new(std::size_t size) { + return or_abort(plain_memory(size)); +} + +BOOST_NOINLINE void* operator new[](std::size_t size) { + return or_abort(plain_memory(size)); +} + +BOOST_NOINLINE void* operator new(std::size_t size, const std::nothrow_t& /*tag*/) noexcept { + return plain_memory(size); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, const std::nothrow_t& /*tag*/) noexcept { + return plain_memory(size); +} + +BOOST_NOINLINE void* operator new(std::size_t size, std::align_val_t alignment) { + return or_abort(aligned_memory(size, alignment)); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, std::align_val_t alignment) { + return or_abort(aligned_memory(size, alignment)); +} + +BOOST_NOINLINE void* operator new(std::size_t size, std::align_val_t alignment, + const std::nothrow_t& /*tag*/) noexcept { + return aligned_memory(size, alignment); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, std::align_val_t alignment, + const std::nothrow_t& /*tag*/) noexcept { + return aligned_memory(size, alignment); +} + +BOOST_NOINLINE void operator delete(void* memory) noexcept { + free_plain(memory); +} + +BOOST_NOINLINE void operator delete[](void* memory) noexcept { + free_plain(memory); +} + +BOOST_NOINLINE void operator delete(void* memory, std::size_t /*size*/) noexcept { + free_plain(memory); +} + +BOOST_NOINLINE void operator delete[](void* memory, std::size_t /*size*/) noexcept { + free_plain(memory); +} + +BOOST_NOINLINE void operator delete(void* memory, const std::nothrow_t& /*tag*/) noexcept { + free_plain(memory); +} + +BOOST_NOINLINE void operator delete[](void* memory, const std::nothrow_t& /*tag*/) noexcept { + free_plain(memory); +} + +BOOST_NOINLINE void operator delete(void* memory, std::align_val_t /*alignment*/) noexcept { + free_aligned(memory); +} + +BOOST_NOINLINE void operator delete[](void* memory, std::align_val_t /*alignment*/) noexcept { + free_aligned(memory); +} + +BOOST_NOINLINE void operator delete(void* memory, std::size_t /*size*/, + std::align_val_t /*alignment*/) noexcept { + free_aligned(memory); +} + +BOOST_NOINLINE void operator delete[](void* memory, std::size_t /*size*/, + std::align_val_t /*alignment*/) noexcept { + free_aligned(memory); +} + +BOOST_NOINLINE void operator delete(void* memory, std::align_val_t /*alignment*/, + const std::nothrow_t& /*tag*/) noexcept { + free_aligned(memory); +} + +BOOST_NOINLINE void operator delete[](void* memory, std::align_val_t /*alignment*/, + const std::nothrow_t& /*tag*/) noexcept { + free_aligned(memory); +} + +// NOLINTEND(readability-inconsistent-declaration-parameter-name) diff --git a/test/counting.hpp b/test/counting.hpp new file mode 100644 index 0000000..d254821 --- /dev/null +++ b/test/counting.hpp @@ -0,0 +1,252 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The instruments of the allocation tests: the calls of the global operator new that +// counting.cpp's replacements count, what a standard container allocates for itself, a memory +// resource that counts what it hands out and takes back, and an arena, a monotonic resource over +// memory taken before anything is counted, whose upstream is the null resource, so that an +// allocation past its end fails rather than reach the global heap. A program that includes this +// header links counting.cpp. + +#ifndef WEBCPP_TEST_DOCUMENT_COUNTING_HPP +#define WEBCPP_TEST_DOCUMENT_COUNTING_HPP + +#include <boost/interprocess/exceptions.hpp> +#include <boost/throw_exception.hpp> + +#include <cstddef> +#include <cstdint> +#include <memory> +#include <memory_resource> +#include <new> +#include <vector> + +namespace webcpp::test { + +/** The calls of the global operator new, of every form, the program has made so far. */ +std::uint64_t global_news() noexcept; + +/** The calls of the global operator delete, of every form, the program has made so far. */ +std::uint64_t global_deletes() noexcept; + +/** The calls of the global operator new made since it was built: what a block of code made. */ +class global_count { +public: + /** Counts from now. */ + global_count() noexcept : news_(global_news()), deletes_(global_deletes()) {} + + /** The calls of operator new since it was built. */ + [[nodiscard]] std::uint64_t news() const noexcept { return global_news() - news_; } + + /** The calls of operator delete since it was built. */ + [[nodiscard]] std::uint64_t deletes() const noexcept { return global_deletes() - deletes_; } + +private: + std::uint64_t news_; + std::uint64_t deletes_; +}; + +/** + What a standard container allocates for itself through its allocator, rebound, whatever it holds: + the MSVC STL's checked iterators (`_ITERATOR_DEBUG_LEVEL` above 0, the default of a debug build) + allocate a proxy for each container when it is constructed and when it is moved, in its noexcept + constructors as well, where an allocator's failure ends the program; the other standard libraries + allocate nothing so. Measured once, on an empty `std::pmr::vector`. +*/ +struct container_bookkeeping { + /** The blocks one container allocates for itself: none, or its proxy. */ + std::uint64_t blocks = 0; + + /** The size of such a block; 0 when there is none. */ + std::size_t bytes = 0; + + /** The alignment of such a block; 0 when there is none. */ + std::size_t alignment = 0; +}; + +/** What a standard container allocates for itself on this standard library. */ +const container_bookkeeping& bookkeeping(); + +/** + Whether a block of `bytes` at `alignment` may be a standard container's own, as @ref bookkeeping + measures it; never on a standard library that allocates none. Where one does, a resource cannot + tell such a block from one of the document's of the same size and alignment, as the two 64-bit + words a change's plan may reserve: the resources here neither count nor refuse either. No operation + whose allocations a test counts exactly makes such a block of its own (keys, texts and pieces are + of `char`, stacks of 16 frames and more, images 16-aligned), and a failure at one that other + operations make is proven on the other standard libraries. +*/ +bool is_bookkeeping(std::size_t bytes, std::size_t alignment); + +/** A memory resource that counts what it hands out and takes back, from `upstream`. */ +class counting_resource final : public std::pmr::memory_resource { +public: + /** A resource over `upstream`, which outlives it. */ + explicit counting_resource(std::pmr::memory_resource* upstream) noexcept + : upstream_(upstream) {} + + /** The allocations it made, a standard container's own (@ref is_bookkeeping) left out. */ + [[nodiscard]] std::uint64_t allocations() const noexcept { return allocations_; } + + /** The deallocations it made, a standard container's own left out. */ + [[nodiscard]] std::uint64_t deallocations() const noexcept { return deallocations_; } + + /** + Every allocation it made, a standard container's own among them: what an operation that is + to take nothing at all of a monotonic resource, which never reuses a block, must leave as it + was. + */ + [[nodiscard]] std::uint64_t all_allocations() const noexcept { return all_allocations_; } + + /** + The bytes handed out and not yet taken back, a standard container's own among them: all of + it comes back. + */ + [[nodiscard]] std::uint64_t bytes_in_use() const noexcept { return in_use_; } + + /** The largest alignment asked of it. */ + [[nodiscard]] std::size_t largest_alignment() const noexcept { return largest_alignment_; } + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + void* memory = upstream_->allocate(bytes, alignment); + if (!is_bookkeeping(bytes, alignment)) { + ++allocations_; + } + ++all_allocations_; + in_use_ += bytes; + largest_alignment_ = alignment > largest_alignment_ ? alignment : largest_alignment_; + return memory; + } + + void do_deallocate(void* memory, std::size_t bytes, std::size_t alignment) override { + if (!is_bookkeeping(bytes, alignment)) { + ++deallocations_; + } + in_use_ -= bytes; + upstream_->deallocate(memory, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } + + std::pmr::memory_resource* upstream_; + std::uint64_t allocations_ = 0; + std::uint64_t deallocations_ = 0; + std::uint64_t all_allocations_ = 0; + std::uint64_t in_use_ = 0; + std::size_t largest_alignment_ = 0; +}; + +/** + A memory resource that hands out what `upstream` gives for its first `budget` allocations and fails + every later one with `Failure`, through `boost::throw_exception`: an allocator that runs out at a + chosen step of an operation, for tests built with exceptions. + + A standard container's own block (@ref is_bookkeeping) is handed out whatever the budget, and + counts for none of it: the standard library allocates it in noexcept constructors, where a refusal + ends the program, so that no operation could make that refusal errc::capacity. + + @tparam Failure What a refusal throws: `std::bad_alloc`, or Boost.Interprocess's `bad_alloc`, which + an allocator of Boost.Interprocess throws and which derives from `std::exception` alone. +*/ +template <class Failure> +class basic_failing_resource final : public std::pmr::memory_resource { +public: + /** A resource over `upstream`, which outlives it, that allows `budget` allocations. */ + basic_failing_resource(std::pmr::memory_resource* upstream, std::uint64_t budget) noexcept + : upstream_(upstream), budget_(budget) {} + + /** Allows `budget` more allocations from now. */ + void allow(std::uint64_t budget) noexcept { budget_ = budget; } + + /** The allocations it refused. */ + [[nodiscard]] std::uint64_t refusals() const noexcept { return refusals_; } + + /** The bytes handed out and not yet taken back. */ + [[nodiscard]] std::uint64_t bytes_in_use() const noexcept { return in_use_; } + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + if (!is_bookkeeping(bytes, alignment)) { + if (budget_ == 0) { + ++refusals_; + boost::throw_exception(Failure()); + } + --budget_; + } + void* memory = upstream_->allocate(bytes, alignment); + in_use_ += bytes; + return memory; + } + + void do_deallocate(void* memory, std::size_t bytes, std::size_t alignment) override { + in_use_ -= bytes; + upstream_->deallocate(memory, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } + + std::pmr::memory_resource* upstream_; + std::uint64_t budget_; + std::uint64_t refusals_ = 0; + std::uint64_t in_use_ = 0; +}; + +/** A resource that fails with `std::bad_alloc`, as every standard allocator does. */ +using failing_resource = basic_failing_resource<std::bad_alloc>; + +/** A resource that fails with Boost.Interprocess's `bad_alloc`, as its allocators do. */ +using interprocess_failing_resource = basic_failing_resource<boost::interprocess::bad_alloc>; + +/** + A monotonic resource over `bytes` bytes taken when it is built, whose upstream is the null + resource, counted: what passes its end fails with `std::bad_alloc`, and nothing reaches the + global heap once it is built. +*/ +class arena { +public: + /** An arena of `bytes` bytes. */ + explicit arena(std::size_t bytes) + : buffer_(bytes), + monotonic_(buffer_.data(), buffer_.size(), std::pmr::null_memory_resource()), + counted_(&monotonic_) {} + + /** An arena is not copied: its resources refer to its buffer. */ + arena(const arena&) = delete; + + /** An arena is not copied: its resources refer to its buffer. */ + arena& operator=(const arena&) = delete; + + /** An arena is not moved: its resources refer to its buffer. */ + arena(arena&&) = delete; + + /** An arena is not moved: its resources refer to its buffer. */ + arena& operator=(arena&&) = delete; + + /** Gives its buffer back. */ + ~arena() = default; + + /** The counted resource, which allocates in the buffer. */ + [[nodiscard]] counting_resource& resource() noexcept { return counted_; } + + /** A polymorphic allocator of the counted resource. */ + [[nodiscard]] std::pmr::polymorphic_allocator<std::byte> allocator() noexcept { + return {&counted_}; + } + +private: + std::vector<std::byte> buffer_; + std::pmr::monotonic_buffer_resource monotonic_; + counting_resource counted_; +}; + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_DOCUMENT_COUNTING_HPP diff --git a/test/quote_test.cpp b/test/quote_test.cpp new file mode 100644 index 0000000..7e4d7f5 --- /dev/null +++ b/test/quote_test.cpp @@ -0,0 +1,271 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// quote writes a string as JSON.stringify quotes it, the bytes Node 26 writes held here as +// literals: every escape, C1's controls and other text past ASCII, a lone surrogate of UTF-16, long +// strings; it appends, refuses the text a strict decoder (Node's TextDecoder, fatal) refuses and +// leaves the output unchanged then, and allocates through the output alone, a std::pmr::string on +// a resource of its own, which a replaced operator new proves. + +#include <webcpp/document/quote.hpp> + +#include <boost/core/lightweight_test.hpp> + +#include "require.hpp" + +#include <cstddef> +#include <cstdint> +#include <cstdlib> +#include <initializer_list> +#include <memory_resource> +#include <new> +#include <string> +#include <string_view> +#include <vector> + +namespace wd = webcpp::document; + +namespace { + +// Whether operator new counts, and what it counted: global and mutable, since operator new is. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +bool counting = false; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +std::uint64_t news = 0; + +} // namespace + +// operator new replaced, to count the allocations of the program's own heap while `counting`. The +// standard library names its parameters with reserved names, which a program cannot use. +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name) +void* operator new(std::size_t size) { + if (counting) { + ++news; + } + void* memory = std::malloc(size == 0 ? 1 : size); + if (memory == nullptr) { + // A test built without exceptions has no std::bad_alloc to throw. + std::abort(); + } + return memory; +} + +void operator delete(void* memory) noexcept { + std::free(memory); +} + +void operator delete(void* memory, std::size_t /*size*/) noexcept { + std::free(memory); +} + +// NOLINTEND(readability-inconsistent-declaration-parameter-name) + +namespace { + +/** A memory resource that counts what it hands out, from `upstream`. */ +class counting_resource final : public std::pmr::memory_resource { +public: + /** A resource over `upstream`, which outlives it. */ + explicit counting_resource(std::pmr::memory_resource* upstream) noexcept + : upstream_(upstream) {} + + /** The allocations it made. */ + [[nodiscard]] std::uint64_t allocations() const noexcept { return allocations_; } + +private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + ++allocations_; + return upstream_->allocate(bytes, alignment); + } + + void do_deallocate(void* memory, std::size_t bytes, std::size_t alignment) override { + upstream_->deallocate(memory, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { + return this == &other; + } + + std::pmr::memory_resource* upstream_; + std::uint64_t allocations_ = 0; +}; + +// UTF-8 text quoted into a std::string, the result checked. +std::string literal_of(std::string_view utf8) { + std::string out; + webcpp::test::require(BOOST_TEST(wd::quote(utf8, out).has_value())); + return out; +} + +// UTF-16 text quoted into a std::string. +std::string literal_of(std::u16string_view utf16) { + std::string out; + wd::quote(utf16, out); + return out; +} + +// UTF-16 code units, lone surrogates among them. +std::u16string units(std::initializer_list<char16_t> list) { + return {list}; +} + +// x"\<BS><FF><LF><CR><TAB><U+0001><U+001F>/é<U+2028>😀, in UTF-8, as stringify_test holds it. +constexpr std::string_view plain_text = + "x\"\\\b\f\n\r\t\x01\x1f/" + "\xc3\xa9" + "\xe2\x80\xa8" + "\xf0\x9f\x98\x80"; + +// What JSON.stringify writes of it. +constexpr std::string_view quoted_text = R"("x\"\\\b\f\n\r\t\u0001\u001f/)" + "\xc3\xa9" + "\xe2\x80\xa8" + "\xf0\x9f\x98\x80\""; + +void quotes_as_json_stringify() { + BOOST_TEST_EQ(literal_of(plain_text), quoted_text); + BOOST_TEST_EQ(literal_of(""), R"("")"); + // Every unit below U+0020, then U+007F, which is not escaped. + std::string controls; + for (char c = 0; c < 0x20; ++c) { + controls.push_back(c); + } + controls.push_back('\x7f'); + const std::string expected = + R"("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f)" + R"(\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c)" + R"(\u001d\u001e\u001f)" + "\x7f\""; + BOOST_TEST_EQ(literal_of(controls), expected); + // U+0080 to U+009F, C1's controls, which JSON.stringify writes as they are: C2 80 to C2 9F in + // UTF-8, valid though a byte 80 alone is refused. + std::string c1; + for (std::uint32_t unit = 0x80; unit < 0xa0; ++unit) { + c1 += '\xc2'; + c1 += static_cast<char>(unit); + } + BOOST_TEST_EQ(literal_of(c1), '"' + c1 + '"'); + // Long strings, past any buffer the writer keeps: one with no escape, one of escapes alone. + const std::string long_text(10000, 'z'); + BOOST_TEST_EQ(literal_of(long_text), '"' + long_text + '"'); + std::string escaped_quotes = "\""; + for (std::size_t i = 0; i < 10000; ++i) { + escaped_quotes += R"(\")"; + } + escaped_quotes += '"'; + BOOST_TEST_EQ(literal_of(std::string(10000, '"')), escaped_quotes); +} + +void a_lone_surrogate_of_utf16() { + // The cases stringify_test pins for a document of js_traits, which holds UTF-16. + // Plain literals: MSVC 14.3 does not read a raw string in these macros' arguments as one. + BOOST_TEST_EQ(literal_of(units({0xD800})), "\"\\ud800\""); + BOOST_TEST_EQ(literal_of(units({0xDC00})), "\"\\udc00\""); + BOOST_TEST_EQ(literal_of(units({0xDC00, 0xD800})), "\"\\udc00\\ud800\""); + BOOST_TEST_EQ(literal_of(units({u'a', 0xDBFF, u'b'})), "\"a\\udbffb\""); + BOOST_TEST_EQ(literal_of(units({0xD83D, 0xDE00})), "\"\xf0\x9f\x98\x80\""); + BOOST_TEST_EQ(literal_of(units({0xD83D, 0xDE00, 0xD83D})), "\"\xf0\x9f\x98\x80\\ud83d\""); + BOOST_TEST_EQ(literal_of(units({0x7F, 0xE9, 0x20AC, 0xFFFF})), + "\"\x7f\xc3\xa9\xe2\x82\xac\xef\xbf\xbf\""); + BOOST_TEST_EQ(literal_of(units({})), R"("")"); + // A group of units repeated past the writer's buffer of 256 bytes, and what JSON.stringify + // writes of one group. + constexpr std::string_view group = R"(\"\ud800)" + "\xc3\xa9" + "\xf0\x9f\x98\x80" + R"(\n)"; + std::u16string many; + std::string expected = "\""; + for (std::size_t i = 0; i < 300; ++i) { + many += units({u'"', 0xD800, 0xE9, 0xD83D, 0xDE00, u'\n'}); + expected += group; + } + expected += '"'; + BOOST_TEST_EQ(literal_of(many), expected); +} + +void appends() { + std::string out = "["; + BOOST_TEST(wd::quote("a", out).has_value()); + out += ','; + wd::quote(u"b", out); + out += ']'; + BOOST_TEST_EQ(out, R"(["a","b"])"); +} + +void refuses_what_is_not_utf8() { + for (const std::string_view text : { + // A stray continuation byte, a byte UTF-8 never holds, a surrogate encoded, an + // overlong form, a sequence cut short, and one past U+10FFFF. + "\x80", + "a\xff", + "\xed\xa0\x80", + "\xc0\xaf", + "\xe2\x82", + "\xf4\x90\x80\x80", + // Lead bytes past F4, which UTF-8 never holds, before three continuation bytes, and + // F8 before four, the five-byte form of RFC 2279. + "\xf5\x80\x80\x80", + "\xf8\x88\x80\x80", + "\xf8\x88\x80\x80\x80", + "\xfe\x80\x80\x80", + "\xff\x80\x80\x80", + // Overlong forms of three and four bytes: U+0000 as E0 80 80 and as F0 80 80 80. + "\xe0\x80\x80", + "\xf0\x80\x80\x80", + // A sequence of four bytes cut short, at the end of the text and before ASCII: the + // last one's 61 is an "a". + "\xf0\x9f\x98", + "\xf0\x9f", + "\xf0", + "\xf0\x9f\x98\x61", + }) { + std::string out = "kept"; + const wd::result<void> refused = wd::quote(text, out); + BOOST_TEST(refused.has_error() && refused.error() == wd::errc::type); + BOOST_TEST_EQ(out, "kept"); + } +} + +void allocates_through_the_output_alone() { + // The arena's memory, taken from operator new before it counts; a monotonic arena never + // reuses what a growing string frees, so it holds every size the string grows through. + std::vector<std::byte> storage(std::size_t{1} << 20U); + std::pmr::monotonic_buffer_resource arena(storage.data(), storage.size(), + std::pmr::null_memory_resource()); + counting_resource resource(&arena); + std::pmr::string out(&resource); + constexpr std::size_t lines = 10000; + constexpr std::size_t triples = 1000; + const std::string long_text(lines, '\n'); + std::u16string long_units; + for (std::size_t i = 0; i < triples; ++i) { + long_units += units({u'a', 0xD800, 0xE9}); + } + news = 0; + counting = true; + const bool utf8 = wd::quote(long_text, out).has_value(); + const std::size_t utf8_size = out.size(); + wd::quote(std::u16string_view(long_units), out); + counting = false; + BOOST_TEST(utf8); + BOOST_TEST_EQ(news, 0U); + BOOST_TEST_GT(resource.allocations(), 0U); + // Each line feed becomes \n, and each 'a', lone surrogate and é a, \ud800 and its 2 bytes. + BOOST_TEST_EQ(utf8_size, 2 + (lines * 2)); + BOOST_TEST_EQ(out.size(), utf8_size + 2 + (triples * (1 + 6 + 2))); +} + +} // namespace + +int main() { + quotes_as_json_stringify(); + a_lone_surrogate_of_utf16(); + appends(); + refuses_what_is_not_utf8(); + allocates_through_the_output_alone(); + return boost::report_errors(); +}