From b622b22a2dd66a1cf09449dfc21ecf5658b07380 Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Tue, 18 Aug 2026 20:41:58 +0000 Subject: [PATCH] feat(seq): template MessageSeq on the container, like StringSeq MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MessageSeq was templated on the ELEMENT and held std::vector *out, i.e. the destination was hard-wired. StringSeq is templated on the CONTAINER and holds C &out, which is why it already serves both storage profiles. This brings MessageSeq to the same shape, so it can collect into an InlineVector as well as a std::vector. That is the prerequisite for generated C++ dropping its own sofabgen::WrapperSeq: the static-storage profiles instantiate it as WrapperSeq>, which the element-templated MessageSeq could not express — which is also why MessageSeq was emitted zero times and WrapperSeq was emitted instead (generator#345). The old spelling keeps working. detail::namesSeqContainer() tells the two readings apart from the argument alone: an argument names a container when its value_type is something this collector reads as an element. The two can only collide for an element that is itself a sequence of messages or a row of rows, and under the element reading such an element goes to IStreamImpl::read, which has no overload for it — so what the container reading takes over is code that never compiled. Closes #116. --- README.md | 12 ++- include/sofab/sofab.hpp | 166 ++++++++++++++++++++++++++--------- test/test_roundtrip.cpp | 189 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 320 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 8254a69..0f44c12 100644 --- a/README.md +++ b/README.md @@ -618,17 +618,23 @@ alongside the growable ones: | `array`, `count N` | `std::vector` | `sofab::InlineVector` | ```cpp -sofab::FixedString<24> name; // maxlen 24 +sofab::FixedString<24> name; // maxlen 24 sofab::InlineVector, 4> tags; // count 4, maxlen 8 +sofab::InlineVector rows; // count 4, struct elements case 1: is.readString(name, 24); break; // same call either way case 2: { sofab::StringSeq c{tags, 4, 8}; is.read(c); } break; +case 3: { sofab::MessageSeq c; c.out = &rows; is.read(c); } break; ``` The call sites are spelled identically for both storage kinds — `readString`, `readBlob` and `readArray` pick the branch off the destination's own capabilities, -and the collectors deduce their container — so switching a field's storage is a -change of member type and nothing else. The wire is unaffected in both directions. +and every collector — `StringSeq`, `BlobSeq` and `MessageSeq` alike — is templated +on the *container*, so switching a field's storage is a change of member type and +nothing else. The wire is unaffected in both directions. A `MessageSeq` given a +heap-free destination takes that container's capacity as its element bound unless +a schema `count` sets `cap` explicitly, since a full inline container cannot grow +to reach a higher index. Semantics are unchanged too: a payload past the declared bound is `INVALID` (§7.1) rather than truncated, and one past the container's own capacity is diff --git a/include/sofab/sofab.hpp b/include/sofab/sofab.hpp index 0b71b4d..0019e23 100644 --- a/include/sofab/sofab.hpp +++ b/include/sofab/sofab.hpp @@ -4666,25 +4666,80 @@ namespace sofab } }; + namespace detail + { + /** + * @brief Whether a @ref MessageSeq template argument names the destination + * **container** rather than the element type. + * + * @ref MessageSeq is templated on the container, exactly as @ref StringSeq + * is, which is what lets it collect into an @ref InlineVector as well as a + * @c std::vector. It used to be templated on the ELEMENT, with + * `std::vector` hard-wired as the destination, and that spelling keeps + * working: the two readings are told apart here, from the argument alone. + * + * An argument names a container when its `value_type` is something this + * collector reads as an element — a message, or a row container. The two + * readings can only collide for an argument whose `value_type` is itself + * one of those two, i.e. an element that is a sequence of messages or a row + * of rows; under the element reading such an element is handed to + * @ref IStreamImpl::read, which has no overload for it, so what the + * container reading takes over is code that never compiled. + */ + template + constexpr bool namesSeqContainer() noexcept + { + if constexpr (requires { typename A::value_type; }) + { + using V = typename A::value_type; + return std::is_base_of_v || requires { typename V::value_type; }; + } + else + { + return false; + } + } + } // namespace detail + /** - * @brief Collects a struct/union or nested-array wrapper sequence into a - * `std::vector`. + * @brief Collects a struct/union or nested-array wrapper sequence into the + * container it is handed. * - * One element is emplaced and read per child: @ref IStreamImpl::read descends - * into a struct/union element's own sub-sequence, or reads a nested array row, - * exactly as it would for a scalar field. + * One element is placed and read per child: @ref IStreamImpl::read descends + * into a struct/union element's own sub-sequence, and a native-scalar row goes + * through @ref IStreamImpl::readArray — exactly as a top-level field of that + * type would be read. * * The target is held by pointer rather than a bound reference so one instance * can serve several fields. * - * @tparam T Element type — an @ref IStreamMessage, or a container for a - * nested-array row. + * @tparam A Destination **container**, as @ref StringSeq takes it: + * `std::vector` for the growable storage mode, + * `InlineVector` for the heap-free one; its `value_type` is the + * element type. The older ELEMENT spelling `MessageSeq`, which + * always collected into a `std::vector`, still compiles — see + * @ref detail::namesSeqContainer for how the two are told apart. */ - template + template struct MessageSeq : IStreamMessage { - std::vector *out = nullptr; - long cap = -1; /**< Schema `count` N, or -1; an id at or past N is INVALID (§5.1/§7). */ + /** Destination container: @p A itself, or `std::vector` for the element spelling. */ + using Container = std::conditional_t(), A, std::vector>; + /** Element type — an @ref IStreamMessage, or a container for a nested-array row. */ + using Elem = typename Container::value_type; + + Container *out = nullptr; /**< Destination; a null one collects nothing. */ + + /** + * @brief Schema `count` N, or -1; an id at or past N is INVALID (§5.1/§7). + * + * Defaults to the destination's own capacity when it publishes one + * (@ref detail::destCapacity), so a heap-free container arrives bounded + * even when the caller declares nothing — its `emplace_back` reuses the + * last slot once full, which is a length the gap fill below would never + * reach. `-1`, i.e. unbounded, for a growable container, as before. + */ + long cap = detail::destCapacity(); /** * @brief The declared element type, published to the stream (§7.3), as @@ -4696,15 +4751,15 @@ namespace sofab * neither rule covers, which leaves the bound to the check below. */ static constexpr int elemWire = []() constexpr -> int { - if constexpr (std::is_base_of_v) + if constexpr (std::is_base_of_v) return static_cast(detail::Wire::SequenceStart); - else if constexpr (requires { typename T::value_type; }) + else if constexpr (requires { typename Elem::value_type; }) { - using Elem = typename T::value_type; - if constexpr (std::is_integral_v && !std::is_same_v) - return static_cast(std::is_unsigned_v ? detail::Wire::ArrayUnsigned - : detail::Wire::ArraySigned); - else if constexpr (std::is_same_v || std::is_same_v) + using RowElem = typename Elem::value_type; + if constexpr (std::is_integral_v && !std::is_same_v) + return static_cast(std::is_unsigned_v ? detail::Wire::ArrayUnsigned + : detail::Wire::ArraySigned); + else if constexpr (std::is_same_v || std::is_same_v) return static_cast(detail::Wire::ArrayFixlen); else return -1; @@ -4716,23 +4771,33 @@ namespace sofab /** §7.4 replace-whole, and absent ⇒ never called: @copydoc StringSeq::prepare */ void prepare() noexcept { if (out) out->clear(); } - void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t count) noexcept override + void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override { - /* §5.1/§7 over-index reject, as a backstop for a direct call. Coming - * through @ref IStreamImpl::read this is unreachable: `cap` is handed - * to the stream as its element bound and rejected one step earlier, - * before a truncated element could outrun it -- which is why - * @ref StringSeq / @ref BlobSeq carry no copy of it. Kept here because - * `deserialize` is public. §7.3 runs first here too, in the same order - * the stream uses, so the two entry points cannot disagree: an element - * whose wire type contradicts @ref elemWire is not an element, and an - * id that is not an index cannot breach the index bound. */ - if (cap >= 0 && static_cast(id) >= static_cast(cap)) + if (!out) return; + /* §7.3 first, in the same order the stream uses, so the two entry points + * cannot disagree: an element whose wire type contradicts @ref elemWire + * is not this array's element at all. It is skipped like an unknown id, + * which means the destination has to be left exactly as it was -- so the + * decision comes before the placement below -- and an id that is not an + * index cannot breach the index bound either. Coming through + * @ref IStreamImpl::read the same test has already run one step earlier + * whenever this collector publishes a bound; it is kept here because + * `deserialize` is public and an unbounded array publishes none. */ + if constexpr (elemWire >= 0) + { + if (static_cast(is.wire()) != elemWire) return; /* §7.3 */ + } + /* §5.1/§7 over-index reject, decided from the id alone and before the + * container grows, which is also what keeps an announced index from + * becoming an allocation. The bound is `cap`, and the container's own + * capacity whenever `cap` declares none: a heap-free destination must be + * bounded by something, since its `emplace_back` stops advancing at the + * capacity and the gap fill would then never reach the id. Growable + * containers fold this to the `cap` test they had. */ + constexpr long fixedCap = detail::destCapacity(); + if (const long bound = cap >= 0 ? cap : fixedCap; + bound >= 0 && static_cast(id) >= static_cast(bound)) { - if constexpr (elemWire >= 0) - { - if (static_cast(is.wire()) != elemWire) return; /* §7.3 */ - } is.invalidate(); return; } @@ -4743,17 +4808,32 @@ namespace sofab * Appending instead would silently SHORTEN the array by the size of * the gap: wire `06 0005 07 16 0009 07` (elements at id 0 and id 2, * id 1 absent) is the 3-element array `[5, 0, 9]`, not `[5, 9]`. - * Same placement rule as @ref StringSeq / @ref BlobSeq; the growth is - * bounded by the `cap` reject above whenever the schema declares a - * `count`. */ - while (out->size() <= static_cast(id)) out->emplace_back(); - T &row = (*out)[id]; - /* A count-less native-array row is a std::vector the span read fills - * only up to its current size, so size it to the row's wire count - * first. Struct/union rows and fixed std::array rows have no resize(). */ - if constexpr (requires { row.resize(count); } && !std::is_base_of_v) - row.resize(count); - is.read(row); + * Same placement rule as @ref StringSeq / @ref BlobSeq. */ + while (out->size() <= static_cast(id)) (void)out->emplace_back(); + Elem &row = (*out)[static_cast(id)]; + if constexpr (std::is_base_of_v) + { + is.read(row); /* the element's own sub-sequence */ + } + else if constexpr (requires { row.resize(size_t{}); }) + { + /* A native-scalar row is sized by the wire count, and + * @ref IStreamImpl::readArray is what owns that: it settles the + * row's array tag, refuses a count the row cannot hold instead of + * truncating into it (§3), and grows only as far as the bytes in + * hand could ever fill -- so an announced count of 2^31 never + * becomes an allocation. A bare `resize(count)` here got all three + * wrong. A heap-free row's capacity IS the schema `count` it was + * generated for, so it is passed as one and a row past it is the + * INVALID of §7.1 rather than a receiver-side LimitExceeded. */ + (void)is.readArray(row, detail::destCapacity()); + } + else + { + /* A fixed-extent row (`std::array`, a bound span) publishes no + * resize: read()'s low-level contract fills what it holds. */ + is.read(row); + } } }; diff --git a/test/test_roundtrip.cpp b/test/test_roundtrip.cpp index fa8f675..3f6a005 100644 --- a/test/test_roundtrip.cpp +++ b/test/test_roundtrip.cpp @@ -60,13 +60,19 @@ static int g_checks = 0; * lets holdBackAllocationFailure() both COUNT allocations (proving the shallow * path makes none) and fail one on demand (proving a failed spill is reported * as an error instead of terminating the process). Under -fno-exceptions the - * arming flag is never set and this stays a plain counting allocator. */ + * arming flag is never set and this stays a plain counting allocator. + * + * The byte total beside the count is what messageSeqStorageProfiles() needs: a + * decoder talked into sizing a row from an announced count allocates ONCE, so + * the count alone cannot tell a 3-element row from a 2^31-element one. */ static unsigned long g_allocCount = 0; +static unsigned long g_allocBytes = 0; static bool g_failNextAlloc = false; void *operator new(size_t n) { ++g_allocCount; + g_allocBytes += n; #if defined(__cpp_exceptions) && __cpp_exceptions if (g_failNextAlloc) { g_failNextAlloc = false; throw std::bad_alloc(); } #endif @@ -2873,6 +2879,62 @@ struct CappedMsg : sofab::IStreamMessage } }; +/* --- MessageSeq is templated on the CONTAINER ------------------------------ + * + * The same wrapper array, collected into both storage profiles: a growable + * `std::vector` and a heap-free `InlineVector`. The collector call is spelled + * identically for the two, exactly as StringSeq / BlobSeq already are, and the + * ELEMENT spelling `MessageSeq` that CappedMsg above still uses keeps + * meaning `std::vector`. --- */ + +static_assert(std::is_same_v::Container, std::vector>, + "the element spelling still names a std::vector destination"); +static_assert(std::is_same_v>::Container, + std::vector>>, + "a native-scalar ROW is an element, not a destination"); +static_assert(std::is_same_v>::Container, + std::vector>, + "a container of messages is the destination"); +static_assert(std::is_same_v>::Container, + sofab::InlineVector>, + "a heap-free container of messages is the destination"); +static_assert(std::is_same_v< + sofab::MessageSeq, 3>>::Container, + sofab::InlineVector, 3>>, + "a heap-free container of rows is the destination"); + +/* Growable storage, addressed by the container spelling; `count: 3` on id 1. */ +struct DynRowsMsg : sofab::IStreamMessage +{ + std::vector rows; /* id 1 -- count 3 */ + std::vector> matrix; /* id 4 -- unbounded rows */ + void deserialize(sofab::IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override + { + switch (id) + { + case 1: { sofab::MessageSeq> c; c.out = &rows; c.cap = 3; is.read(c); break; } + case 4: { sofab::MessageSeq>> c; c.out = &matrix; is.read(c); break; } + } + } +}; + +/* The heap-free twin: the same schema in fixed storage. No `cap` is set on + * purpose -- the container's own capacity is what bounds the element id. */ +struct FixedRowsMsg : sofab::IStreamMessage +{ + sofab::InlineVector rows; /* id 1 -- count 3 */ + sofab::InlineVector, 3> matrix; /* id 4 -- count 3, row count 2 */ + void deserialize(sofab::IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override + { + switch (id) + { + case 1: { sofab::MessageSeq> c; c.out = &rows; is.read(c); break; } + case 4: { sofab::MessageSeq, 3>> c; + c.out = &matrix; is.read(c); break; } + } + } +}; + static void messageLayerFraming() { const SeqRow dflt{}; @@ -3224,6 +3286,128 @@ struct F41GenMsg : sofab::IStreamMessage } }; +/* --- MessageSeq: one collector, both storage profiles ---------------------- + * + * Templating it on the container is what lets a heap-free destination use it, + * and none of what that decides is visible on the wire: two implementations can + * disagree about a gap-filled row, about how much an announced count may + * allocate, or about an index sitting exactly at the capacity, and still emit + * byte-identical output. The shared vectors cannot reach any of that, so these + * checks are the only ones that can. --- */ +static void messageSeqStorageProfiles() +{ + /* elements at id 0 and id 2, id 1 absent -- the auditor's M3 wire, at field + * id 1, which both destinations below decode. */ + const auto gapWire = fromHex("0e060005071600090707"); + + { + /* the container spelling on growable storage: placement as before. */ + sofab::IStreamObject in; + auto r = in.feed(gapWire.data(), gapWire.size()); + CHECK(r.complete(), "MessageSeq>: the id-gap wire decodes COMPLETE"); + CHECK((*in).rows.size() == 3, "MessageSeq>: the id gap is filled, length 3"); + if ((*in).rows.size() == 3) + CHECK((*in).rows[0].a == 5 && (*in).rows[1].a == 0 && (*in).rows[2].a == 9, + "MessageSeq>: every element lands at its id: [5, 0, 9]"); + } + { + /* ...and on the heap-free destination, which is what the re-template + * adds. Its decode allocates nothing: the elements live in the message. */ + const unsigned long allocBefore = g_allocCount; + sofab::IStreamObject in; + auto r = in.feed(gapWire.data(), gapWire.size()); + CHECK(r.complete(), "MessageSeq>: the id-gap wire decodes COMPLETE"); + CHECK((*in).rows.size() == 3, "MessageSeq>: the id gap is filled, length 3"); + if ((*in).rows.size() == 3) + CHECK((*in).rows[0].a == 5 && (*in).rows[1].a == 0 && (*in).rows[2].a == 9, + "MessageSeq>: every element lands at its id: [5, 0, 9]"); + CHECK(g_allocCount == allocBefore, + "MessageSeq: collecting into heap-free storage allocates nothing"); + } + { + /* §5.1/§7.4: a repeated element id continues the element already placed + * at that index -- it does not append a second one. */ + sofab::IStreamObject in; + auto w = fromHex("0e0600050706000907" "07"); + CHECK(in.feed(w.data(), w.size()).complete(), "a repeated element id decodes COMPLETE"); + CHECK((*in).rows.size() == 1, "a repeated element id replaces, it does not append"); + if ((*in).rows.size() == 1) + CHECK((*in).rows[0].a == 9, "the later occurrence of an element id wins"); + } + + /* --- capacity edges. The heap-free destination declares no `cap`, so its + * own capacity is the bound: without one, emplace_back would stop + * advancing at N and the gap fill would never reach the id. --- */ + { + sofab::MessageSeq> fixed; + sofab::MessageSeq> growable; + CHECK(fixed.cap == 3, "a heap-free destination bounds the element id by its capacity"); + CHECK(growable.cap == -1, "a growable destination stays unbounded unless a count says otherwise"); + } + { + /* id == cap - 1 is the last legal index, and it grows the array to N. */ + sofab::IStreamObject in; + auto w = fromHex("0e" "1600090707"); + CHECK(in.feed(w.data(), w.size()).complete(), "an element at id N-1 decodes COMPLETE"); + CHECK((*in).rows.size() == 3, "an element at id N-1 grows the array to exactly N"); + if ((*in).rows.size() == 3) + CHECK((*in).rows[2].a == 9, "the element at id N-1 lands at index N-1"); + } + { + /* id == cap is one past it: INVALID (§5.1/§7), decided from the id alone, + * with nothing placed and nothing grown. */ + sofab::IStreamObject in; + auto w = fromHex("0e" "1e00090707"); + CHECK(in.feed(w.data(), w.size()).invalid(), "an element at id N is INVALID"); + CHECK((*in).rows.empty(), "the rejected element grows nothing"); + } + { + /* the same reject on growable storage, where `cap` is the schema + * `count: 3` rather than the container. */ + sofab::IStreamObject in; + auto w = fromHex("0e" "1e00090707"); + /* Counted from HERE, not from the top of the block: constructing the + * decoder and the wire vector allocates, and folding that in would make + * the check pass or fail on setup rather than on the rejected element. */ + const unsigned long allocBefore = g_allocCount; + CHECK(in.feed(w.data(), w.size()).invalid(), "count: 3 rejects an element at id 3"); + CHECK((*in).rows.empty() && g_allocCount == allocBefore, + "the rejected element is never allocated for"); + } + + /* --- native-scalar rows, whose length is an announced count: unauthenticated + * input until the ceilings have run. --- */ + { + sofab::IStreamObject in; + auto w = fromHex("26" "03" "02" "0102" "07"); /* field 4, row 0 = [1, 2] */ + CHECK(in.feed(w.data(), w.size()).complete(), "a heap-free row at its capacity decodes COMPLETE"); + CHECK((*in).matrix.size() == 1 && (*in).matrix[0].size() == 2 && + (*in).matrix[0][0] == 1 && (*in).matrix[0][1] == 2, + "a heap-free row keeps the wire elements"); + } + { + /* §3: a row count past what the row can hold is refused, never truncated + * into it -- and INVALID rather than LimitExceeded, because a heap-free + * row's capacity IS the schema `count` it was generated for. */ + sofab::IStreamObject in; + auto w = fromHex("26" "03" "03" "010203" "07"); + CHECK(in.feed(w.data(), w.size()).invalid(), + "a row count past the row's capacity is INVALID, not a silent truncation"); + } + { + /* adversarial: an announced row count near 2^31 with three payload bytes. + * The count must not become an allocation -- the row grows only as far as + * the bytes in hand could ever fill. */ + const unsigned long bytesBefore = g_allocBytes; + sofab::IStreamObject in; + auto w = fromHex("26" "03" "8080808008" "010203" "07"); + auto r = in.feed(w.data(), w.size()); + CHECK(!r.complete(), "a row whose announced count outruns its payload is not COMPLETE"); + CHECK(g_allocBytes - bytesBefore < 4096, + "an announced row count near 2^31 allocates for the bytes in hand, not for the count"); + } +} + static void overIndexSkipOrdering() { auto feed = [](const char *hex) { @@ -5882,6 +6066,8 @@ static void decoderReuseAcrossTypes() checkStreamReuse("RowsAtOneMsg"); checkStreamReuse("BoundedSeqMsg"); checkStreamReuse("CappedMsg"); + checkStreamReuse("DynRowsMsg"); + checkStreamReuse("FixedRowsMsg"); checkStreamReuse("F41Msg"); checkStreamReuse("F41GenMsg"); checkStreamReuse("F56Msg"); @@ -5923,6 +6109,7 @@ int main() strictUtf8(); messageLayerFraming(); wrapperArrayCollectors(); + messageSeqStorageProfiles(); overIndexSkipOrdering(); skippedSubtreeSuspendsBound(); truncatedNestedFieldIsNotDeclined();