From 8ab7bc6dc57632a39a936c925da21b89130b28c0 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:51:10 -0300 Subject: [PATCH 01/23] document: quote, JSON.stringify's quoting of a string alone A public quote(text, out) appends a string to a string of the caller's as a JSON string literal, with the bytes stringify writes of the same string: the writer's QuoteJSONString moves to , and the writer calls it. The UTF-8 overload refuses text that is not UTF-8 with errc::type and leaves the output unchanged; the UTF-16 overload escapes a lone surrogate as JSON.stringify does since ES2019. Only the output allocates, which the test proves with a std::pmr::string on a counting resource and a replaced operator new. --- include/webcpp/document.hpp | 1 + include/webcpp/document/detail/writer.hpp | 91 +------- include/webcpp/document/quote.hpp | 192 ++++++++++++++++ test/Jamfile | 3 + test/quote_test.cpp | 263 ++++++++++++++++++++++ 5 files changed, 468 insertions(+), 82 deletions(-) create mode 100644 include/webcpp/document/quote.hpp create mode 100644 test/quote_test.cpp diff --git a/include/webcpp/document.hpp b/include/webcpp/document.hpp index 7eecdbd..cecd0f4 100644 --- a/include/webcpp/document.hpp +++ b/include/webcpp/document.hpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/document/detail/writer.hpp b/include/webcpp/document/detail/writer.hpp index 6489949..495ab4b 100644 --- a/include/webcpp/document/detail/writer.hpp +++ b/include/webcpp/document/detail/writer.hpp @@ -17,9 +17,9 @@ #include #include -#include #include #include +#include #include #include @@ -336,88 +336,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(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 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(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(to_utf8(units.substr(i, 1), buffer.data() + used)); - } else if (unit >= 0x20 && unit != u'"' && unit != u'\\') { - buffer[used++] = static_cast(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 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 + 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. */ diff --git a/include/webcpp/document/quote.hpp b/include/webcpp/document/quote.hpp new file mode 100644 index 0000000..6a82d80 --- /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 + +#include +#include + +#include +#include +#include +#include + +namespace webcpp::document { + +namespace detail { + +/** An output of @ref quote: a string, appended to by `append(data, size)`. */ +template +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 +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 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 +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(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 +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 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(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(to_utf8(units.substr(i, 1), buffer.data() + used)); + } else if (unit >= 0x20 && unit != u'"' && unit != u'\\') { + buffer[used++] = static_cast(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 + requires detail::appendable +result 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 + requires detail::appendable +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/test/Jamfile b/test/Jamfile index a830500..e910bc7 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 : emscripten:-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. diff --git a/test/quote_test.cpp b/test/quote_test.cpp new file mode 100644 index 0000000..194ee88 --- /dev/null +++ b/test/quote_test.cpp @@ -0,0 +1,263 @@ +// 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 stringify_test pins with Node 26 +// and the bytes stringify writes of the same string: every escape, text past ASCII, a lone +// surrogate of UTF-16, a long string; it appends, refuses text that is not UTF-8 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 + +#include +#include + +#include + +#include "require.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 { + +using js_document = wd::basic_document; + +/** 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; +}; + +// A document holding `v`, set at its root. +template +Document document_of(const T& v) { + auto made = Document::create(); + webcpp::test::require(BOOST_TEST(made.has_value())); + Document d = std::move(*made); + auto root = d.root(); + webcpp::test::require(BOOST_TEST(root.set(v).has_value())); + return d; +} + +// 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 list) { + return {list}; +} + +// x"\/é😀, 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); + // A long string, past any buffer the writer keeps. + const std::string long_text(10000, 'z'); + BOOST_TEST_EQ(literal_of(long_text), '"' + long_text + '"'); +} + +void quotes_as_stringify_writes() { + std::string controls; + for (char c = 0; c < 0x20; ++c) { + controls.push_back(c); + } + const std::string long_text(10000, '"'); + for (const std::string_view text : { + plain_text, + std::string_view(controls), + std::string_view(long_text), + std::string_view(), + }) { + BOOST_TEST_EQ(literal_of(text), wd::stringify(document_of(text))); + BOOST_TEST_EQ(literal_of(text), wd::stringify(document_of(text))); + } +} + +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"("")"); + // The bytes stringify writes of the same units, past the writer's buffer of 256 bytes. + std::u16string many; + for (int i = 0; i < 300; ++i) { + many += units({u'"', 0xD800, 0xE9, 0xD83D, 0xDE00, u'\n'}); + } + BOOST_TEST_EQ(literal_of(many), + wd::stringify(document_of(std::u16string_view(many)))); +} + +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() { + // 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. + for (const std::string_view text : + {"\x80", "a\xff", "\xed\xa0\x80", "\xc0\xaf", "\xe2\x82", "\xf4\x90\x80\x80"}) { + std::string out = "kept"; + const wd::result 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 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(); + quotes_as_stringify_writes(); + a_lone_surrogate_of_utf16(); + appends(); + refuses_what_is_not_utf8(); + allocates_through_the_output_alone(); + return boost::report_errors(); +} From d6a6d0732cb638cb4fa5bc95663c0cc2e7bb1c02 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 19:53:12 -0300 Subject: [PATCH 02/23] document: the page shows quote, writing a JSON text field by field Writing JSON gains a section, A string alone, quoted, whose listing is a new region of document_streaming.cpp: a JSON text written field by field into a std::pmr::string on a monotonic arena, a lone surrogate of UTF-16, and text that is not UTF-8 refused. The changelog names quote under Unreleased. --- doc/changelog.adoc | 1 + doc/stringify.adoc | 26 +++++++++++++++++++++++ example/document_streaming.cpp | 32 ++++++++++++++++++++++++++++- example/document_streaming.expected | 2 ++ 4 files changed, 60 insertions(+), 1 deletion(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 513d174..1b1b450 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,6 +16,7 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] +* 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/stringify.adoc b/doc/stringify.adoc index 133b57d..b978908 100644 --- a/doc/stringify.adoc +++ b/doc/stringify.adoc @@ -45,3 +45,29 @@ 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. + +[#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/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 From 1cad77e969dc5f3ba4f121cd161d15a005659ed9 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:18:17 -0300 Subject: [PATCH 03/23] document: pin quote's tests on JSON.stringify's bytes, and widen its UTF-8 cases The test compared quote with stringify, which writes strings through the same detail::quote_json, so those checks proved nothing. It now compares quote with the bytes Node 26 writes, held as literals: a long string of quotes, each escaped, and a run of UTF-16 groups past the writer's buffer. It accepts C1's controls, C2 80 to C2 9F, as they are, and refuses lead bytes past F4, overlong forms of three and four bytes, and sequences of four bytes cut short, as Node's TextDecoder in its fatal mode refuses them. --- test/quote_test.cpp | 104 ++++++++++++++++++++++++-------------------- 1 file changed, 56 insertions(+), 48 deletions(-) diff --git a/test/quote_test.cpp b/test/quote_test.cpp index 194ee88..7e4d7f5 100644 --- a/test/quote_test.cpp +++ b/test/quote_test.cpp @@ -4,17 +4,14 @@ // 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 stringify_test pins with Node 26 -// and the bytes stringify writes of the same string: every escape, text past ASCII, a lone -// surrogate of UTF-16, a long string; it appends, refuses text that is not UTF-8 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. +// 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 -#include -#include - #include #include "require.hpp" @@ -27,7 +24,6 @@ #include #include #include -#include #include namespace wd = webcpp::document; @@ -69,8 +65,6 @@ void operator delete(void* memory, std::size_t /*size*/) noexcept { namespace { -using js_document = wd::basic_document; - /** A memory resource that counts what it hands out, from `upstream`. */ class counting_resource final : public std::pmr::memory_resource { public: @@ -99,17 +93,6 @@ class counting_resource final : public std::pmr::memory_resource { std::uint64_t allocations_ = 0; }; -// A document holding `v`, set at its root. -template -Document document_of(const T& v) { - auto made = Document::create(); - webcpp::test::require(BOOST_TEST(made.has_value())); - Document d = std::move(*made); - auto root = d.root(); - webcpp::test::require(BOOST_TEST(root.set(v).has_value())); - return d; -} - // UTF-8 text quoted into a std::string, the result checked. std::string literal_of(std::string_view utf8) { std::string out; @@ -157,26 +140,23 @@ void quotes_as_json_stringify() { R"(\u001d\u001e\u001f)" "\x7f\""; BOOST_TEST_EQ(literal_of(controls), expected); - // A long string, past any buffer the writer keeps. + // 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(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 + '"'); -} - -void quotes_as_stringify_writes() { - std::string controls; - for (char c = 0; c < 0x20; ++c) { - controls.push_back(c); - } - const std::string long_text(10000, '"'); - for (const std::string_view text : { - plain_text, - std::string_view(controls), - std::string_view(long_text), - std::string_view(), - }) { - BOOST_TEST_EQ(literal_of(text), wd::stringify(document_of(text))); - BOOST_TEST_EQ(literal_of(text), wd::stringify(document_of(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() { @@ -191,13 +171,20 @@ void a_lone_surrogate_of_utf16() { 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"("")"); - // The bytes stringify writes of the same units, past the writer's buffer of 256 bytes. + // 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; - for (int i = 0; i < 300; ++i) { + std::string expected = "\""; + for (std::size_t i = 0; i < 300; ++i) { many += units({u'"', 0xD800, 0xE9, 0xD83D, 0xDE00, u'\n'}); + expected += group; } - BOOST_TEST_EQ(literal_of(many), - wd::stringify(document_of(std::u16string_view(many)))); + expected += '"'; + BOOST_TEST_EQ(literal_of(many), expected); } void appends() { @@ -210,10 +197,32 @@ void appends() { } void refuses_what_is_not_utf8() { - // 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. - for (const std::string_view text : - {"\x80", "a\xff", "\xed\xa0\x80", "\xc0\xaf", "\xe2\x82", "\xf4\x90\x80\x80"}) { + 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 refused = wd::quote(text, out); BOOST_TEST(refused.has_error() && refused.error() == wd::errc::type); @@ -254,7 +263,6 @@ void allocates_through_the_output_alone() { int main() { quotes_as_json_stringify(); - quotes_as_stringify_writes(); a_lone_surrogate_of_utf16(); appends(); refuses_what_is_not_utf8(); From 1875c308f90ec2a22c3e633950e8c0491d99f6e3 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:48:42 -0300 Subject: [PATCH 04/23] document: the storage's allocator, which holds the image basic_owned and basic_external are the storages of a document, owned and external the standard allocator's, pmr::owned and pmr::external a memory resource's, with pmr::document, pmr::basic_document, pmr::value, pmr::const_value and pmr::parser. A document is allocator-aware as the standard containers are: its owned image is allocated, grown and freed through the allocator, rebound to 16-byte blocks; a move takes the allocator; a move assignment between allocators that are not equal and do not propagate copies the image; the copy constructor asks select_on_container_copy_construction; create, clone, from_image, format, open, parse, parse_into and the parser take an allocator; and the documents that pop, shift, splice, slice and concat make are in the source's allocator. With exceptions, an allocator that has no room for the image is errc::capacity. The tree's reading half, tree_view, reads a document of any allocator, so a deep copy crosses allocators. The working state still uses the standard allocator but for compaction's stack, which follows. --- include/webcpp/document.hpp | 1 + include/webcpp/document/containers.hpp | 18 +- include/webcpp/document/detail/convert.hpp | 98 ++- include/webcpp/document/detail/fwd.hpp | 3 +- include/webcpp/document/detail/handler.hpp | 17 +- include/webcpp/document/detail/heap.hpp | 236 ++++-- include/webcpp/document/detail/tree.hpp | 798 ++++++++++-------- .../webcpp/document/detail/value_array.hpp | 82 +- .../webcpp/document/detail/value_sugar.hpp | 20 +- include/webcpp/document/detail/writer.hpp | 6 +- include/webcpp/document/document.hpp | 355 ++++++-- include/webcpp/document/parse.hpp | 56 ++ include/webcpp/document/parser.hpp | 33 +- include/webcpp/document/storage.hpp | 154 ++++ include/webcpp/document/stringify.hpp | 4 +- include/webcpp/document/value.hpp | 80 +- test/Jamfile | 6 + test/allocator_test.cpp | 349 ++++++++ test/counting.cpp | 186 ++++ test/counting.hpp | 135 +++ 20 files changed, 2015 insertions(+), 622 deletions(-) create mode 100644 include/webcpp/document/storage.hpp create mode 100644 test/allocator_test.cpp create mode 100644 test/counting.cpp create mode 100644 test/counting.hpp diff --git a/include/webcpp/document.hpp b/include/webcpp/document.hpp index cecd0f4..d65ae99 100644 --- a/include/webcpp/document.hpp +++ b/include/webcpp/document.hpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/document/containers.hpp b/include/webcpp/document/containers.hpp index 0510142..0f53042 100644 --- a/include/webcpp/document/containers.hpp +++ b/include/webcpp/document/containers.hpp @@ -113,7 +113,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 +123,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 +135,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 +147,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. @@ -159,7 +163,7 @@ struct walker { 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; @@ -226,7 +230,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; } @@ -251,7 +255,7 @@ template requires settable 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; } diff --git a/include/webcpp/document/detail/convert.hpp b/include/webcpp/document/detail/convert.hpp index 7c6662c..4353dad 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,7 @@ #include #include #include +#include #include #include #include @@ -84,7 +87,7 @@ concept readable = std::same_as || std::same_as || std::same_as> || std::same_as>; -template +template > struct converter; /** @@ -92,13 +95,19 @@ 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 +template > 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) + : prepared(Allocator()) {} + + /** A value holding `null`, its buffers in `alloc`. */ + explicit prepared(const Allocator& alloc) noexcept + : 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 +118,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{})), + : alloc_(other.alloc_), + item_(std::exchange(other.item_, item{})), 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{}); @@ -133,19 +146,30 @@ class prepared { /** The item, valid while this object lives and is not changed. */ [[nodiscard]] const item& 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& from, std::uint64_t id) noexcept { + void copy_of(const tree_view& from, std::uint64_t id) noexcept { clear(); item_.from = &from; item_.from_id = id; } private: - template + template friend struct converter; + /** A buffer of `T` in the allocator. */ + template + using buffer = std::vector>; + + /** A list of buffers of `T`, each in the allocator. */ + template + using buffers = std::vector, rebound>>; + /** Holds `null` again, and owns nothing. */ void clear() noexcept { item_ = item{}; @@ -155,6 +179,9 @@ class prepared { entries_.clear(); } + /** The allocator. */ + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS Allocator alloc_; + /** The item. */ item item_; @@ -162,23 +189,23 @@ class prepared { // is added after it. /** Text transcoded to UTF-8. */ - std::vector> utf8_; + buffers utf8_; /** Text transcoded to UTF-16. */ - std::vector> utf16_; + buffers utf16_; /** Bytes decoded from text. */ - std::vector> bytes_; + buffers bytes_; /** The entries of each literal container, a nested one pointing at its own. */ - std::vector>> entries_; + buffers> entries_; }; /** The conversions' work, with access to what a @ref prepared value owns: C++ values into items, and nodes back into C++ values. */ -template +template struct converter { /** The traits' number. */ using number_type = Traits::number; @@ -190,7 +217,7 @@ struct converter { using kind_t = webcpp::document::kind; /** A prepared value of these traits. */ - using prepared_t = prepared; + using prepared_t = prepared; /** An item of these traits. */ using item_t = item; @@ -199,7 +226,7 @@ struct converter { using node_t = node; /** A tree of these traits. */ - using tree_t = tree; + using tree_t = tree_view; /** Whether strings are stored as UTF-16 code units. */ static constexpr bool utf16_text = std::same_as; @@ -406,8 +433,8 @@ struct converter { if constexpr (!javascript_shape) { if (revive_bytes) { if (result> decoded = decode(text); decoded.has_value()) { - const std::vector& bytes = - owner.bytes_.emplace_back(std::move(decoded).unsafe_value()); + const auto& bytes = owner.bytes_.emplace_back( + decoded.unsafe_value().begin(), decoded.unsafe_value().end(), owner.alloc_); return hold_form(owner, owner.item_, std::span(bytes)); } } @@ -492,8 +519,8 @@ struct converter { } out.kind = kind_t::string; if constexpr (utf16_text) { - std::vector& units = - owner.utf16_.emplace_back(static_cast(utf16_length(v))); + auto& units = + owner.utf16_.emplace_back(static_cast(utf16_length(v)), owner.alloc_); to_utf16(v, units.data()); out.text = std::as_bytes(std::span(units)); } else { @@ -512,8 +539,8 @@ struct converter { if (!valid_utf16(v)) { return errc::type; } - std::vector& chars = - owner.utf8_.emplace_back(static_cast(utf8_size(v))); + auto& chars = + owner.utf8_.emplace_back(static_cast(utf8_size(v)), owner.alloc_); to_utf8(v, chars.data()); out.kind = kind_t::string; out.text = std::as_bytes(std::span(chars)); @@ -553,7 +580,7 @@ struct converter { return {}; } const std::span> entries = - owner.entries_.emplace_back(members.size()); + owner.entries_.emplace_back(members.size(), owner.alloc_); out.entries = entries.data(); out.entry_count = entries.size(); for (std::size_t i = 0; i < members.size(); ++i) { @@ -578,7 +605,7 @@ struct converter { return {}; } const std::span> entries = - owner.entries_.emplace_back(elements.size()); + owner.entries_.emplace_back(elements.size(), owner.alloc_); out.entries = entries.data(); out.entry_count = entries.size(); for (std::size_t i = 0; i < elements.size(); ++i) { @@ -995,19 +1022,20 @@ struct converter { 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 +template requires preparable -result prepare(const T& v, prepared& out) noexcept { - return converter::prepare_value(v, out); +result prepare(const T& v, prepared& out) noexcept { + return converter::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 -result prepare_number(std::string_view json_number, prepared& out) noexcept { - return converter::prepare_number_text(json_number, out); +template +result prepare_number(std::string_view json_number, + prepared& out) noexcept { + return converter::prepare_number_text(json_number, out); } /** @@ -1015,10 +1043,10 @@ result prepare_number(std::string_view json_number, prepared& 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 +template result prepare_string(std::string_view utf8, bool revive_dates, bool revive_bytes, - prepared& out) noexcept { - return converter::prepare_json_string(utf8, revive_dates, revive_bytes, out); + prepared& out) noexcept { + return converter::prepare_json_string(utf8, revive_dates, revive_bytes, out); } /** The item of an empty container, `null`, or for a root @ref kind::undefined. */ @@ -1044,7 +1072,7 @@ item empty_item(webcpp::document::kind k) noexcept { */ template requires readable -result read(const tree& t, const node* n) noexcept { +result read(const tree_view& t, const node* n) noexcept { if (n == nullptr) { return errc::type; } @@ -1057,7 +1085,7 @@ result read(const tree& t, const node* n) noexcept { in any order. A null node is undefined, equal only to another. */ template -bool equal(const tree& a, const node* x, const tree& b, +bool equal(const tree_view& a, const node* x, const tree_view& b, const node* y) noexcept { return converter::equal_trees(a, x, b, y); } 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 +#include #include 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..d7c49d3 100644 --- a/include/webcpp/document/detail/handler.hpp +++ b/include/webcpp/document/detail/handler.hpp @@ -212,10 +212,11 @@ class handler { /** A new document: owned, within the options' limit, or formatted in the external buffer. */ result> make_document() noexcept { - if constexpr (std::same_as) { - return basic_document::create(owner_->options_.max_document_bytes); + if constexpr (owned_storage) { + return basic_document::create(owner_->alloc_, + owner_->options_.max_document_bytes); } else { - return format(owner_->buffer_); + return format(owner_->buffer_, owner_->alloc_); } } @@ -226,7 +227,9 @@ class handler { } /** The tree of the document being built. */ - [[nodiscard]] tree& tree_of() const noexcept { return *access::tree_of(document()); } + [[nodiscard]] tree& 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 { @@ -269,7 +272,7 @@ class handler { replaces the value in its first place), or an element appended; returns its id. */ result place(const item& v) noexcept { - tree& t = tree_of(); + auto& t = tree_of(); if (frames_.empty()) { if (const result done = t.assign(root_id, v); !done.has_value()) { return done.error(); @@ -342,7 +345,7 @@ class handler { /** Turns the object `id` into bytes when it has the shape `JSON.stringify` gives a Uint8Array. */ result revive_bytes(std::uint64_t id) noexcept { - tree& t = tree_of(); + auto& t = tree_of(); result> bytes = read>(t, t.find(id)); if (!bytes.has_value()) { return {}; @@ -412,7 +415,7 @@ class handler { the array's last, a member is found by its key, and the root is left holding `undefined`. */ result take_out() noexcept { - tree& t = tree_of(); + auto& t = tree_of(); if (frames_.empty()) { return t.assign(root_id, empty_item(webcpp::document::kind::undefined)); } diff --git a/include/webcpp/document/detail/heap.hpp b/include/webcpp/document/detail/heap.hpp index 9762eb8..4095263 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 @@ -21,6 +21,8 @@ #include +#include +#include #include // lint-world: a heap in a buffer #include // lint-world: an offset, no process #include // lint-world: a mutex that locks nothing @@ -28,13 +30,16 @@ #include #include +#include #include #include #include #include +#include #include #include #include +#include #include namespace webcpp::document::detail { @@ -324,22 +329,91 @@ 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 any allocator, rebound to + it, gives the heap the alignment it needs. */ -class region { +struct alignas(16) image_block { + /** The block's bytes. */ + std::array bytes; +}; + +/** + 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); + } + + /** 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. + + @tparam Allocator An allocator of `std::byte`, rebound to @ref image_block for the image. +*/ +template +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 owned(std::uint64_t size, std::uint64_t max_bytes) noexcept { + static result 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); + basic_region made(a); + std::byte* bytes = made.allocate(size); if (bytes == nullptr) { return errc::capacity; } std::memset(bytes, 0, static_cast(size)); - region made; made.data_ = bytes; made.size_ = size; made.max_bytes_ = max_bytes; @@ -349,8 +423,9 @@ class region { } /** An owned copy of an image's bytes, whose heap is the image's own. */ - static result owned_copy(std::span bytes, - std::uint64_t max_bytes) noexcept { + static result owned_copy(std::span bytes, + std::uint64_t max_bytes, + const Allocator& a = Allocator()) noexcept { if (bytes.size() > max_bytes) { return errc::capacity; } @@ -358,12 +433,12 @@ class region { if (bytes.size() < smallest()) { return errc::not_a_document; } - std::byte* copy = allocate(bytes.size()); + basic_region made(a); + std::byte* copy = made.allocate(bytes.size()); if (copy == nullptr) { return errc::capacity; } std::memcpy(copy, bytes.data(), bytes.size()); - region made; made.data_ = copy; made.size_ = bytes.size(); made.max_bytes_ = max_bytes; @@ -372,8 +447,9 @@ class region { } /** An external region over `buffer`, as it is: for an image already there. */ - static region external(std::span buffer) noexcept { - region made; + static basic_region external(std::span 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 +457,8 @@ class region { } /** An external region over `buffer`, zeroed, with an empty heap after the header. */ - static result external_empty(std::span buffer) noexcept { + static result external_empty(std::span 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(buffer.data()) % 16 != 0) { @@ -389,52 +466,47 @@ 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) = default; + + /** An empty region, which holds no bytes, with the allocator `a`. */ + explicit basic_region(const Allocator& a) noexcept : alloc_(a) {} - /** 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)) {} + /** Takes the bytes and a copy of the allocator of `other`, which is left empty. */ + basic_region(basic_region&& other) noexcept : alloc_(other.alloc_) { take(other); } - /** Frees its own bytes, then takes the bytes of `other`, which is left empty. */ - region& operator=(region&& other) noexcept { + /** + 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); 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 @@ -459,7 +531,7 @@ class region { const std::uint64_t old_size = size_; std::memcpy(bigger, data_, static_cast(old_size)); std::memset(bigger + old_size, 0, static_cast(new_size - old_size)); - deallocate(data_); + deallocate(data_, old_size); data_ = bigger; size_ = new_size; // The heap's links are offsets, so the copy is a heap already: it only takes the new end. @@ -486,13 +558,23 @@ class region { return false; } std::memcpy(smaller, data_, static_cast(size)); - deallocate(data_); + deallocate(data_, size_); data_ = smaller; size_ = size; return true; } private: + /** The allocator of the image's blocks. */ + using block_allocator = + typename std::allocator_traits::template rebind_alloc; + + /** Its traits. */ + using block_traits = std::allocator_traits; + + /** Whether the allocator is the standard one, whose `allocate` is the global operator new. */ + static constexpr bool standard = std::same_as>; + /** 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 +585,53 @@ class region { return std::numeric_limits::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( - ::operator new(static_cast(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((size + sizeof(image_block) - 1) / sizeof(image_block)); + } + + /** + A new buffer of `size` bytes, 16-aligned and uninitialized, or null when the allocator has + none: its `std::bad_alloc` is caught, with exceptions. + */ + std::byte* 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. + return static_cast( + ::operator new(static_cast(size), std::align_val_t{16}, std::nothrow)); + } else { + block_allocator blocks(alloc_); + const std::size_t count = blocks_of(size); + if (count > block_traits::max_size(blocks)) { + return nullptr; + } +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + try { + return reinterpret_cast( + std::to_address(block_traits::allocate(blocks, count))); + } catch (const std::bad_alloc&) { + return nullptr; + } +#else + return reinterpret_cast( + std::to_address(block_traits::allocate(blocks, count))); +#endif + } } - /** Frees a buffer @ref allocate made. */ - static void deallocate(std::byte* bytes) noexcept { - ::operator delete(bytes, std::align_val_t{16}); + /** Frees a buffer of `size` bytes that @ref allocate made. */ + void deallocate(std::byte* bytes, std::uint64_t size) noexcept { + if constexpr (standard) { + ::operator delete(bytes, std::align_val_t{16}); + } else { + block_allocator blocks(alloc_); + using pointer = typename block_traits::pointer; + block_traits::deallocate( + blocks, + std::pointer_traits::pointer_to(*reinterpret_cast(bytes)), + blocks_of(size)); + } } /** Its heap, as @ref heap_of finds it. */ @@ -530,7 +650,7 @@ class region { /** Frees its bytes when it owns them, and leaves it empty. */ void release() noexcept { if (owned_ && data_ != nullptr) { - deallocate(data_); + deallocate(data_, size_); } data_ = nullptr; size_ = 0; @@ -538,14 +658,14 @@ class region { 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 region of an image in the standard allocator. */ +using region = basic_region>; + /** 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(r.data() + header_bytes)); } diff --git a/include/webcpp/document/detail/tree.hpp b/include/webcpp/document/detail/tree.hpp index 01f9456..208ec23 100644 --- a/include/webcpp/document/detail/tree.hpp +++ b/include/webcpp/document/detail/tree.hpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -46,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -330,6 +332,9 @@ template inline constexpr std::uint64_t node_probe_bytes = sizeof(node) + 128; template +class tree_view; + +template > class tree; template @@ -362,8 +367,8 @@ struct item { /** How many entries. */ std::size_t entry_count = 0; - /** The tree of a subtree to copy deeply, or null. */ - const tree* from = nullptr; + /** The tree of a subtree to copy deeply, of a document of any allocator, or null. */ + const tree_view* from = nullptr; /** The id of the subtree's node in `from`. */ std::uint64_t from_id = 0; @@ -408,112 +413,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 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 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 sizes{ - sizeof(nodes_type), - node_probe_bytes, - node_probe_bytes, - }; - 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(block) - r.data(), container_offset)); - auto* nodes = new (block) nodes_type(allocator(&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(); - 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 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(r.data()) % 16 != 0) { - return errc::not_a_document; - } - // A seal is checked by whoever opens the image, before it attaches. - const std::span bytes(r.data(), static_cast(r.size())); - if (const auto checked = check_image(bytes, layout_tag(), 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; } @@ -603,26 +514,401 @@ class tree { for (const node_type* n = first_child(parent); n != nullptr; n = next_sibling(*n)) { f(*n); } - } - - /** An array's length or an object's key count; 0 for any other node. */ - [[nodiscard]] std::uint64_t count(std::uint64_t container_id) const noexcept { - const node_type* n = find(container_id); - if (is_kind(n, kind_t::array)) { - return word(n->scalar, length_at); + } + + /** An array's length or an object's key count; 0 for any other node. */ + [[nodiscard]] std::uint64_t count(std::uint64_t container_id) const noexcept { + const node_type* n = find(container_id); + if (is_kind(n, kind_t::array)) { + return word(n->scalar, length_at); + } + if (is_kind(n, kind_t::object)) { + return word(n->scalar, key_count_at); + } + return 0; + } + + /** How many nodes the tree holds. */ + [[nodiscard]] std::uint64_t node_count() const noexcept { + const nodes_type* nodes = nodes_of(); + return nodes == nullptr ? 0 : nodes->size(); + } + + /** + 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()) { + 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 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* nodes() const noexcept { return nodes_of(); } + +protected: + /** The node of this tree. */ + using node_type = node; + + /** The container of this tree's nodes. */ + using nodes_type = container; + + /** A node's scalar. */ + using scalar_type = std::array>; + + /** The kinds of values, which a node's member `kind` hides inside it. */ + using kind_t = webcpp::document::kind; + + /** Whether keys and strings are stored as UTF-16 code units. */ + static constexpr bool utf16_text = std::same_as; + + /** Whether objects walk their members by key. */ + static constexpr bool sorted_keys = std::same_as; + + /** 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 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(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(); + const auto begin = reinterpret_cast(region_->data()); + const auto within = [begin, size](const auto* p) { + const auto at = reinterpret_cast(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::max() - b + ? std::numeric_limits::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 bytes) noexcept { + return {reinterpret_cast(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(); + 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(); + 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(); + 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 + 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 + 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(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; + } + + /** 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. 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. + + @tparam Traits The traits. + @tparam Allocator The allocator of the region, which grows an owned image and, rebound, holds what + an operation stages before it changes anything. +*/ +template +class tree : public tree_view { + /** The reading half. */ + using view = tree_view; + + 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::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; + + using view::count; + using view::element; + using view::find; + using view::first_child; + using view::member; + using view::next_sibling; + + // 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 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 sizes{ + sizeof(nodes_type), + node_probe_bytes, + node_probe_bytes, + }; + 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(block) - r.data(), container_offset)); + auto* nodes = new (block) nodes_type(allocator(&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(); + 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 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(r.data()) % 16 != 0) { + return errc::not_a_document; + } + // A seal is checked by whoever opens the image, before it attaches. + const std::span bytes(r.data(), static_cast(r.size())); + if (const auto checked = check_image(bytes, layout_tag(), 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; } - if (is_kind(n, kind_t::object)) { - return word(n->scalar, key_count_at); + heap& h = heap_of(r); + if (h.get_size() > header.size - header_bytes || !h.check_sanity()) { + return errc::not_a_document; } - return 0; + 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; } - /** How many nodes the tree holds. */ - [[nodiscard]] std::uint64_t node_count() const noexcept { - const nodes_type* nodes = nodes_of(); - return nodes == nullptr ? 0 : nodes->size(); + /** 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(*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 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. @@ -844,14 +1130,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,37 +1152,16 @@ 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()) { - 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. // NOLINTBEGIN(bugprone-exception-escape) @@ -910,8 +1175,9 @@ class tree { @return The tree over `to`; @ref errc::type when `from` is attached to nothing, @ref errc::capacity when `to` is not of `bytes` bytes. */ - static result compact_to(region& to, const tree& from, std::uint64_t bytes) noexcept { - const nodes_type* from_nodes = from.nodes_of(); + static result 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; @@ -933,7 +1199,7 @@ class tree { BOOST_ASSERT(std::cmp_equal(static_cast(block) - to.data(), container_offset)); auto* nodes = new (block) nodes_type(allocator(&h)); - compaction copier{from, c, h, nodes}; + compaction copier{from, c, h, nodes, to.get_allocator()}; if (!copier.copy_tree(*root)) { return errc::capacity; } @@ -956,89 +1222,7 @@ class tree { // 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* 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 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(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; - - /** The container of this tree's nodes. */ - using nodes_type = container; - - /** A node's scalar. */ - using scalar_type = std::array>; - - /** The kinds of values, which a node's member `kind` hides inside it. */ - using kind_t = webcpp::document::kind; - - /** Whether keys and strings are stored as UTF-16 code units. */ - static constexpr bool utf16_text = std::same_as; - - /** Whether objects walk their members by key. */ - static constexpr bool sorted_keys = std::same_as; - - /** 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; - /** The group a node of `group` takes while an operation sets it aside, erased or renumbered: no node is ever left there, and no other node of its parent is in it. @@ -1056,7 +1240,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 +1251,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; @@ -1147,7 +1334,7 @@ class tree { if (!copy(root, 0, index_group, 0)) { return false; } - std::vector stack; + std::vector> stack(alloc); if (const node_type* first = from.first_child(root_id)) { stack.push_back({first, root_id, 0}); } @@ -1220,7 +1407,7 @@ class tree { const item* 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; @@ -1253,134 +1440,21 @@ class tree { std::uint64_t created = 0; }; - /** - 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(); - const auto begin = reinterpret_cast(region_->data()); - const auto within = [begin, size](const auto* p) { - const auto at = reinterpret_cast(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::max() - b - ? std::numeric_limits::max() - : a + b; - } - /** 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 bytes) noexcept { - return {reinterpret_cast(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(); - 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(); - 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(); - 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 - 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 - 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(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. */ @@ -1572,9 +1646,9 @@ class tree { } /** Reads the node `id` of `from` into the staged node `slot`, its children into new nodes. */ - result read_copy(change& c, std::size_t slot, const tree* from, std::uint64_t id, + result 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 || @@ -1608,8 +1682,8 @@ class tree { value of this tree, or a key or text a caller read from it. */ void own_views(change& c) const { - const std::byte* first = region_->data(); - const std::byte* last = first + region_->size(); + const std::byte* first = storage().data(); + const std::byte* last = first + storage().size(); const std::less<> before; const auto own = [&](std::span& view) { if (view.empty() || !before(view.data(), last) || @@ -1647,15 +1721,15 @@ class tree { } } bool owned = false; - while (!probe(heap_of(*region_), sizes)) { - if (!region_->is_owned()) { + while (!probe(heap_of(storage()), sizes)) { + if (!storage().is_owned()) { return errc::capacity; } if (!owned) { own_views(c); owned = true; } - if (!region_->grow(grown_size(*region_, total))) { + if (!storage().grow(grown_size(storage(), total))) { return errc::capacity; } sync_header(c.next_id); @@ -1683,7 +1757,7 @@ class tree { if (const auto room = find_room(c); !room.has_value()) { return room; } - heap& h = heap_of(*region_); + heap& h = heap_of(storage()); std::vector> made(c.nodes.size()); for (std::size_t i = 0; i < c.nodes.size(); ++i) { if (!c.nodes[i].existing) { @@ -1736,7 +1810,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. */ @@ -1774,7 +1848,7 @@ class tree { } } auto& ids = nodes.template get(); - heap& h = heap_of(*region_); + heap& h = heap_of(storage()); for (const std::uint64_t victim : std::views::reverse(subtree)) { const auto found = ids.find(victim); byte_string key = found->key; @@ -1792,7 +1866,7 @@ class tree { result append(std::uint64_t array, std::uint64_t length, std::uint64_t fill, const item* 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) { + if (fill >= storage().max_bytes() / node_probe_bytes) { return errc::capacity; } change c = start_change(); @@ -1811,8 +1885,6 @@ class tree { 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..5007bff 100644 --- a/include/webcpp/document/detail/value_array.hpp +++ b/include/webcpp/document/detail/value_array.hpp @@ -66,8 +66,8 @@ constexpr std::uint64_t splice_count(std::int64_t count, std::uint64_t start, /** The tree and node a copy source reads. */ template struct source_read { - /** The tree. */ - const tree* from = nullptr; + /** The tree, of a document of any allocator. */ + const tree_view* from = nullptr; /** The node, or null when the source reads `undefined`. */ const node* n = nullptr; @@ -76,7 +76,7 @@ struct source_read { /** Where a document's value is read: its tree and its root; @ref errc::type when moved from. */ template result> read_source(const basic_document& d) noexcept { - const tree* t = access::tree_of(d); + const tree_view* t = access::tree_of(d); if (t == nullptr) { return errc::type; } @@ -131,10 +131,11 @@ result prepare_elements(std::array, sizeof...(T)>& held, return {}; } -/** A new owned document whose value is `v`, read before the call returns. */ -template -result> owned_holding(const item& v) noexcept { - auto made = basic_document::create(); +/** A new owned document in `alloc` whose value is `v`, read before the call returns. */ +template +result>> owned_holding( + const item& v, const Allocator& alloc) noexcept { + auto made = basic_document>::create(alloc); if (!made.has_value()) { return made.error(); } @@ -159,9 +160,9 @@ item array_of(std::span> entries) noexcept { // NOLINTBEGIN(bugprone-exception-escape) /** Appends to `out` an entry copying each of the `n` elements of `array` in `from`, from `at`. */ -template -void copy_elements(const tree& from, std::uint64_t array, std::uint64_t at, std::uint64_t n, - std::vector>& out) { +template +void copy_elements(const tree_view& from, std::uint64_t array, std::uint64_t at, + std::uint64_t n, Entries& out) { const node* 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& entry = out.emplace_back(); @@ -177,12 +178,11 @@ void copy_elements(const tree& 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 -result> splice_elements(tree& t, std::uint64_t array, - std::uint64_t at, std::uint64_t n, - std::span> items, - bool single) noexcept { - result> removed = errc::type; +template +result>> splice_elements( + tree& t, std::uint64_t array, std::uint64_t at, std::uint64_t n, + std::span> items, bool single) noexcept { + result>> removed = errc::type; if (single) { // With nothing to remove, it holds undefined, which JavaScript's pop of [] returns. item one = empty_item(webcpp::document::kind::undefined); @@ -190,12 +190,12 @@ result> splice_elements(tree& 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> entries; entries.reserve(static_cast(n)); - copy_elements(t, array, at, n, entries); - removed = owned_holding(array_of(entries)); + copy_elements(t, array, at, n, entries); + removed = owned_holding(array_of(entries), t.get_allocator()); } if (!removed.has_value()) { return removed; @@ -214,8 +214,8 @@ template class concatenation { public: /** Appends a copy of each element of `array` in `from`. */ - void add_elements(const tree& from, std::uint64_t array) { - copy_elements(from, array, 0, from.count(array), entries_); + void add_elements(const tree_view& from, std::uint64_t array) { + copy_elements(from, array, 0, from.count(array), entries_); } /** Appends an argument: an array's elements, spread, or the value. */ @@ -328,28 +328,28 @@ basic_value basic_value::at(std::int64_t index // NOLINTBEGIN(bugprone-exception-escape) template -result> basic_const_value::slice( +result>> basic_const_value::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& 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> entries; if (last > first) { entries.reserve(static_cast(last - first)); - detail::copy_elements(t, id, first, last - first, entries); + detail::copy_elements(t, id, first, last - first, entries); } - return detail::owned_holding(detail::array_of(entries)); + return detail::owned_holding(detail::array_of(entries), t.get_allocator()); } template template -result> basic_const_value::concat( - const T&... v) const noexcept +result>> +basic_const_value::concat(const T&... v) const noexcept requires(detail::settable && ...) { const std::uint64_t id = id_of(webcpp::document::kind::array); @@ -366,7 +366,8 @@ result> basic_const_value::concat return added.error(); } } - return detail::owned_holding(detail::array_of(c.entries())); + return detail::owned_holding(detail::array_of(c.entries()), + tree_ptr()->get_allocator()); } // NOLINTEND(bugprone-exception-escape) @@ -387,7 +388,7 @@ result basic_value::push(const T&... v) noexcept !made.has_value()) { return made.error(); } - detail::tree* t = writable_tree(); + auto* t = writable_tree(); if (const auto done = t->insert_elements(id, t->count(id), items); !done.has_value()) { return done.error(); } @@ -395,24 +396,26 @@ result basic_value::push(const T&... v) noexcept } template -result> basic_value::pop() noexcept { +result>> +basic_value::pop() noexcept { const std::uint64_t id = this->id_of(webcpp::document::kind::array); if (id == 0) { return errc::type; } - detail::tree* t = writable_tree(); + auto* t = writable_tree(); const std::uint64_t length = t->count(id); return detail::splice_elements(*t, id, length == 0 ? 0 : length - 1, length == 0 ? 0 : 1, {}, true); } template -result> basic_value::shift() noexcept { +result>> +basic_value::shift() noexcept { const std::uint64_t id = this->id_of(webcpp::document::kind::array); if (id == 0) { return errc::type; } - detail::tree* t = writable_tree(); + auto* t = writable_tree(); return detail::splice_elements(*t, id, 0, t->count(id) == 0 ? 0 : 1, {}, true); } @@ -432,7 +435,7 @@ result basic_value::unshift(const T&... v) noexc !made.has_value()) { return made.error(); } - detail::tree* t = writable_tree(); + auto* t = writable_tree(); if (const auto done = t->insert_elements(id, 0, items); !done.has_value()) { return done.error(); } @@ -441,9 +444,8 @@ result basic_value::unshift(const T&... v) noexc template template -result> basic_value::splice(std::int64_t start, - std::int64_t count, - const T&... v) noexcept +result>> basic_value::splice( + std::int64_t start, std::int64_t count, const T&... v) noexcept requires(detail::settable && ...) { const std::uint64_t id = this->id_of(webcpp::document::kind::array); @@ -457,7 +459,7 @@ result> basic_value::splice(std:: !made.has_value()) { return made.error(); } - detail::tree* 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(*t, id, at, detail::splice_count(count, at, length), @@ -465,13 +467,13 @@ result> basic_value::splice(std:: } template -result> basic_value::splice( +result>> basic_value::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* 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(*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 #include +#include #include #include #include @@ -49,13 +50,26 @@ T value_or_raise(result&& made) { template basic_document::basic_document() - requires detail::exceptions_enabled && std::same_as + requires detail::exceptions_enabled && detail::owned_storage : basic_document(detail::value_or_raise(create())) {} +template +basic_document::basic_document(const allocator_type& alloc) + requires detail::exceptions_enabled && detail::owned_storage + : basic_document(detail::value_or_raise(create(alloc))) {} + template basic_document::basic_document(const basic_document& other) - requires detail::exceptions_enabled && std::same_as - : basic_document(detail::value_or_raise(other.clone())) {} + requires detail::exceptions_enabled && detail::owned_storage + : basic_document(detail::value_or_raise( + other.clone(std::allocator_traits::select_on_container_copy_construction( + other.get_allocator())))) {} + +template +basic_document::basic_document(const basic_document& other, + const allocator_type& alloc) + requires detail::exceptions_enabled && detail::owned_storage + : basic_document(detail::value_or_raise(other.clone(alloc))) {} template template diff --git a/include/webcpp/document/detail/writer.hpp b/include/webcpp/document/detail/writer.hpp index 495ab4b..0cc85f2 100644 --- a/include/webcpp/document/detail/writer.hpp +++ b/include/webcpp/document/detail/writer.hpp @@ -147,7 +147,7 @@ template class json_writer { public: /** A walk of `t` writing to `out` with `indent` spaces a level, already clamped. */ - json_writer(const tree& t, std::uint32_t indent, Out& out) noexcept + json_writer(const tree_view& t, std::uint32_t indent, Out& out) noexcept : tree_(&t), indent_(indent), out_(&out) {} /** @@ -371,7 +371,7 @@ class json_writer { status_ = out_->put(text); } - const tree* tree_; + const tree_view* tree_; std::uint32_t indent_; Out* out_; std::vector stack_; @@ -384,7 +384,7 @@ class json_writer { */ template requires output -result write_json(const tree& t, const node* root, std::uint32_t indent, +result write_json(const tree_view& t, const node* root, std::uint32_t indent, Out& out) { if (root == nullptr || root->kind == webcpp::document::kind::undefined) { return {}; diff --git a/include/webcpp/document/document.hpp b/include/webcpp/document/document.hpp index 73d27b9..50bcf19 100644 --- a/include/webcpp/document/document.hpp +++ b/include/webcpp/document/document.hpp @@ -20,35 +20,24 @@ #include #include #include +#include #include +#include + #include #include #include #include #include +#include +#include #include #include #include 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 result> format(std::span 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 +result>> format(std::span buffer, + const Allocator& alloc) noexcept; + /** Opens the image already in a buffer, in place. @@ -83,6 +88,22 @@ template result> open(std::span 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 +result>> open( + std::span buffer, const Allocator& alloc, verify check = verify::seal) noexcept; + /** Copies an image into a new owned document. @@ -102,6 +123,24 @@ result> from_image(std::span 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 +result>> from_image( + std::span 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,34 +149,63 @@ result> from_image(std::span 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 basic_document { static_assert(document_traits, "the traits do not satisfy document_traits"); - static_assert(std::same_as || std::same_as, - "a document's storage is owned or external"); + static_assert(detail::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 = typename 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 create(std::uint64_t max_bytes = default_max_bytes) noexcept - requires std::same_as + requires detail::owned_storage + { + 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 create(const allocator_type& alloc, + std::uint64_t max_bytes = default_max_bytes) noexcept + requires detail::owned_storage { - auto made = detail::region::owned(std::min(first_bytes, max_bytes / 16 * 16), max_bytes); + 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::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())); @@ -151,20 +219,45 @@ class basic_document { @see "The sugar that throws", in the guide. */ basic_document() - requires detail::exceptions_enabled && std::same_as; + requires detail::exceptions_enabled && detail::owned_storage; /** - Copies a document's image into a new owned document, as @ref clone does, throwing on failure; - only with exceptions. + 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 && detail::owned_storage; + + /** + 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 && std::same_as; + requires detail::exceptions_enabled && detail::owned_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 && detail::owned_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 +267,33 @@ 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, 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_); + basic_document& operator=(basic_document&& other) noexcept(moves_cheaply) { + if (this == &other) { + return *this; + } + if constexpr (!moves_cheaply && detail::owned_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 +304,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 +320,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> clone() const noexcept { + [[nodiscard]] result>> 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>> 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 - ? region_.max_bytes() - : std::max(default_max_bytes, region_.size()); - return from_image(image(), limit, verify::none); + return from_image(image(), alloc, copy_limit(), verify::none); } /** @@ -316,7 +444,7 @@ class basic_document { @return Success; @ref errc::capacity when the smaller buffer cannot be allocated. */ result shrink_to_fit() noexcept - requires std::same_as + requires detail::owned_storage { return tree_.shrink_to_fit(); } @@ -338,17 +466,17 @@ class basic_document { @see "Images", in the guide. */ result compact() noexcept - requires std::same_as + requires detail::owned_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::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 +494,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> compact_into( + [[nodiscard]] result>> compact_into( std::span buffer) const noexcept; /** @@ -453,21 +582,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; + + /** The tree of the storage's allocator. */ + using tree_type = detail::tree; + + /** The allocator's traits. */ + using alloc_traits = std::allocator_traits; + + /** + 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_); + } + + /** 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 ? 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()); } - detail::region region_; - detail::tree tree_; + 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 +using basic_document = webcpp::document::basic_document; + +/** + 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 +670,7 @@ namespace detail { `value.hpp` defines after this header: `Access` defers its lookup to where a call is instantiated. */ template -basic_document adopt(region r) noexcept { +basic_document adopt(basic_region r) noexcept { return Access::template make_document(std::move(r)); } @@ -483,19 +678,32 @@ basic_document adopt(region r) noexcept { template result> format(std::span buffer) noexcept { - auto made = detail::region::external_empty(buffer); + return format(buffer, std::allocator()); +} + +template +result>> format(std::span buffer, + const Allocator& alloc) noexcept { + auto made = detail::basic_region::external_empty(buffer, alloc); if (!made.has_value()) { return made.error(); } - if (const auto formatted = detail::tree::format(made.unsafe_value()); + if (const auto formatted = detail::tree::format(made.unsafe_value()); !formatted.has_value()) { return formatted.error(); } - return detail::adopt(std::move(made.unsafe_value())); + return detail::adopt>(std::move(made.unsafe_value())); } template result> open(std::span buffer, verify check) noexcept { + return open(buffer, std::allocator(), check); +} + +template +result>> open(std::span buffer, + const Allocator& alloc, + verify check) noexcept { if (reinterpret_cast(buffer.data()) % 16 != 0) { return errc::not_a_document; } @@ -506,38 +714,46 @@ result> open(std::span 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(header.size))); - if (const auto attached = detail::tree::attach(r); !attached.has_value()) { + auto r = detail::basic_region::external( + buffer.first(static_cast(header.size)), alloc); + if (const auto attached = detail::tree::attach(r); !attached.has_value()) { return attached.error(); } - return detail::adopt(std::move(r)); + return detail::adopt>(std::move(r)); } template result> from_image(std::span bytes, std::uint64_t max_bytes, verify check) noexcept { + return from_image(bytes, std::allocator(), max_bytes, check); +} + +template +result>> from_image(std::span bytes, + const Allocator& alloc, + std::uint64_t max_bytes, + verify check) noexcept { if (const auto checked = check_image(bytes, detail::layout_tag(), 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(header.size)), max_bytes); + auto made = detail::basic_region::owned_copy( + bytes.first(static_cast(header.size)), max_bytes, alloc); if (!made.has_value()) { return made.error(); } - if (const auto attached = detail::tree::attach(made.unsafe_value()); + if (const auto attached = detail::tree::attach(made.unsafe_value()); !attached.has_value()) { return attached.error(); } - return detail::adopt(std::move(made.unsafe_value())); + return detail::adopt>(std::move(made.unsafe_value())); } template -result> basic_document::compact_into( - std::span buffer) const noexcept { +result>> +basic_document::compact_into(std::span buffer) const noexcept { if (region_.data() == nullptr) { return errc::type; } @@ -550,16 +766,17 @@ result> basic_document::compac if (bytes > buffer.size()) { return errc::capacity; } - auto made = detail::region::external_empty(buffer.first(static_cast(bytes))); + auto made = region_type::external_empty(buffer.first(static_cast(bytes)), + region_.get_allocator()); if (!made.has_value()) { return made.error(); } - if (const auto built = detail::tree::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(bytes)); - return detail::adopt(std::move(made.unsafe_value())); + return detail::adopt>(std::move(made.unsafe_value())); } } // namespace webcpp::document diff --git a/include/webcpp/document/parse.hpp b/include/webcpp/document/parse.hpp index 061ab54..05daaf1 100644 --- a/include/webcpp/document/parse.hpp +++ b/include/webcpp/document/parse.hpp @@ -86,6 +86,35 @@ result> parse(std::string_view text, return p.finish(); } +/** + `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. + + @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 +// 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. +// NOLINTNEXTLINE(bugprone-exception-escape) +result>> parse(std::string_view text, + const parse_options& o, + const Allocator& alloc) noexcept { + basic_parser> p(o, alloc); + if (const result written = p.write(text); !written.has_value()) { + return written.error(); + } + return p.finish(); +} + /** Reads JSON text into a new document in a buffer its user owns, as @ref parse does. @@ -109,6 +138,33 @@ result> parse_into(std::span buffer, return p.finish(); } +/** + 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`. + + @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. + @see "Allocators", in the guide. +*/ +template +// 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. +// NOLINTNEXTLINE(bugprone-exception-escape) +result>> parse_into( + std::span buffer, std::string_view text, const parse_options& o, + const Allocator& alloc) noexcept { + basic_parser> p(buffer, o, alloc); + if (const result written = p.write(text); !written.has_value()) { + return written.error(); + } + return p.finish(); +} + /** `JSON.parse(text)`, throwing on failure as JavaScript does; only with exceptions. diff --git a/include/webcpp/document/parser.hpp b/include/webcpp/document/parser.hpp index ee25035..396131d 100644 --- a/include/webcpp/document/parser.hpp +++ b/include/webcpp/document/parser.hpp @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -176,24 +177,31 @@ struct subscription { template class basic_parser { public: + /** The allocator of the document and of the parser's working state. */ + using allocator_type = typename 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 - : options_(o), json_(json_options(o), *this) {} + explicit basic_parser(const parse_options& o = {}, + const allocator_type& alloc = allocator_type()) noexcept + requires detail::owned_storage + : options_(o), alloc_(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 buffer, const parse_options& o = {}) noexcept - requires std::same_as - : options_(o), buffer_(buffer), json_(json_options(o), *this) {} + explicit basic_parser(std::span buffer, const parse_options& o = {}, + const allocator_type& alloc = allocator_type()) noexcept + requires detail::external_storage + : options_(o), alloc_(alloc), buffer_(buffer), json_(json_options(o), *this) {} /** A parser is not copied: its handler and its document refer to it. */ basic_parser(const basic_parser&) = delete; @@ -469,6 +477,7 @@ class basic_parser { } parse_options options_; + BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS allocator_type alloc_; std::span buffer_; std::optional> document_; std::vector> subscriptions_; @@ -486,6 +495,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; + +} // namespace pmr + } // namespace webcpp::document #include diff --git a/include/webcpp/document/storage.hpp b/include/webcpp/document/storage.hpp new file mode 100644 index 0000000..d14c4d7 --- /dev/null +++ b/include/webcpp/document/storage.hpp @@ -0,0 +1,154 @@ +// 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 + +#include +#include +#include +#include + +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 + parser's, the tree's and the writer's working state. 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. + + @tparam Allocator An allocator of `std::byte`; `std::allocator` by default, whose + documents are those of @ref owned. + @see "Images", in the guide. + @see "Allocators", in the guide. +*/ +template > +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: + the parser's, the tree's and the writer's. + + @tparam Allocator An allocator of `std::byte`; `std::allocator` by default, whose + documents are those of @ref external. + @see "Images", in the guide. + @see "Allocators", in the guide. +*/ +template > +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>; + +/** + 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>; + +} // 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 +concept byte_allocator = + requires { typename A::value_type; } && std::same_as && + requires(A& a, std::size_t n) { a.allocate(n); } && std::copy_constructible && + std::equality_comparable; + +/** Whether `S` is @ref basic_owned of an allocator. */ +template +inline constexpr bool is_owned = false; + +/** Whether `S` is @ref basic_owned of an allocator: it is. */ +template +inline constexpr bool is_owned> = true; + +/** Whether `S` is @ref basic_external of an allocator. */ +template +inline constexpr bool is_external = false; + +/** Whether `S` is @ref basic_external of an allocator: it is. */ +template +inline constexpr bool is_external> = true; + +/** A storage that owns its image: @ref basic_owned of an allocator of `std::byte`. */ +template +concept owned_storage = is_owned && byte_allocator; + +/** A storage over a buffer its user owns: @ref basic_external of an allocator of `std::byte`. */ +template +concept external_storage = is_external && byte_allocator; + +/** A document's storage, owned or external. */ +template +concept storage = owned_storage || external_storage; + +/** + 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 +using owned_of = basic_owned; + +/** The allocator `A` gives for objects of `T`. */ +template +using rebound = typename std::allocator_traits::template rebind_alloc; + +} // 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..4421c4f 100644 --- a/include/webcpp/document/stringify.hpp +++ b/include/webcpp/document/stringify.hpp @@ -49,7 +49,7 @@ inline constexpr std::uint64_t default_chunk = 4096; template std::string stringify(basic_const_value v, std::uint32_t indent = 0) { std::string text; - const detail::tree* t = detail::access::tree_of(v); + const detail::tree_view* t = detail::access::tree_of(v); if (t == nullptr) { return text; } @@ -95,7 +95,7 @@ template requires detail::sink> result stringify_to(basic_const_value v, Sink&& sink, std::uint32_t indent = 0, std::uint64_t chunk = default_chunk) { - const detail::tree* t = detail::access::tree_of(v); + const detail::tree_view* t = detail::access::tree_of(v); if (t == nullptr) { return {}; } diff --git a/include/webcpp/document/value.hpp b/include/webcpp/document/value.hpp index 1036343..9a437d2 100644 --- a/include/webcpp/document/value.hpp +++ b/include/webcpp/document/value.hpp @@ -195,19 +195,22 @@ class WEBCPP_DOCUMENT_NO_DANGLING children { struct access { /** The tree of a document, or null when it was moved from. */ template - static tree* tree_of(basic_document& d) noexcept { + static tree* tree_of( + basic_document& d) noexcept { return d.region_.data() == nullptr ? nullptr : &d.tree_; } /** The tree of a document, or null when it was moved from. */ template - static const tree* tree_of(const basic_document& d) noexcept { + static const tree* tree_of( + const basic_document& d) noexcept { return d.region_.data() == nullptr ? nullptr : &d.tree_; } /** The tree of a handle's document, or null when it names nothing. */ template - static const tree* tree_of(const basic_const_value& v) noexcept { + static const tree* tree_of( + const basic_const_value& v) noexcept { return v.tree_ptr(); } @@ -232,7 +235,8 @@ struct access { /** The document of a region whose tree was formatted or attached, the tree rebound to it. */ template - static basic_document make_document(region r) noexcept { + static basic_document make_document( + basic_region r) noexcept { return basic_document(std::move(r)); } }; @@ -382,7 +386,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { [[nodiscard]] result get() const noexcept requires detail::readable { - const detail::tree* t = tree_ptr(); + const auto* t = tree_ptr(); if (t == nullptr) { return errc::type; } @@ -562,7 +566,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> slice( + [[nodiscard]] result>> slice( std::int64_t start = 0, std::int64_t stop = std::numeric_limits::max()) const noexcept; @@ -575,7 +579,8 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { @ref errc::capacity when it does not fit. */ template - [[nodiscard]] result> concat(const T&... v) const noexcept + [[nodiscard]] result>> concat( + const T&... v) const noexcept requires(detail::settable && ...); /** @@ -656,13 +661,14 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { // NOLINTEND(bugprone-exception-escape) /** The tree of the handle's document, or null when it names nothing or the document none. */ - [[nodiscard]] const detail::tree* tree_ptr() const noexcept { + [[nodiscard]] const detail::tree* 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* resolve() const noexcept { - const detail::tree* t = tree_ptr(); + const auto* t = tree_ptr(); if (t == nullptr) { return nullptr; } @@ -933,7 +939,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_valuekind != webcpp::document::kind::object) { return errc::type; } - const detail::tree& from = *source.tree_ptr(); + const detail::tree_view& 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 keys; @@ -972,7 +978,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value> pop() noexcept; + [[nodiscard]] result>> pop() noexcept; /** `Array.prototype.shift`: removes the first element. @@ -980,7 +986,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value> shift() noexcept; + [[nodiscard]] result>> shift() noexcept; /** `Array.prototype.unshift`: inserts each value at the front, in order. @@ -1009,9 +1015,8 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value - [[nodiscard]] result> splice(std::int64_t start, - std::int64_t count, - const T&... v) noexcept + [[nodiscard]] result>> splice( + std::int64_t start, std::int64_t count, const T&... v) noexcept requires(detail::settable && ...); /** @@ -1021,7 +1026,8 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value> splice(std::int64_t start) noexcept; + [[nodiscard]] result>> splice( + std::int64_t start) noexcept; /** `Array.prototype.reverse`: reverses the elements in place. @@ -1081,15 +1087,16 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value(doc, where, id, index, key) {} /** The tree of the handle's document, to write; null when it names nothing. */ - [[nodiscard]] detail::tree* writable_tree() const noexcept { + [[nodiscard]] detail::tree* 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 - static result*, const detail::node*>> copy_from( - const basic_document& d) noexcept { - const detail::tree* t = detail::access::tree_of(d); + static result*, const detail::node*>> + copy_from(const basic_document& d) noexcept { + const detail::tree_view* t = detail::access::tree_of(d); if (t == nullptr) { return errc::type; } @@ -1098,8 +1105,8 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value - static result*, const detail::node*>> copy_from( - const basic_const_value& v) noexcept { + static result*, const detail::node*>> + copy_from(const basic_const_value& v) noexcept { return std::pair(detail::access::tree_of(v), detail::access::node_of(v)); } @@ -1117,7 +1124,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value store(const detail::item& v) noexcept { - detail::tree* t = writable_tree(); + auto* t = writable_tree(); if (t == nullptr) { return errc::type; } @@ -1144,7 +1151,7 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value store_undefined() noexcept { - detail::tree* t = writable_tree(); + auto* t = writable_tree(); if (t == nullptr) { return errc::type; } @@ -1190,6 +1197,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; + +/** + A handle of a `pmr::document`, read only. + + @see "Allocators", in the guide. +*/ +using const_value = webcpp::document::basic_const_value; + +} // namespace pmr + // The members below make handles, which are complete only here. template @@ -1239,7 +1264,8 @@ auto children_iterator::operator*() const noexcept -> val return basic_const_value(doc_, place::node, child_, 0, {}); } else { // A key is a view of the image, valid until the document's next change. - 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(child_); text_view_t key; if (n != nullptr) { @@ -1263,7 +1289,7 @@ auto children_iterator::operator*() const noexcept -> val template children_iterator& children_iterator::operator++() 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(child_); const node* next = n == nullptr ? nullptr : t->next_sibling(*n); child_ = next == nullptr ? 0 : next->id; @@ -1273,7 +1299,7 @@ children_iterator::operator++() noexcept { template children_iterator children::begin() const noexcept { // The root's parent is 0: the children of 0 are those of nothing, not the root. - const tree* t = + const tree_view* t = doc_ == nullptr || parent_ == 0 ? nullptr : access::tree_of(std::as_const(*doc_)); const node* first = t == nullptr ? nullptr : t->first_child(parent_); return {doc_, first == nullptr ? 0 : first->id}; diff --git a/test/Jamfile b/test/Jamfile index e910bc7..b51c417 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -126,6 +126,12 @@ webcpp.run shared : shared_test.cpp ; webcpp.run shared_interprocess : shared_test.cpp : on 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 ; + # 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_test.cpp b/test/allocator_test.cpp new file mode 100644 index 0000000..04ba9ca --- /dev/null +++ b/test/allocator_test.cpp @@ -0,0 +1,349 @@ +// 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 + +#include + +#include "counting.hpp" +#include "require.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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 convert an allocator to its rebound type implicitly. + /** The same allocator for another type. */ + template + tallying_allocator( + const tallying_allocator& other) noexcept // NOLINT(misc-explicit-constructor) + : counts_(other.counts()) {} + + /** Room for `n` objects of `T`, aligned for `T`. */ + T* allocate(std::size_t n) { + ++counts_->allocations; + return static_cast(::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 + friend bool operator==(const tallying_allocator& a, const tallying_allocator& b) noexcept { + return a.counts_ == b.counts(); + } + +private: + allocator_counts* counts_; +}; + +/** The bytes of `d`'s image, copied. */ +template +std::vector bytes_of(const Document& d) { + const std::span image = d.image(); + return {image.begin(), image.end()}; +} + +/** Whether two documents' images are the same bytes; it allocates nothing. */ +template +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; + 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 buffer{}; + alignas(16) std::array 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 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>; + using document = wd::basic_document; + const tallying_allocator 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); +} + +#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())); + const wd::pmr::document copied(*made); + 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 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)); +} + +#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(); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + copies_select_allocator(); + full_allocator_is_capacity(); +#endif + return boost::report_errors(); +} diff --git a/test/counting.cpp b/test/counting.cpp new file mode 100644 index 0000000..6a1c133 --- /dev/null +++ b/test/counting.cpp @@ -0,0 +1,186 @@ +// 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. + +#include "counting.hpp" + +#include + +#include +#include +#include +#include + +#ifdef _MSC_VER +#include +#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. +void* aligned_memory(std::size_t size, std::align_val_t alignment) noexcept { + ++news; + const auto align = static_cast(alignment); + 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; +} + +} // namespace + +namespace webcpp::test { + +std::uint64_t global_news() noexcept { + return news; +} + +std::uint64_t global_deletes() noexcept { + return deletes; +} + +} // 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..34a985f --- /dev/null +++ b/test/counting.hpp @@ -0,0 +1,135 @@ +// 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, 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 +#include +#include +#include + +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_; +}; + +/** 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. */ + [[nodiscard]] std::uint64_t allocations() const noexcept { return allocations_; } + + /** The deallocations it made. */ + [[nodiscard]] std::uint64_t deallocations() const noexcept { return deallocations_; } + + /** The bytes handed out and not yet taken 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); + ++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 { + ++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 in_use_ = 0; + std::size_t largest_alignment_ = 0; +}; + +/** + 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_(std::make_unique(bytes)), + monotonic_(buffer_.get(), bytes, 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 allocator() noexcept { + return std::pmr::polymorphic_allocator(&counted_); + } + +private: + std::unique_ptr buffer_; + std::pmr::monotonic_buffer_resource monotonic_; + counting_resource counted_; +}; + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_DOCUMENT_COUNTING_HPP From 6408ab4b1e78b1dd846aba019a0d684aa18bdecd Mon Sep 17 00:00:00 2001 From: R Date: Sat, 14 Nov 2026 22:49:42 -0300 Subject: [PATCH 05/23] document: the allocation tests' places, a failing resource, and member_stored Four test programs, empty yet, for the working state of the tree, the handles, the parser and the writer in a document's allocator; a resource that fails from a chosen allocation on; and tree_view::member_stored, a lookup by a key in the stored encoding, which transcodes nothing. --- include/webcpp/document/detail/tree.hpp | 14 +++++++ test/Jamfile | 9 +++++ test/allocator_parse_test.cpp | 18 +++++++++ test/allocator_stringify_test.cpp | 18 +++++++++ test/allocator_tree_test.cpp | 18 +++++++++ test/allocator_values_test.cpp | 18 +++++++++ test/counting.hpp | 50 +++++++++++++++++++++++++ 7 files changed, 145 insertions(+) create mode 100644 test/allocator_parse_test.cpp create mode 100644 test/allocator_stringify_test.cpp create mode 100644 test/allocator_tree_test.cpp create mode 100644 test/allocator_values_test.cpp diff --git a/include/webcpp/document/detail/tree.hpp b/include/webcpp/document/detail/tree.hpp index 208ec23..e945ea7 100644 --- a/include/webcpp/document/detail/tree.hpp +++ b/include/webcpp/document/detail/tree.hpp @@ -469,6 +469,19 @@ class tree_view { // 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* 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* element(std::uint64_t array, std::uint64_t index) const noexcept { @@ -805,6 +818,7 @@ class tree : public tree_view { using view::find; using view::first_child; using view::member; + using view::member_stored; using view::next_sibling; // An operation ends the program where the process heap, which holds what it stages, runs diff --git a/test/Jamfile b/test/Jamfile index b51c417..1eefa98 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -131,6 +131,15 @@ webcpp.run shared_interprocess : shared_test.cpp # 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. +webcpp.run allocator_tree : allocator_tree_test.cpp counting.cpp ; +webcpp.run allocator_values : allocator_values_test.cpp counting.cpp ; +webcpp.run allocator_parse : allocator_parse_test.cpp counting.cpp + : emscripten:-sALLOW_MEMORY_GROWTH ; +webcpp.run allocator_stringify : allocator_stringify_test.cpp counting.cpp + : emscripten:-sALLOW_MEMORY_GROWTH ; # Compact images: equal content gives equal bytes, the exact size, a caller's # buffer. diff --git a/test/allocator_parse_test.cpp b/test/allocator_parse_test.cpp new file mode 100644 index 0000000..fb37c97 --- /dev/null +++ b/test/allocator_parse_test.cpp @@ -0,0 +1,18 @@ +// 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: to be written. + +#include + +#include + +#include "counting.hpp" +#include "require.hpp" + +int main() { + return boost::report_errors(); +} diff --git a/test/allocator_stringify_test.cpp b/test/allocator_stringify_test.cpp new file mode 100644 index 0000000..2530fd6 --- /dev/null +++ b/test/allocator_stringify_test.cpp @@ -0,0 +1,18 @@ +// 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 in the document's allocator: to be written. + +#include + +#include + +#include "counting.hpp" +#include "require.hpp" + +int main() { + return boost::report_errors(); +} diff --git a/test/allocator_tree_test.cpp b/test/allocator_tree_test.cpp new file mode 100644 index 0000000..74e1be8 --- /dev/null +++ b/test/allocator_tree_test.cpp @@ -0,0 +1,18 @@ +// 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: to be written. + +#include + +#include + +#include "counting.hpp" +#include "require.hpp" + +int main() { + return boost::report_errors(); +} diff --git a/test/allocator_values_test.cpp b/test/allocator_values_test.cpp new file mode 100644 index 0000000..dea05c4 --- /dev/null +++ b/test/allocator_values_test.cpp @@ -0,0 +1,18 @@ +// 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: to be written. + +#include + +#include + +#include "counting.hpp" +#include "require.hpp" + +int main() { + return boost::report_errors(); +} diff --git a/test/counting.hpp b/test/counting.hpp index 34a985f..ba93073 100644 --- a/test/counting.hpp +++ b/test/counting.hpp @@ -13,10 +13,13 @@ #ifndef WEBCPP_TEST_DOCUMENT_COUNTING_HPP #define WEBCPP_TEST_DOCUMENT_COUNTING_HPP +#include + #include #include #include #include +#include namespace webcpp::test { @@ -88,6 +91,53 @@ class counting_resource final : public std::pmr::memory_resource { 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 `std::bad_alloc`, through `boost::throw_exception`: an allocator that runs out + at a chosen step of an operation, for tests built with exceptions. +*/ +class failing_resource final : public std::pmr::memory_resource { +public: + /** A resource over `upstream`, which outlives it, that allows `budget` allocations. */ + 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 (budget_ == 0) { + ++refusals_; + boost::throw_exception(std::bad_alloc()); + } + --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 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 From cf0da8b1f3c35ad6d643188b18159ef29948bfce Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:09:38 -0300 Subject: [PATCH 06/23] document: nothing, a document that holds nothing and allocates nothing basic_document::nothing(alloc) is the state a moved-from document is in, named: 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, so that a library can hand one out where it has no document to give, without exceptions too. Also clean what clang-tidy reported in the storage, the region and the move assignment, and in the counting tests' arena. --- include/webcpp/document/detail/heap.hpp | 12 ++++++-- include/webcpp/document/document.hpp | 20 ++++++++++++- include/webcpp/document/storage.hpp | 2 +- test/allocator_test.cpp | 38 +++++++++++++++++++++---- test/counting.hpp | 9 +++--- 5 files changed, 67 insertions(+), 14 deletions(-) diff --git a/include/webcpp/document/detail/heap.hpp b/include/webcpp/document/detail/heap.hpp index 4095263..0631233 100644 --- a/include/webcpp/document/detail/heap.hpp +++ b/include/webcpp/document/detail/heap.hpp @@ -337,6 +337,9 @@ struct alignas(16) image_block { std::array bytes; }; +template +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. @@ -376,6 +379,10 @@ class region_bytes { owned_ = std::exchange(other.owned_, false); } +private: + template + friend class basic_region; + /** The first byte, or null. */ std::byte* data_ = nullptr; @@ -566,8 +573,7 @@ class basic_region : public region_bytes { private: /** The allocator of the image's blocks. */ - using block_allocator = - typename std::allocator_traits::template rebind_alloc; + using block_allocator = std::allocator_traits::template rebind_alloc; /** Its traits. */ using block_traits = std::allocator_traits; @@ -626,7 +632,7 @@ class basic_region : public region_bytes { ::operator delete(bytes, std::align_val_t{16}); } else { block_allocator blocks(alloc_); - using pointer = typename block_traits::pointer; + using pointer = block_traits::pointer; block_traits::deallocate( blocks, std::pointer_traits::pointer_to(*reinterpret_cast(bytes)), diff --git a/include/webcpp/document/document.hpp b/include/webcpp/document/document.hpp index 50bcf19..3e09989 100644 --- a/include/webcpp/document/document.hpp +++ b/include/webcpp/document/document.hpp @@ -171,7 +171,7 @@ class basic_document { public: /** The allocator of the image, when owned, and of the working state of the operations. */ - using allocator_type = typename Storage::allocator_type; + using allocator_type = Storage::allocator_type; /** Makes a new owned document, holding `null`, in a default-constructed allocator. @@ -211,6 +211,21 @@ class basic_document { 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. @@ -282,6 +297,9 @@ class basic_document { `noexcept`. @see "Allocators", in the guide. */ + // It is noexcept only for allocators that propagate or are always equal, which never take + // the copy, the one path that throws. + // NOLINTNEXTLINE(bugprone-exception-escape) basic_document& operator=(basic_document&& other) noexcept(moves_cheaply) { if (this == &other) { return *this; diff --git a/include/webcpp/document/storage.hpp b/include/webcpp/document/storage.hpp index d14c4d7..12830fb 100644 --- a/include/webcpp/document/storage.hpp +++ b/include/webcpp/document/storage.hpp @@ -145,7 +145,7 @@ using owned_of = basic_owned; /** The allocator `A` gives for objects of `T`. */ template -using rebound = typename std::allocator_traits::template rebind_alloc; +using rebound = std::allocator_traits::template rebind_alloc; } // namespace detail diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 04ba9ca..8daeb0c 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -66,9 +66,8 @@ class tallying_allocator { // The Allocator requirements convert an allocator to its rebound type implicitly. /** The same allocator for another type. */ template - tallying_allocator( - const tallying_allocator& other) noexcept // NOLINT(misc-explicit-constructor) - : counts_(other.counts()) {} + // NOLINTNEXTLINE(misc-explicit-constructor) + tallying_allocator(const tallying_allocator& other) noexcept : counts_(other.counts()) {} /** Room for `n` objects of `T`, aligned for `T`. */ T* allocate(std::size_t n) { @@ -148,7 +147,7 @@ void image_in_resource() { void default_storage_unchanged() { { const global_count global; - auto made = wd::document::create(); + const auto made = wd::document::create(); require(BOOST_TEST(made.has_value())); BOOST_TEST_EQ(global.news(), 1U); } @@ -274,6 +273,32 @@ void any_allocator() { BOOST_TEST_EQ(counts.deallocations, 3U); } +// 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 +void holding_nothing() { + using document = wd::basic_document; + arena a(mebibyte); + const wd::document source = sample(); + 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); + BOOST_TEST(none.root().set(1).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) { + 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 @@ -284,7 +309,8 @@ void copies_select_allocator() { const wd::document source = sample(); auto made = wd::from_image(source.image(), a.allocator()); require(BOOST_TEST(made.has_value())); - const wd::pmr::document copied(*made); + // 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()); @@ -341,6 +367,8 @@ int main() { clone_into_resources(); external_carries_allocator(); any_allocator(); + holding_nothing(); + holding_nothing(); #ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS copies_select_allocator(); full_allocator_is_capacity(); diff --git a/test/counting.hpp b/test/counting.hpp index ba93073..3135a9c 100644 --- a/test/counting.hpp +++ b/test/counting.hpp @@ -20,6 +20,7 @@ #include #include #include +#include namespace webcpp::test { @@ -147,8 +148,8 @@ class arena { public: /** An arena of `bytes` bytes. */ explicit arena(std::size_t bytes) - : buffer_(std::make_unique(bytes)), - monotonic_(buffer_.get(), bytes, std::pmr::null_memory_resource()), + : 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. */ @@ -171,11 +172,11 @@ class arena { /** A polymorphic allocator of the counted resource. */ [[nodiscard]] std::pmr::polymorphic_allocator allocator() noexcept { - return std::pmr::polymorphic_allocator(&counted_); + return {&counted_}; } private: - std::unique_ptr buffer_; + std::vector buffer_; std::pmr::monotonic_buffer_resource monotonic_; counting_resource counted_; }; From 9715657818e99bc32884749047c74e26e9290d78 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:37:50 -0300 Subject: [PATCH 07/23] document: every operation's working state in the document's allocator The document's allocator, rebound, now holds all that an operation needs while it runs, for owned and external documents alike, and nothing of it reaches the global operator new: - the tree stages a change's nodes, values, probe sizes and doomed roots in it, transcodes a new UTF-16 key straight into its block of the image, and sorts a literal's repeated keys in it; a lookup by a UTF-8 key compares it with stored UTF-16 keys unit by unit, and an erasure lists its subtree through the erased nodes' own scalars, so neither allocates nor fails; erase_member_by_id erases a member by its node; compaction's stack; - a handle of a missing member holds its key there, copies included; a value is prepared there; Object.assign's keys, the array methods' entries and the containers' views likewise; == walks both trees with no stack at all; - the parser's frames, path, keys, pending text, selectors and callbacks, which a type-erased delivery in the allocator holds instead of std::function; finish(last) gives Boost.JSON the last chunk with more=false, so that parse, parse_into and a whole text given to finish never suspend and never allocate Boost.JSON's stack, the one allocation a parse in chunks still makes in the global heap; - the writer's stack and the piece stringify_to holds back for its sink. With exceptions, an allocator with no room is errc::capacity and the operation changes nothing, since every change allocates its working state before its first change; stringify, which returns its text, throws std::bad_alloc. The four allocator tests count the global operator new, check each resource is given back all it handed out, and fail every operation at each of its allocations in turn. --- include/webcpp/document/containers.hpp | 86 +- include/webcpp/document/detail/convert.hpp | 297 ++++-- include/webcpp/document/detail/handler.hpp | 94 +- include/webcpp/document/detail/selector.hpp | 149 +++- include/webcpp/document/detail/tree.hpp | 764 +++++++++++----- .../webcpp/document/detail/value_array.hpp | 122 ++- include/webcpp/document/detail/writer.hpp | 171 +++- include/webcpp/document/parse.hpp | 56 +- include/webcpp/document/parser.hpp | 326 ++++++- include/webcpp/document/stringify.hpp | 48 +- include/webcpp/document/value.hpp | 313 +++++-- test/allocator_parse_test.cpp | 768 +++++++++++++++- test/allocator_stringify_test.cpp | 646 +++++++++++++- test/allocator_tree_test.cpp | 842 +++++++++++++++++- test/allocator_values_test.cpp | 663 +++++++++++++- 15 files changed, 4710 insertions(+), 635 deletions(-) diff --git a/include/webcpp/document/containers.hpp b/include/webcpp/document/containers.hpp index 0f53042..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 { @@ -156,9 +154,6 @@ 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. @@ -170,18 +165,13 @@ struct walker { } 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 { @@ -216,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; } @@ -251,9 +244,10 @@ 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_view* from = access::tree_of(v); if (from == nullptr) { @@ -330,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_); @@ -356,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); @@ -377,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); @@ -406,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_)); } @@ -564,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_)); } @@ -887,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_); } @@ -906,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(); } @@ -917,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; }; @@ -1128,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(); @@ -1256,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_); } @@ -1301,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/convert.hpp b/include/webcpp/document/detail/convert.hpp index 4353dad..c037a1d 100644 --- a/include/webcpp/document/detail/convert.hpp +++ b/include/webcpp/document/detail/convert.hpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -52,6 +53,30 @@ namespace webcpp::document::detail { +// Only the allocator's std::bad_alloc 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 `std::bad_alloc` + 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)()) { +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + try { + return std::forward(f)(); + } catch (const std::bad_alloc&) { + return errc::capacity; + } +#else + return std::forward(f)(); +#endif +} + +// 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 && @@ -170,6 +195,14 @@ class prepared { template using buffers = std::vector, rebound>>; + /** A new buffer of `size` values of `T` in the allocator, added to `list`. */ + template + buffer& add(buffers& list, std::size_t size) { + // Made, then moved in: a polymorphic allocator constructs an element with itself after the + // arguments, which a size and an allocator already are. + return list.emplace_back(buffer(size, rebound(alloc_))); + } + /** Holds `null` again, and owns nothing. */ void clear() noexcept { item_ = item{}; @@ -237,11 +270,27 @@ struct converter { /** Whether bytes are base64url text rather than base64. */ static constexpr bool url = std::same_as; + /** A buffer of bytes in `A`, rebound. */ + template + using bytes_in = std::vector>; + + /** + 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 - static result prepare_value(const T& v, prepared_t& out) { + static result prepare_value(const T& v, prepared_t& out) noexcept { out.clear(); - result held = hold(out, v); + result held = bad_alloc_as_capacity([&] { return hold(out, v); }); if (!held.has_value()) { out.clear(); } @@ -260,9 +309,10 @@ struct converter { /** Prepares a JSON string from nothing, revived as asked; on failure `out` holds `null`. */ static result 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 held = hold_json_string(out, utf8, revive_dates, revive_bytes); + result held = bad_alloc_as_capacity( + [&] { return hold_json_string(out, utf8, revive_dates, revive_bytes); }); if (!held.has_value()) { out.clear(); } @@ -432,9 +482,10 @@ struct converter { // Under javascript_bytes, bytes are an object's shape, which no string has. if constexpr (!javascript_shape) { if (revive_bytes) { - if (result> decoded = decode(text); decoded.has_value()) { - const auto& bytes = owner.bytes_.emplace_back( - decoded.unsafe_value().begin(), decoded.unsafe_value().end(), owner.alloc_); + if (result> decoded = decode(text, owner.alloc_); + decoded.has_value()) { + const auto& bytes = + owner.bytes_.emplace_back(std::move(decoded.unsafe_value())); return hold_form(owner, owner.item_, std::span(bytes)); } } @@ -519,8 +570,7 @@ struct converter { } out.kind = kind_t::string; if constexpr (utf16_text) { - auto& units = - owner.utf16_.emplace_back(static_cast(utf16_length(v)), owner.alloc_); + auto& units = owner.add(owner.utf16_, static_cast(utf16_length(v))); to_utf16(v, units.data()); out.text = std::as_bytes(std::span(units)); } else { @@ -539,8 +589,7 @@ struct converter { if (!valid_utf16(v)) { return errc::type; } - auto& chars = - owner.utf8_.emplace_back(static_cast(utf8_size(v)), owner.alloc_); + auto& chars = owner.add(owner.utf8_, static_cast(utf8_size(v))); to_utf8(v, chars.data()); out.kind = kind_t::string; out.text = std::as_bytes(std::span(chars)); @@ -579,8 +628,7 @@ struct converter { if (members.empty()) { return {}; } - const std::span> entries = - owner.entries_.emplace_back(members.size(), owner.alloc_); + const std::span> 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) { @@ -604,8 +652,7 @@ struct converter { if (elements.empty()) { return {}; } - const std::span> entries = - owner.entries_.emplace_back(elements.size(), owner.alloc_); + const std::span> 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) { @@ -617,10 +664,20 @@ struct converter { return {}; } - /** Base64 or base64url text, by the policy, decoded: @ref errc::type when it is not. */ - static result> decode(std::string_view text) { + /** Room for the bytes of base64 text of `size` characters, in `alloc`. */ + template + static bytes_in room_for_base64(std::size_t size, const A& alloc) { // Four characters make at most three bytes, and the last group of base64url's fewer. - std::vector out(((text.size() / 4) * 3) + 3); + return bytes_in(((size / 4) * 3) + 3, rebound(alloc)); + } + + /** + Base64 or base64url text, by the policy, decoded into a buffer of `alloc`: @ref errc::type when + it is not. + */ + template + static result> decode(std::string_view text, const A& alloc) { + bytes_in out = room_for_base64(text.size(), alloc); const result size = read_base64(text, out.data(), url); if (!size.has_value()) { return errc::type; @@ -629,6 +686,41 @@ struct converter { 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(unit) : '\0'; + } + + /** + UTF-16 base64 text, by the policy, decoded into a buffer of `alloc` a block at a time, made + ASCII on the stack, so that no copy of the text is allocated: @ref errc::type when it is not. + */ + template + static result> decode(std::u16string_view units, const A& alloc) { + bytes_in out = room_for_base64(units.size(), alloc); + // 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 chars{}; + std::size_t done = 0; + std::size_t written = 0; + do { + const std::size_t count = std::min(units.size() - done, ascii_block); + std::ranges::transform(units.substr(done, count), chars.begin(), ascii_of); + done += count; + if (done != units.size() && chars[count - 1] == '=') { + return errc::type; + } + const result size = + read_base64(std::string_view(chars.data(), count), out.data() + written, url); + if (!size.has_value()) { + return errc::type; + } + written += static_cast(size.unsafe_value()); + } while (done != units.size()); + out.resize(written); + return out; + } + /** Reads a node of a kind @ref read reads, as `T`. */ template static result read_as(const tree_t& t, const node_t& n) { @@ -653,7 +745,7 @@ struct converter { } else if constexpr (std::same_as) { return read_date_of(n); } else if constexpr (std::same_as>) { - return read_bytes(t, n); + return read_bytes(t, n, std::allocator()); } else { if (n.kind != kind_t::bytes) { return errc::type; @@ -842,67 +934,70 @@ 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 - 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_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(unit) : '\0'; - }); - return std::forward(f)(std::string_view(chars)); + std::array 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)(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 read_date_of(const node_t& n) { + static result read_date_of(const node_t& n) noexcept { if (n.kind == kind_t::date) { return n.template load(); } if (n.kind != kind_t::string) { return errc::type; } - const std::optional date = - with_ascii(n, [](std::string_view text) { return read_date(text); }); + const std::optional 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> 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 + static result> read_bytes(const tree_t& t, const node_t& n, const A& alloc) { if (n.kind == kind_t::bytes) { const std::span bytes = n.text.view(); - return std::vector(bytes.begin(), bytes.end()); + return bytes_in(bytes.begin(), bytes.end(), rebound(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. */ - static result> read_byte_object(const tree_t& t, const node_t& n) { + template + static result> 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 out; + bytes_in out{rebound(alloc)}; out.reserve(static_cast(count)); for (std::uint64_t i = 0; i < count; ++i) { std::array key{}; @@ -953,70 +1048,73 @@ struct converter { return x.template load() == y.template load(); } - /** 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(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>& 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> 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 @@ -1060,6 +1158,10 @@ item 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. @@ -1079,6 +1181,23 @@ result read(const tree_view& t, const node* n) noexcept { return converter::template read_as(t, *n); } +// NOLINTEND(bugprone-exception-escape) + +/** + Reads a node as bytes, as @ref read reads `std::vector`, 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 +result>> read_bytes_with( + const tree_view& t, const node* n, const Allocator& alloc) noexcept { + if (n == nullptr) { + return errc::type; + } + return bad_alloc_as_capacity([&] { return converter::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, @@ -1090,8 +1209,6 @@ bool equal(const tree_view& a, const node* x, const tree_view::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/handler.hpp b/include/webcpp/document/detail/handler.hpp index d7c49d3..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 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(-1); - /** The handler of `owner`, which outlives it. */ - explicit handler(basic_parser& owner) noexcept : owner_(&owner) {} + /** The handler of `owner`, which outlives it, its working state in `owner`'s allocator. */ + explicit handler(basic_parser& owner) noexcept + : owner_(&owner), + frames_(rebound(owner.alloc_)), + path_(rebound(owner.alloc_)), + keys_(rebound(owner.alloc_)), + key_(rebound(owner.alloc_)), + text_(rebound(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,6 +220,13 @@ 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, rebound>; + /** The bytes policy whose bytes are an object's shape, revived when the object ends. */ static constexpr bool bytes_as_objects = std::same_as; @@ -238,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(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()) { @@ -342,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 revive_bytes(std::uint64_t id) noexcept { auto& t = tree_of(); - result> bytes = read>(t, t.find(id)); + 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 made; + prepared made(owner_->alloc_); if (const result held = prepare(std::span(bytes.unsafe_value()), made); !held.has_value()) { @@ -434,22 +484,28 @@ class handler { basic_parser* owner_; /** The containers being read, the innermost last. */ - std::vector frames_; + std::vector> frames_; /** The text's path of the value being read, its first `steps_` entries; the rest are spare. */ - std::vector path_; + std::vector> 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> 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 value_; + prepared value_; }; } // namespace webcpp::document::detail diff --git a/include/webcpp/document/detail/selector.hpp b/include/webcpp/document/detail/selector.hpp index c67000c..ff866c3 100644 --- a/include/webcpp/document/detail/selector.hpp +++ b/include/webcpp/document/detail/selector.hpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -32,12 +33,21 @@ #include #include +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS +#include +#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 +71,52 @@ 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 +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, rebound> 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>; + +/** + 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 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; + + /** + 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 std::bad_alloc 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 parse(std::string_view text) noexcept { - if (text.empty() || text.front() != '$') { - return errc::type; + static result parse(std::string_view text, + const Allocator& alloc = Allocator()) noexcept { +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + try { + return read(text, alloc); + } catch (const std::bad_alloc&) { + return errc::capacity; } - selector parsed; - std::string_view rest = text.substr(1); - while (!rest.empty()) { - std::optional step = read_step(rest); - if (!step) { - return errc::type; - } - parsed.steps_.push_back(std::move(*step)); - } - return parsed; +#else + return read(text, alloc); +#endif } /** Whether a path matches: as many steps as the selector, each matched by its step. */ @@ -110,13 +133,46 @@ class selector { } /** The steps after `$`; none for `$` alone, which matches the root. */ - [[nodiscard]] std::span steps() const noexcept { return steps_; } + [[nodiscard]] std::span steps() const noexcept { return steps_; } private: + /** A key's text in the allocator. */ + using string_type = std::basic_string, rebound>; + + /** A selector without steps, which holds them in `alloc`. */ + explicit basic_selector(const Allocator& alloc) noexcept + : steps_(rebound(alloc)) {} + + /** Parses a selector's text, its steps allocated through `alloc`, which may throw. */ + static result 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 = 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(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 +191,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 read_step(std::string_view& rest) { + static std::optional 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 read_dotted(std::string_view& rest) { + static std::optional 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 +219,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 read_bracketed(std::string_view& rest) { + static std::optional 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 key = read_quoted(rest); - if (!key) { + if (!read_quoted(rest, step.key)) { return std::nullopt; } - step.key = std::move(*key); } else { const std::optional index = read_index(rest); if (!index) { @@ -202,31 +255,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 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 +301,12 @@ class selector { } /** The steps after `$`, in order. */ - std::vector steps_; + std::vector> steps_; }; +/** A parsed selector held in the standard allocator. */ +using selector = basic_selector>; + } // 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 e945ea7..520d2f3 100644 --- a/include/webcpp/document/detail/tree.hpp +++ b/include/webcpp/document/detail/tree.hpp @@ -9,13 +9,23 @@ 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 fail. 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 @@ -41,12 +51,12 @@ #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -183,12 +193,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 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) { + 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) { + 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) { @@ -237,6 +275,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(lead_of(byte_at(utf8, i)).length, 1); + const std::string_view character(utf8.data() + i, std::min(length, utf8.size() - i)); + std::array decoded{}; + const auto count = static_cast(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; + } }; /** @@ -435,40 +506,23 @@ class tree_view { 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* 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; } - if constexpr (utf16_text) { - if (!valid_utf8(key)) { - return nullptr; - } - // Most keys are short: they are transcoded on the stack. - std::array small{}; - std::vector large; - const std::uint64_t units = utf16_length(key); - char16_t* out = small.data(); - if (units > small.size()) { - large.resize(static_cast(units)); - out = large.data(); - } - to_utf16(key, out); - return member_in( - *nodes, object, - as_chars(std::as_bytes(std::span(out, static_cast(units))))); - } else { - return member_in(*nodes, object, key); + // Text that is not UTF-8 is no stored key's, and the UTF-16 order decodes only UTF-8. + if (utf16_text && !valid_utf8(key)) { + return nullptr; } + 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. @@ -716,9 +770,25 @@ class tree_view { return it == ids.end() ? nullptr : &*it; } - /** The child of `object` whose key is `key`, in the traits' encoding, or null. */ + /** + 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 static const node_type* member_in(const nodes_type& nodes, std::uint64_t object, - std::string_view key) noexcept { + const Key& key) noexcept { const auto& keys = nodes.template get(); const auto it = keys.find(std::make_tuple(object, key)); return it == keys.end() ? nullptr : &*it; @@ -764,6 +834,10 @@ class tree_view { return header; } +private: + template + friend class tree; + /** The bytes of the image it reads, or null when it is attached to nothing. */ region_bytes* region_ = nullptr; }; @@ -773,12 +847,14 @@ class tree_view { 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. + @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 what - an operation stages before it changes anything. + @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 tree : public tree_view { @@ -797,6 +873,7 @@ class tree : public tree_view { 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; @@ -821,9 +898,9 @@ class tree : public tree_view { using view::member_stored; using view::next_sibling; - // 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. + // 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`. @@ -923,9 +1000,10 @@ class tree : public tree_view { /** The allocator of its region, which holds what an operation stages. */ [[nodiscard]] Allocator get_allocator() const noexcept { return storage().get_allocator(); } - // 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. + // 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. @@ -937,11 +1015,13 @@ class tree : public tree_view { return errc::type; } change c = start_change(); - add_existing(c, *target, v, id == root_id); - if (const auto read = read_values(c); !read.has_value()) { - return read; - } - return write(c, [] {}); + return write( + c, + [&]() -> result { + add_existing(c, *target, v, id == root_id); + return read_values(c); + }, + [] {}); } /** @@ -955,12 +1035,10 @@ class tree : public tree_view { 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()) { + if (!valid_utf8(key)) { return errc::type; } - if (const node_type* existing = member_in(*nodes, object, as_chars(*stored))) { + 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(); @@ -969,11 +1047,16 @@ class tree : public tree_view { } 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()) { + std::uint64_t id = 0; + change c = start_change(); + if (const auto done = write( + c, + [&]() -> result { + 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); @@ -990,18 +1073,21 @@ class tree : public tree_view { 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()) { + change c = start_change(); + if (const auto done = write( + c, + [&]() -> result { + 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); @@ -1010,7 +1096,10 @@ class tree : public tree_view { return {}; } - /** Erases the member `key` and its subtree; whether it was there. */ + /** + Erases the member `key` and its subtree; whether it was there. It allocates nothing and + cannot run out of room. + */ result erase_member(std::uint64_t object, std::string_view key) noexcept { const node_type* o = find(object); if (!is_kind(o, kind_t::object)) { @@ -1020,11 +1109,26 @@ class tree : public tree_view { 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); + 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 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; } @@ -1051,12 +1155,18 @@ class tree : public tree_view { return splice(array, at, 0, v); } - /** Erases `n` elements from `at` and their subtrees, the later elements renumbered. */ + /** + Erases `n` elements from `at` and their subtrees, the later elements renumbered. It allocates + nothing and cannot run out of room. + */ result 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. */ + /** + 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 splice(std::uint64_t array, std::uint64_t at, std::uint64_t remove, std::span> v) noexcept { const node_type* a = find(array); @@ -1067,19 +1177,23 @@ class tree : public tree_view { if (at > length || remove > length - at) { return errc::range; } - 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); - } - for (std::size_t i = 0; i < v.size(); ++i) { - add_element(c, array, at + i, &v[i]); - } - 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 { + 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)); @@ -1089,8 +1203,8 @@ class tree : public tree_view { 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); @@ -1176,18 +1290,22 @@ class tree : public tree_view { return {}; } - // 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 compact_to(region_type& to, const view& from, std::uint64_t bytes) noexcept { @@ -1237,6 +1355,12 @@ class tree : public tree_view { // NOLINTEND(bugprone-exception-escape) 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 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 node is ever left there, and no other node of its parent is in it. @@ -1245,8 +1369,10 @@ class tree : public tree_view { return static_cast(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, @@ -1343,14 +1469,30 @@ class tree : public tree_view { 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>; + + /** 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 { + 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> stack(alloc); - if (const node_type* first = from.first_child(root_id)) { - stack.push_back({first, root_id, 0}); + stack_type stack{rebound(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(); @@ -1367,8 +1509,9 @@ class tree : public tree_view { 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; @@ -1392,10 +1535,17 @@ class tree : public tree_view { 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 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; @@ -1410,6 +1560,12 @@ class tree : public tree_view { /** 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. */ @@ -1430,22 +1586,44 @@ class tree : public tree_view { 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 + using list = std::vector>; + + /** + 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(alloc)), + doomed(rebound(alloc)), + work(rebound(alloc)), + sizes(rebound(alloc)), + copies(rebound(alloc)) {} + /** The nodes it writes, in the order their blocks are probed and allocated. */ - std::vector nodes; + list nodes; - /** The subtrees it erases once the new nodes are in place. */ - std::vector doomed; + /** The roots of the subtrees it erases once the new nodes are in place. */ + list doomed; /** Values still to be read into staged nodes. */ - std::vector work; + list work; + + /** The sizes of the blocks it allocates in the image, in the order it allocates them. */ + list sizes; + + /** The sum of `sizes`, or the largest value when that overflows. */ + std::uint64_t total = 0; - /** Keys transcoded to UTF-16. */ - std::vector> keys16; + /** 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> copies; + /** The bytes of what its keys and strings viewed inside the image, before the image grew. + */ + list copies; /** The id the change's first new node takes. */ std::uint64_t next_id = 0; @@ -1454,6 +1632,40 @@ class tree : public tree_view { 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) + /** + Runs `stage`, which allocates in the allocator what an operation needs before it changes + anything, and returns its result: with exceptions, the allocator's `std::bad_alloc` is + @ref errc::capacity, nothing having changed; without them, an allocator that fails ends the + program, as it does itself. + */ + template + static result staging(Stage&& stage) noexcept { +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + try { + return std::forward(stage)(); + } catch (const std::bad_alloc&) { + return errc::capacity; + } +#else + return std::forward(stage)(); +#endif + } + + // 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_bytes& r, std::uint64_t total) noexcept { return saturated_sum(r.size(), saturated_sum(total, total)); @@ -1471,9 +1683,9 @@ class tree : public tree_view { 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; } @@ -1481,21 +1693,12 @@ class tree : public tree_view { /** 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> encode_key(change& c, std::string_view utf8) { - if (!valid_utf8(utf8)) { - return std::nullopt; - } - if constexpr (utf16_text) { - std::vector& units = - c.keys16.emplace_back(static_cast(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. */ @@ -1533,15 +1736,18 @@ class tree : public tree_view { } } - /** 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 stored_key, std::uint64_t& next, - const item& v) { + std::uint64_t& next, const item& 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; @@ -1570,29 +1776,33 @@ class tree : public tree_view { std::span> entries, std::uint64_t& next, std::uint64_t& added, bool assign_existing) const { constexpr std::size_t placed = std::numeric_limits::max(); - std::map 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 runs{rebound(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& 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& 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& 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; } } @@ -1693,39 +1903,60 @@ class tree : public tree_view { /** 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 { + result 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 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(bytes)); const auto own = [&](std::span& 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(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 find_room(change& c) { - std::vector sizes; - std::uint64_t total = 0; - const auto add = [&](std::uint64_t size) { - sizes.push_back(size); - total = saturated_sum(total, size); + result 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()); } @@ -1734,19 +1965,24 @@ class tree : public tree_view { add(node_probe_bytes); } } - bool owned = false; - while (!probe(heap_of(storage()), sizes)) { - if (!storage().is_owned()) { - return errc::capacity; - } - if (!owned) { - own_views(c); - owned = true; - } - if (!storage().grow(grown_size(storage(), 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 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 {}; } @@ -1762,53 +1998,85 @@ class tree : public tree_view { } /** - 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(block)); + byte_string made; + made.data = static_cast(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 - result write(change& c, Arrange&& arrange) { + template + result write(change& c, Stage&& stage, Arrange&& arrange) { + if (const auto planned = staging([&]() -> result { + if (const auto gathered = std::forward(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(storage()); - std::vector> 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); + 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)(); 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& 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(); - 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); }); } } @@ -1847,32 +2115,102 @@ class tree : public tree_view { 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, the key count kept. */ + 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(); + 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(); - // Each node's children are listed after it, so the list read backwards is children first. - std::vector subtree{id}; - std::size_t listed = 0; - while (listed < subtree.size()) { - const std::uint64_t parent = subtree[listed++]; + auto& ids = nodes.template get(); + auto& order = nodes.template get(); + // 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(); heap& h = heap_of(storage()); - 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); + 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. @@ -1884,16 +2222,16 @@ class tree : public tree_view { 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 { + 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)); diff --git a/include/webcpp/document/detail/value_array.hpp b/include/webcpp/document/detail/value_array.hpp index 5007bff..f3c303f 100644 --- a/include/webcpp/document/detail/value_array.hpp +++ b/include/webcpp/document/detail/value_array.hpp @@ -17,6 +17,8 @@ #include +#include + #include #include #include @@ -93,9 +95,9 @@ result> read_source(const basic_const_value 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 +template requires settable -result prepare_element(const T& v, prepared& out) noexcept { +result prepare_element(const T& v, prepared& out) noexcept { if constexpr (copy_source) { const auto s = read_source(v); if (!s.has_value()) { @@ -111,12 +113,24 @@ result prepare_element(const T& v, prepared& out) noexcept { } } +/** `sizeof...(I)` prepared values, each holding its buffers in `alloc`. */ +template +std::array, sizeof...(I)> prepared_values( + const Allocator& alloc, std::index_sequence /*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(I), prepared(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 -result prepare_elements(std::array, sizeof...(T)>& held, +template +result prepare_elements(std::array, sizeof...(T)>& held, std::array, sizeof...(T)>& items, std::index_sequence /*indices*/, const T&... v) noexcept { if constexpr (sizeof...(T) != 0) { @@ -155,10 +169,6 @@ item array_of(std::span> 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 void copy_elements(const tree_view& from, std::uint64_t array, std::uint64_t at, @@ -192,10 +202,13 @@ result>> splice_elements( } removed = owned_holding(one, t.get_allocator()); } else { - std::vector> entries; - entries.reserve(static_cast(n)); - copy_elements(t, array, at, n, entries); - removed = owned_holding(array_of(entries), t.get_allocator()); + removed = bad_alloc_as_capacity([&] { + std::vector, rebound>> entries( + t.get_allocator()); + entries.reserve(static_cast(n)); + copy_elements(t, array, at, n, entries); + return owned_holding(array_of(entries), t.get_allocator()); + }); } if (!removed.has_value()) { return removed; @@ -208,11 +221,17 @@ result>> splice_elements( /** 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 +template class concatenation { public: + /** No entry yet, each to be held in `alloc`. */ + explicit concatenation(const Allocator& alloc) noexcept + : alloc_(alloc), + held_(rebound>(alloc)), + entries_(rebound>(alloc)) {} + /** Appends a copy of each element of `array` in `from`. */ void add_elements(const tree_view& from, std::uint64_t array) { copy_elements(from, array, 0, from.count(array), entries_); @@ -272,7 +291,7 @@ class concatenation { /** Appends one value. */ template result add_value(const T& v) { - prepared& p = held_.emplace_back(); + prepared& 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> held_; + std::vector, rebound>> held_; /** The array's entries, in order. */ - std::vector> entries_; + std::vector, rebound>> entries_; }; -// NOLINTEND(bugprone-exception-escape) - } // namespace webcpp::document::detail namespace webcpp::document { @@ -323,10 +343,6 @@ basic_value basic_value::at(std::int64_t index return this->template element_handle(k); } -// The copies' entries are staged on the process heap, whose exhaustion ends the program, as the -// library tolerates. -// NOLINTBEGIN(bugprone-exception-escape) - template result>> basic_const_value::slice( std::int64_t start, std::int64_t stop) const noexcept { @@ -338,12 +354,16 @@ result>> basic_const_value> entries; - if (last > first) { - entries.reserve(static_cast(last - first)); - detail::copy_elements(t, id, first, last - first, entries); - } - return detail::owned_holding(detail::array_of(entries), t.get_allocator()); + return detail::bad_alloc_as_capacity([&] { + std::vector, + detail::rebound>> + entries(t.get_allocator()); + if (last > first) { + entries.reserve(static_cast(last - first)); + detail::copy_elements(t, id, first, last - first, entries); + } + return detail::owned_holding(detail::array_of(entries), t.get_allocator()); + }); } template @@ -356,22 +376,23 @@ basic_const_value::concat(const T&... v) const noexcept if (id == 0) { return errc::type; } - detail::concatenation c; - c.add_elements(*tree_ptr(), id); - if constexpr (sizeof...(T) != 0) { - result added; - // The fold stops at the first argument that fails. - static_cast(((added = c.add(v), added.has_value()) && ...)); - if (!added.has_value()) { - return added.error(); - } - } - return detail::owned_holding(detail::array_of(c.entries()), - tree_ptr()->get_allocator()); + return detail::bad_alloc_as_capacity( + [&]() -> result>> { + detail::concatenation c(tree_ptr()->get_allocator()); + c.add_elements(*tree_ptr(), id); + if constexpr (sizeof...(T) != 0) { + result added; + // The fold stops at the first argument that fails. + static_cast(((added = c.add(v), added.has_value()) && ...)); + if (!added.has_value()) { + return added.error(); + } + } + return detail::owned_holding(detail::array_of(c.entries()), + tree_ptr()->get_allocator()); + }); } -// NOLINTEND(bugprone-exception-escape) - template template result basic_value::push(const T&... v) noexcept @@ -381,14 +402,15 @@ result basic_value::push(const T&... v) noexcept if (id == 0) { return errc::type; } - std::array, sizeof...(T)> held{}; + auto* t = writable_tree(); + auto held = + detail::prepared_values(t->get_allocator(), std::index_sequence_for()); std::array, sizeof...(T)> items{}; if (const auto made = detail::prepare_elements(held, items, std::index_sequence_for(), v...); !made.has_value()) { return made.error(); } - auto* t = writable_tree(); if (const auto done = t->insert_elements(id, t->count(id), items); !done.has_value()) { return done.error(); } @@ -428,14 +450,15 @@ result basic_value::unshift(const T&... v) noexc if (id == 0) { return errc::type; } - std::array, sizeof...(T)> held{}; + auto* t = writable_tree(); + auto held = + detail::prepared_values(t->get_allocator(), std::index_sequence_for()); std::array, sizeof...(T)> items{}; if (const auto made = detail::prepare_elements(held, items, std::index_sequence_for(), v...); !made.has_value()) { return made.error(); } - auto* t = writable_tree(); if (const auto done = t->insert_elements(id, 0, items); !done.has_value()) { return done.error(); } @@ -452,14 +475,15 @@ result>> basic_value, sizeof...(T)> held{}; + auto* t = writable_tree(); + auto held = + detail::prepared_values(t->get_allocator(), std::index_sequence_for()); std::array, sizeof...(T)> items{}; if (const auto made = detail::prepare_elements(held, items, std::index_sequence_for(), v...); !made.has_value()) { return made.error(); } - 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(*t, id, at, detail::splice_count(count, at, length), diff --git a/include/webcpp/document/detail/writer.hpp b/include/webcpp/document/detail/writer.hpp index 0cc85f2..9b20582 100644 --- a/include/webcpp/document/detail/writer.hpp +++ b/include/webcpp/document/detail/writer.hpp @@ -9,6 +9,9 @@ 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, is in the document's + allocator, rebound, and is the only thing it allocates besides its output. */ #ifndef WEBCPP_DOCUMENT_DETAIL_WRITER_HPP @@ -20,6 +23,7 @@ #include #include #include +#include #include #include @@ -29,10 +33,12 @@ #include #include #include +#include #include #include #include #include +#include #include namespace webcpp::document::detail { @@ -40,6 +46,19 @@ 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 has room for at first, 16 bytes each: a document nested 16 deep + is written with one allocation of its stack. +*/ +inline constexpr std::size_t first_frames = 16; + +/** + The room the piece `stringify_to` holds back takes at first when its chunk is larger: a chunk of + the default size or smaller is allocated once, at its size, and a larger one, which may be larger + than the whole text, grows by doubling to what the text needs. +*/ +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`. @@ -57,34 +76,64 @@ concept output = requires(Out& out, std::string_view text) { { out.put(text) } -> std::same_as>; }; +/** + Runs `allocate`, which allocates through the writer's allocator: with exceptions, the allocator's + `std::bad_alloc` is @ref errc::capacity; without, an allocator that fails ends the program, as it + does itself. +*/ +template +result allocating(Allocate&& allocate) { +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + try { + std::forward(allocate)(); + } catch (const std::bad_alloc&) { + return errc::capacity; + } +#else + std::forward(allocate)(); +#endif + return {}; +} + /** 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 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 +/** + 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 `Allocator`, rebound. +*/ +template 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, the + piece it holds 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::clamp(chunk, 1, std::numeric_limits::max()))) {} + std::clamp(chunk, 1, std::numeric_limits::max()))), + pending_(piece_allocator(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 put(std::string_view text) { while (!text.empty()) { // A full piece of the text itself is handed over without a copy. @@ -96,6 +145,9 @@ class chunked_output { continue; } const std::size_t taken = std::min(chunk_ - pending_.size(), text.size()); + if (const result room = make_room(pending_.size() + taken); !room) { + return room; + } pending_.append(text.substr(0, taken)); text.remove_prefix(taken); if (pending_.size() == chunk_) { @@ -120,6 +172,9 @@ class chunked_output { } private: + /** The allocator of the piece held back. */ + using piece_allocator = rebound; + /** Hands one piece to the sink, a sink returning `void` succeeding. */ result hand(std::string_view piece) { if constexpr (std::same_as, void>) { @@ -130,28 +185,61 @@ class chunked_output { } } + /** + Makes room in the piece for `size` bytes, at most the chunk, before it takes them: the smaller + of the chunk and @ref first_piece_room the first time, then twice the room, up to the chunk, + so that each growth is one allocation. + */ + result make_room(std::size_t size) { + if (size <= pending_.capacity()) { + return {}; + } + std::size_t room = room_ == 0 ? std::min(chunk_, first_piece_room) : room_; + while (room < size) { + room = room > chunk_ / 2 ? chunk_ : 2 * room; + } + if (const result made = allocating([this, room] { pending_.reserve(room); }); !made) { + return made; + } + room_ = room; + return {}; + } + + /** The sink, used in place. */ Sink* sink_; + + /** The largest piece. */ std::size_t chunk_; - std::string pending_; + + /** The room the piece was last given, 0 before it was given any. */ + std::size_t room_ = 0; + + /** The text not yet handed over, shorter than a chunk. */ + std::basic_string, piece_allocator> pending_; }; /** 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, 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 +template class json_writer { public: - /** A walk of `t` writing to `out` with `indent` spaces a level, already clamped. */ - json_writer(const tree_view& 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& t, std::uint32_t indent, Out& out, + const Allocator& alloc) noexcept + : tree_(&t), indent_(indent), out_(&out), stack_(frame_allocator(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 run(const node& root) { write_value(root); @@ -174,6 +262,9 @@ class json_writer { bool first = true; }; + /** The allocator of the stack. */ + using frame_allocator = rebound; + /** Whether strings and keys are stored as UTF-16 code units. */ static constexpr bool utf16_text = std::same_as; @@ -227,15 +318,40 @@ 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& n, bool object) { + if (!status_) { + return; + } const node* 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: @ref first_frames frames, then twice the room each time it is + full; with exceptions, an allocator with no room stops the writing with @ref errc::capacity. + */ + bool push(const frame& f) { + if (stack_.size() == stack_.capacity()) { + const std::size_t room = stack_.capacity() == 0 ? first_frames : 2 * stack_.capacity(); + if (const result made = allocating([this, room] { stack_.reserve(room); }); + !made) { + status_ = made; + return false; + } + } + // There is room: it does not allocate. + stack_.push_back(f); + return true; } /** Writes a number as JavaScript's Number::toString writes the traits' `number`. */ @@ -371,25 +487,34 @@ class json_writer { status_ = out_->put(text); } + /** The tree read. */ const tree_view* tree_; + + /** The spaces of a level, already clamped. */ std::uint32_t indent_; + + /** The output written to. */ Out* out_; - std::vector stack_; + + /** The containers the walk is inside, the innermost last. */ + std::vector stack_; + + /** The first failure, which stops the writing, or success. */ result 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, its stack in `alloc`, rebound; a null `root`, `undefined`, writes nothing. */ -template +template requires output result write_json(const tree_view& t, const node* root, std::uint32_t indent, - Out& out) { + Out& out, const Allocator& alloc) { if (root == nullptr || root->kind == webcpp::document::kind::undefined) { return {}; } - json_writer writer(t, std::min(indent, max_indent), out); + json_writer writer(t, std::min(indent, max_indent), out, alloc); return writer.run(*root); } diff --git a/include/webcpp/document/parse.hpp b/include/webcpp/document/parse.hpp index 05daaf1..5b382b1 100644 --- a/include/webcpp/document/parse.hpp +++ b/include/webcpp/document/parse.hpp @@ -70,20 +70,18 @@ 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 -// 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> parse(std::string_view text, const parse_options& o = {}) noexcept { basic_parser p(o); - if (const result written = p.write(text); !written.has_value()) { - return written.error(); - } - return p.finish(); + return p.finish(text); } /** @@ -91,7 +89,9 @@ result> parse(std::string_view text, @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. + 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`. @@ -102,17 +102,14 @@ result> parse(std::string_view text, @see "Allocators", in the guide. */ template -// 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>> parse(std::string_view text, const parse_options& o, const Allocator& alloc) noexcept { basic_parser> p(o, alloc); - if (const result written = p.write(text); !written.has_value()) { - return written.error(); - } - return p.finish(); + return p.finish(text); } /** @@ -125,44 +122,42 @@ result>> parse(std::string_view te @return The document; the errors of @ref parse, and @ref errc::capacity when the buffer is full. */ template -// 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> parse_into(std::span buffer, std::string_view text, const parse_options& o = {}) noexcept { basic_parser p(buffer, o); - if (const result written = p.write(text); !written.has_value()) { - return written.error(); - } - return p.finish(); + return p.finish(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. + @return The document; the errors of @ref parse_into, and @ref errc::capacity when `alloc` has no + room. @see "Allocators", in the guide. */ template -// 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>> parse_into( std::span buffer, std::string_view text, const parse_options& o, const Allocator& alloc) noexcept { basic_parser> p(buffer, o, alloc); - if (const result written = p.write(text); !written.has_value()) { - return written.error(); - } - return p.finish(); + return p.finish(text); } /** @@ -174,7 +169,7 @@ result>> parse_into( @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 @@ -187,10 +182,7 @@ template requires detail::exceptions_enabled basic_document parse_or_throw(std::string_view text, const parse_options& o) { basic_parser p(o); - if (const result written = p.write(text); !written.has_value()) { - detail::raise(written.error(), p.offset()); - } - result> made = p.finish(); + result> made = p.finish(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 396131d..c445722 100644 --- a/include/webcpp/document/parser.hpp +++ b/include/webcpp/document/parser.hpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -42,6 +43,7 @@ #ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS #include +#include #endif namespace webcpp::document { @@ -144,11 +146,180 @@ concept selector_callback = std::same_as, path_view>, result>); -/** 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 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; + + /** + 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 + requires selector_callback, Traits, Storage> + static delivery make(F&& f, const allocator_type& alloc) { + using held = std::decay_t; + using held_allocator = rebound; + using held_traits = std::allocator_traits; + held_allocator a(alloc); + storage_for storage(a); + held_traits::construct(a, storage.get(), std::forward(f)); + storage.release(); + // A callable that is a function pointer makes its storage a pointer to a pointer. + return delivery(static_cast(storage.get()), &operations_of, 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 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. */ + struct operations { + /** Calls the callable at `object` with a value and its path. */ + result (*call)(void* object, const handle& v, path_view where); + + /** Destroys the callable at `object` and gives its storage back to `alloc`. */ + void (*destroy)(void* object, const allocator_type& alloc) noexcept; + }; + + /** + 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 storage_for { + public: + /** The allocator's traits, rebound to `T`. */ + using traits = std::allocator_traits>; + + /** Storage for one `T` from `allocator`, which outlives it; what the allocator throws. */ + explicit storage_for(rebound& 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_; + + /** 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 + static result call_as(void* object, const handle& v, path_view where) { + F& f = *static_cast(object); + if constexpr (std::same_as, 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 + static void destroy_as(void* object, const allocator_type& alloc) noexcept { + using held_allocator = rebound; + using held_traits = std::allocator_traits; + held_allocator a(alloc); + F* const f = static_cast(object); + const typename held_traits::pointer place = + std::pointer_traits::pointer_to(*f); + held_traits::destroy(a, f); + held_traits::deallocate(a, place, 1); + } + + /** The operations of a callable of type `F`. */ + template + static constexpr operations operations_of{.call = &call_as, .destroy = &destroy_as}; + + /** 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 struct subscription { /** The places it matches. */ - selector where; + basic_selector where; /** Whether the value is dropped after its delivery, as `on` asks, or kept, as `observe` does. @@ -156,7 +327,7 @@ struct subscription { bool take = false; /** The callback, its `void` made success. */ - std::function(basic_const_value, path_view)> deliver; + delivery deliver; }; } // namespace detail @@ -170,6 +341,15 @@ 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 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. @see "Parsing", in the guide. @@ -178,7 +358,7 @@ template class basic_parser { public: /** The allocator of the document and of the parser's working state. */ - using allocator_type = typename Storage::allocator_type; + using allocator_type = Storage::allocator_type; /** A parser of an owned document. @@ -186,10 +366,13 @@ class basic_parser { @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 = {}, + explicit basic_parser(const parse_options& o = parse_options(), const allocator_type& alloc = allocator_type()) noexcept requires detail::owned_storage - : options_(o), alloc_(alloc), json_(json_options(o), *this) {} + : 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. @@ -198,10 +381,14 @@ class basic_parser { @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 buffer, const parse_options& o = {}, + explicit basic_parser(std::span buffer, const parse_options& o = parse_options(), const allocator_type& alloc = allocator_type()) noexcept requires detail::external_storage - : options_(o), alloc_(alloc), buffer_(buffer), json_(json_options(o), *this) {} + : 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; @@ -223,8 +410,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 write(std::string_view chunk) { if (!failure_.has_value()) { @@ -242,7 +429,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()) { @@ -259,17 +446,41 @@ class basic_parser { @return The document; the errors of @ref write, and @ref errc::syntax for text that ends early. */ - result> finish() { + result> finish() { return finish(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 `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> finish(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(json_.write_some(false, nullptr, 0, ec)); - if (const result 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 settled = settle(ec, used); !settled.has_value()) { return settled.error(); } ended_ = true; @@ -317,11 +528,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`. @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 @@ -338,7 +552,8 @@ class basic_parser { `result`. @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 @@ -374,7 +589,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 settled = settle(ec, used); !settled.has_value()) { return settled.error(); @@ -398,6 +613,28 @@ 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; 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) { +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + try { + return json_.write_some(more, chunk.data(), chunk.size(), ec); + } catch (const std::bad_alloc&) { + failure_ = errc::capacity; + ec = failure_.error(); + return 0; + } +#else + return json_.write_some(more, chunk.data(), chunk.size(), ec); +#endif + } + /** 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; @@ -449,30 +686,45 @@ class basic_parser { return failure_; } - /** Adds a subscription, its callback's `void` made success. */ + /** A subscription of this parser. */ + using subscription_type = detail::subscription; + + /** The allocator of the subscriptions. */ + using subscriptions_allocator = detail::rebound; + + /** + 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 result subscribe(std::string_view text, F&& f, bool take) { - result parsed = detail::selector::parse(text); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + try { + return add(text, std::forward(f), take); + } catch (const std::bad_alloc&) { + return errc::capacity; + } +#else + return add(text, std::forward(f), take); +#endif + } + + /** + Adds a subscription, made whole before it is added, so that what fails to allocate leaves + the subscriptions as they were. + */ + template + result add(std::string_view text, F&& f, bool take) { + result> parsed = + detail::basic_selector::parse(text, alloc_); if (!parsed.has_value()) { return parsed.error(); } - using callback = std::decay_t; - detail::subscription added; - added.where = std::move(parsed).unsafe_value(); - added.take = take; - if constexpr (std::same_as, path_view>, - void>) { - added.deliver = [g = callback(std::forward(f))]( - const basic_const_value& v, - path_view where) mutable -> result { - g(v, where); - return {}; - }; - } else { - added.deliver = callback(std::forward(f)); - } - subscriptions_.push_back(std::move(added)); + subscriptions_.push_back(subscription_type{ + .where = std::move(parsed).unsafe_value(), + .take = take, + .deliver = detail::delivery::make(std::forward(f), alloc_), + }); return {}; } @@ -480,7 +732,7 @@ class basic_parser { BOOST_ATTRIBUTE_NO_UNIQUE_ADDRESS allocator_type alloc_; std::span buffer_; std::optional> document_; - std::vector> subscriptions_; + std::vector subscriptions_; boost::json::basic_parser> json_; result failure_; boost::system::error_code cause_; diff --git a/include/webcpp/document/stringify.hpp b/include/webcpp/document/stringify.hpp index 4421c4f..425f477 100644 --- a/include/webcpp/document/stringify.hpp +++ b/include/webcpp/document/stringify.hpp @@ -18,7 +18,10 @@ #include #include +#include + #include +#include #include #include #include @@ -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. The writer's stack, a frame of 16 bytes for each container it is inside, with room + for 16 frames at first and twice the room each time it is full, is in the document's allocator, + rebound, 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, with exceptions, + the document's allocator none for the stack; without exceptions, an allocator that fails ends the + program, as it does itself. @see "Writing JSON", in the guide. */ template std::string stringify(basic_const_value v, std::uint32_t indent = 0) { std::string text; - const detail::tree_view* 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); + // 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, t->get_allocator())) { + boost::throw_exception(std::bad_alloc()); + } return text; } @@ -69,6 +83,7 @@ std::string stringify(basic_const_value 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 std::string stringify(const basic_document& d, std::uint32_t indent = 0) { @@ -80,6 +95,13 @@ std::string stringify(const basic_document& d, std::uint32_t in /** Writes a value as @ref stringify does, in pieces of at most `chunk` bytes, to a sink. + It allocates only its working state, in the document's allocator, rebound, and frees it when it + returns: its stack, a frame of 16 bytes for each container it is inside, with room for 16 frames + at first and twice the room each time it is full; and the piece it holds back until it is full, + given the smaller of `chunk` and 4096 bytes the first time it holds more than a string's own + small buffer does, then, for a larger chunk, twice its room, up to `chunk`, each time it is full. + 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`. @@ -87,22 +109,27 @@ std::string stringify(const basic_document& 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 requires detail::sink> result stringify_to(basic_const_value v, Sink&& sink, std::uint32_t indent = 0, std::uint64_t chunk = default_chunk) { - const detail::tree_view* 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> out(sink, chunk); + detail::chunked_output, typename Storage::allocator_type> out( + sink, chunk, alloc); if (const result 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 +148,8 @@ result stringify_to(basic_const_value 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 requires detail::sink> diff --git a/include/webcpp/document/value.hpp b/include/webcpp/document/value.hpp index 9a437d2..4074921 100644 --- a/include/webcpp/document/value.hpp +++ b/include/webcpp/document/value.hpp @@ -29,11 +29,15 @@ #include #include +#include +#include #include #include #include #include #include +#include +#include #include #include #include @@ -191,6 +195,134 @@ 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 +using key_string = std::basic_string, rebound>; + +/** + `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 +std::optional> hold_key(std::string_view key, const A& alloc) noexcept { + auto held = bad_alloc_as_capacity([&]() -> result> { + return key_string(key.data(), key.size(), rebound(alloc)); + }); + if (!held.has_value()) { + return std::nullopt; + } + return std::optional>(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 +std::optional copy_key(const std::optional& 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::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::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 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& from, const node& parent, bool elements, + const Allocator& alloc) + : keys_(rebound(alloc)), + entries_(rebound>(alloc)) { + std::size_t count = 0; + std::size_t bytes = 0; + for (const node* 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* 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> entries() const noexcept { + return entries_; + } + +private: + /** Whether keys are stored as UTF-16 code units. */ + static constexpr bool utf16_text = std::same_as; + + /** The size of the UTF-8 of the key of `n`. */ + static std::size_t key_size(const node& n) noexcept { + if constexpr (utf16_text) { + return static_cast(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(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& n, std::size_t at) noexcept { + if constexpr (utf16_text) { + return static_cast(to_utf8(n.key.units(), keys_.data() + at)); + } else { + std::ranges::copy(n.key.chars(), keys_.begin() + static_cast(at)); + return n.key.chars().size(); + } + } + + /** The keys, one after another. */ + std::vector> keys_; + + /** The entries, in the source's order. */ + std::vector, rebound>> 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. */ @@ -252,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. @@ -641,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; + /** 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* doc, detail::place where, std::uint64_t id, std::uint64_t index, std::string_view key) noexcept @@ -655,10 +848,24 @@ 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) 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* tree_ptr() @@ -676,7 +883,9 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_const_value { const detail::node* 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; } @@ -735,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_; /** What the handle names. */ detail::place place_ = detail::place::nothing; @@ -886,11 +1098,21 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value p; - p.copy_of(*from, n->id); - return store(p.value()); + detail::item copy; + copy.from = from; + copy.from_id = n->id; + return store(copy); } else { - detail::prepared p; + // A handle of nothing has no document whose allocator could hold the prepared value: + // the value is prepared in the standard allocator, so that its own error comes first. + if (this->doc_ == nullptr) { + detail::prepared p; + if (const auto made = detail::prepare(v, p); !made.has_value()) { + return made; + } + return errc::type; + } + detail::prepared p(this->doc_->get_allocator()); if (const auto made = detail::prepare(v, p); !made.has_value()) { return made; } @@ -912,9 +1134,6 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_valueerase_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. @@ -940,26 +1159,14 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value& 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 keys; - std::vector ids; - for (const detail::node* 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> 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); + auto* t = writable_tree(); + return detail::bad_alloc_as_capacity([&]() -> result { + const detail::assigned_members 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. @@ -1081,6 +1288,9 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value* doc, detail::place where, std::uint64_t id, std::uint64_t index, std::string_view key) noexcept @@ -1110,18 +1320,6 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value& n) { - if constexpr (std::same_as) { - const std::u16string_view units = n.key.units(); - std::string out(static_cast(detail::utf8_size(units)), '\0'); - detail::to_utf8(units, out.data()); - return out; - } else { - return std::string(n.key.chars()); - } - } - /** Stores an item at this place: the node replaced, or the member or element created. */ result store(const detail::item& v) noexcept { auto* t = writable_tree(); @@ -1131,7 +1329,10 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_valueplace_) { 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(); } @@ -1143,9 +1344,6 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_valueplace_) { 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(); } @@ -1181,14 +1382,13 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_valuekind == webcpp::document::kind::array) { return t->assign(this->id_, detail::empty_item(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. */ @@ -1255,9 +1455,6 @@ basic_const_value basic_document::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 auto children_iterator::operator*() const noexcept -> value_type { if constexpr (Kind == children_of::values) { @@ -1284,8 +1481,6 @@ auto children_iterator::operator*() const noexcept -> val } } -// NOLINTEND(bugprone-exception-escape) - template children_iterator& children_iterator::operator++() noexcept { diff --git a/test/allocator_parse_test.cpp b/test/allocator_parse_test.cpp index fb37c97..1d67a8c 100644 --- a/test/allocator_parse_test.cpp +++ b/test/allocator_parse_test.cpp @@ -4,15 +4,781 @@ // 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: to be written. +// 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(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 #include #include "counting.hpp" +#include "parse_corpus.hpp" #include "require.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 +using pmr_parser = wd::basic_parser; + +/** Whether two documents' images are the same bytes; it allocates nothing. */ +template +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 samples() { + const text_pair key = long_text('k'); + const text_pair other = long_text('o'); + const text_pair value = long_text('v'); + std::vector 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 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 +void parse_calls_no_global_new(const sample& s) { + const auto reference = wd::parse(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(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 +void parse_into_calls_no_global_new(const sample& s) { + const auto buffers = std::make_unique>(); + const auto reference = wd::parse_into((*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((*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 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 +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`, selectors with a long key; returns + which were added. +*/ +template +std::array subscribe(Parser& p, tally& t, const selected& s) { + std::array 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(where.index(1))) { + ++t.wrong; + } + ++t.deliveries[items]; + }).has_value(); + added[meta] = p.observe("$.meta", [&t](const auto& v, wd::path_view) -> wd::result { + 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& 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 +tally selected_tally() { + const selected s = selected_text(); + tally t; + wd::basic_parser p; + require(BOOST_TEST(all_added(subscribe(p, t, s)))); + require(BOOST_TEST(p.finish(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(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 +void selectors_call_no_global_new() { + const selected s = selected_text(); + const tally expected = selected_tally(); + tally reference_tally; + wd::basic_parser reference_parser; + require(BOOST_TEST(all_added(subscribe(reference_parser, reference_tally, s)))); + const auto reference = reference_parser.finish(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 p({}, a.allocator()); + BOOST_TEST(all_added(subscribe(p, t, s))); + const auto made = p.finish(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 +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 +void chunks_call_only_the_stack(std::string_view text, bool selectors) { + const selected s = selected_text(); + tally reference_tally; + wd::basic_parser reference_parser; + if (selectors) { + require(BOOST_TEST(all_added(subscribe(reference_parser, reference_tally, s)))); + } + const auto reference = reference_parser.finish(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 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); + BOOST_TEST_EQ(stack_allocations(R"(["[[[",{"a":"]\"]"}])", 1), 2U); + chunks_call_only_the_stack(deep, false); +} + +/** + Checks that `finish(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 +void finish_is_write_then_finish(std::string_view text, const wd::parse_options& o) { + wd::basic_parser whole(o); + const auto at_once = whole.finish(text); + wd::basic_parser split(o); + const wd::result written = split.write(text); + const auto in_two = written.has_value() + ? split.finish() + : wd::result>(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(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 +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(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(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(text, limited); + } +} + +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + +/** An allocator of `resource`. */ +std::pmr::polymorphic_allocator 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 +void parse_runs_out(const sample& s) { + const auto reference = wd::parse(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(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 +void parse_into_runs_out(const sample& s) { + const auto buffers = std::make_unique>(); + const auto reference = wd::parse_into((*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((*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 +void refused_selectors_were_not_added(Parser& p, webcpp::test::failing_resource& failing, + const std::array& added, const tally& t, + const tally& expected, std::string_view text) { + failing.allow(plenty); + BOOST_TEST(p.finish(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 +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("[1]").error() == wd::errc::capacity); + p.reset(); + BOOST_TEST(p.finish("[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 +void parser_runs_out(bool in_chunks) { + const selected s = selected_text(); + const tally expected = selected_tally(); + tally reference_tally; + wd::basic_parser reference_parser; + require(BOOST_TEST(all_added(subscribe(reference_parser, reference_tally, s)))); + const auto reference = reference_parser.finish(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 p({}, allocator_of(failing)); + const std::array 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(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(s); + parse_runs_out(s); + parse_into_runs_out(s); + parse_into_runs_out(s); + } + parser_runs_out(false); + parser_runs_out(false); + parser_runs_out(true); + parser_runs_out(true); +} + +#endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS + +} // namespace + int main() { + const std::vector texts = samples(); + for (const sample& s : texts) { + parse_calls_no_global_new(s); + parse_calls_no_global_new(s); + parse_into_calls_no_global_new(s); + parse_into_calls_no_global_new(s); + } + selectors_call_no_global_new(); + selectors_call_no_global_new(); + const selected s = selected_text(); + chunks_call_only_the_stack(s.text, true); + chunks_call_only_the_stack(s.text, true); + chunks_call_only_the_stack(texts[2].text, false); + chunks_call_only_the_stack(texts[4].text, false); + the_stack_rule(); + finish_is_write_then_finish(); + finish_is_write_then_finish(); +#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 index 2530fd6..a931784 100644 --- a/test/allocator_stringify_test.cpp +++ b/test/allocator_stringify_test.cpp @@ -4,7 +4,16 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The writer's working state in the document's allocator: to be written. +// The writer's working state 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 its stack and the piece it holds back alone, as often as +// their rooms double; stringify calls the global operator new exactly as often as its std::string +// grows; 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, and std::bad_alloc for stringify, while a sink's own std::bad_alloc +// propagates. #include @@ -13,6 +22,641 @@ #include "counting.hpp" #include "require.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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 +wd::basic_document make_document() { + auto made = wd::basic_document::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 +void nest(wd::basic_value top, std::size_t levels, bool alternate) { + // A handle cannot be assigned without exceptions: the next one is constructed in place. + std::optional> 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 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 +wd::basic_document nested() { + wd::basic_document doc = make_document(); + 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 +wd::basic_document sample() { + wd::basic_document doc = make_document(); + 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 bytes(301); + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast((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(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) { + // 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 +std::vector texts_of(const Document& source, std::span indents) { + std::vector 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 +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 +wd::pmr::basic_document owned_copy(const wd::basic_document& source, + std::pmr::memory_resource* resource) { + auto made = wd::from_image(source.image(), + std::pmr::polymorphic_allocator(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 +std::vector buffer_of(const wd::basic_document& source) { + std::vector 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 +wd::basic_document external_copy(std::vector& buffer, + std::pmr::memory_resource* resource) { + auto opened = wd::open(std::as_writable_bytes(std::span(buffer)), + std::pmr::polymorphic_allocator(resource)); + require(BOOST_TEST(opened.has_value())); + return std::move(*opened); +} + +/** + The allocations of the writer's stack to hold `frames` frames at once: room for 16 frames first, + then twice the room each time it is full. +*/ +constexpr std::uint64_t stack_allocations(std::uint64_t frames) { + std::uint64_t count = 0; + for (std::uint64_t room = 0; room < frames; 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: the smaller of `chunk` and 4096 bytes the first time, then twice the + room, up to `chunk`, each time it is full; none while the piece fits the string's own buffer. +*/ +std::uint64_t piece_allocations(std::uint64_t chunk, std::uint64_t size) { + const std::uint64_t most = std::min(chunk, size); + if (most <= std::pmr::string().capacity()) { + return 0; + } + std::uint64_t count = 1; + for (std::uint64_t room = std::min(chunk, 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& sizes) noexcept : sizes_(&sizes) {} + + /** Records the size of `text`. */ + wd::result put(std::string_view text) { + sizes_->push_back(text.size()); + return {}; + } + +private: + /** The sizes, in the order the pieces came. */ + std::vector* 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 +void writes_in_its_arena(const Document& doc, const Source& source, arena& a, + std::span indents, + const std::vector& 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 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 +void owned_in_arena(const wd::basic_document& source, + std::span indents) { + const std::vector expected = texts_of(source, indents); + arena a(source.image().size() + working_room); + { + const wd::pmr::basic_document 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 +void external_in_arena(const wd::basic_document& source, + std::span indents) { + const std::vector expected = texts_of(source, indents); + std::vector buffer = buffer_of(source); + arena a(working_room); + { + const auto doc = external_copy(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 indents{0, 2, 10}; + const std::array compact{0}; + owned_in_arena(sample(), indents); + owned_in_arena(sample(), indents); + external_in_arena(sample(), indents); + owned_in_arena(nested(), compact); + owned_in_arena(nested(), compact); + external_in_arena(nested(), 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 +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 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, its stack and the piece it holds back 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. +void the_writer_allocates_its_stack_and_piece() { + { + const wd::document source = nested(); + 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(); + const std::string expected = wd::stringify(source); + std::vector buffer = buffer_of(source); + arena docs(working_room); + arena outs(working_room); + const auto doc = external_copy(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 growing the piece past its first room. + const auto source = sample(); + 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, and the arena makes the allocations of a stack of `frames` frames, and takes them back. +*/ +template +void calls_new_for_its_string_alone(const wd::basic_document& source, std::uint64_t frames, + std::span indents) { + arena a(source.image().size() + working_room); + const wd::pmr::basic_document 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 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()) + .has_value()); + std::uint64_t reference_news = 0; + std::uint64_t reference_deletes = 0; + { + std::string reference; + const global_count global; + 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 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); + BOOST_TEST_EQ(deletes, reference_deletes); + BOOST_TEST(text == expected); + } + BOOST_TEST_EQ(a.resource().allocations() - made, stack_allocations(frames)); + BOOST_TEST_EQ(a.resource().bytes_in_use(), held); + } +} + +// stringify returns a std::string, the program's value in the standard allocator: it calls the +// global operator new for that string alone, its stack in the document's resource. +void stringify_calls_new_for_its_string_alone() { + const std::array indents{0, 2, 10}; + const std::array compact{0}; + calls_new_for_its_string_alone(sample(), sample_frames, indents); + calls_new_for_its_string_alone(sample(), sample_frames, indents); + calls_new_for_its_string_alone(nested(), deep_frames, compact); +} + +// 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 quoted = wd::quote(std::string_view(utf8), out); + wd::quote(std::u16string_view(utf16), out); + const wd::result 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 +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 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 every budget from 0 until it + succeeds: each step that fails throws std::bad_alloc, the document and the resource as they were, + and as many steps fail as the stack of `frames` frames allocates. +*/ +template +void bad_alloc_at_every_step(const Document& doc, const Source& source, + webcpp::test::failing_resource& failing, std::uint32_t indent, + std::uint64_t frames) { + const std::string expected = wd::stringify(source, indent); + const std::uint64_t held = failing.bytes_in_use(); + std::uint64_t budget = 0; + for (;; ++budget) { + failing.allow(budget); + bool thrown = false; + try { + const std::string text = wd::stringify(doc, indent); + BOOST_TEST(text == expected); + } catch (const std::bad_alloc&) { + thrown = true; + } + BOOST_TEST(same_image(doc, source)); + BOOST_TEST_EQ(failing.bytes_in_use(), held); + if (!thrown || !BOOST_TEST_LT(budget, stack_allocations(frames))) { + break; + } + } + BOOST_TEST_EQ(budget, stack_allocations(frames)); +} + +// 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(); + 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 stringify throw std::bad_alloc, and changes nothing: 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(); + 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)); + } + bad_alloc_at_every_step(doc, source, failing, 0, deep_frames); + failing.allow(unlimited); + } + { + const auto source = nested(); + 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(); + const std::uint64_t size = wd::stringify(source).size(); + std::vector buffer = buffer_of(source); + const auto doc = external_copy(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(); + 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)); + bad_alloc_at_every_step(doc, source, failing, 2, sample_frames); + 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(); + 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_tree_test.cpp b/test/allocator_tree_test.cpp index 74e1be8..128ee5f 100644 --- a/test/allocator_tree_test.cpp +++ b/test/allocator_tree_test.cpp @@ -4,15 +4,855 @@ // 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: to be written. +// 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 #include +#include #include "counting.hpp" #include "require.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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; + +/** The region of a tree in a memory resource. */ +using pmr_region = detail::basic_region; + +/** A tree of `Traits` in a memory resource. */ +template +using pmr_tree = detail::tree; + +constexpr std::size_t mebibyte = std::size_t{1} << 20U; + +/** The size an image here may grow to. */ +constexpr std::uint64_t max_bytes = 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 +auto long_string_of() { + if constexpr (std::same_as) { + 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 +T take(wd::result 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 +wd::result set_value(Handle& h, std::size_t i) { + switch (i % 4) { + case 0: return h.set(static_cast(i)); + case 1: return h.set(i % 8 == 1); + case 2: return h.set(nullptr); + default: return h.set(long_string_of()); + } +} + +// 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 +void members_in_resource() { + using document = wd::pmr::basic_document; + 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{}).has_value())); + // The keys, and the handles that name them, are made before anything is counted. + std::vector keys; + keys.reserve(members); + for (std::size_t i = 0; i < members; ++i) { + keys.push_back(long_key(i)); + } + std::vector 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(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 +void arrays_in_resource() { + using document = wd::pmr::basic_document; + arena a(16 * mebibyte); + { + document d = take(document::create(a.allocator())); + require(BOOST_TEST(d.root().set(wd::array{}).has_value())); + auto list = d.root(); + const auto text = long_string_of(); + 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 +wd::pmr::basic_document sample(const pmr_allocator& alloc) { + auto d = take(wd::parse(sample_json, wd::parse_options(), alloc)); + require(BOOST_TEST(d.root()[long_key(0)].set(long_string_of()).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 +void copies_in_resource() { + using document = wd::pmr::basic_document; + arena a(16 * mebibyte); + arena b(4 * mebibyte); + { + const document source = sample(b.allocator()); + document d = take(document::create(a.allocator())); + require(BOOST_TEST(d.root().set(wd::object{}).has_value())); + 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 +detail::item integer(std::int64_t v) { + detail::item i; + i.kind = wd::kind::number; + i.number = detail::repr::integer; + i.store(v); + return i; +} + +/** An item holding `v`. */ +template +detail::item boolean(bool v) { + detail::item i; + i.kind = wd::kind::boolean; + i.store(v); + return i; +} + +/** An item holding the long string, in the traits' encoding. */ +template +detail::item long_string() { + detail::item i; + i.kind = wd::kind::string; + i.text = std::as_bytes(std::span(long_string_of())); + return i; +} + +/** An item holding an empty container of `k`, or a literal one of `entries`, which outlive it. */ +template +detail::item container(wd::kind k, + std::span> entries = {}) { + detail::item 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 +detail::item copy_of(const detail::tree_view& from, std::uint64_t id) { + detail::item 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 +struct pmr_fixture { + /** A new tree holding null, in `alloc`. */ + explicit pmr_fixture(const pmr_allocator& alloc) + : r(take(pmr_region::owned(4096, max_bytes, alloc))), + t(take(pmr_tree::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(), max_bytes, alloc))), + t(take(pmr_tree::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 image() const { + return {r.data(), static_cast(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 t; +}; + +/** The id of the member `key` of `object`, which must be there. */ +template +std::uint64_t id_of(const detail::tree_view& t, std::uint64_t object, + std::string_view key) { + const detail::node* n = t.member(object, key); + require(BOOST_TEST(n != nullptr)); + return n->id; +} + +/** + 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 +bool same_tree(const pmr_fixture& a, const pmr_fixture& b) { + const auto same_node = [](const detail::node& x, const detail::node& 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(), + b.t.nodes()->template get(), same_node); +} + +/** + 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 +std::pair build_sample(pmr_tree& t) { + const std::uint64_t root = detail::root_id; + require(BOOST_TEST(t.assign(root, container(wd::kind::object)).has_value())); + require(BOOST_TEST(t.set_member(root, "small", integer(1)).has_value())); + const std::uint64_t nested = + take(t.set_member(root, "nested", container(wd::kind::object))); + const std::uint64_t inner = take(t.set_member(nested, "a", container(wd::kind::array))); + for (std::uint64_t i = 0; i < 6; ++i) { + const auto value = + i % 2 == 0 ? long_string() : integer(static_cast(i)); + require(BOOST_TEST(t.set_element(inner, i, value).has_value())); + } + require(BOOST_TEST(t.set_member(nested, long_key(1), boolean(true)).has_value())); + const std::uint64_t list = take(t.set_member(root, "list", container(wd::kind::array))); + for (std::uint64_t i = 0; i < 5; ++i) { + require(BOOST_TEST( + t.set_element(list, i, integer(static_cast(i))).has_value())); + } + require(BOOST_TEST(t.set_element(list, 2, copy_of(t, nested)).has_value())); + require(BOOST_TEST(t.set_member(root, long_key(0), long_string()).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 +void tree_operations_in_resource() { + using entry = detail::literal_entry; + const std::uint64_t root = detail::root_id; + arena a(4 * mebibyte); + { + pmr_fixture f(a.allocator()); + const auto [nested, list] = build_sample(f.t); + const std::array 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({ + {.key = keys[2], .value = integer(7)}, + {.key = "x", .value = boolean(true)}, + }); + const auto entries = std::to_array({ + {.key = "x", .value = integer(1)}, + {.key = keys[1], .value = long_string()}, + {.key = "x", .value = integer(2)}, + {.key = "inner", .value = container(wd::kind::object, inner)}, + {.key = keys[0], .value = integer(3)}, + }); + const std::array, 2> inserted{ + copy_of(f.t, nested), + long_string(), + }; + 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()); + BOOST_TEST(set.has_value()); + first = set.has_value() ? *set : 0; + BOOST_TEST(f.t.set_members(root, entries).has_value()); + const detail::node* 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* x = f.t.member(root, "x"); + require(BOOST_TEST(x != nullptr)); + BOOST_TEST_EQ(x->template load(), 2); + const detail::node* assigned = f.t.member(root, keys[0]); + require(BOOST_TEST(assigned != nullptr)); + BOOST_TEST_EQ(assigned->id, first); + BOOST_TEST_EQ(assigned->template load(), 3); + 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 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 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 f(a.allocator()); + const std::uint64_t root = detail::root_id; + require(BOOST_TEST(f.t.assign(root, container(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(static_cast(i))) + .has_value())); + } + const global_count global; + for (std::size_t i = 0; i < keys.size(); ++i) { + const detail::node* n = f.t.member(root, keys[i]); + if (i % 2 == 0) { + BOOST_TEST(n != nullptr && + n->template load() == static_cast(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::max(); + +/** Whether an erasure erased. */ +bool erased(const wd::result& 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 +void erasures_allocate_nothing() { + const std::uint64_t root = detail::root_id; + failing_resource failing(std::pmr::new_delete_resource(), unlimited); + { + pmr_fixture 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(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 +std::vector erasure_digests(pmr_fixture& 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(wd::kind::array))); + for (std::uint64_t i = 0; i < 16; ++i) { + require( + BOOST_TEST(f.t.set_element(many, i, container(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(wd::kind::array))); + const auto n = static_cast(i); + require(BOOST_TEST(f.t.set_element(x, 0, integer(n)).has_value())); + require(BOOST_TEST(f.t.set_element(x, 1, long_string()).has_value())); + require(BOOST_TEST(f.t.set_member(e, long_key(i), boolean(true)).has_value())); + } + std::vector 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(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 +void erasures_keep_the_image(const std::array& pinned) { + pmr_fixture f{pmr_allocator(std::pmr::new_delete_resource())}; + const std::vector digests = erasure_digests(f); + BOOST_TEST_ALL_EQ(digests.begin(), digests.end(), pinned.begin(), pinned.end()); +} + +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + +/** 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 +std::uint64_t fail_each_allocation(const wd::pmr::basic_document& 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(source.image(), alloc)); + require(BOOST_TEST(operation(expected, [] {}).has_value())); + for (; budget < step_limit; ++budget) { + failing.allow(unlimited); + auto copy = take(wd::from_image(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 +std::uint64_t fail_each_allocation_in_tree(const pmr_fixture& source, Operation operation) { + failing_resource failing(std::pmr::new_delete_resource(), unlimited); + const pmr_allocator alloc(&failing); + std::uint64_t budget = 0; + { + pmr_fixture expected(source, alloc); + require(BOOST_TEST(operation(expected.t).has_value())); + for (; budget < step_limit; ++budget) { + failing.allow(unlimited); + pmr_fixture 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 +void handles_fail_softly() { + const auto text = long_string_of(); + const std::string key = long_key(5); + const wd::pmr::basic_document source = + sample(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 +void tree_fails_softly() { + using entry = detail::literal_entry; + const std::uint64_t root = detail::root_id; + pmr_fixture source{pmr_allocator(std::pmr::new_delete_resource())}; + const auto [nested, list] = build_sample(source.t); + const std::array keys{long_key(20), long_key(21)}; + const auto inner = std::to_array({ + {.key = keys[1], .value = long_string()}, + {.key = "y", .value = boolean(false)}, + }); + const auto entries = std::to_array({ + {.key = keys[0], .value = integer(1)}, + {.key = "nested", .value = long_string()}, + {.key = keys[0], .value = container(wd::kind::object, inner)}, + {.key = "z", .value = container(wd::kind::array, inner)}, + {.key = "small", .value = boolean(true)}, + }); + const std::uint64_t set_member = fail_each_allocation_in_tree( + source, [&](auto& t) { return t.set_member(root, keys[0], long_string()); }); + 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, 2> items{ + copy_of(t, nested), + long_string(), + }; + 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(); + members_in_resource(); + arrays_in_resource(); + arrays_in_resource(); + copies_in_resource(); + copies_in_resource(); + tree_operations_in_resource(); + tree_operations_in_resource(); + lookups_by_utf8_keys(); + erasures_allocate_nothing(); + erasures_allocate_nothing(); + erasures_keep_the_image({ + 0x38c76b4a395b0326, + 0x2c14970cfa6dc330, + 0x35ea097c472ac20c, + 0xa19a73e9032fd691, + 0x58bf4826b5bdea1c, + 0x1e6bf1349054d6b2, + 0x704f7f300d9124fc, + 0x8ba81cffbbc560cc, + 0x040a767c2a348e42, + 0x74fb654128b4b9dd, + 0xbdec20dae902004d, + }); + erasures_keep_the_image({ + 0x850a39306007c1dc, + 0x961d2dd418e3b7be, + 0x946f2e49edf7876b, + 0x66f5808c528b7a0e, + 0x1963759dd134db47, + 0xbca805ce38c0d5f6, + 0xdbeb1136b36154e9, + 0xc30c77810664054e, + 0xeb9d9db5c1c49417, + 0xcce96cf5f1d6a0e4, + 0xc72fa788f772579e, + }); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + handles_fail_softly(); + handles_fail_softly(); + tree_fails_softly(); + tree_fails_softly(); +#endif return boost::report_errors(); } diff --git a/test/allocator_values_test.cpp b/test/allocator_values_test.cpp index dea05c4..f726d2c 100644 --- a/test/allocator_values_test.cpp +++ b/test/allocator_values_test.cpp @@ -4,7 +4,14 @@ // 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: to be written. +// 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 handle of nothing reports +// its value's own error first; 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 fail. #include @@ -13,6 +20,660 @@ #include "counting.hpp" #include "require.hpp" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 +using pmr_document = wd::basic_document; + +/** 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 +wd::basic_document parsed(std::string_view json) { + auto made = wd::parse(json); + require(BOOST_TEST(made.has_value())); + return std::move(*made); +} + +/** The document `json` holds, in the arena `a`. */ +template +pmr_document in_arena(arena& a, std::string_view json) { + const auto source = parsed(json); + auto made = wd::from_image(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 +struct kept_documents { + /** The documents, in the order made. */ + std::array, 8> documents{}; + + /** How many there are. */ + std::size_t count = 0; + + /** Keeps `made`, which must be a document. */ + void keep(wd::result&& 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 +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 +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 +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(json); + set_scenario(reference, f); + { + auto d = in_arena(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 +void missing_member_handles() { + arena a(16 * mebibyte); + const sample_values f; + constexpr std::string_view json = R"({"o":{}})"; + auto reference = parsed(json); + BOOST_TEST(reference["o"][f.key].set(f.members).has_value()); + { + auto d = in_arena(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 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 +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 +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(json); + erase_scenario(reference, f); + { + auto d = in_arena(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 +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 +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(R"({")" + f.other_key + R"(":{"deep":[1]},"x":2})"); + auto reference = parsed(json); + assign_scenario(reference, other); + { + auto d = in_arena(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 +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(a, x_json); + const auto y = in_arena(a, y_json); + const auto z = in_arena(a, deeper); + const auto w = in_arena(a, renamed); + const auto v = in_arena(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 +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 +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(json); + kept_documents> expected; + array_scenario(reference, f, expected); + { + auto d = in_arena(a, json); + kept_documents> 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 +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 +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(json); + views_scenario(reference, f); + { + auto d = in_arena(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); +} + +// 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( + 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 +void external_scenario(Document& d, const sample_values& f, Kept& kept) { + BOOST_TEST(d.root().set(f.members).has_value()); + 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)); +} + +void external_document() { + arena a(16 * mebibyte); + const sample_values f; + auto reference = parsed("null"); + kept_documents expected; + external_scenario(reference, f, expected); + alignas(16) std::array buffer{}; + { + auto made = wd::format(std::span(buffer), a.allocator()); + require(BOOST_TEST(made.has_value())); + kept_documents 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 handle of nothing reports a value's own error before its place's errc::type, as when the +// value is prepared first: its value is prepared in the standard allocator, since there is no +// document whose allocator could hold it, so nothing here is counted. +template +void nothing_reports_value_first() { + arena a(mebibyte); + const sample_values f; + auto d = in_arena(a, R"({"a":1})"); + auto nothing = d["missing"]["x"]; + BOOST_TEST(nothing.is_undefined()); + BOOST_TEST(nothing.set(std::numeric_limits::infinity()).error() == + wd::errc::range); + const wd::date_ms late{std::chrono::milliseconds{wd::detail::date_limit_ms + 1}}; + BOOST_TEST(nothing.set(late).error() == wd::errc::range); + BOOST_TEST(nothing.set(std::string_view("\xFF")).error() == wd::errc::type); + BOOST_TEST(nothing.set(1).error() == wd::errc::type); + BOOST_TEST(nothing.set(f.text).error() == wd::errc::type); + BOOST_TEST(nothing.set(f.members).error() == wd::errc::type); + BOOST_TEST(nothing.set(d["a"]).error() == wd::errc::type); + BOOST_TEST(nothing.set(wd::undefined).error() == wd::errc::type); + same_value(d, parsed(R"({"a":1})")); +} + +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + +/** What a resource that is never to run out allows. */ +constexpr std::uint64_t unlimited = std::numeric_limits::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 with + the document as it was. Returns how many budgets failed. +*/ +template +std::uint64_t fails_softly(const std::string& json, Op op) { + arena a(16 * mebibyte); + const auto source = parsed(json); + const std::string before = source.root().stringify(); + webcpp::test::failing_resource failing(&a.resource(), unlimited); + const std::pmr::polymorphic_allocator alloc(&failing); + std::uint64_t failures = 0; + for (std::uint64_t budget = 0; budget < 1000; ++budget) { + failing.allow(unlimited); + auto d = wd::from_image(source.image(), alloc); + require(BOOST_TEST(d.has_value())); + failing.allow(budget); + const boost::system::error_code done = op(*d); + failing.allow(unlimited); + if (!done) { + BOOST_TEST_GT(failures, 0U); + return failures; + } + BOOST_TEST(done == wd::errc::capacity); + 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 +void never_fails(const std::string& json, Op op) { + arena a(16 * mebibyte); + const auto source = parsed(json); + const std::string before = source.root().stringify(); + webcpp::test::failing_resource failing(&a.resource(), unlimited); + auto d = wd::from_image(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 +boost::system::error_code error_of(const wd::result& 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 +void unheld_key() { + arena a(16 * mebibyte); + const sample_values f; + const auto source = parsed(R"({"o":{}})"); + webcpp::test::failing_resource failing(&a.resource(), unlimited); + auto made = wd::from_image(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 +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(json, [&](auto& d) { return d["a"].set(f.members).error(); }); + fails_softly(json, [&](auto& d) { return d[f.key].set(f.members).error(); }); + fails_softly(json, [&](auto& d) { return d["list"].push(f.elements, f.text).error(); }); + fails_softly(json, [&](auto& d) { + return error_of(d["list"].concat(f.elements, f.members, f.text), + d.get_allocator().resource()); + }); + fails_softly(json, [&](auto& d) { + return error_of(d["list"].splice(1, 2, f.members, f.elements), + d.get_allocator().resource()); + }); + fails_softly(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(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 +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(json, [&](auto& d) { return d["o"][f.key].set(wd::undefined).error(); }); + never_fails(json, [&](auto& d) { return d["o"].erase(f.key).error(); }); + never_fails(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(json, [&](auto& d) { + d["o"].as_object()->clear(); + return none; + }); + never_fails(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(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(json, [&](auto& d) { + d["list"].as_array()->pop_back(); + return none; + }); + never_fails(json, [&](auto& d) { + d["list"].as_array()->clear(); + return none; + }); + never_fails(json, [&](auto& d) { return d["list"].as_array()->resize(1).error(); }); +} + +#endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS + +} // namespace + int main() { + set_literals(); + set_literals(); + missing_member_handles(); + missing_member_handles(); + erase_through_undefined(); + erase_through_undefined(); + assign_members(); + assign_members(); + deep_equality(); + deep_equality(); + array_methods(); + array_methods(); + view_members(); + view_members(); + bounds_by_utf16_units(); + external_document(); + nothing_reports_value_first(); + nothing_reports_value_first(); +#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS + failures_change_nothing(); + failures_change_nothing(); + erasures_never_fail(); + erasures_never_fail(); + unheld_key(); + unheld_key(); +#endif return boost::report_errors(); } From 8046861d4fe51f073886712bb6982c77dfabadf1 Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:44:11 -0300 Subject: [PATCH 08/23] document: the allocation tests run on Emscripten The tree's and the values' allocation tests take arenas of several MB, so their memory may grow on Emscripten, and the external document's buffer of 64 KiB is on the heap, past Emscripten's stack of 64 KiB. --- test/Jamfile | 9 ++++++--- test/allocator_values_test.cpp | 12 ++++++++++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/test/Jamfile b/test/Jamfile index 1eefa98..1328cb4 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -133,9 +133,12 @@ webcpp.run shared_interprocess : shared_test.cpp 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. -webcpp.run allocator_tree : allocator_tree_test.cpp counting.cpp ; -webcpp.run allocator_values : allocator_values_test.cpp counting.cpp ; +# 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 + : emscripten:-sALLOW_MEMORY_GROWTH ; +webcpp.run allocator_values : allocator_values_test.cpp counting.cpp + : emscripten:-sALLOW_MEMORY_GROWTH ; webcpp.run allocator_parse : allocator_parse_test.cpp counting.cpp : emscripten:-sALLOW_MEMORY_GROWTH ; webcpp.run allocator_stringify : allocator_stringify_test.cpp counting.cpp diff --git a/test/allocator_values_test.cpp b/test/allocator_values_test.cpp index f726d2c..a919abe 100644 --- a/test/allocator_values_test.cpp +++ b/test/allocator_values_test.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -433,15 +434,22 @@ void external_scenario(Document& d, const sample_values& f, Kept& kept) { kept.keep(d["list"].concat(f.elements)); } +/** The buffer of an external document, 16-aligned. */ +struct alignas(16) external_buffer { + /** Its bytes. */ + std::array bytes{}; +}; + void external_document() { arena a(16 * mebibyte); const sample_values f; auto reference = parsed("null"); kept_documents expected; external_scenario(reference, f, expected); - alignas(16) std::array buffer{}; + // On the heap, before anything is counted: Emscripten's stack is 64 KiB. + const auto buffer = std::make_unique(); { - auto made = wd::format(std::span(buffer), a.allocator()); + auto made = wd::format(std::span(buffer->bytes), a.allocator()); require(BOOST_TEST(made.has_value())); kept_documents kept; { From cc9c91739920b7b624888f31e2b6930678e2567c Mon Sep 17 00:00:00 2001 From: R Date: Sun, 15 Nov 2026 00:44:29 -0300 Subject: [PATCH 09/23] document: the page's Allocators section, its program, and the changelog A section of its own, after Images, names the storages and what their allocator holds, shows a document parsed, changed and written in a resource of the program's own, cloned into a second and moved back, lists how each document is made in an allocator, how moves and copies treat it, what an allocator with no room does, what stays outside it, and which types can be shared between processes, as the coding guidelines ask. The pages on images, parsing, writing JSON, errors, the sugar and testing say what is now true of their memory, and AGENTS.md the section, its program and the rule an operation's allocations follow. --- AGENTS.md | 21 +- doc/allocation.adoc | 283 +++++++++++++++++++++++++++ doc/changelog.adoc | 4 + doc/document.adoc | 2 + doc/errors.adoc | 16 +- doc/exceptions.adoc | 3 + doc/images.adoc | 18 +- doc/introduction.adoc | 7 +- doc/parsing.adoc | 21 +- doc/stringify.adoc | 13 +- doc/testing.adoc | 16 ++ example/Jamfile | 1 + example/document_allocators.cpp | 86 ++++++++ example/document_allocators.expected | 5 + 14 files changed, 467 insertions(+), 29 deletions(-) create mode 100644 doc/allocation.adoc create mode 100644 example/document_allocators.cpp create mode 100644 example/document_allocators.expected diff --git a/AGENTS.md b/AGENTS.md index c4d7db5..2892bb9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,12 @@ 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`), and is made before the operation's first change, so that with + exceptions a `std::bad_alloc` is `errc::capacity` with nothing changed; an erasure, a lookup and + `==` allocate nothing. 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 +50,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 +74,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..054b8f3 --- /dev/null +++ b/doc/allocation.adoc @@ -0,0 +1,283 @@ +// 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, 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 any allocator gives +the image the alignment its heap needs: a memory resource is asked for an alignment of 16. 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 +writer's stack and the piece it holds back for its sink, 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 fail. + +[#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, 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`, and the document catches +it where the operation can still return: the operation returns `errc::capacity` and changes +nothing, as for a full image. 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 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`; +* what has no result to return the failure in throws `std::bad_alloc`: `stringify`, whose result is + the text, and the move assignment between allocators that differ (<<document-allocators-moves>>); + and the sugar throws its `wd::capacity_error` (<<document-exceptions>>). + +*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(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, 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-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` does. 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. 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 1b1b450..23e9faf 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,6 +16,10 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] +* 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 returns + `errc::capacity` and changes nothing. * Added `quote`, which appends a string to a string of the caller's as `JSON.stringify` quotes it. // end::unreleased[] 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..f2eb161 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` @@ -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 operation changes nothing; 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..f660dc8 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(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(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/stringify.adoc b/doc/stringify.adoc index b978908..6b6f786 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 +(<<document-allocators-outside>>), so its failure is a `std::bad_alloc`: the standard allocator's, +for the text, or, with exceptions, the document's allocator's, for its stack. 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 @@ -46,6 +48,13 @@ 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` allocates only its stack, which takes the place of recursion, and the chunk it has +not yet handed to the sink, both in the document's allocator (<<document-allocators>>). 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 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 From 070da566ca482506748bc9e73a4b3dedb68e2e64 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:17:42 -0300 Subject: [PATCH 10/23] document: an image's blocks 16-aligned or given back, through the allocator's own pointer An allocator may ignore an over-aligned request, and a 16-aligned block is over-aligned wherever std::max_align_t's alignment is 8 (arm64 macOS, MSVC): an image at another alignment put rbtree_best_fit's first block where the tree does not look. A buffer that is not 16-aligned is now given back at once and the operation returns errc::capacity. The region keeps the allocator's pointer to the image as the allocator gave it and gives the blocks back through it, never through a pointer rebuilt from the address, which a pointer that carries a segment or a tag would not be. Tests: an allocator that aligns to 8, and one whose pointer carries a tag. --- doc/allocation.adoc | 19 +- include/webcpp/document/detail/heap.hpp | 158 +++++++++----- include/webcpp/document/storage.hpp | 4 + test/allocator_test.cpp | 273 ++++++++++++++++++++++++ 4 files changed, 399 insertions(+), 55 deletions(-) diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 054b8f3..08f7fc5 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -58,12 +58,19 @@ containers: `wd::pmr::document`, the default traits' document of `wd::pmr::owned 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 any allocator gives -the image the alignment its heap needs: a memory resource is asked for an alignment of 16. 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. +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 +`std::max_align_t`'s alignment 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 diff --git a/include/webcpp/document/detail/heap.hpp b/include/webcpp/document/detail/heap.hpp index 0631233..9e2f448 100644 --- a/include/webcpp/document/detail/heap.hpp +++ b/include/webcpp/document/detail/heap.hpp @@ -329,8 +329,9 @@ inline heap_costs measure_heap_costs() noexcept { } /** - The unit an owned image is allocated in: 16 bytes, 16-aligned, so that any allocator, rebound to - it, gives the heap the alignment it needs. + 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. */ struct alignas(16) image_block { /** The block's bytes. */ @@ -401,6 +402,10 @@ class region_bytes { 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> @@ -416,16 +421,14 @@ class basic_region : public region_bytes { return errc::capacity; } basic_region made(a); - std::byte* bytes = made.allocate(size); - if (bytes == nullptr) { + const buffer allocated = made.allocate(size); + if (allocated.bytes == nullptr) { return errc::capacity; } - std::memset(bytes, 0, static_cast<std::size_t>(size)); - 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; } @@ -441,15 +444,13 @@ class basic_region : public region_bytes { return errc::not_a_document; } basic_region made(a); - std::byte* copy = made.allocate(bytes.size()); - if (copy == nullptr) { + const buffer copy = made.allocate(bytes.size()); + if (copy.bytes == nullptr) { return errc::capacity; } - std::memcpy(copy, bytes.data(), bytes.size()); - 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; } @@ -483,7 +484,10 @@ class basic_region : public region_bytes { explicit basic_region(const Allocator& a) noexcept : alloc_(a) {} /** Takes the bytes and a copy of the allocator of `other`, which is left empty. */ - basic_region(basic_region&& other) noexcept : alloc_(other.alloc_) { take(other); } + 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 @@ -500,6 +504,7 @@ class basic_region : public region_bytes { BOOST_ASSERT(alloc_ == other.alloc_ || !other.owned_); } take(other); + kept_ = std::exchange(other.kept_, kept_pointer{}); return *this; } @@ -531,16 +536,15 @@ class basic_region : public region_bytes { 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_, old_size); - 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; @@ -560,14 +564,13 @@ class basic_region : public region_bytes { 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_, size_); - data_ = smaller; - size_ = size; + std::memcpy(smaller.bytes, data_, static_cast<std::size_t>(size)); + deallocate(held(), size_); + hold(smaller, size); return true; } @@ -578,6 +581,27 @@ class basic_region : public region_bytes { /** 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>>; @@ -597,49 +621,81 @@ class basic_region : public region_bytes { } /** - A new buffer of `size` bytes, 16-aligned and uninitialized, or null when the allocator has - none: its `std::bad_alloc` is caught, with exceptions. + A new buffer of `size` bytes, 16-aligned and uninitialized, or none when the allocator has + none: its `std::bad_alloc` is caught, with exceptions. A buffer the allocator gives at another + alignment, as one that ignores an over-aligned request may, is given back, and is none too. */ - std::byte* allocate(std::uint64_t size) noexcept { + 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. - return static_cast<std::byte*>( - ::operator new(static_cast<std::size_t>(size), std::align_val_t{16}, std::nothrow)); + return {static_cast<std::byte*>(::operator new(static_cast<std::size_t>(size), + std::align_val_t{16}, std::nothrow))}; } else { block_allocator blocks(alloc_); const std::size_t count = blocks_of(size); if (count > block_traits::max_size(blocks)) { - return nullptr; + return {}; } #ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS try { - return reinterpret_cast<std::byte*>( - std::to_address(block_traits::allocate(blocks, count))); + return aligned_or_given_back(blocks, block_traits::allocate(blocks, count), count); } catch (const std::bad_alloc&) { - return nullptr; + return {}; } #else - return reinterpret_cast<std::byte*>( - std::to_address(block_traits::allocate(blocks, count))); + return aligned_or_given_back(blocks, block_traits::allocate(blocks, count), count); #endif } } - /** Frees a buffer of `size` bytes that @ref allocate made. */ - void deallocate(std::byte* bytes, std::uint64_t size) noexcept { + /** + 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(bytes, std::align_val_t{16}); + ::operator delete(b.bytes, std::align_val_t{16}); } else { block_allocator blocks(alloc_); - using pointer = block_traits::pointer; - block_traits::deallocate( - blocks, - std::pointer_traits<pointer>::pointer_to(*reinterpret_cast<image_block*>(bytes)), - blocks_of(size)); + 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)); + } } } + /** 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. */ [[nodiscard]] heap& own_heap() const noexcept { return *std::launder(reinterpret_cast<heap*>(data_ + header_bytes)); @@ -656,15 +712,19 @@ class basic_region : public region_bytes { /** Frees its bytes when it owns them, and leaves it empty. */ void release() noexcept { if (owned_ && data_ != nullptr) { - deallocate(data_, size_); + deallocate(held(), size_); } data_ = nullptr; + kept_ = kept_pointer{}; size_ = 0; max_bytes_ = 0; 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. */ diff --git a/include/webcpp/document/storage.hpp b/include/webcpp/document/storage.hpp index 12830fb..46bcefa 100644 --- a/include/webcpp/document/storage.hpp +++ b/include/webcpp/document/storage.hpp @@ -30,6 +30,10 @@ namespace webcpp::document { 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. + @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. diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 8daeb0c..4fcdee6 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -20,6 +20,7 @@ #include <algorithm> #include <array> +#include <concepts> #include <cstddef> #include <cstdint> #include <memory> @@ -27,6 +28,7 @@ #include <new> #include <span> #include <string_view> +#include <type_traits> #include <utility> #include <vector> @@ -94,6 +96,193 @@ class tallying_allocator { allocator_counts* counts_; }; +/** 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) {} + + // The Allocator requirements convert an allocator to its rebound type implicitly. + /** 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 static_cast<T*>(static_cast<void*>(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 = static_cast<std::byte*>(static_cast<void*>(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) {} + + // The Allocator requirements convert an allocator to its rebound type implicitly. + /** 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) { @@ -273,6 +462,88 @@ void any_allocator() { BOOST_TEST_EQ(counts.deallocations, 3U); } +// 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. @@ -367,6 +638,8 @@ int main() { clone_into_resources(); external_carries_allocator(); any_allocator(); + under_aligned_image_is_capacity(); + fancy_pointers_kept(); holding_nothing<wd::pmr::owned>(); holding_nothing<wd::pmr::external>(); #ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS From 5f5f837c83e8674485c13478a54454c4a7fed143 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:26:17 -0300 Subject: [PATCH 11/23] document: Boost.Interprocess's bad_alloc is an allocator's failure too An operation caught only std::bad_alloc inside noexcept functions, so an allocator of Boost.Interprocess, whose bad_alloc derives from std::exception alone, ended the program. detail::unless_allocation_fails, the one place that catches an allocator's failure, takes std::bad_alloc, a type derived from it, and Boost.Interprocess's bad_alloc; the image, a change's staging, the conversions, the writer, the selectors and the parser go through it. The page and the storages state the requirement: what an allocator throws besides those ends the program. Test: a resource that fails with Boost.Interprocess's bad_alloc at every step of the operations that allocate. --- doc/allocation.adoc | 9 +- include/webcpp/document/detail/allocation.hpp | 54 ++++++++ include/webcpp/document/detail/convert.hpp | 22 ++-- include/webcpp/document/detail/heap.hpp | 21 ++-- include/webcpp/document/detail/selector.hpp | 17 +-- include/webcpp/document/detail/tree.hpp | 18 +-- include/webcpp/document/detail/writer.hpp | 21 ++-- include/webcpp/document/parser.hpp | 33 ++--- include/webcpp/document/storage.hpp | 8 +- test/allocator_test.cpp | 115 ++++++++++++++++++ test/counting.hpp | 21 +++- 11 files changed, 248 insertions(+), 91 deletions(-) create mode 100644 include/webcpp/document/detail/allocation.hpp diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 08f7fc5..2b206e0 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -201,9 +201,12 @@ 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`, and the document catches -it where the operation can still return: the operation returns `errc::capacity` and changes -nothing, as for a full image. A change allocates all of its working state before its first change +*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 changes nothing, as for a full image. 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 as it was. A few places have their own way to say it: 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 c037a1d..be63fd2 100644 --- a/include/webcpp/document/detail/convert.hpp +++ b/include/webcpp/document/detail/convert.hpp @@ -53,26 +53,20 @@ namespace webcpp::document::detail { -// Only the allocator's std::bad_alloc can leave `f`: the sizes it asks are of what memory already -// holds, below every container's max_size, so no std::length_error. +// 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 `std::bad_alloc` - 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. + 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)()) { -#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS - try { - return std::forward<F>(f)(); - } catch (const std::bad_alloc&) { - return errc::capacity; - } -#else - return std::forward<F>(f)(); -#endif + 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) diff --git a/include/webcpp/document/detail/heap.hpp b/include/webcpp/document/detail/heap.hpp index 9e2f448..b586462 100644 --- a/include/webcpp/document/detail/heap.hpp +++ b/include/webcpp/document/detail/heap.hpp @@ -19,6 +19,7 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/detail/allocation.hpp> #include <webcpp/document/errors.hpp> #include <boost/assert.hpp> @@ -622,8 +623,9 @@ class basic_region : public region_bytes { /** A new buffer of `size` bytes, 16-aligned and uninitialized, or none when the allocator has - none: its `std::bad_alloc` is caught, with exceptions. A buffer the allocator gives at another - alignment, as one that ignores an over-aligned request may, is given back, and is none too. + 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) { @@ -637,15 +639,12 @@ class basic_region : public region_bytes { if (count > block_traits::max_size(blocks)) { return {}; } -#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS - try { - return aligned_or_given_back(blocks, block_traits::allocate(blocks, count), count); - } catch (const std::bad_alloc&) { - return {}; - } -#else - return aligned_or_given_back(blocks, block_traits::allocate(blocks, count), count); -#endif + return unless_allocation_fails( + [&] { + return aligned_or_given_back(blocks, block_traits::allocate(blocks, count), + count); + }, + [] { return buffer{}; }); } } diff --git a/include/webcpp/document/detail/selector.hpp b/include/webcpp/document/detail/selector.hpp index ff866c3..fbf5947 100644 --- a/include/webcpp/document/detail/selector.hpp +++ b/include/webcpp/document/detail/selector.hpp @@ -19,6 +19,7 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/detail/allocation.hpp> #include <webcpp/document/errors.hpp> #include <webcpp/document/storage.hpp> @@ -103,20 +104,14 @@ class basic_selector { Without exceptions an allocator that fails ends the program, as the allocator itself does. */ - // Only an allocation throws here, and std::bad_alloc 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. + // 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<basic_selector> parse(std::string_view text, const Allocator& alloc = Allocator()) noexcept { -#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS - try { - return read(text, alloc); - } catch (const std::bad_alloc&) { - return errc::capacity; - } -#else - return read(text, alloc); -#endif + 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. */ diff --git a/include/webcpp/document/detail/tree.hpp b/include/webcpp/document/detail/tree.hpp index 520d2f3..f610ed7 100644 --- a/include/webcpp/document/detail/tree.hpp +++ b/include/webcpp/document/detail/tree.hpp @@ -33,6 +33,7 @@ #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> @@ -1647,21 +1648,14 @@ class tree : public tree_view<Traits> { // NOLINTBEGIN(bugprone-exception-escape) /** Runs `stage`, which allocates in the allocator what an operation needs before it changes - anything, and returns its result: with exceptions, the allocator's `std::bad_alloc` is - @ref errc::capacity, nothing having changed; without them, an allocator that fails ends the - program, as it does itself. + 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. */ template <class Stage> static result<void> staging(Stage&& stage) noexcept { -#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS - try { - return std::forward<Stage>(stage)(); - } catch (const std::bad_alloc&) { - return errc::capacity; - } -#else - return std::forward<Stage>(stage)(); -#endif + return unless_allocation_fails(std::forward<Stage>(stage), + [] { return result<void>(errc::capacity); }); } // NOLINTEND(bugprone-exception-escape) diff --git a/include/webcpp/document/detail/writer.hpp b/include/webcpp/document/detail/writer.hpp index 9b20582..89dbbef 100644 --- a/include/webcpp/document/detail/writer.hpp +++ b/include/webcpp/document/detail/writer.hpp @@ -19,6 +19,7 @@ #include <webcpp/document/config.hpp> +#include <webcpp/document/detail/allocation.hpp> #include <webcpp/document/detail/tree.hpp> #include <webcpp/document/errors.hpp> #include <webcpp/document/number.hpp> @@ -78,21 +79,17 @@ concept output = requires(Out& out, std::string_view text) { /** Runs `allocate`, which allocates through the writer's allocator: with exceptions, the allocator's - `std::bad_alloc` is @ref errc::capacity; without, an allocator that fails ends the program, as it - does itself. + 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) { -#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS - try { - std::forward<Allocate>(allocate)(); - } catch (const std::bad_alloc&) { - return errc::capacity; - } -#else - std::forward<Allocate>(allocate)(); -#endif - return {}; + 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. */ diff --git a/include/webcpp/document/parser.hpp b/include/webcpp/document/parser.hpp index c445722..fb3e914 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> @@ -619,20 +620,17 @@ class basic_parser { 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; it is @ref errc::capacity, which fails the parser until @ref reset. + 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) { -#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS - try { - return json_.write_some(more, chunk.data(), chunk.size(), ec); - } catch (const std::bad_alloc&) { - failure_ = errc::capacity; - ec = failure_.error(); - return 0; - } -#else - return json_.write_some(more, chunk.data(), chunk.size(), ec); -#endif + 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. */ @@ -698,15 +696,8 @@ class basic_parser { */ template <class F> result<void> subscribe(std::string_view text, F&& f, bool take) { -#ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS - try { - return add(text, std::forward<F>(f), take); - } catch (const std::bad_alloc&) { - return errc::capacity; - } -#else - return add(text, std::forward<F>(f), take); -#endif + return detail::unless_allocation_fails([&] { return add(text, std::forward<F>(f), take); }, + [] { return result<void>(errc::capacity); }); } /** diff --git a/include/webcpp/document/storage.hpp b/include/webcpp/document/storage.hpp index 46bcefa..6feb1aa 100644 --- a/include/webcpp/document/storage.hpp +++ b/include/webcpp/document/storage.hpp @@ -32,7 +32,9 @@ namespace webcpp::document { 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. + 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. @@ -50,7 +52,9 @@ struct basic_owned { 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: - the parser's, the tree's and the writer's. + the parser's, the tree's and the writer's. 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. diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 4fcdee6..0a8b0f0 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -27,6 +27,7 @@ #include <memory_resource> #include <new> #include <span> +#include <string> #include <string_view> #include <type_traits> #include <utility> @@ -626,6 +627,119 @@ void full_allocator_is_capacity() { 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; and a move +// assignment that cannot copy throws std::bad_alloc. +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, {}, alloc)); }); + capacity_until_it_fits(failing, [&]() -> boost::system::error_code { + wd::pmr::parser p({}, 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(); + }); + 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); + BOOST_TEST(same_image(from, *other)); +} + #endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS } // namespace @@ -645,6 +759,7 @@ int main() { #ifndef WEBCPP_DOCUMENT_NO_EXCEPTIONS copies_select_allocator(); full_allocator_is_capacity(); + interprocess_failure_is_capacity(); #endif return boost::report_errors(); } diff --git a/test/counting.hpp b/test/counting.hpp index 3135a9c..31eae0f 100644 --- a/test/counting.hpp +++ b/test/counting.hpp @@ -13,6 +13,7 @@ #ifndef WEBCPP_TEST_DOCUMENT_COUNTING_HPP #define WEBCPP_TEST_DOCUMENT_COUNTING_HPP +#include <boost/interprocess/exceptions.hpp> #include <boost/throw_exception.hpp> #include <cstddef> @@ -94,13 +95,17 @@ class counting_resource final : public std::pmr::memory_resource { /** A memory resource that hands out what `upstream` gives for its first `budget` allocations and fails - every later one with `std::bad_alloc`, through `boost::throw_exception`: an allocator that runs out - at a chosen step of an operation, for tests built with exceptions. + 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. + + @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. */ -class failing_resource final : public std::pmr::memory_resource { +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. */ - failing_resource(std::pmr::memory_resource* upstream, std::uint64_t budget) noexcept + basic_failing_resource(std::pmr::memory_resource* upstream, std::uint64_t budget) noexcept : upstream_(upstream), budget_(budget) {} /** Allows `budget` more allocations from now. */ @@ -116,7 +121,7 @@ class failing_resource final : public std::pmr::memory_resource { void* do_allocate(std::size_t bytes, std::size_t alignment) override { if (budget_ == 0) { ++refusals_; - boost::throw_exception(std::bad_alloc()); + boost::throw_exception(Failure()); } --budget_; void* memory = upstream_->allocate(bytes, alignment); @@ -139,6 +144,12 @@ class failing_resource final : public std::pmr::memory_resource { 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 From 23d9660fbfc7dd49e07ecda006dbcac2e3f57a47 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:34:33 -0300 Subject: [PATCH 12/23] document: const reads that ask the document's allocator for nothing A standard container allocates nothing in a const member, so several threads may read one at once; a pmr document's const reads raced inside its resource. stringify now keeps its stack in its std::string's allocator and asks the document's allocator for nothing. The writer's stack has room of its own for 16 frames, and the piece stringify_to holds back 4096 bytes of its own, the default chunk's, so that a value nested 16 deep written in chunks of at most 4096 bytes allocates nothing, and a dozen small texts no longer take 4 KiB each of a monotonic arena; past that room they grow in the document's allocator by doubling. allocation.adoc lists the const reads that still allocate there (stringify_to past its room, a missing member of a long key, clone, slice, concat, compact_into), and allocation.adoc and sharing.adoc say that threads using them at once need a synchronized resource. Tests: the const reads ask nothing, a dozen small texts in a 64 KiB arena, and the writer's allocations counted past its own room. --- doc/allocation.adoc | 48 ++++-- doc/sharing.adoc | 7 + doc/stringify.adoc | 18 ++- include/webcpp/document/detail/writer.hpp | 180 +++++++++++++++------- include/webcpp/document/stringify.hpp | 32 ++-- test/allocator_stringify_test.cpp | 133 ++++++++-------- test/allocator_values_test.cpp | 49 ++++++ 7 files changed, 318 insertions(+), 149 deletions(-) diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 2b206e0..197d046 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -13,8 +13,9 @@ 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, and -says which of document's types can be shared between processes. +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 @@ -75,7 +76,8 @@ 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 -writer's stack and the piece it holds back for its sink, the key a handle of a missing member +frames of `stringify_to`'s stack 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 @@ -217,9 +219,9 @@ allocations leaves the document as it was. A few places have their own way to sa of the text; * a handle of a missing member whose key finds no room reads `undefined`, and a change through it is `errc::capacity`; -* what has no result to return the failure in throws `std::bad_alloc`: `stringify`, whose result is - the text, and the move assignment between allocators that differ (<<document-allocators-moves>>); - and the sugar throws its `wd::capacity_error` (<<document-exceptions>>). +* 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>>). *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 @@ -240,7 +242,8 @@ A few allocations are not in the document's allocator, each for a reason of its or to the `finish(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, the `std::string` of + 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 @@ -256,6 +259,31 @@ A few allocations are not in the document's allocator, each for a reason of its 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: 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 @@ -284,8 +312,10 @@ array methods and the containers' views; a parse of a whole text, with selectors `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` does. With exceptions, each operation runs again over a -resource that fails at its first allocation, then its second, and so on until the operation +`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. 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 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 6b6f786..1788731 100644 --- a/doc/stringify.adoc +++ b/doc/stringify.adoc @@ -21,10 +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`, in the standard allocator whatever the document's -(<<document-allocators-outside>>), so its failure is a `std::bad_alloc`: the standard allocator's, -for the text, or, with exceptions, the document's allocator's, for its stack. A program that must -not meet one, or that keeps its text in memory of its own, writes to a sink. +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 @@ -48,10 +48,12 @@ 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` allocates only its stack, which takes the place of recursion, and the chunk it has -not yet handed to the sink, both in the document's allocator (<<document-allocators>>). 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 +`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>>). diff --git a/include/webcpp/document/detail/writer.hpp b/include/webcpp/document/detail/writer.hpp index 89dbbef..89dda43 100644 --- a/include/webcpp/document/detail/writer.hpp +++ b/include/webcpp/document/detail/writer.hpp @@ -10,8 +10,10 @@ 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, is in the document's - allocator, rebound, and is the only thing it allocates besides its output. + 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 @@ -48,15 +50,16 @@ namespace webcpp::document::detail { inline constexpr std::uint32_t max_indent = 10; /** - The frames the writer's stack has room for at first, 16 bytes each: a document nested 16 deep - is written with one allocation of its stack. + 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 room the piece `stringify_to` holds back takes at first when its chunk is larger: a chunk of - the default size or smaller is allocated once, at its size, and a larger one, which may be larger - than the whole text, grows by doubling to what the text needs. + 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; @@ -111,21 +114,22 @@ class string_output { /** 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 `Allocator`, rebound. + 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. */ 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, the - piece it holds back in `alloc`. + 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()))), - pending_(piece_allocator(alloc)) {} + larger_(piece_allocator(alloc)) {} /** Takes `text`, handing the sink each full piece; the sink's failure is returned, and with @@ -134,22 +138,23 @@ class chunked_output { 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()); - if (const result<void> room = make_room(pending_.size() + taken); !room) { + const std::size_t taken = std::min(chunk_ - held_, text.size()); + if (const result<void> room = make_room(held_ + taken); !room) { return room; } - pending_.append(text.substr(0, taken)); + 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; } @@ -160,18 +165,21 @@ 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 the piece held back. */ + /** The allocator of a piece larger than its own room. */ using piece_allocator = rebound<Allocator, char>; + /** The first byte of the piece held back: in its own room, or in the larger one. */ + [[nodiscard]] char* piece() noexcept { return larger_.empty() ? own_.data() : larger_.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>) { @@ -183,22 +191,26 @@ class chunked_output { } /** - Makes room in the piece for `size` bytes, at most the chunk, before it takes them: the smaller - of the chunk and @ref first_piece_room the first time, then twice the room, up to the chunk, - so that each growth is one allocation. + 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) { - if (size <= pending_.capacity()) { + const std::size_t room = larger_.empty() ? own_.size() : larger_.size(); + if (size <= room) { return {}; } - std::size_t room = room_ == 0 ? std::min(chunk_, first_piece_room) : room_; - while (room < size) { - room = room > chunk_ / 2 ? chunk_ : 2 * room; + std::size_t grown = room; + while (grown < size) { + grown = grown > chunk_ / 2 ? chunk_ : 2 * grown; } - if (const result<void> made = allocating([this, room] { pending_.reserve(room); }); !made) { + std::vector<char, piece_allocator> larger(larger_.get_allocator()); + if (const result<void> made = allocating([&larger, grown] { larger.resize(grown); }); + !made) { return made; } - room_ = room; + std::ranges::copy(std::string_view(piece(), held_), larger.data()); + larger_.swap(larger); return {}; } @@ -208,17 +220,85 @@ class chunked_output { /** The largest piece. */ std::size_t chunk_; - /** The room the piece was last given, 0 before it was given any. */ - std::size_t room_ = 0; + /** 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 text not yet handed over, shorter than a chunk. */ - std::basic_string<char, std::char_traits<char>, piece_allocator> pending_; + /** The piece's room once it holds more than its own, empty until then. */ + std::vector<char, piece_allocator> 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. +*/ +template <class Frame, class Allocator> +class frame_stack { +public: + /** An empty stack, its deeper frames in `alloc`. */ + explicit frame_stack(const Allocator& alloc) noexcept + : deeper_(rebound<Allocator, Frame>(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 ? own_[size_ - 1] : deeper_.back(); + } + + /** Removes the innermost frame; the stack holds one. */ + void pop_back() noexcept { + if (size_ > first_frames) { + 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_.size() == deeper_.capacity()) { + const std::size_t room = + deeper_.capacity() == 0 ? first_frames : 2 * deeper_.capacity(); + if (const result<void> made = allocating([this, room] { deeper_.reserve(room); }); + !made) { + return made; + } + } + // There is room: it does not allocate. + deeper_.push_back(f); + ++size_; + return {}; + } + +private: + /** The outermost frames. */ + std::array<Frame, first_frames> own_{}; + + /** The frames past them, innermost last. */ + std::vector<Frame, rebound<Allocator, Frame>> 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, in `Allocator`, rebound: 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. @@ -232,7 +312,7 @@ class json_writer { */ json_writer(const tree_view<Traits>& t, std::uint32_t indent, Out& out, const Allocator& alloc) noexcept - : tree_(&t), indent_(indent), out_(&out), stack_(frame_allocator(alloc)) {} + : 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, @@ -259,9 +339,6 @@ class json_writer { bool first = true; }; - /** The allocator of the stack. */ - using frame_allocator = rebound<Allocator, frame>; - /** Whether strings and keys are stored as UTF-16 code units. */ static constexpr bool utf16_text = std::same_as<typename Traits::string, utf16>; @@ -334,20 +411,14 @@ class json_writer { } /** - Pushes a frame, room made first: @ref first_frames frames, then twice the room each time it is - full; with exceptions, an allocator with no room stops the writing with @ref errc::capacity. + 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 (stack_.size() == stack_.capacity()) { - const std::size_t room = stack_.capacity() == 0 ? first_frames : 2 * stack_.capacity(); - if (const result<void> made = allocating([this, room] { stack_.reserve(room); }); - !made) { - status_ = made; - return false; - } + if (const result<void> pushed = stack_.push(f); !pushed) { + status_ = pushed; + return false; } - // There is room: it does not allocate. - stack_.push_back(f); return true; } @@ -494,7 +565,7 @@ class json_writer { Out* out_; /** The containers the walk is inside, the innermost last. */ - std::vector<frame, frame_allocator> stack_; + frame_stack<frame, Allocator> stack_; /** The first failure, which stops the writing, or success. */ result<void> status_{}; @@ -502,7 +573,8 @@ class json_writer { /** Writes the subtree of `root` as `JSON.stringify(value, null, indent)` does, `indent` clamped to - @ref max_indent, its stack in `alloc`, rebound; 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, class Allocator> requires output<Out> diff --git a/include/webcpp/document/stringify.hpp b/include/webcpp/document/stringify.hpp index 425f477..63f484c 100644 --- a/include/webcpp/document/stringify.hpp +++ b/include/webcpp/document/stringify.hpp @@ -42,9 +42,10 @@ inline constexpr std::uint64_t default_chunk = 4096; the traits' bytes policy. The text is a `std::string`, the program's value in the standard allocator whatever the - document's. The writer's stack, a frame of 16 bytes for each container it is inside, with room - for 16 frames at first and twice the room each time it is full, is in the document's allocator, - rebound, and freed when it returns. + 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. @@ -52,9 +53,8 @@ inline constexpr std::uint64_t default_chunk = 4096; @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. - @throws std::bad_alloc When the standard allocator has no room for the text or, with exceptions, - the document's allocator none for the stack; without exceptions, an allocator that fails ends the - program, as it does itself. + @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> @@ -65,9 +65,9 @@ std::string stringify(basic_const_value<Traits, Storage> v, std::uint32_t indent return text; } detail::string_output out(text); - // 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, t->get_allocator())) { + // 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; @@ -95,12 +95,14 @@ 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. - It allocates only its working state, in the document's allocator, rebound, and frees it when it - returns: its stack, a frame of 16 bytes for each container it is inside, with room for 16 frames - at first and twice the room each time it is full; and the piece it holds back until it is full, - given the smaller of `chunk` and 4096 bytes the first time it holds more than a string's own - small buffer does, then, for a larger chunk, twice its room, up to `chunk`, each time it is full. - What the sink allocates is the program's own. + 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. diff --git a/test/allocator_stringify_test.cpp b/test/allocator_stringify_test.cpp index a931784..f3f6490 100644 --- a/test/allocator_stringify_test.cpp +++ b/test/allocator_stringify_test.cpp @@ -4,16 +4,18 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The writer's working state 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 its stack and the piece it holds back alone, as often as -// their rooms double; stringify calls the global operator new exactly as often as its std::string -// grows; 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, and std::bad_alloc for stringify, while a sink's own std::bad_alloc -// propagates. +// 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> @@ -214,12 +216,13 @@ wd::basic_document<Traits, wd::pmr::external> external_copy(std::vector<block>& } /** - The allocations of the writer's stack to hold `frames` frames at once: room for 16 frames first, - then twice the room each time it is full. + 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 < frames; room = room == 0 ? 16 : 2 * room) { + for (std::uint64_t room = 0; room < deeper; room = room == 0 ? 16 : 2 * room) { ++count; } return count; @@ -227,17 +230,13 @@ constexpr std::uint64_t stack_allocations(std::uint64_t frames) { /** The allocations of the piece `stringify_to` holds back, for a text of `size` bytes written in - pieces smaller than any room: the smaller of `chunk` and 4096 bytes the first time, then twice the - room, up to `chunk`, each time it is full; none while the piece fits the string's own buffer. + 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. */ -std::uint64_t piece_allocations(std::uint64_t chunk, std::uint64_t size) { +constexpr std::uint64_t piece_allocations(std::uint64_t chunk, std::uint64_t size) { const std::uint64_t most = std::min(chunk, size); - if (most <= std::pmr::string().capacity()) { - return 0; - } - std::uint64_t count = 1; - for (std::uint64_t room = std::min<std::uint64_t>(chunk, 4096); room < most; - room = std::min(chunk, 2 * room)) { + std::uint64_t count = 0; + for (std::uint64_t room = 4096; room < most; room = std::min(chunk, 2 * room)) { ++count; } return count; @@ -363,10 +362,11 @@ void allocates_its_stack_and_piece(const Document& doc, arena& docs, arena& outs BOOST_TEST_EQ(docs.resource().bytes_in_use(), held); } -// The writer allocates, in the document's resource, its stack and the piece it holds back 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. +// 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>(); @@ -390,7 +390,7 @@ void the_writer_allocates_its_stack_and_piece() { allocates_its_stack_and_piece(doc, docs, outs, expected, deep_frames, 4096); } { - // The run of 10,000 bytes reaches the sink without growing the piece past its first room. + // 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); @@ -405,7 +405,7 @@ void the_writer_allocates_its_stack_and_piece() { /** 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, and the arena makes the allocations of a stack of `frames` frames, and takes them back. + text does, and as the stack of `frames` frames needs; 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, @@ -442,17 +442,18 @@ void calls_new_for_its_string_alone(const wd::basic_document<Traits>& source, st 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); - BOOST_TEST_EQ(deletes, reference_deletes); + BOOST_TEST_EQ(news, reference_news + stack_allocations(frames)); + BOOST_TEST_EQ(deletes, reference_deletes + stack_allocations(frames)); BOOST_TEST(text == expected); } - BOOST_TEST_EQ(a.resource().allocations() - made, stack_allocations(frames)); + 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: it calls the -// global operator new for that string alone, its stack in the document's resource. +// 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}; @@ -461,6 +462,27 @@ void stringify_calls_new_for_its_string_alone() { 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 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().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().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. @@ -540,33 +562,17 @@ void capacity_at_every_step(const Document& doc, const Source& source, } /** - stringify of `doc`, whose working state `failing` holds, with every budget from 0 until it - succeeds: each step that fails throws std::bad_alloc, the document and the resource as they were, - and as many steps fail as the stack of `frames` frames allocates. + 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 bad_alloc_at_every_step(const Document& doc, const Source& source, - webcpp::test::failing_resource& failing, std::uint32_t indent, - std::uint64_t frames) { - const std::string expected = wd::stringify(source, indent); - const std::uint64_t held = failing.bytes_in_use(); - std::uint64_t budget = 0; - for (;; ++budget) { - failing.allow(budget); - bool thrown = false; - try { - const std::string text = wd::stringify(doc, indent); - BOOST_TEST(text == expected); - } catch (const std::bad_alloc&) { - thrown = true; - } - BOOST_TEST(same_image(doc, source)); - BOOST_TEST_EQ(failing.bytes_in_use(), held); - if (!thrown || !BOOST_TEST_LT(budget, stack_allocations(frames))) { - break; - } - } - BOOST_TEST_EQ(budget, stack_allocations(frames)); +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 @@ -600,9 +606,9 @@ void a_sinks_bad_alloc_propagates() { 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 stringify throw std::bad_alloc, and changes nothing: 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. +// 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); { @@ -613,7 +619,7 @@ void a_resource_with_no_room() { capacity_at_every_step(doc, source, failing, 0, chunk, stack_allocations(deep_frames) + piece_allocations(chunk, size)); } - bad_alloc_at_every_step(doc, source, failing, 0, deep_frames); + stringify_asks_nothing(doc, source, failing, 0); failing.allow(unlimited); } { @@ -639,7 +645,7 @@ void a_resource_with_no_room() { const auto doc = owned_copy(source, &failing); capacity_at_every_step(doc, source, failing, 2, 4096, stack_allocations(sample_frames) + piece_allocations(4096, size)); - bad_alloc_at_every_step(doc, source, failing, 2, sample_frames); + stringify_asks_nothing(doc, source, failing, 2); failing.allow(unlimited); } BOOST_TEST_EQ(failing.bytes_in_use(), 0U); @@ -653,6 +659,7 @@ 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(); diff --git a/test/allocator_values_test.cpp b/test/allocator_values_test.cpp index a919abe..5ae126b 100644 --- a/test/allocator_values_test.cpp +++ b/test/allocator_values_test.cpp @@ -395,6 +395,53 @@ void view_members() { 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() { @@ -671,6 +718,8 @@ int main() { 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(); nothing_reports_value_first<wd::default_traits>(); From a7bdc888fc1b4a7399f13a815c57010dc0caf04c Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:39:02 -0300 Subject: [PATCH 13/23] document: a move assignment that never copies is noexcept, and allocators that rebind explicitly pmr::external's move assignment never copies, its image being no allocator's, and is now noexcept with every external storage and every allocator that propagates or is always equal; static_asserts pin it. The Allocator requirements ask only that a rebound allocator be constructed from another, A a(b): a prepared value's buffers and the array methods' entries converted the document's allocator implicitly, and now construct their own. Tests: an allocator whose rebinding constructor is explicit, stateful and neither standard nor polymorphic, through the parser whole and in chunks with a selector, the handles, Object.assign, the array methods, compaction, a copy and stringify_to past its own room, under both traits; an allocator that propagates on a move assignment; and one always equal though stateful. The tests' aligned operator new now takes any power of two, as the standard's does, which an allocator of char asks. --- doc/allocation.adoc | 3 +- include/webcpp/document/detail/convert.hpp | 7 +- include/webcpp/document/detail/heap.hpp | 5 +- .../webcpp/document/detail/value_array.hpp | 5 +- include/webcpp/document/document.hpp | 11 +- test/allocator_test.cpp | 207 +++++++++++++++++- test/counting.cpp | 8 +- 7 files changed, 230 insertions(+), 16 deletions(-) diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 197d046..8f49395 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -180,7 +180,8 @@ A document is allocator-aware as the standard containers are: 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, the move assignment is `noexcept`. + 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, diff --git a/include/webcpp/document/detail/convert.hpp b/include/webcpp/document/detail/convert.hpp index be63fd2..bcbee90 100644 --- a/include/webcpp/document/detail/convert.hpp +++ b/include/webcpp/document/detail/convert.hpp @@ -126,7 +126,12 @@ class prepared { /** A value holding `null`, its buffers in `alloc`. */ explicit prepared(const Allocator& alloc) noexcept - : alloc_(alloc), utf8_(alloc), utf16_(alloc), bytes_(alloc), entries_(alloc) {} + // Each list's allocator is constructed from `alloc`, which need not convert to it. + : alloc_(alloc), + utf8_(rebound<Allocator, buffer<char>>(alloc)), + utf16_(rebound<Allocator, buffer<char16_t>>(alloc)), + bytes_(rebound<Allocator, buffer<std::byte>>(alloc)), + entries_(rebound<Allocator, buffer<literal_entry<Traits>>>(alloc)) {} /** A prepared value is not copied: its item points into it. */ prepared(const prepared&) = delete; diff --git a/include/webcpp/document/detail/heap.hpp b/include/webcpp/document/detail/heap.hpp index b586462..76cd9b9 100644 --- a/include/webcpp/document/detail/heap.hpp +++ b/include/webcpp/document/detail/heap.hpp @@ -116,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) diff --git a/include/webcpp/document/detail/value_array.hpp b/include/webcpp/document/detail/value_array.hpp index f3c303f..669ba61 100644 --- a/include/webcpp/document/detail/value_array.hpp +++ b/include/webcpp/document/detail/value_array.hpp @@ -204,7 +204,7 @@ result<basic_document<Traits, basic_owned<Allocator>>> splice_elements( } else { removed = bad_alloc_as_capacity([&] { std::vector<literal_entry<Traits>, rebound<Allocator, literal_entry<Traits>>> entries( - t.get_allocator()); + 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()); @@ -357,7 +357,8 @@ result<basic_document<Traits, detail::owned_of<Storage>>> basic_const_value<Trai return detail::bad_alloc_as_capacity([&] { std::vector<detail::literal_entry<Traits>, detail::rebound<allocator_type, detail::literal_entry<Traits>>> - entries(t.get_allocator()); + 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); diff --git a/include/webcpp/document/document.hpp b/include/webcpp/document/document.hpp index 3e09989..57a3976 100644 --- a/include/webcpp/document/document.hpp +++ b/include/webcpp/document/document.hpp @@ -293,14 +293,15 @@ class basic_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, for which it is - `noexcept`. + 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. */ - // It is noexcept only for allocators that propagate or are always equal, which never take - // the copy, the one path that throws. + // 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) { + basic_document& operator=(basic_document&& other) noexcept(moves_cheaply || + detail::external_storage<Storage>) { if (this == &other) { return *this; } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 0a8b0f0..b0f63ed 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -66,7 +66,9 @@ class tallying_allocator { /** An allocator that counts in `counts`, which outlives it. */ explicit tallying_allocator(allocator_counts* counts) noexcept : counts_(counts) {} - // The Allocator requirements convert an allocator to its rebound type implicitly. + // 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) @@ -97,6 +99,85 @@ class tallying_allocator { 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. */ @@ -123,7 +204,7 @@ class aligning_allocator { /** An allocator that does as `control` says and counts there; `control` outlives it. */ explicit aligning_allocator(alignment_control* control) noexcept : control_(control) {} - // The Allocator requirements convert an allocator to its rebound type implicitly. + // 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) @@ -243,7 +324,7 @@ class tagging_allocator { /** An allocator that counts in `counts`, which outlives it. */ explicit tagging_allocator(tag_counts* counts) noexcept : counts_(counts) {} - // The Allocator requirements convert an allocator to its rebound type implicitly. + // 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) @@ -463,6 +544,122 @@ void any_allocator() { 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, {}, alloc); + require(BOOST_TEST(whole.has_value())); + parser p({}, 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()); + } + 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()); + auto sliced = d["list"].slice(1); + auto joined = d["list"].concat(d["list"], text); + auto popped = d["list"].pop(); + 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 @@ -752,6 +949,10 @@ int main() { 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>(); diff --git a/test/counting.cpp b/test/counting.cpp index 6a1c133..94552ad 100644 --- a/test/counting.cpp +++ b/test/counting.cpp @@ -13,6 +13,7 @@ #include <boost/config.hpp> +#include <algorithm> #include <cstddef> #include <cstdint> #include <cstdlib> @@ -37,10 +38,13 @@ void* plain_memory(std::size_t size) noexcept { } // 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. +// 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 auto align = static_cast<std::size_t>(alignment); + 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); From f1de52875db927a36c15574856286b7dc783b4a3 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:40:47 -0300 Subject: [PATCH 14/23] document: set refuses a change it cannot make before it prepares the value A handle of nothing prepared the value in the global heap, and a handle of a document that holds nothing, or of a place gone since, in the document's allocator, before set returned errc::type, against the page's promise that such a document allocates nothing. set now asks first whether the place can take a change (a document with an image, a node still there, a missing member of an object with a UTF-8 key it could hold, a missing element of an array) and refuses with errc::type, or errc::capacity for a key it could not hold, before anything is prepared: the refusal comes before the value's own errors and allocates nothing. Tests: every kind of value through four places that cannot take it, and a document that holds nothing, with no allocation anywhere. --- include/webcpp/document/value.hpp | 56 ++++++++++++++++++++++++++----- test/allocator_test.cpp | 5 +++ test/allocator_values_test.cpp | 54 ++++++++++++++++++----------- 3 files changed, 87 insertions(+), 28 deletions(-) diff --git a/include/webcpp/document/value.hpp b/include/webcpp/document/value.hpp index 4074921..6caa68d 100644 --- a/include/webcpp/document/value.hpp +++ b/include/webcpp/document/value.hpp @@ -1074,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. @@ -1103,14 +1105,10 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, copy.from_id = n->id; return store(copy); } else { - // A handle of nothing has no document whose allocator could hold the prepared value: - // the value is prepared in the standard allocator, so that its own error comes first. - if (this->doc_ == nullptr) { - detail::prepared<Traits> p; - if (const auto made = detail::prepare(v, p); !made.has_value()) { - return made; - } - return errc::type; + // 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()) { @@ -1320,6 +1318,46 @@ class WEBCPP_DOCUMENT_NO_DANGLING basic_value : public basic_const_value<Traits, return std::pair(detail::access::tree_of(v), detail::access::node_of(v)); } + /** + 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 { auto* t = writable_tree(); diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index b0f63ed..77c0fe1 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -750,6 +750,9 @@ 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()); @@ -757,6 +760,8 @@ void holding_nothing() { BOOST_TEST(none.image().empty()); BOOST_TEST_EQ(none.capacity(), 0U); BOOST_TEST(none.root().set(1).error() == wd::errc::type); + BOOST_TEST(none.root().set(members).error() == wd::errc::type); + BOOST_TEST(none.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); diff --git a/test/allocator_values_test.cpp b/test/allocator_values_test.cpp index 5ae126b..8de8866 100644 --- a/test/allocator_values_test.cpp +++ b/test/allocator_values_test.cpp @@ -8,10 +8,10 @@ // 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 handle of nothing reports -// its value's own error first; 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 fail. +// 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 fail. #include <webcpp/document.hpp> @@ -518,27 +518,43 @@ void external_document() { BOOST_TEST_EQ(a.resource().bytes_in_use(), 0U); } -// A handle of nothing reports a value's own error before its place's errc::type, as when the -// value is prepared first: its value is prepared in the standard allocator, since there is no -// document whose allocator could hold it, so nothing here is counted. +// 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 nothing_reports_value_first() { +void refused_first() { arena a(mebibyte); const sample_values f; - auto d = in_arena<Traits>(a, R"({"a":1})"); + auto d = in_arena<Traits>(a, R"({"a":1,"o":{},"l":[],"gone":2})"); auto nothing = d["missing"]["x"]; + auto member = d["o"]["new"]; + auto element = d["l"][std::uint64_t{3}]; + 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()); - BOOST_TEST(nothing.set(std::numeric_limits<boost::decimal::decimal64_t>::infinity()).error() == - wd::errc::range); const wd::date_ms late{std::chrono::milliseconds{wd::detail::date_limit_ms + 1}}; - BOOST_TEST(nothing.set(late).error() == wd::errc::range); - BOOST_TEST(nothing.set(std::string_view("\xFF")).error() == wd::errc::type); - BOOST_TEST(nothing.set(1).error() == wd::errc::type); - BOOST_TEST(nothing.set(f.text).error() == wd::errc::type); - BOOST_TEST(nothing.set(f.members).error() == wd::errc::type); + 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); - same_value(d, parsed<Traits>(R"({"a":1})")); + 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 @@ -722,8 +738,8 @@ int main() { const_reads_ask_nothing<wd::js_traits>(); bounds_by_utf16_units(); external_document(); - nothing_reports_value_first<wd::default_traits>(); - nothing_reports_value_first<wd::js_traits>(); + 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>(); From 9be99611e090e572922b613d03e387bda938c4cb Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:42:00 -0300 Subject: [PATCH 15/23] document: the allocation tests catch a leak on a failure path, under every key order fails_softly now requires each failure to be the resource's one refusal and every byte the operation took before it given back, besides the document's content as it was, so that a leak on a path of failure fails. The tree's allocation tests ran under JavaScript's key order alone; they run under sorted and insertion_order keys too. --- test/allocator_tree_test.cpp | 38 +++++++++++++++++++++++++++++++++- test/allocator_values_test.cpp | 11 ++++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/test/allocator_tree_test.cpp b/test/allocator_tree_test.cpp index 128ee5f..37eb45f 100644 --- a/test/allocator_tree_test.cpp +++ b/test/allocator_tree_test.cpp @@ -56,6 +56,18 @@ 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. */ constexpr std::uint64_t max_bytes = std::uint64_t{64} << 20U; @@ -451,7 +463,17 @@ void tree_operations_in_resource() { require(BOOST_TEST(assigned != nullptr)); BOOST_TEST_EQ(assigned->id, first); BOOST_TEST_EQ(assigned->template load<std::int64_t>(), 3); - BOOST_TEST_EQ(f.t.next_sibling(*assigned)->id, x->id); + 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); @@ -819,9 +841,19 @@ int main() { 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, @@ -853,6 +885,10 @@ int main() { 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 index 8de8866..057ce59 100644 --- a/test/allocator_values_test.cpp +++ b/test/allocator_values_test.cpp @@ -564,8 +564,10 @@ 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 with - the document as it was. Returns how many budgets failed. + `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) { @@ -579,14 +581,19 @@ std::uint64_t fails_softly(const std::string& json, Op op) { 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; } From 4ee1ebd692efa48ed42fa52fdb6622ef76555b7b Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:47:39 -0300 Subject: [PATCH 16/23] document: a value's buffers allocated when it needs them, and kept to reuse Reviving bytes, every string allocated a buffer sized for base64 before the text was read, and every object read as bytes reserved its count before its shape was checked: the text is now read first, without allocating, and the buffer allocated at the bytes' exact size, and an object's shape is checked before its buffer, so that text that is not base64 and objects of another shape allocate nothing. A prepared value's clear() freed its buffers, against the parser's keeping it to reuse them: it now keeps them, with their room, for the values prepared next, so that the parser's strings transcoded to UTF-16 allocate as often as the longest grows. Tests: parses that revive bytes allocate as often as parses that do not, and a prepared value's strings and bytes allocate once. --- include/webcpp/document/detail/convert.hpp | 185 ++++++++++++++------- include/webcpp/document/traits.hpp | 11 +- test/allocator_parse_test.cpp | 61 +++++++ 3 files changed, 197 insertions(+), 60 deletions(-) diff --git a/include/webcpp/document/detail/convert.hpp b/include/webcpp/document/detail/convert.hpp index bcbee90..3cdf0cc 100644 --- a/include/webcpp/document/detail/convert.hpp +++ b/include/webcpp/document/detail/convert.hpp @@ -126,12 +126,8 @@ class prepared { /** A value holding `null`, its buffers in `alloc`. */ explicit prepared(const Allocator& alloc) noexcept - // Each list's allocator is constructed from `alloc`, which need not convert to it. - : alloc_(alloc), - utf8_(rebound<Allocator, buffer<char>>(alloc)), - utf16_(rebound<Allocator, buffer<char16_t>>(alloc)), - bytes_(rebound<Allocator, buffer<std::byte>>(alloc)), - entries_(rebound<Allocator, buffer<literal_entry<Traits>>>(alloc)) {} + // 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; @@ -190,25 +186,69 @@ class prepared { template <class T> using buffer = std::vector<T, rebound<Allocator, T>>; - /** A list of buffers of `T`, each in the allocator. */ + /** + 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> - using buffers = std::vector<buffer<T>, rebound<Allocator, buffer<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; - /** A new buffer of `size` values of `T` in the allocator, added to `list`. */ + /** 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>& list, std::size_t size) { + 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. - return list.emplace_back(buffer<T>(size, rebound<Allocator, T>(alloc_))); + buffer<T>& made = b.list.emplace_back(buffer<T>(size, rebound<Allocator, T>(alloc_))); + ++b.used; + return made; } - /** Holds `null` again, and owns nothing. */ + /** 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. */ @@ -478,13 +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<bytes_in<Allocator>> decoded = decode(text, owner.alloc_); - decoded.has_value()) { - const auto& 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)); } } @@ -663,25 +704,47 @@ struct converter { return {}; } - /** Room for the bytes of base64 text of `size` characters, in `alloc`. */ - template <class A> - static bytes_in<A> room_for_base64(std::size_t size, const A& alloc) { - // Four characters make at most three bytes, and the last group of base64url's fewer. - return bytes_in<A>(((size / 4) * 3) + 3, rebound<A, std::byte>(alloc)); + /** + 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; + } + 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`: @ref errc::type when - it is not. + 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> - static result<bytes_in<A>> decode(std::string_view text, const A& alloc) { - bytes_in<A> out = room_for_base64(text.size(), alloc); - const result<std::uint64_t> size = read_base64(text, out.data(), url); + 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 errc::type; + return size.error(); } - out.resize(static_cast<std::size_t>(size.unsafe_value())); + bytes_in<A> out(static_cast<std::size_t>(size.unsafe_value()), + rebound<A, std::byte>(alloc)); + decode_into(text, out.data()); return out; } @@ -691,17 +754,16 @@ struct converter { } /** - UTF-16 base64 text, by the policy, decoded into a buffer of `alloc` a block at a time, made - ASCII on the stack, so that no copy of the text is allocated: @ref errc::type when it is not. + 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. */ - template <class A> - static result<bytes_in<A>> decode(std::u16string_view units, const A& alloc) { - bytes_in<A> out = room_for_base64(units.size(), alloc); + 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::size_t written = 0; + std::uint64_t written = 0; do { const std::size_t count = std::min(units.size() - done, ascii_block); std::ranges::transform(units.substr(done, count), chars.begin(), ascii_of); @@ -710,14 +772,14 @@ struct converter { return errc::type; } const result<std::uint64_t> size = - read_base64(std::string_view(chars.data(), count), out.data() + written, url); + read_base64(std::string_view(chars.data(), count), + out == nullptr ? nullptr : out + written, url); if (!size.has_value()) { return errc::type; } - written += static_cast<std::size_t>(size.unsafe_value()); + written += size.unsafe_value(); } while (done != units.size()); - out.resize(written); - return out; + return written; } /** Reads a node of a kind @ref read reads, as `T`. */ @@ -990,32 +1052,39 @@ struct converter { /** 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. + 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. */ 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); - bytes_in<A> out{rebound<A, std::byte>(alloc)}; - 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 { 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/test/allocator_parse_test.cpp b/test/allocator_parse_test.cpp index 1d67a8c..173ef93 100644 --- a/test/allocator_parse_test.cpp +++ b/test/allocator_parse_test.cpp @@ -759,6 +759,66 @@ void running_out() { } // namespace +/** 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); +} + int main() { const std::vector<sample> texts = samples(); for (const sample& s : texts) { @@ -777,6 +837,7 @@ int main() { 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 From 1bce979758cb7dc68aed853bd1a319f21d220a64 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:52:17 -0300 Subject: [PATCH 17/23] document: the last chunk is finish_with's, finish as it was published finish(std::string_view last) overloaded the published finish(), so that &basic_parser::finish no longer compiled without a cast. The member that takes the last chunk, or the whole text, is now finish_with, which parse and parse_into call, and finish() is untouched; a static_assert pins its address. The changelog names the one source break of the storages, a forward declaration of owned or external, which are aliases now, and the new member. --- doc/allocation.adoc | 2 +- doc/changelog.adoc | 8 +++++-- doc/parsing.adoc | 8 +++---- include/webcpp/document/parse.hpp | 10 ++++---- include/webcpp/document/parser.hpp | 8 +++---- test/allocator_parse_test.cpp | 38 +++++++++++++++++------------- 6 files changed, 42 insertions(+), 32 deletions(-) diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 8f49395..975759b 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -240,7 +240,7 @@ A few allocations are not in the document's allocator, each for a reason of its 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(last)` of a parser that was given no text before, never suspends, and + 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 diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 23e9faf..0a95f83 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,10 +16,14 @@ 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 returns - `errc::capacity` and changes nothing. +* 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[] diff --git a/doc/parsing.adoc b/doc/parsing.adoc index f660dc8..d4e73a0 100644 --- a/doc/parsing.adoc +++ b/doc/parsing.adoc @@ -73,9 +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; `finish(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: +`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] ---- @@ -93,7 +93,7 @@ another text, its selectors kept (<<document-selectors>>). The parser's working 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(last)`, as `wd::parse` gives it, never needs one (<<document-allocators-outside>>). +to `finish_with(last)`, as `wd::parse` gives it, never needs one (<<document-allocators-outside>>). [#document-parsing-errors] === Errors and offsets diff --git a/include/webcpp/document/parse.hpp b/include/webcpp/document/parse.hpp index 5b382b1..075f23a 100644 --- a/include/webcpp/document/parse.hpp +++ b/include/webcpp/document/parse.hpp @@ -81,7 +81,7 @@ template <class Traits = default_traits> result<basic_document<Traits, owned>> parse(std::string_view text, const parse_options& o = {}) noexcept { basic_parser<Traits, owned> p(o); - return p.finish(text); + return p.finish_with(text); } /** @@ -109,7 +109,7 @@ result<basic_document<Traits, basic_owned<Allocator>>> parse(std::string_view te const parse_options& o, const Allocator& alloc) noexcept { basic_parser<Traits, basic_owned<Allocator>> p(o, alloc); - return p.finish(text); + return p.finish_with(text); } /** @@ -129,7 +129,7 @@ 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); - return p.finish(text); + return p.finish_with(text); } /** @@ -157,7 +157,7 @@ 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(text); + return p.finish_with(text); } /** @@ -182,7 +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); - result<basic_document<Traits, owned>> made = p.finish(text); + 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 fb3e914..d4f57b4 100644 --- a/include/webcpp/document/parser.hpp +++ b/include/webcpp/document/parser.hpp @@ -345,7 +345,7 @@ struct subscription { 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 never suspends Boost.JSON's + 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 @@ -447,11 +447,11 @@ 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() { return finish(std::string_view()); } + 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 `finish()` return. + `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 @@ -462,7 +462,7 @@ 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(std::string_view last) { + result<basic_document<Traits, Storage>> finish_with(std::string_view last) { if (!failure_.has_value()) { return failed().error(); } diff --git a/test/allocator_parse_test.cpp b/test/allocator_parse_test.cpp index 173ef93..6f11eaf 100644 --- a/test/allocator_parse_test.cpp +++ b/test/allocator_parse_test.cpp @@ -8,7 +8,7 @@ // 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(text) is write(text) then finish(), its errors, offsets and causes +// 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. @@ -29,6 +29,7 @@ #include <memory_resource> #include <string> #include <string_view> +#include <type_traits> #include <vector> namespace wd = webcpp::document; @@ -372,14 +373,14 @@ tally selected_tally() { tally t; wd::basic_parser<Traits> p; require(BOOST_TEST(all_added(subscribe(p, t, s)))); - require(BOOST_TEST(p.finish(s.text).has_value())); + 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(text): registration, +// 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> @@ -389,7 +390,7 @@ void selectors_call_no_global_new() { 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(s.text); + const auto reference = reference_parser.finish_with(s.text); require(BOOST_TEST(reference.has_value())); arena a(16 * mebibyte); @@ -400,7 +401,7 @@ void selectors_call_no_global_new() { { pmr_parser<Traits> p({}, a.allocator()); BOOST_TEST(all_added(subscribe(p, t, s))); - const auto made = p.finish(s.text); + const auto made = p.finish_with(s.text); BOOST_TEST(made.has_value() && same_image(*made, *reference)); } news = global.news(); @@ -480,7 +481,7 @@ void chunks_call_only_the_stack(std::string_view text, bool selectors) { if (selectors) { require(BOOST_TEST(all_added(subscribe(reference_parser, reference_tally, s)))); } - const auto reference = reference_parser.finish(text); + 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); @@ -526,13 +527,13 @@ void the_stack_rule() { } /** - Checks that `finish(text)` gives what `write(text)` then `finish()` give: the same document or + 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(text); + 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() @@ -552,9 +553,9 @@ void finish_is_write_then_finish(std::string_view text, const wd::parse_options& } } -// finish(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. +// 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()) { @@ -676,7 +677,7 @@ void refused_selectors_were_not_added(Parser& p, webcpp::test::failing_resource& const std::array<bool, selector_count>& added, const tally& t, const tally& expected, std::string_view text) { failing.allow(plenty); - BOOST_TEST(p.finish(text).has_value()); + 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); } @@ -694,9 +695,9 @@ void a_parser_that_ran_out_stays_failed(Parser& p, webcpp::test::failing_resourc BOOST_TEST_GT(failing.refusals(), 0U); failing.allow(plenty); BOOST_TEST(p.write(" ").error() == wd::errc::capacity); - BOOST_TEST(p.finish("[1]").error() == wd::errc::capacity); + BOOST_TEST(p.finish_with("[1]").error() == wd::errc::capacity); p.reset(); - BOOST_TEST(p.finish("[1]").has_value()); + BOOST_TEST(p.finish_with("[1]").has_value()); } // A parser whose allocator runs out while it registers its selectors returns errc::capacity and @@ -709,7 +710,7 @@ void parser_runs_out(bool in_chunks) { 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(s.text); + 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) { @@ -723,7 +724,7 @@ void parser_runs_out(bool in_chunks) { ++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(s.text).has_value()) { + : p.finish_with(s.text).has_value()) { parsed = true; BOOST_TEST(t == expected); BOOST_TEST_EQ(failing.refusals(), 0U); @@ -759,6 +760,11 @@ void running_out() { } // namespace +// 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) { From da46473f9900f738c9cbb9f61bcd204fadc54e6d Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 02:54:00 -0300 Subject: [PATCH 18/23] document: the page and the comments say exactly what an erasure and a failure leave An erasure cannot run out of room, but it still returns errc::type for what is no object or no array and errc::range for elements past the end. An operation that fails for want of room leaves the document's content as it was, while the bytes of the heap's free space may differ and a failed parse_into leaves its buffer formatted. The storages list the working state their allocator holds, the parser's Storage names the storages of any allocator, a member's erasure lowers its object's key count, and two code spans that Asciidoctor rendered with a typographic apostrophe are reworded. AGENTS.md states the allocator's rules as they are now. --- AGENTS.md | 11 +++++-- doc/allocation.adoc | 38 ++++++++++++++----------- doc/errors.adoc | 10 +++---- include/webcpp/document/detail/tree.hpp | 9 +++--- include/webcpp/document/parser.hpp | 4 ++- include/webcpp/document/storage.hpp | 9 ++++-- test/allocator_values_test.cpp | 2 +- 7 files changed, 49 insertions(+), 34 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2892bb9..c544b15 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,9 +33,14 @@ specific to document. (`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`), and is made before the operation's first change, so that with - exceptions a `std::bad_alloc` is `errc::capacity` with nothing changed; an erasure, a lookup and - `==` allocate nothing. The `allocator*` tests count the global `operator new` and fail an + 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 diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 975759b..8911755 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -61,10 +61,10 @@ 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 -`std::max_align_t`'s alignment 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 +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 @@ -76,13 +76,15 @@ 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 `stringify_to`'s stack 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 +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 fail. +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 @@ -204,14 +206,16 @@ 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 changes nothing, as for a full image. An +*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 as it was. A few places have their own way to say it: +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 diff --git a/doc/errors.adoc b/doc/errors.adoc index f2eb161..3087119 100644 --- a/doc/errors.adoc +++ b/doc/errors.adoc @@ -79,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] ---- @@ -91,10 +91,10 @@ include::{examples}/document_no_exceptions.cpp[tag=compare,indent=0] include::{examples}/document_no_exceptions.expected[lines=9] ---- -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 operation changes nothing; without them, an +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` diff --git a/include/webcpp/document/detail/tree.hpp b/include/webcpp/document/detail/tree.hpp index f610ed7..efe401b 100644 --- a/include/webcpp/document/detail/tree.hpp +++ b/include/webcpp/document/detail/tree.hpp @@ -23,9 +23,10 @@ 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 fail. 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. + 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 @@ -2109,7 +2110,7 @@ class tree : public tree_view<Traits> { set_scalar(array, s); } - /** Erases the member `id` of the object `o` and its subtree, the key count kept. */ + /** 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; diff --git a/include/webcpp/document/parser.hpp b/include/webcpp/document/parser.hpp index d4f57b4..a1734b4 100644 --- a/include/webcpp/document/parser.hpp +++ b/include/webcpp/document/parser.hpp @@ -352,7 +352,9 @@ struct subscription { 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> diff --git a/include/webcpp/document/storage.hpp b/include/webcpp/document/storage.hpp index 6feb1aa..4a4a4b7 100644 --- a/include/webcpp/document/storage.hpp +++ b/include/webcpp/document/storage.hpp @@ -26,7 +26,10 @@ namespace webcpp::document { 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 - parser's, the tree's and the writer's working state. A move takes the allocator with the image, + 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. @@ -51,8 +54,8 @@ struct basic_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. - The image never grows, and `Allocator` holds only the working state of the document's operations: - the parser's, the tree's and the writer's. With exceptions, an allocator that has no room throws + 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. diff --git a/test/allocator_values_test.cpp b/test/allocator_values_test.cpp index 057ce59..9fe87e1 100644 --- a/test/allocator_values_test.cpp +++ b/test/allocator_values_test.cpp @@ -11,7 +11,7 @@ // 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 fail. +// it was, while an erasure asks the allocator for nothing and cannot run out of room. #include <webcpp/document.hpp> From e95b40966ee453913d458cbaf6656ab87ee2a1c7 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 03:22:34 -0300 Subject: [PATCH 19/23] document: the lint's findings in the allocation work and in quote's Doc Comment clang-tidy, with exceptions and without, found a braced return without its trailing comma in the region, a string_view::substr that the analysis sees throw inside a noexcept read of base64, and in the tests handles and results that can be const, casts through void, a function too complex, helpers outside the anonymous namespace, single characters appended as strings, a test helper unused without exceptions, and a source read after a move that threw by design. The fluent-chain rule found calls three deep in the allocation tests. The Doc Comments rule found a colon after @ref quote, which MrDocs drops. --- include/webcpp/document/detail/convert.hpp | 3 +- include/webcpp/document/detail/heap.hpp | 6 ++- include/webcpp/document/quote.hpp | 2 +- test/allocator_parse_test.cpp | 8 ++-- test/allocator_test.cpp | 46 ++++++++++++++-------- test/allocator_tree_test.cpp | 40 +++++++++---------- test/allocator_values_test.cpp | 8 ++-- 7 files changed, 64 insertions(+), 49 deletions(-) diff --git a/include/webcpp/document/detail/convert.hpp b/include/webcpp/document/detail/convert.hpp index 3cdf0cc..c840700 100644 --- a/include/webcpp/document/detail/convert.hpp +++ b/include/webcpp/document/detail/convert.hpp @@ -766,7 +766,8 @@ struct converter { std::uint64_t written = 0; do { const std::size_t count = std::min(units.size() - done, ascii_block); - std::ranges::transform(units.substr(done, count), chars.begin(), ascii_of); + 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; diff --git a/include/webcpp/document/detail/heap.hpp b/include/webcpp/document/detail/heap.hpp index 76cd9b9..11ed0f2 100644 --- a/include/webcpp/document/detail/heap.hpp +++ b/include/webcpp/document/detail/heap.hpp @@ -632,8 +632,10 @@ class basic_region : public region_bytes { if constexpr (standard) { // std::allocator allocates with the global operator new: its form that returns null // keeps a failure a value without exceptions too. - return {static_cast<std::byte*>(::operator new(static_cast<std::size_t>(size), - std::align_val_t{16}, std::nothrow))}; + 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); diff --git a/include/webcpp/document/quote.hpp b/include/webcpp/document/quote.hpp index 6a82d80..fb68c3e 100644 --- a/include/webcpp/document/quote.hpp +++ b/include/webcpp/document/quote.hpp @@ -26,7 +26,7 @@ namespace webcpp::document { namespace detail { -/** An output of @ref quote: a string, appended to by `append(data, size)`. */ +/** 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); }; diff --git a/test/allocator_parse_test.cpp b/test/allocator_parse_test.cpp index 6f11eaf..6c27b15 100644 --- a/test/allocator_parse_test.cpp +++ b/test/allocator_parse_test.cpp @@ -758,8 +758,6 @@ void running_out() { #endif // WEBCPP_DOCUMENT_NO_EXCEPTIONS -} // namespace - // 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( @@ -788,8 +786,8 @@ void allocations_when_needed() { strings += std::string(i == 0 ? "" : ",") + R"("not base64, )" + std::string(i, 'x') + '"'; objects += std::string(i == 0 ? "" : ",") + R"({"a":1,"0":2})"; } - strings += "]"; - objects += "]"; + 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), @@ -825,6 +823,8 @@ void allocations_when_needed() { BOOST_TEST_EQ(a.resource().allocations(), decoded); } +} // namespace + int main() { const std::vector<sample> texts = samples(); for (const sample& s : texts) { diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 77c0fe1..04afbfa 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -215,14 +215,14 @@ class aligning_allocator { ++control_->allocations; auto* block = static_cast<std::byte*>(::operator new((n * sizeof(T)) + 16, std::align_val_t{16})); - return static_cast<T*>(static_cast<void*>(block + offset())); + 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 = static_cast<std::byte*>(static_cast<void*>(p)); + 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}); } @@ -621,15 +621,15 @@ void explicit_rebinding() { 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, {}, alloc); + auto whole = wd::parse<Traits>(json, wd::parse_options(), alloc); require(BOOST_TEST(whole.has_value())); - parser p({}, alloc); + 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()); } - auto chunked = p.finish(); + const auto chunked = p.finish(); require(BOOST_TEST(chunked.has_value())); BOOST_TEST_EQ(seen, 3U); auto& d = *whole; @@ -639,10 +639,10 @@ void explicit_rebinding() { 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()); - auto sliced = d["list"].slice(1); - auto joined = d["list"].concat(d["list"], text); - auto popped = d["list"].pop(); - auto spliced = d["list"].splice(0, 1, text); + 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()); @@ -759,9 +759,10 @@ void holding_nothing() { BOOST_TEST(none.root().is_undefined()); BOOST_TEST(none.image().empty()); BOOST_TEST_EQ(none.capacity(), 0U); - BOOST_TEST(none.root().set(1).error() == wd::errc::type); - BOOST_TEST(none.root().set(members).error() == wd::errc::type); - BOOST_TEST(none.root()["key"].set(elements).error() == wd::errc::type); + 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); @@ -861,8 +862,7 @@ void capacity_until_it_fits(webcpp::test::interprocess_failing_resource& failing // 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; and a move -// assignment that cannot copy throws std::bad_alloc. +// 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); @@ -878,9 +878,10 @@ void interprocess_failure_is_capacity() { 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, {}, alloc)); }); + 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({}, alloc); + wd::pmr::parser p(wd::parse_options(), alloc); if (const auto added = p.on("$.list[*]", [](const auto&, wd::path_view) {}); !added) { return added.error(); } @@ -921,6 +922,15 @@ void interprocess_failure_is_capacity() { } 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())); @@ -939,7 +949,8 @@ void interprocess_failure_is_capacity() { } failing.allow(std::uint64_t{1} << 40U); BOOST_TEST(thrown); - BOOST_TEST(same_image(from, *other)); + // 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 @@ -966,6 +977,7 @@ int main() { 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 index 37eb45f..c668356 100644 --- a/test/allocator_tree_test.cpp +++ b/test/allocator_tree_test.cpp @@ -134,7 +134,7 @@ void members_in_resource() { arena a(16 * mebibyte); { document d = take(document::create(a.allocator())); - require(BOOST_TEST(d.root().set(wd::object{}).has_value())); + 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); @@ -181,7 +181,7 @@ void arrays_in_resource() { arena a(16 * mebibyte); { document d = take(document::create(a.allocator())); - require(BOOST_TEST(d.root().set(wd::array{}).has_value())); + 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(); @@ -238,7 +238,7 @@ void copies_in_resource() { { const document source = sample<Traits>(b.allocator()); document d = take(document::create(a.allocator())); - require(BOOST_TEST(d.root().set(wd::object{}).has_value())); + 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(); @@ -357,23 +357,6 @@ std::uint64_t id_of(const detail::tree_view<Traits>& t, std::uint64_t object, return n->id; } -/** - 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); -} - /** 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. @@ -651,6 +634,23 @@ void erasures_keep_the_image(const std::array<std::uint64_t, 11>& pinned) { #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; diff --git a/test/allocator_values_test.cpp b/test/allocator_values_test.cpp index 9fe87e1..12d6185 100644 --- a/test/allocator_values_test.cpp +++ b/test/allocator_values_test.cpp @@ -471,7 +471,7 @@ void bounds_by_utf16_units() { // 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).has_value()); + 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()); @@ -528,9 +528,9 @@ void refused_first() { const sample_values f; auto d = in_arena<Traits>(a, R"({"a":1,"o":{},"l":[],"gone":2})"); auto nothing = d["missing"]["x"]; - auto member = d["o"]["new"]; - auto element = d["l"][std::uint64_t{3}]; - auto gone = d["gone"]; + 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"); From b6f526c7e218477a97b6e5660d04e06b0fa0d2f7 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 10:58:39 -0300 Subject: [PATCH 20/23] document: a held callable's place declared with auto, which clang-tidy reads alike on every standard library On libstdc++ allocator_traits::pointer is an alias of T*, so a const before it qualified the pointer through an alias, which misc-misplaced-const refuses; libc++ declares the alias otherwise and the local lint did not see it. --- include/webcpp/document/parser.hpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/include/webcpp/document/parser.hpp b/include/webcpp/document/parser.hpp index a1734b4..6a5d240 100644 --- a/include/webcpp/document/parser.hpp +++ b/include/webcpp/document/parser.hpp @@ -292,8 +292,7 @@ class delivery { using held_traits = std::allocator_traits<held_allocator>; held_allocator a(alloc); F* const f = static_cast<F*>(object); - const typename held_traits::pointer place = - std::pointer_traits<typename held_traits::pointer>::pointer_to(*f); + const auto place = std::pointer_traits<typename held_traits::pointer>::pointer_to(*f); held_traits::destroy(a, f); held_traits::deallocate(a, place, 1); } From 4a211b91e044443ae17243a878bbd3330fb9ed9e Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 15:12:53 -0300 Subject: [PATCH 21/23] document: builds with MSVC 14.3 and 14.5 tree_view::member checks the key of a UTF-16 document for UTF-8 under if constexpr: the plain if's condition is the constant false under the default traits, which MSVC 14.3 refuses in every program (C4127, an error under /WX). Each member of a selector's table of operations has an initializer, as trystero's handler's has, else MSVC 14.3 and 14.5 warn that operations_of, which sets every member, is filled with zeros (C4268). allocator_tree_test names its image limit image_limit: basic_document::create's parameter max_bytes hid the test's global of that name, and MSVC warns of that wherever it compiles the member (C4459). allocator_parse_test names the raw string that holds an escaped quote outside BOOST_TEST_EQ, whose argument MSVC 14.3's preprocessor splits there (C2017). Each was reproduced with MSVC 19.44 and 19.50 on Compiler Explorer; fixed, each compiles there under /W4 /WX, and the table's callbacks, before and after, are called as they should be. --- include/webcpp/document/detail/tree.hpp | 6 ++++-- include/webcpp/document/parser.hpp | 12 +++++++++--- test/allocator_parse_test.cpp | 5 ++++- test/allocator_tree_test.cpp | 12 ++++++++---- 4 files changed, 25 insertions(+), 10 deletions(-) diff --git a/include/webcpp/document/detail/tree.hpp b/include/webcpp/document/detail/tree.hpp index efe401b..7a19f03 100644 --- a/include/webcpp/document/detail/tree.hpp +++ b/include/webcpp/document/detail/tree.hpp @@ -519,8 +519,10 @@ class tree_view { return nullptr; } // Text that is not UTF-8 is no stored key's, and the UTF-16 order decodes only UTF-8. - if (utf16_text && !valid_utf8(key)) { - return nullptr; + if constexpr (utf16_text) { + if (!valid_utf8(key)) { + return nullptr; + } } return member_in(*nodes, object, lookup_key(key)); } diff --git a/include/webcpp/document/parser.hpp b/include/webcpp/document/parser.hpp index 6a5d240..53a1101 100644 --- a/include/webcpp/document/parser.hpp +++ b/include/webcpp/document/parser.hpp @@ -210,13 +210,19 @@ class delivery { } private: - /** What a callable of one type does: be called, and be destroyed with its storage. */ + /** + 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); + 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; + void (*destroy)(void* object, const allocator_type& alloc) noexcept = nullptr; }; /** diff --git a/test/allocator_parse_test.cpp b/test/allocator_parse_test.cpp index 6c27b15..cdacfaa 100644 --- a/test/allocator_parse_test.cpp +++ b/test/allocator_parse_test.cpp @@ -522,7 +522,10 @@ void the_stack_rule() { 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); - BOOST_TEST_EQ(stack_allocations(R"(["[[[",{"a":"]\"]"}])", 1), 2U); + // 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); } diff --git a/test/allocator_tree_test.cpp b/test/allocator_tree_test.cpp index c668356..4129a1f 100644 --- a/test/allocator_tree_test.cpp +++ b/test/allocator_tree_test.cpp @@ -68,8 +68,12 @@ struct insertion_traits : wd::js_traits { using object = wd::insertion_order; }; -/** The size an image here may grow to. */ -constexpr std::uint64_t max_bytes = std::uint64_t{64} << 20U; +/** + 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 = @@ -315,12 +319,12 @@ 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, max_bytes, 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(), max_bytes, 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; From cd1d48daeae36a542074e7b15bdddc08a386ecca Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 15:12:53 -0300 Subject: [PATCH 22/23] document: the writer makes the lists of its deeper frames and of a larger piece only when it needs them A stringify_to that keeps to its stack's and its piece's own rooms now makes no standard container. The MSVC STL's checked iterators, a debug build's default, allocate a proxy through a container's allocator when the container is made, so each such stringify_to took two blocks of the document's resource there: against the page's reads that allocate nothing, which several threads may make at once whatever the resource, and against the dozen small texts that take nothing of a 64 KiB arena. --- include/webcpp/document/detail/writer.hpp | 68 ++++++++++++++++------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/include/webcpp/document/detail/writer.hpp b/include/webcpp/document/detail/writer.hpp index 89dda43..277d400 100644 --- a/include/webcpp/document/detail/writer.hpp +++ b/include/webcpp/document/detail/writer.hpp @@ -29,6 +29,8 @@ #include <webcpp/document/storage.hpp> #include <webcpp/document/traits.hpp> +#include <boost/config.hpp> + #include <algorithm> #include <array> #include <concepts> @@ -37,6 +39,7 @@ #include <functional> #include <limits> #include <new> +#include <optional> #include <span> #include <string> #include <string_view> @@ -116,6 +119,10 @@ class string_output { 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 { @@ -129,7 +136,7 @@ class chunked_output { : sink_(&sink), chunk_(static_cast<std::size_t>( std::clamp<std::uint64_t>(chunk, 1, std::numeric_limits<std::size_t>::max()))), - larger_(piece_allocator(alloc)) {} + alloc_(alloc) {} /** Takes `text`, handing the sink each full piece; the sink's failure is returned, and with @@ -177,8 +184,13 @@ class chunked_output { /** 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_.empty() ? own_.data() : larger_.data(); } + [[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) { @@ -196,7 +208,7 @@ class chunked_output { moved into it, so that each growth is one allocation. */ result<void> make_room(std::size_t size) { - const std::size_t room = larger_.empty() ? own_.size() : larger_.size(); + const std::size_t room = larger_.has_value() ? larger_->size() : own_.size(); if (size <= room) { return {}; } @@ -204,13 +216,16 @@ class chunked_output { while (grown < size) { grown = grown > chunk_ / 2 ? chunk_ : 2 * grown; } - std::vector<char, piece_allocator> larger(larger_.get_allocator()); + 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()); - larger_.swap(larger); + if (!larger_.has_value()) { + larger_.emplace(alloc_); + } + larger_->swap(larger); return {}; } @@ -226,21 +241,27 @@ class chunked_output { /** The piece's room of its own. */ std::array<char, first_piece_room> own_{}; - /** The piece's room once it holds more than its own, empty until then. */ - std::vector<char, piece_allocator> larger_; + /** 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 - : deeper_(rebound<Allocator, Frame>(alloc)) {} + explicit frame_stack(const Allocator& alloc) noexcept : alloc_(alloc) {} /** How many frames it holds. */ [[nodiscard]] std::size_t size() const noexcept { return size_; } @@ -250,13 +271,13 @@ class frame_stack { /** The innermost frame; the stack holds one. */ [[nodiscard]] Frame& back() noexcept { - return size_ <= first_frames ? own_[size_ - 1] : deeper_.back(); + 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_.pop_back(); + if (size_ > first_frames && deeper_.has_value()) { + deeper_->pop_back(); } --size_; } @@ -270,26 +291,35 @@ class frame_stack { own_[size_++] = f; return {}; } - if (deeper_.size() == deeper_.capacity()) { - const std::size_t room = - deeper_.capacity() == 0 ? first_frames : 2 * deeper_.capacity(); - if (const result<void> made = allocating([this, room] { deeper_.reserve(room); }); + 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); + 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 frames past them, innermost last. */ - std::vector<Frame, rebound<Allocator, Frame>> deeper_; + /** 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; From b584b8f2e7c0c7eefe6009e9c660a935734417a1 Mon Sep 17 00:00:00 2001 From: R <github.overboard312@passmail.net> Date: Sun, 15 Nov 2026 15:12:53 -0300 Subject: [PATCH 23/23] document: the allocation tests count and fail the document's own blocks on every standard library The MSVC STL's checked iterators allocate a 16-byte proxy through a container's allocator whenever the container is made or moved, in its noexcept constructors too. The debug lanes therefore counted more blocks than the document asked for, and ended the program (exit status 3) where a failing resource refused a proxy inside such a constructor. counting.cpp measures what an empty std::pmr::vector allocates. A counting resource leaves blocks of that size and alignment out of its counts, and a failing resource never refuses one nor counts it against its budget; where a standard library allocates nothing so, nothing is measured and the tests are what they were. A block of the document's own of that size and alignment, as the two 64-bit words a change's plan may reserve, is neither counted nor refused there: no operation whose allocations are counted exactly makes one, as a run with the measure forced to it on Clang and GCC shows, and the failures at it are proven on the other standard libraries. The small texts of stringify_to are counted with every block, so that a container the writer made for them fails there too; stringify is compared with a reference string made in the same count, its stack's list with what a container allocates for itself. The page says what such a build allocates, and that a proxy an allocator has no room for ends the program. --- doc/allocation.adoc | 37 ++++++++------ test/allocator_stringify_test.cpp | 22 ++++++--- test/counting.cpp | 59 +++++++++++++++++++++- test/counting.hpp | 81 ++++++++++++++++++++++++++----- 4 files changed, 163 insertions(+), 36 deletions(-) diff --git a/doc/allocation.adoc b/doc/allocation.adoc index 8911755..dae06c3 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -228,6 +228,12 @@ document's content as it was. A few places have their own way to say it: 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 @@ -277,8 +283,9 @@ few allocate in the document's allocator, rebound: 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: the handle - holds a copy of the key, and so does each copy of such a handle; + `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. @@ -314,15 +321,17 @@ buffer whose upstream is the null resource, and checks that they made no call of `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. 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>>). +`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/test/allocator_stringify_test.cpp b/test/allocator_stringify_test.cpp index f3f6490..697b5ae 100644 --- a/test/allocator_stringify_test.cpp +++ b/test/allocator_stringify_test.cpp @@ -405,7 +405,9 @@ void the_writer_allocates_its_stack_and_piece() { /** 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, and as the stack of `frames` frames needs; the arena makes no allocation. + 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, @@ -424,8 +426,10 @@ void calls_new_for_its_string_alone(const wd::basic_document<Traits>& source, st std::uint64_t reference_news = 0; std::uint64_t reference_deletes = 0; { - std::string reference; + // 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)); @@ -436,14 +440,16 @@ void calls_new_for_its_string_alone(const wd::basic_document<Traits>& source, st 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_allocations(frames)); - BOOST_TEST_EQ(deletes, reference_deletes + stack_allocations(frames)); + 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); @@ -463,14 +469,14 @@ void stringify_calls_new_for_its_string_alone() { } // 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 the arena holds the document alone, which stays -// as it was. +// 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().allocations(); + 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; @@ -479,7 +485,7 @@ void small_texts_take_nothing() { }).has_value()); BOOST_TEST_EQ(out, R"({"user":"Ada","langs":["Analytical","Note G"],"draft":true})"); } - BOOST_TEST_EQ(a.resource().allocations(), allocations); + BOOST_TEST_EQ(a.resource().all_allocations(), allocations); BOOST_TEST_EQ(a.resource().bytes_in_use(), held); } diff --git a/test/counting.cpp b/test/counting.cpp index 94552ad..85a8399 100644 --- a/test/counting.cpp +++ b/test/counting.cpp @@ -7,17 +7,20 @@ // 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. +// 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> @@ -82,6 +85,50 @@ void* or_abort(void* memory) noexcept { 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 { @@ -94,6 +141,16 @@ 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 diff --git a/test/counting.hpp b/test/counting.hpp index 31eae0f..d254821 100644 --- a/test/counting.hpp +++ b/test/counting.hpp @@ -5,10 +5,11 @@ // 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, 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. +// 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 @@ -48,6 +49,38 @@ class global_count { 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: @@ -55,13 +88,23 @@ class counting_resource final : public std::pmr::memory_resource { explicit counting_resource(std::pmr::memory_resource* upstream) noexcept : upstream_(upstream) {} - /** The allocations it made. */ + /** 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. */ + /** The deallocations it made, a standard container's own left out. */ [[nodiscard]] std::uint64_t deallocations() const noexcept { return deallocations_; } - /** The bytes handed out and not yet taken back. */ + /** + 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. */ @@ -70,14 +113,19 @@ class counting_resource final : public std::pmr::memory_resource { private: void* do_allocate(std::size_t bytes, std::size_t alignment) override { void* memory = upstream_->allocate(bytes, alignment); - ++allocations_; + 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 { - ++deallocations_; + if (!is_bookkeeping(bytes, alignment)) { + ++deallocations_; + } in_use_ -= bytes; upstream_->deallocate(memory, bytes, alignment); } @@ -89,6 +137,7 @@ class counting_resource final : public std::pmr::memory_resource { 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; }; @@ -98,6 +147,10 @@ class counting_resource final : public std::pmr::memory_resource { 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. */ @@ -119,11 +172,13 @@ class basic_failing_resource final : public std::pmr::memory_resource { private: void* do_allocate(std::size_t bytes, std::size_t alignment) override { - if (budget_ == 0) { - ++refusals_; - boost::throw_exception(Failure()); + if (!is_bookkeeping(bytes, alignment)) { + if (budget_ == 0) { + ++refusals_; + boost::throw_exception(Failure()); + } + --budget_; } - --budget_; void* memory = upstream_->allocate(bytes, alignment); in_use_ += bytes; return memory;