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_.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`, 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` or
+`wd::basic_external`, of any allocator of `std::byte`:
+
+[cols="2,2,3",options="header"]
+|===
+| Storage | Allocator | The image
+
+| `wd::owned`, the default
+| `std::allocator`
+| the document's own, from the global aligned `operator new`
+
+| `wd::external`
+| `std::allocator`
+| a buffer its user owns (<>)
+
+| `wd::pmr::owned`
+| `std::pmr::polymorphic_allocator`
+| the document's own, from the allocator's `std::pmr::memory_resource`
+
+| `wd::pmr::external`
+| `std::pmr::polymorphic_allocator`
+| a buffer its user owns
+
+| `wd::basic_owned`
+| 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`
+| 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`, 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::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
+(<>). The image grows by doubling, as <>
+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 (<>)
+
+| `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(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
+ (<>)
+
+| `wd::from_image(bytes, alloc)`
+| an owned copy of an image (<>)
+
+| `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
+ (<>)
+
+| `pop`, `shift`, `splice`, `slice`, `concat`
+| the values they return, owned documents in the source's allocator, an external source's
+ included (<>)
+|===
+
+`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 (<>), 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 (<>), 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` (<>); and the sugar throws its
+ `wd::capacity_error` (<>).
+
+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()` 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` (<>), and the shared and leased documents,
+ `wd::shared_document` and `wd::leased_document` (<>, <>), 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, <>):
+ 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 (<>), and so are the
+reads into a type of the program's own, `get()` 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 (<>): 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-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 (<>).
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 ``
+ 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 (<>)
| 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
+(<>). 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`
+(<>).
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()`.
* *`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 (<>).
* *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 (<>):
[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`
+| 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` its user owns and keeps alive, such as a browser's memory, 16-aligned
+| `wd::external`; `wd::basic_external`
+| a `std::span` 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 (<>).
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; <>, <>, <>, <> and
<> write and read JSON text, whole or in pieces, and <>
shows the containers a {cpp} program walks. <> chooses what a document stores;
-<> shows the binary image, <> sends it, and <>
-shares it. <> compares document with Boost.JSON, <>
-teaches the sugar that throws, and <> lists every error. <> shows
+<> shows the binary image, <> places it and every
+operation's memory in an allocator, <> sends it, and <> shares it.
+<> compares document with Boost.JSON, <> teaches the
+sugar that throws, and <> lists every error. <> shows
how document is tested, <> what it costs, and the <>
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` parses into a document of other traits, as `wd::parse(text)`
does in <>; `wd::parse_into(buffer, text)` parses into a buffer the program owns
-(<>); and `wd::parse_or_throw(text)`, with exceptions only, throws as
-`JSON.parse` does (<>).
+(<>); `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 (<>); and `wd::parse_or_throw(text)`, with
+exceptions only, throws as `JSON.parse` does (<>).
[#document-parsing-options]
=== Limits and revivers
@@ -71,8 +73,9 @@ builds itself, with `create`, keeps a limit of 1 GiB (<>).
`wd::parser` is the parser itself, `wd::basic_parser` 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 (<>).
+another text, its selectors kept (<>). 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-parsing-errors]
=== Errors and offsets
@@ -94,7 +101,9 @@ another text, its selectors kept (<>).
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` (<>), and a limit passed `errc::capacity`.
+is `errc::range` (<>), 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
+(<>).
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 <> 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 (<>): 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 (<>): 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-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 (<>).
+
+| `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 : 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
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+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 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 alloc(&arena);
+
+ // JSON.parse(text): the image and the parse's working state in the arena.
+ wd::result 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 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 copy =
+ doc.clone(std::pmr::polymorphic_allocator(&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
+#include
#include
#include
+#include
#include
#include
+#include
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 storage(1024);
+ std::pmr::monotonic_buffer_resource arena(storage.data(), storage.size());
+ std::pmr::string message(&arena);
+ message += R"({"type":)";
+ if (const wd::result quoted = wd::quote("offer", message); quoted.has_error()) {
+ return 1;
+ }
+ message += R"(,"sdp":)";
+ if (const wd::result 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 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
#include
#include
+#include
#include
+#include
#include
#include
#include
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
#include
#include
-#include
#include
#include
#include
#include
-#include
namespace webcpp::document {
@@ -113,7 +111,9 @@ struct walker {
static constexpr bool sorted_keys = std::same_as;
/** The container of an attached tree's nodes. */
- static const container& nodes_of(const tree& t) noexcept { return *t.nodes(); }
+ static const container& nodes_of(const tree_view& 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& t, std::uint64_t parent, walk w) noexcept {
+ static const node_type* first(const tree_view& 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& t, std::uint64_t parent, walk w) noexcept {
+ static const node_type* last(const tree_view& 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& t, const node_type& child, walk w,
+ static const node_type* step(const tree_view& t, const node_type& child, walk w,
bool forward) noexcept {
const container& 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(), 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& t, std::uint64_t object,
+ static const node_type* bound(const tree_view& 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();
if constexpr (std::same_as) {
- std::vector units(static_cast(utf16_length(utf8)));
- to_utf16(utf8, units.data());
- const std::span bytes = std::as_bytes(std::span(units));
- return bound_in(keys, object,
- {reinterpret_cast(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
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
- 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
+ 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
const node* container_node(basic_document* doc, std::uint64_t id,
webcpp::document::kind k) noexcept {
- const tree* t = doc == nullptr ? nullptr : access::tree_of(std::as_const(*doc));
+ const tree_view* t = doc == nullptr ? nullptr : access::tree_of(std::as_const(*doc));
const node* n = t == nullptr ? nullptr : t->find(id);
return n == nullptr || n->kind != k ? nullptr : n;
}
@@ -247,11 +244,12 @@ inline constexpr bool is_document> = 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
+template
requires settable
-result prepare_for_view(const T& v, prepared& out, bool undefined_is_null) noexcept {
+result prepare_for_view(const T& v, prepared& out,
+ bool undefined_is_null) noexcept {
if constexpr (copy_source) {
- const tree* from = access::tree_of(v);
+ const tree_view* 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(doc_, child_);
@@ -352,11 +347,9 @@ class WEBCPP_DOCUMENT_NO_DANGLING child_iterator {
/** The current child, held, for `it->second` and `it->get()`. */
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* t = tree_ptr();
+ const tree_view* t = tree_ptr();
const node* n = t == nullptr ? nullptr : t->find(child_);
const node* next =
n == nullptr ? nullptr : walker::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* t = tree_ptr();
+ const tree_view* t = tree_ptr();
const node* previous = nullptr;
if (t != nullptr && child_ == 0) {
previous = walker::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* tree_ptr() const noexcept {
+ [[nodiscard]] const tree_view* 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* tree_ptr() const noexcept {
+ [[nodiscard]] const detail::tree_view* 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* tree_ptr() const noexcept {
+ [[nodiscard]] const detail::tree* 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* writable_tree() const noexcept {
+ [[nodiscard]] detail::tree* writable_tree() const noexcept {
return detail::access::tree_of(*doc_);
}
@@ -902,7 +898,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_object_ref {
template
[[nodiscard]] result> put(std::string_view key, const T& v,
bool created) const noexcept {
- detail::prepared p;
+ detail::prepared 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& 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) {
- const std::u16string_view units = m.key.units();
- std::string key(static_cast(detail::utf8_size(units)), '\0');
- detail::to_utf8(units, key.data());
- static_cast(writable_tree()->erase_member(id_, key));
- } else {
- static_cast(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* 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 p;
+ detail::tree* t = writable_tree();
+ detail::prepared p(t->get_allocator());
if (const auto made = detail::prepare_for_view(v, p, true); !made.has_value()) {
return made.error();
}
const detail::item item = p.value();
- detail::tree* 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* tree_ptr() const noexcept {
+ [[nodiscard]] const detail::tree* 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* writable_tree() const noexcept {
+ [[nodiscard]] detail::tree* 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
+
+#include // lint-world: its allocators' failure, no segment
+
+#include
+#include
+
+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
+auto unless_allocation_fails(Run&& run, [[maybe_unused]] Failed&& failed)
+ -> decltype(std::forward(run)()) {
+#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS
+ try {
+ return std::forward(run)();
+ } catch (const std::bad_alloc&) {
+ return failed();
+ } catch (const boost::interprocess::bad_alloc&) {
+ return failed();
+ }
+#else
+ return std::forward(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
#include
#include
+#include
#include
+#include
#include
#include
@@ -39,6 +41,8 @@
#include
#include
#include
+#include
+#include
#include
#include
#include
@@ -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
+auto bad_alloc_as_capacity(F&& f) noexcept -> decltype(std::forward(f)()) {
+ using result_type = decltype(std::forward(f)());
+ return unless_allocation_fails(std::forward(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
concept number_integer = std::integral && !std::same_as && !std::same_as &&
@@ -84,7 +106,7 @@ concept readable =
std::same_as || std::same_as ||
std::same_as> || std::same_as