SofaBuffers C++ 0.12.0
Pure-C++20 SofaBuffers — API Documentation
Loading...
Searching...
No Matches
sofab.hpp
Go to the documentation of this file.
1/*!
2 * @file sofab.hpp
3 * @brief SofaBuffers — pure C++20 implementation (no C backend).
4 *
5 * A from-scratch, header-only implementation of the SofaBuffers wire format in
6 * modern C++20. It mirrors the public API of the C-backed `sofab/sofab.hpp`
7 * (same `sofab::OStream` / `sofab::IStream*` surface) but shares no code with
8 * the C library — encoding and decoding are implemented directly here.
9 *
10 * Design:
11 * - Encoding stays fully streamable: an `OStream` writes into a caller buffer
12 * and invokes a flush callback when it fills, so a message can exceed RAM.
13 * - Decoding is optimised for the common case where the whole message is
14 * already in contiguous memory: a protobuf-style cursor advances a pointer
15 * over the buffer (no per-byte state machine). The streaming `feed()` API is
16 * retained — bytes are accumulated and complete top-level fields are
17 * dispatched as they become available — so chunked input still works.
18 * - Modern techniques: `std::span`, `std::bit_cast`, concepts, `if constexpr`,
19 * `[[nodiscard]]`. Endianness is handled explicitly (LE on the wire) so no
20 * host-endian branching is needed.
21 *
22 * SPDX-License-Identifier: MIT
23 */
24
25#ifndef SOFAB_HPP
26#define SOFAB_HPP
27
28/**
29 * @defgroup cpp20_api C++20 API
30 * @{
31 */
32
33#include <array>
34#include <bit>
35#include <concepts>
36#include <cstdint>
37#include <cstring>
38#include <functional>
39#include <limits>
40#include <memory>
41#include <span>
42#include <string>
43#include <string_view>
44#include <type_traits>
45#include <vector>
46
47#include "sofab/bits_equal.hpp"
48
49/**
50 * @def SOFAB_STRICT_UTF8
51 * @brief Compile-time gate for strict UTF-8 validation of `string` payloads
52 * (spec MESSAGE_SPEC §8, CORELIB_PLAN §6.4).
53 *
54 * SofaBuffers `string` fields carry UTF-8 text; `blob` is the type for opaque
55 * bytes. With the check **ON** (the default, `1`) an invalid-UTF-8 `string` is
56 * rejected **symmetrically**: on decode it is the `INVALID` outcome
57 * (@ref sofab::Error::InvalidMessage), on encode it is refused with
58 * @ref sofab::Error::InvalidArgument. `blob` is never validated in either
59 * direction, and a **skipped** `string` is never validated (only a materialised
60 * read is).
61 *
62 * The knob is compile-time because this header carries no runtime encode-side
63 * configuration object (an `OStream` is constructed from buffers only), so a
64 * single `#define` is the only way to gate encode and decode with one symmetric
65 * switch — the "compile-time (`#define`)" option §6.4 explicitly permits for
66 * C++. Define `SOFAB_STRICT_UTF8` to `0` before including this header for a
67 * documented **non-strict** build: the validation code then folds away entirely
68 * (zero `.text`/`.rodata` cost) and payloads are stored verbatim — raw, never
69 * lossy. Such a build is expected to still build and conformance-test the
70 * check-ON configuration (§6.4).
71 */
72#ifndef SOFAB_STRICT_UTF8
73# define SOFAB_STRICT_UTF8 1
74#endif
75
76namespace sofab
77{
78 /** Version of the SofaBuffers public API implemented by this header. */
79 inline constexpr int API_VERSION = 1;
80
81 /* ---------------------------------------------------------------------- */
82 /* Wire-format limits */
83 /* */
84 /* Fixed by MESSAGE_SPEC §6.2 and identical in every corelib. */
85 /* Not configurable and not a policy: exceeding one is malformed */
86 /* input, not a local decision. */
87 /* Receiver-side caps a caller CHOOSES are @ref Limits. */
88 /* ---------------------------------------------------------------------- */
89
90 /**
91 * Largest valid field id (`INT32_MAX`). Encoding a larger id is
92 * @ref Error::InvalidArgument; decoding one is @ref Error::InvalidMessage.
93 */
94 inline constexpr uint32_t ID_MAX = 0x7fffffffu;
95 /**
96 * Largest fixlen payload byte-length (`INT32_MAX`). Encoding a longer
97 * payload is @ref Error::InvalidArgument; decoding one is
98 * @ref Error::InvalidMessage.
99 */
100 inline constexpr uint32_t FIXLEN_MAX = 0x7fffffffu;
101 /**
102 * Largest array element count (`INT32_MAX`). Encoding a longer array is
103 * @ref Error::InvalidArgument; decoding one is @ref Error::InvalidMessage.
104 */
105 inline constexpr uint32_t ARRAY_MAX = 0x7fffffffu;
106 /**
107 * Maximum nested-sequence depth (§4.9). Deeper nesting is rejected
108 * (encode: @ref Error::InvalidArgument; decode: @ref Error::InvalidMessage).
109 */
110 inline constexpr int MAX_DEPTH = 255;
111
112 /**
113 * @brief Smallest output buffer this port accepts **for streaming** (§5.1).
114 *
115 * This implementation writes byte-at-a-time whenever the buffer is tight —
116 * every write funnels through @ref OStreamImpl::pushBytes, which falls back to
117 * a per-byte push that flushes across the boundary — so it splits **atomic
118 * units** too and declares the smallest value §5.1 admits, `1`. A caller
119 * therefore never has to reserve headroom: any non-empty buffer streams a
120 * message of any size, and the bytes are identical to the one-shot path.
121 *
122 * **It binds a buffer installed together with a flush sink**, and only such a
123 * buffer: `buflen - offset >= MIN_OUTPUT_BUFFER` is checked where the buffer is
124 * handed over — a constructor or @ref OStream::setBuffer — and never partway
125 * through a message. A buffer installed **without** a sink is subject to no
126 * minimum at all: no flush can occur, so it either holds the message or reports
127 * @ref Error::BufferFull, and a two-byte message still encodes into two bytes.
128 *
129 * A rejected installation leaves the stream inert and latched at
130 * @ref Error::InvalidArgument (@ref OStreamImpl::ok is false,
131 * @ref OStreamImpl::error reports it); no write it is then asked for touches
132 * the buffer.
133 */
134 inline constexpr size_t MIN_OUTPUT_BUFFER = 1;
135
136 /**
137 * @brief Always-false trait used to trigger `static_assert` in the
138 * otherwise-unreachable branch of an `if constexpr` chain.
139 *
140 * Because the value depends on the template parameter, the assertion only
141 * fires when that branch is actually instantiated, which is the idiomatic
142 * way to reject unsupported types at compile time.
143 *
144 * @tparam T The type the dependent assertion is bound to.
145 */
146 template <typename>
147 inline constexpr bool always_false_v = false;
148
149 /** Status codes returned by the encode/decode API; `None` signals success. */
150 enum class Error
151 {
152 None = 0, /**< Operation succeeded (decode: `COMPLETE`, §7). */
153 /**
154 * Encode-only: the encoder ran out of room. Either the output buffer
155 * filled and no flush callback was set, or — the rare second case —
156 * @ref OStreamImpl::sequenceBeginLazy could not allocate room to hold one
157 * more sequence header back (see @ref OStreamImpl::sequenceBeginLazy).
158 */
159 BufferFull = 3,
160 /**
161 * An argument was out of range (e.g. a field id above the limit) — and,
162 * on the decode side, §6.3's **third refusal tier**: a value that broke
163 * neither the schema bound nor a receiver cap but does not fit the
164 * **destination the caller handed over** (§6.6.3).
165 *
166 * "The third is a mistake in the **call**, not a property of the message
167 * or of the deployment, and the other two codes each say something untrue
168 * about it. `InvalidMessage` would mark a well-formed message malformed —
169 * the same bytes decode for a caller who passes a larger destination, and
170 * no §5.2.2 condition is present. `LimitExceeded` would promise a limit to
171 * raise that was never configured." (§6.3)
172 */
173 InvalidArgument = 1,
174 InvalidMessage = 4, /**< The input bytes are malformed (decode: `INVALID`, §7). */
175 /**
176 * Decode-only: the fed bytes end **inside** a field — a partial varint
177 * (§4.1), a fixlen/array payload shorter than declared (§4.6/§4.8), or an
178 * open sequence (§4.9).
179 *
180 * This is `INCOMPLETE` (§7) and **not** an error: the caller owns
181 * end-of-input and may feed more bytes. Distinct from both @ref None
182 * (`COMPLETE`) and @ref InvalidMessage (`INVALID`).
183 */
184 Incomplete = 5,
185 /**
186 * Decode-only: a receiver-configured cap (§6.2.1) was exceeded on a field
187 * the schema leaves unbounded — the field-span budget
188 * @ref Limits::max_buffered_field, or the `dynCap` handed to
189 * @ref IStreamImpl::readStringCapped, @ref IStreamImpl::readBlobCapped,
190 * @ref IStreamImpl::readArrayCapped or a wrapper-array collector.
191 *
192 * **Policy, not malformation** — deliberately distinct from
193 * @ref InvalidMessage, so a differential fuzzer never reads a local
194 * buffering limit as a conformance divergence. The bytes are never clamped
195 * or truncated; @ref IStreamImpl::feed simply fails with this code.
196 *
197 * **Never raised for a field the schema bounds** (§6.2.1/§6.3). A declared
198 * `maxlen`/`count` is a statement about *validity* and outranks any
199 * receiver-side statement about *capacity*: an over-bound claim is
200 * @ref InvalidMessage no matter how the cap is configured, so the same
201 * bytes cannot come out as a policy refusal on a receiver that happens to
202 * buffer less. Only a schema-**unbounded** field reaches this code.
203 */
204 LimitExceeded = 6,
205 };
206
207 /**
208 * @brief Three-valued decode outcome of a @ref sofab::IStreamImpl::feed call (spec §7).
209 *
210 * The decoder reports where the consumed bytes ended, with **no** separate
211 * `finish`/`finalize` step (§7.1): the same three outcomes apply to a one-shot
212 * buffer and to chunked streaming. Whether an @ref Incomplete result is
213 * acceptable is the caller's decision — a streaming caller reads it as "feed
214 * me the next chunk", a whole-message caller reads it as a truncated message.
215 */
216 enum class DecodeStatus
217 {
218 Complete = 0, /**< Consumed bytes end **exactly** at a field boundary — a valid message. */
219 Incomplete = 1, /**< Consumed bytes end **inside** a field or with an open sequence. Not an error. */
220 Invalid = 2, /**< Bytes are malformed **regardless of what follows**. Terminal. */
221 /**
222 * A configured receiver-side limit (§6.2.1) was exceeded on a
223 * schema-**unbounded** field. The bytes are **well-formed** — the same
224 * message decodes under a looser limit — so this is a *policy* rejection
225 * and **not** @ref DecodeStatus::Invalid — §6.3 requires an implementation
226 * to "keep the two distinguishable to the caller" and forbids reporting
227 * it as `InvalidMessage`. Terminal.
228 *
229 * §6.3 offers two ways to surface it, "either a **fourth decode
230 * outcome**, or a terminal failure carrying the `LimitExceeded` code on
231 * the error channel"; this port does both, so a caller switching on
232 * @ref sofab::IStreamImpl::Result::status alone cannot mistake it for
233 * malformation.
234 */
235 LimitExceeded = 3,
236 /**
237 * The value broke neither the schema bound nor a receiver cap, but does
238 * not fit the **destination this caller handed over** (§6.6.3, §6.3's
239 * third refusal tier). A mistake in the call, not in the message: the
240 * same bytes decode for a caller who passes a larger destination.
241 * Terminal.
242 */
243 InvalidArgument = 4,
244 };
245
246 /** Field identifier on the wire. Valid range is `[0, INT32_MAX]`. */
247 using id = uint32_t;
248
249 /* ---------------------------------------------------------------------- */
250 /* wire-format primitives */
251 /* ---------------------------------------------------------------------- */
252
253
254 /** Implementation details of the wire format; not part of the public API. */
255 namespace detail
256 {
257 /**
258 * @brief Wire type stored in the low 3 bits of every field header.
259 *
260 * Internal. The typed reads compare it themselves (§7.3), so neither generated
261 * nor hand-written code has to name it.
262 */
263 enum class Wire : uint8_t
264 {
265 Unsigned = 0, /**< Unsigned integer encoded as a varint. */
266 Signed = 1, /**< Signed integer, zig-zag encoded as a varint. */
267 Fixlen = 2, /**< Length-prefixed payload (float, string or blob). */
268 ArrayUnsigned = 3, /**< Count-prefixed array of unsigned varints. */
269 ArraySigned = 4, /**< Count-prefixed array of zig-zag varints. */
270 ArrayFixlen = 5, /**< Count-prefixed array of fixed-size elements. */
271 SequenceStart = 6, /**< Opens a nested sub-message. */
272 SequenceEnd = 7, /**< Closes the most recently opened sub-message. */
273 };
274
275 /**
276 * @brief Sub-type of a length-prefixed (`Fixlen`) payload, stored in the low 3 bits of its length word.
277 *
278 * Internal, like @ref Wire. §7.3 bounds the type check at wire type *plus* this
279 * subtype, since `fp32`/`fp64`/`string`/`blob` share @ref Wire::Fixlen.
280 */
281 enum class Fix : uint8_t
282 {
283 Fp32 = 0, /**< 32-bit IEEE-754 float. */
284 Fp64 = 1, /**< 64-bit IEEE-754 double. */
285 String = 2, /**< UTF-8 text. */
286 Blob = 3, /**< Opaque byte string. */
287 };
288
289 /**
290 * @brief Widest base-128 varint: ceil(64/7) == 10 bytes (§4.1).
291 *
292 * The encoder and decoder both use it as the "one more varint definitely
293 * fits" window, so a capacity check can be hoisted out of an element loop
294 * and amortised over a whole chunk instead of paid per element.
295 */
296 inline constexpr size_t VARINT_MAX_BYTES = 10;
297
298 /**
299 * @brief Store a 64-bit word as eight little-endian bytes.
300 *
301 * The wire is little-endian (§4), so on a little-endian host this is the
302 * native representation and compiles to a single unaligned store; on a
303 * big-endian one the word is reversed first. `std::byteswap` is C++23, so
304 * the reversal is spelled out.
305 */
306 inline void storeLittle64(uint8_t *out, uint64_t w) noexcept
307 {
308 if constexpr (std::endian::native == std::endian::big)
309 w = ((w & 0x00000000000000FFull) << 56) | ((w & 0x000000000000FF00ull) << 40) |
310 ((w & 0x0000000000FF0000ull) << 24) | ((w & 0x00000000FF000000ull) << 8) |
311 ((w & 0x000000FF00000000ull) >> 8) | ((w & 0x0000FF0000000000ull) >> 24) |
312 ((w & 0x00FF000000000000ull) >> 40) | ((w & 0xFF00000000000000ull) >> 56);
313 std::memcpy(out, &w, sizeof w);
314 }
315
316 /**
317 * @brief Spread the low 56 bits of @p v into eight 7-bit groups, one per byte.
318 *
319 * Byte `i` of the result holds bits `[7i+6 : 7i]` of @p v, with bit 7 of
320 * each byte clear — exactly the payload layout of the first eight bytes of
321 * a base-128 varint. Three halve-and-shift rounds do it in a handful of
322 * ALU ops, which is what lets the encoder emit eight varint bytes as one
323 * store instead of eight.
324 */
325 constexpr uint64_t spread7(uint64_t v) noexcept
326 {
327 uint64_t w = v & 0x00FFFFFFFFFFFFFFull; /* 56 bits */
328 w = (w & 0x000000000FFFFFFFull) | ((w & 0x00FFFFFFF0000000ull) << 4); /* 2 x 28 */
329 /* The last two rounds are spelled as an add rather than the
330 * split-mask-and-recombine of the first. Once the groups are laid
331 * out, the two halves of a round *partition* the live bits — `w`
332 * equals `(w & keep) + (w & move)` exactly — so
333 * `(w & keep) | ((w & move) << k)` is `w + (2^k - 1) * (w & move)`,
334 * which drops one mask and one OR per round. That is three x86
335 * instructions off every varint the encoder writes; on the shared
336 * `u64 array` workload it is ~8 % of the whole encode. The first
337 * round cannot use it: it would need `w` pre-masked to 56 bits in a
338 * register of its own, which costs back more than it saves. */
339 w += 3u * (w & 0x0FFFC0000FFFC000ull); /* 4 x 14 */
340 w += (w & 0x3F803F803F803F80ull); /* 8 x 7 */
341 return w;
342 }
343
344 /**
345 * @brief Inverse of @ref spread7: pack eight bytes' low 7 bits into one value.
346 *
347 * Byte `i` of @p w contributes bits `[7i+6 : 7i]` of the result; bit 7 of
348 * each byte (the varint continuation flag) is discarded by the masks, so
349 * the caller need not clear it. The three rounds mirror @ref spread7's,
350 * run in the opposite order.
351 */
352 constexpr uint64_t gather7(uint64_t w) noexcept
353 {
354 w = (w & 0x007F007F007F007Full) | ((w & 0x7F007F007F007F00ull) >> 1); /* 4 x 14 */
355 w = (w & 0x00003FFF00003FFFull) | ((w & 0x3FFF00003FFF0000ull) >> 2); /* 2 x 28 */
356 w = (w & 0x000000000FFFFFFFull) | ((w & 0x0FFFFFFF00000000ull) >> 4); /* 56 bits */
357 return w;
358 }
359
360 /**
361 * @brief Store the object representation of a 4- or 8-byte value as
362 * little-endian bytes.
363 *
364 * The wire is little-endian (§4), so on a little-endian host this is one
365 * unaligned store; elsewhere the bytes are laid down individually. The
366 * hand-rolled shift loop this replaces did not fold into a store on GCC
367 * and cost ten instructions per `fp32` field.
368 *
369 * @tparam U Unsigned type holding the bits (`uint32_t` or `uint64_t`).
370 * @param out Destination, with at least `sizeof(U)` writable bytes.
371 * @param bits Value to lay down.
372 */
373 template <std::unsigned_integral U>
374 inline void storeLittleBits(uint8_t *out, U bits) noexcept
375 {
376 if constexpr (std::endian::native == std::endian::little)
377 std::memcpy(out, &bits, sizeof bits);
378 else
379 for (size_t i = 0; i < sizeof(U); ++i)
380 out[i] = static_cast<uint8_t>((bits >> (8 * i)) & 0xffu);
381 }
382
383 /** @brief Inverse of @ref storeLittleBits. */
384 template <std::unsigned_integral U>
385 inline U loadLittleBits(const uint8_t *in) noexcept
386 {
387 U bits;
388 if constexpr (std::endian::native == std::endian::little)
389 std::memcpy(&bits, in, sizeof bits);
390 else
391 {
392 bits = 0;
393 for (size_t i = 0; i < sizeof(U); ++i)
394 bits |= static_cast<U>(in[i]) << (8 * i);
395 }
396 return bits;
397 }
398
399 /** @brief Load eight little-endian bytes as a 64-bit word (see @ref storeLittle64). */
400 inline uint64_t loadLittle64(const uint8_t *in) noexcept
401 {
402 uint64_t w;
403 std::memcpy(&w, in, sizeof w);
404 if constexpr (std::endian::native == std::endian::big)
405 w = ((w & 0x00000000000000FFull) << 56) | ((w & 0x000000000000FF00ull) << 40) |
406 ((w & 0x0000000000FF0000ull) << 24) | ((w & 0x00000000FF000000ull) << 8) |
407 ((w & 0x000000FF00000000ull) >> 8) | ((w & 0x0000FF0000000000ull) >> 24) |
408 ((w & 0x00FF000000000000ull) >> 40) | ((w & 0xFF00000000000000ull) >> 56);
409 return w;
410 }
411
412 /**
413 * @brief Map a signed integer to an unsigned one with the zig-zag scheme.
414 *
415 * Small-magnitude values of either sign map to small unsigned values, so
416 * they encode to short varints.
417 *
418 * @param v Signed value to transform.
419 * @return The zig-zag-encoded unsigned representation.
420 */
421 constexpr uint64_t zigzagEncode(int64_t v) noexcept
422 {
423 return (static_cast<uint64_t>(v) << 1) ^ static_cast<uint64_t>(v >> 63);
424 }
425 /**
426 * @brief Inverse of @ref zigzagEncode.
427 * @param u Zig-zag-encoded unsigned value.
428 * @return The original signed value.
429 */
430 constexpr int64_t zigzagDecode(uint64_t u) noexcept
431 {
432 return static_cast<int64_t>((u >> 1) ^ (~(u & 1) + 1));
433 }
434
435 /**
436 * @brief The integer type an element travels as on the wire.
437 *
438 * Identity for an integer; the underlying type for an enumeration, whose
439 * declared width is what picks the signed or unsigned wire type and the
440 * zig-zag transform (MESSAGE_SPEC §1). `std::is_signed_v` is false for
441 * *every* enumeration, so asking the enum itself would silently answer
442 * "unsigned".
443 *
444 * The specialization is what makes it lazy: `std::conditional_t` would
445 * instantiate `std::underlying_type_t<E>` for a plain integer too, and
446 * that has no `type` — every existing integer array would stop compiling.
447 *
448 * @tparam E Element type as the caller declared it.
449 */
450 template <typename E, bool = std::is_enum_v<E>>
451 struct WireInt { using type = E; };
452 /** @brief Enumeration case of @ref WireInt: the declared underlying type. */
453 template <typename E>
454 struct WireInt<E, true> { using type = std::underlying_type_t<E>; };
455 /** @brief Alias for @ref WireInt. */
456 template <typename E>
457 using WireInt_t = typename WireInt<E>::type;
458
459 /**
460 * @brief Reinterpret a float/double as the unsigned integer holding its bits.
461 * @tparam F Floating-point type (`float` or `double`).
462 * @param v Value whose object representation is extracted.
463 * @return `uint32_t` for a 4-byte `F`, otherwise `uint64_t`.
464 */
465 template <std::floating_point F>
466 constexpr auto floatBits(F v) noexcept
467 {
468 if constexpr (sizeof(F) == 4) return std::bit_cast<uint32_t>(v);
469 else return std::bit_cast<uint64_t>(v);
470 }
471 /**
472 * @brief Reconstruct a floating-point value from its raw bits.
473 * @tparam F Target floating-point type.
474 * @tparam U Unsigned integer type holding the bit pattern.
475 * @param bits Object representation produced by @ref floatBits.
476 * @return The floating-point value those bits encode.
477 */
478 template <std::floating_point F, std::unsigned_integral U>
479 constexpr F bitsFloat(U bits) noexcept
480 {
481 return std::bit_cast<F>(bits);
482 }
483
484 /**
485 * @brief Validate that `[data, data+len)` is well-formed UTF-8.
486 *
487 * A real UTF-8 validator, not a byte-range shortcut — this is a security
488 * surface (CORELIB_PLAN §6.4). It **rejects**:
489 * - overlong encodings, including `C0 80` (Java "Modified UTF-8" NUL),
490 * `C1`-lead 2-byte forms, and the overlong 3-/4-byte `E0 80..`,
491 * `F0 80..` forms;
492 * - UTF-16 surrogate code points `U+D800`–`U+DFFF` (`ED A0..ED BF`);
493 * - code points above `U+10FFFF` (`F4 90..` and any `F5`–`FF` lead);
494 * - bare continuation bytes and any sequence truncated before its
495 * declared length ends (truncated-at-end is INVALID).
496 * It **accepts** an embedded `U+0000` (a single `00` byte): NUL is valid
497 * UTF-8 and representable in the length-framed payload (§6.4).
498 *
499 * `constexpr` and free of `reinterpret_cast`, so it can be evaluated at
500 * compile time and unit-tested directly.
501 *
502 * @param data Pointer to the candidate bytes (may be `nullptr` iff @p len is 0).
503 * @param len Number of bytes to validate.
504 * @return `true` iff every byte forms part of a well-formed UTF-8 sequence.
505 */
506 /* Hoehrmann UTF-8 DFA: class table (0..255) + transition table.
507 * ACCEPT = 0, REJECT = 12. Used only for the multi-byte tail; the
508 * ASCII run is skipped 8 bytes at a time by the SWAR loop below. */
509 inline constexpr uint8_t utf8Dfa[] = {
510 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
511 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
512 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
513 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
514 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
515 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
516 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
517 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8,
518 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
519 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
520 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12,
521 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12,
522 12,36,12,12,12,12,12,12,12,12,12,12,
523 };
524
525 /** @brief The DFA's ACCEPT and REJECT states (see @ref utf8Dfa). */
526 inline constexpr uint32_t UTF8_ACCEPT = 0;
527 inline constexpr uint32_t UTF8_REJECT = 12;
528
529 /**
530 * @brief Step the UTF-8 DFA over @p len bytes and return the state.
531 *
532 * The resumable half of @ref utf8Valid, for a `string` payload that arrives
533 * across more than one `feed`: §6.4.4 requires that "a chunk boundary MUST
534 * NOT affect the outcome" and permits exactly this — "A decoder MAY validate
535 * incrementally provided it carries validator state across `feed` calls; no
536 * assembly buffer is required."
537 *
538 * @ref UTF8_REJECT is absorbing, which is what lets the verdict be **held
539 * back**: §6.4.4's last row makes a byte that can begin no sequence
540 * `INVALID` "reported at payload completion, not before", and a decoder
541 * "MUST NOT report INVALID mid-payload … that input is INCOMPLETE until the
542 * payload ends". The caller therefore steps the state per chunk and consults
543 * it once, when the declared length is reached — where a state other than
544 * @ref UTF8_ACCEPT covers both a rejected byte and a sequence the payload
545 * ended in the middle of.
546 *
547 * @param state State from the previous piece (@ref UTF8_ACCEPT to start).
548 * @param d Bytes of this piece.
549 * @param len Their count.
550 * @return The state after them.
551 */
552 [[nodiscard]] constexpr uint32_t utf8Advance(uint32_t state, const uint8_t *d,
553 size_t len) noexcept
554 {
555 for (size_t i = 0; i < len; ++i)
556 state = utf8Dfa[256u + state + utf8Dfa[d[i]]];
557 return state;
558 }
559
560 [[nodiscard]] constexpr bool utf8Valid(const char *data, size_t len) noexcept
561 {
562 size_t i = 0;
563 while (i < len)
564 {
565 /* The ASCII run, which is where the time goes: payloads in
566 * practice are overwhelmingly ASCII, and a per-byte DFA over such
567 * a run is slower than skipping it. It is walked in two steps,
568 * word-at-a-time while a whole word is left and byte-at-a-time
569 * over what remains, and — this is the point — each step runs to
570 * completion before the other is considered again. Re-testing the
571 * word condition once per byte, as this loop used to, cost a
572 * short ASCII payload four branches per character: validating the
573 * five-byte string of the shared `typical message` workload took
574 * ~62 instructions, a quarter of the whole encode. */
575 if (!std::is_constant_evaluated())
576 {
577 /* Spelled `i + 8 <= len`, not `len - i >= 8`: the two are
578 * equal for `i <= len`, but only the first lets GCC's
579 * value-range pass see that eight bytes at `data + i` are
580 * in bounds — the subtraction reads as a possible unsigned
581 * wrap and costs a bogus -Warray-bounds under -Werror. */
582 while (i + 8 <= len)
583 {
584 uint64_t w;
585 __builtin_memcpy(&w, data + i, 8);
586 if (w & 0x8080808080808080ULL) break;
587 i += 8;
588 }
589 }
590 while (i < len && static_cast<unsigned char>(data[i]) < 0x80) ++i;
591 if (i >= len) return true;
592 /* multi-byte: step the DFA until it is back at ACCEPT (state 0),
593 * then hand control back to the ASCII scan. REJECT is state 12. */
594 uint32_t state = 0;
595 do
596 {
597 state = utf8Dfa[256u + state + utf8Dfa[static_cast<unsigned char>(data[i])]];
598 if (state == 12) return false;
599 ++i;
600 } while (state != 0 && i < len);
601 /* Input ended inside a multi-byte sequence: truncated is INVALID. */
602 if (state != 0) return false;
603 }
604 return true;
605 }
606
607 /**
608 * @brief The "size nothing" sizer: what a typed read does with the
609 * caller's destination between its checks and its delivery when the
610 * caller did not ask for sizing (the destination is used as handed).
611 */
612 struct NoSizer
613 {
614 template <typename D>
615 [[gnu::always_inline]] constexpr void operator()(D &, size_t) const noexcept {}
616 };
617
618 /**
619 * @brief The element ceiling a decode destination @p T publishes, or `-1`
620 * when it publishes none.
621 *
622 * The bound @ref IStreamImpl::readArray compares the wire count against
623 * before it fills anything (MESSAGE_SPEC §3): a heap-free destination that
624 * cannot reach the count must reject it, never truncate into it.
625 *
626 * Told apart by the destination's own capabilities rather than by name, so
627 * a caller's own container works too — a **static `capacity()`** is the
628 * ceiling (@ref InlineVector and friends: `resize` exists but clamps to
629 * `N`), everything else is treated as growable. `T::capacity()` is
630 * deliberately spelled as an unqualified static call: `std::vector`'s
631 * `capacity()` is a non-static member, so naming it this way is ill-formed
632 * and the requirement fails — exactly the growable / heap-free split
633 * @ref IStreamImpl::readString already keys on.
634 *
635 * A destination of **fixed extent that publishes nothing** (`std::array`,
636 * a bound span) is not covered here: that is @ref IStreamImpl::read's
637 * low-level contract, where the leading elements land in the destination
638 * and the rest is parsed only to stay framed.
639 */
640 template <typename T>
641 constexpr long destCapacity() noexcept
642 {
643 if constexpr (requires { T::capacity(); }) return static_cast<long>(T::capacity());
644 else return -1;
645 }
646
647 /**
648 * @brief Room a decode destination **already holds** — bytes for a payload,
649 * elements for an array (CORELIB_PLAN §6.6.3).
650 *
651 * §6.6 forbids the codec growing the caller's destination from a wire
652 * number: "the codec allocates nothing itself but **requires a growable
653 * destination** and grows it, from a wire count or otherwise — violates".
654 * §6.6.3 names the shape that replaces it — a value is delivered "into a
655 * destination the caller hands back after being told the announced count,
656 * **with the codec refusing a destination too short rather than growing
657 * it**" — so every typed read needs one number: how much room is there
658 * *now*.
659 *
660 * Two kinds of destination answer it differently, and the difference is
661 * not a policy the codec picks but a fact the type publishes:
662 *
663 * * a **static capacity** (`T::capacity()` — @ref sofab::FixedString,
664 * @ref sofab::FixedBytes, @ref sofab::InlineVector) is storage the caller already owns
665 * in full. Setting a length inside it allocates nothing, so the room is
666 * the capacity;
667 * * anything else (`std::string`, `std::vector`, `std::array`, a bound
668 * span) offers exactly `size()`. For a heap-growable container that is
669 * the point: the codec writes into what the caller sized and never
670 * creates room, so no allocator call can reach the wire.
671 *
672 * @tparam D Destination type.
673 * @param d The destination.
674 * @return Room in bytes (payload) or elements (array).
675 */
676 template <typename D>
677 constexpr size_t destRoom(const D &d) noexcept
678 {
679 if constexpr (requires { D::capacity(); }) return static_cast<size_t>(D::capacity());
680 else return d.size();
681 }
682
683 /**
684 * @brief Publish the decoded length in a destination that already had the
685 * room — the one container operation the codec performs.
686 *
687 * Never grows: @ref sofab::detail::destRoom has already been compared against the
688 * announced size, so `n` is at most what the destination holds and this is
689 * a length store (@ref sofab::FixedString::set_len) or a **shrink**. A shrink
690 * cannot allocate — `std::string` / `std::vector` never reallocate for a
691 * size below the current one — so §6.6's question, "can a sender make this
692 * allocation bigger by sending different bytes?", has no allocation to ask
693 * it of.
694 *
695 * A destination of fixed extent that publishes neither (`std::array`, a
696 * bound span) keeps its extent; the value's length is the announced count
697 * the caller was told.
698 *
699 * @param d Destination.
700 * @param n Decoded length, already known to fit.
701 */
702 template <typename D>
703 constexpr void destSetLen(D &d, size_t n) noexcept
704 {
705 if constexpr (requires { d.set_len(n); }) d.set_len(n);
706 else if constexpr (requires { d.resize(n); }) { if (d.size() != n) d.resize(n); }
707 }
708 } // namespace detail
709
710 /**
711 * @brief Public UTF-8 validity primitive (spec CORELIB_PLAN §6.4).
712 *
713 * Returns `true` iff @p bytes is well-formed UTF-8 by @ref detail::utf8Valid
714 * (rejecting overlong forms, surrogates and out-of-range code points;
715 * accepting embedded NUL). Independent of @ref SOFAB_STRICT_UTF8 — this is the
716 * validator itself, always available; the compile-time flag only decides
717 * whether the encode/decode paths *invoke* it.
718 *
719 * @param bytes Candidate string payload.
720 * @return `true` iff @p bytes is valid UTF-8.
721 */
722 [[nodiscard]] constexpr bool utf8_valid(std::string_view bytes) noexcept
723 {
724 return detail::utf8Valid(bytes.data(), bytes.size());
725 }
726
727 /* ---------------------------------------------------------------------- */
728 /* Heap-free containers */
729 /* ---------------------------------------------------------------------- */
730
731 /*
732 * The storage a schema-bounded field lowers to when the caller asks for
733 * static storage (generator `allow_dynamic: false`). They are the destination
734 * side of the same contract std::string / std::vector satisfy, so the typed
735 * reads below accept either and one generated header shape serves both.
736 *
737 * These three types are DELIBERATELY identical, in name and behaviour, to
738 * corelib-c-cpp's: the generator emits the same `sofab::FixedString<N>` /
739 * `sofab::FixedBytes<N>` / `sofab::InlineVector<T,N>` member for a bounded
740 * field whichever C++ corelib is selected, so the storage decision stays a
741 * property of the schema rather than of the runtime. Any behavioural change
742 * here has to land in corelib-c-cpp too, or the two profiles stop agreeing on
743 * what a schema means.
744 */
745
746 namespace detail
747 {
748 /*!
749 * @brief Length of the longest prefix of @p sv that is at most @p n bytes
750 * and does not end inside a UTF-8 character; @p sv is longer
751 * than @p n.
752 *
753 * The over-long half of @ref FixedString's assignment-time clamp, one
754 * copy for every capacity: the cut moves back while the first byte left
755 * out is a continuation byte (10xxxxxx), so a valid UTF-8 @p sv keeps a
756 * valid UTF-8 prefix. The common case -- the value fits -- stays inline
757 * in @ref FixedString::assign, where a literal's length folds away.
758 */
759 inline std::size_t utf8Prefix(std::string_view sv, std::size_t n) noexcept
760 {
761 while (n > 0 && (static_cast<unsigned char>(sv[n]) & 0xC0u) == 0x80u)
762 {
763 --n;
764 }
765 return n;
766 }
767 } // namespace detail
768
769 /*!
770 * @brief Fixed-capacity, heap-free string of up to @p N characters.
771 *
772 * A drop-in, embedded-friendly stand-in for @c std::string on both the encode
773 * and decode paths. The characters live in an inline @c std::array, so an
774 * instance allocates nothing, never throws (an over-long value is clamped to
775 * @p N bytes at a UTF-8 character boundary, see @ref assign), and compiles
776 * cleanly under @c -fno-exceptions / @c -fno-rtti. The buffer never
777 * moves, so an instance stays a valid decode destination across every
778 * @ref IStreamImpl::feed chunk.
779 *
780 * The storage is @c N+1 bytes: one extra slot always holds a trailing NUL so
781 * @ref c_str and the @c std::string_view encode path remain valid even at full
782 * length @p N. The buffer is zero-initialised, so the NUL is present from
783 * construction and is re-placed by every length-changing operation.
784 *
785 * @par Generator integration contract
786 * Generated code is spelled exactly as for @c std::string, so this type only
787 * has to keep the surface the typed calls look for:
788 * - decode emits @c is.readString(s, maxlen); — @ref IStreamImpl::readString
789 * picks the heap-free branch off @ref set_len / @ref capacity, rejects an
790 * over-@p N payload as INVALID (§7.1) rather than truncating it, and fills
791 * @ref data before fixing @ref size;
792 * - encode emits @c os.write(id, s); — the implicit @ref operator std::string_view
793 * routes it through the existing string encode branch, byte-for-byte
794 * identical to the same-content @c std::string.
795 *
796 * @tparam N Maximum number of characters (excluding the reserved NUL slot).
797 */
798 template <std::size_t N>
800 {
801 std::array<char, N + 1> buf_{}; //!< Inline storage (+1 for the NUL).
802 std::size_t len_ = 0; //!< Current logical length (<= N).
803
804 public:
805 /*! @brief Character type (mirrors @c std::string). */
806 using value_type = char;
807 /*! @brief Size type (mirrors @c std::string). */
808 using size_type = std::size_t;
809
810 /*! @brief Construct an empty string. */
811 FixedString() noexcept = default;
812
813 /*!
814 * @brief Construct from a NUL-terminated C string (clamped to @p N, see @ref assign).
815 * @param s Source string, or @c nullptr for an empty string.
816 */
817 FixedString(const char *s) noexcept
818 {
819 assign(s ? std::string_view{s} : std::string_view{});
820 }
821
822 /*!
823 * @brief Construct from a string view (clamped to @p N, see @ref assign).
824 * @param sv Source characters (may contain embedded NULs).
825 */
826 FixedString(std::string_view sv) noexcept
827 {
828 assign(sv);
829 }
830
831 /*!
832 * @brief Construct from a @c std::string (the easy on-ramp; truncated to @p N).
833 * @param s Source string.
834 */
835 FixedString(const std::string &s) noexcept
836 {
837 assign(std::string_view{s});
838 }
839
840 /*! @brief Assign from a NUL-terminated C string (clamped to @p N, see @ref assign). */
841 FixedString &operator=(const char *s) noexcept
842 {
843 assign(s ? std::string_view{s} : std::string_view{});
844 return *this;
845 }
846
847 /*! @brief Assign from a string view (clamped to @p N, see @ref assign). */
848 FixedString &operator=(std::string_view sv) noexcept
849 {
850 assign(sv);
851 return *this;
852 }
853
854 /*! @brief Assign from a @c std::string (clamped to @p N, see @ref assign). */
855 FixedString &operator=(const std::string &s) noexcept
856 {
857 assign(std::string_view{s});
858 return *this;
859 }
860
861 /*!
862 * @brief Replace the contents with @p sv, clamped to @p N bytes.
863 *
864 * The assignment-time clamp is a documented contract of the static
865 * storage (the generator's `allow_dynamic: false`): a value longer than
866 * @p N is cut, not refused, before any encoder sees it. The cut never
867 * lands inside a UTF-8 character -- it moves back to the start of the
868 * character that would not fit whole, so the kept prefix is valid UTF-8
869 * whenever @p sv is.
870 *
871 * @param sv Source characters (may contain embedded NULs).
872 * @return Reference to @c *this.
873 */
874 FixedString &assign(std::string_view sv) noexcept
875 {
876 len_ = sv.size() <= N ? sv.size() : detail::utf8Prefix(sv, N);
877 for (std::size_t i = 0; i < len_; ++i)
878 {
879 buf_[i] = sv[i];
880 }
881 buf_[len_] = '\0';
882 return *this;
883 }
884
885 /*!
886 * @brief Decode hook: set the logical length and (re)place the trailing NUL.
887 *
888 * Fixes @c size() to the decoded payload length (clamped to @p N) and
889 * writes the NUL at @c buf_[len_]. @ref IStreamImpl::readString calls it
890 * after copying @c [0, size()) and never touches @c buf_[len_], so the NUL
891 * survives and @ref c_str stays valid. Re-decoding a shorter value
892 * re-terminates here. Its presence is also what marks this type as a
893 * heap-free destination to the typed reads (@c requires { set_len(...) }).
894 *
895 * @param n Requested logical length (clamped to @p N).
896 */
897 void set_len(std::size_t n) noexcept
898 {
899 len_ = n > N ? N : n;
900 buf_[len_] = '\0';
901 }
902
903 /*! @brief Mutable pointer to the character buffer (decode target). */
904 char *data() noexcept { return buf_.data(); }
905 /*! @brief Const pointer to the character buffer. */
906 const char *data() const noexcept { return buf_.data(); }
907 /*! @brief NUL-terminated view of the contents. */
908 const char *c_str() const noexcept { return buf_.data(); }
909
910 /*! @brief Number of characters currently stored. */
911 std::size_t size() const noexcept { return len_; }
912 /*! @brief Alias of @ref size. */
913 std::size_t length() const noexcept { return len_; }
914 /*! @brief True if the string is empty. */
915 bool empty() const noexcept { return len_ == 0; }
916 /*! @brief Maximum number of characters (the template parameter @p N). */
917 static constexpr std::size_t capacity() noexcept { return N; }
918 /*! @brief Alias of @ref capacity. */
919 static constexpr std::size_t max_size() noexcept { return N; }
920
921 /*! @brief Access the character at @p i (no bounds checking). */
922 char &operator[](std::size_t i) noexcept { return buf_[i]; }
923 /*! @brief Access the character at @p i (no bounds checking). */
924 const char &operator[](std::size_t i) const noexcept { return buf_[i]; }
925
926 /*! @brief Iterator to the first character. */
927 char *begin() noexcept { return buf_.data(); }
928 /*! @brief Iterator past the last character. */
929 char *end() noexcept { return buf_.data() + len_; }
930 /*! @brief Const iterator to the first character. */
931 const char *begin() const noexcept { return buf_.data(); }
932 /*! @brief Const iterator past the last character. */
933 const char *end() const noexcept { return buf_.data() + len_; }
934
935 /*! @brief Reset to an empty string. */
936 void clear() noexcept
937 {
938 len_ = 0;
939 buf_[0] = '\0';
940 }
941
942 /*! @brief Non-owning view over the current characters. */
943 std::string_view view() const noexcept
944 {
945 return std::string_view{buf_.data(), len_};
946 }
947
948 /*!
949 * @brief Implicit conversion to @c std::string_view.
950 *
951 * Gives a cheap non-owning view and makes the existing string encode
952 * branch (@c OStreamImpl::write) match a @c FixedString automatically.
953 */
954 operator std::string_view() const noexcept
955 {
956 return view();
957 }
958
959 /*! @brief Copy the contents into an owning @c std::string (allocates). */
960 std::string str() const
961 {
962 return std::string{buf_.data(), len_};
963 }
964
965 /*! @brief Equality against any string view-like operand. */
966 bool operator==(std::string_view rhs) const noexcept
967 {
968 return view() == rhs;
969 }
970
971 /*! @brief Inequality against any string view-like operand. */
972 bool operator!=(std::string_view rhs) const noexcept
973 {
974 return view() != rhs;
975 }
976 };
977
978 /*!
979 * @brief Fixed-capacity, heap-free byte blob of up to @p N bytes.
980 *
981 * The embedded-friendly counterpart of @c std::vector<std::uint8_t> for blob
982 * fields, mirroring @ref FixedString for bytes. The payload lives in an inline
983 * @c std::array, so an instance allocates nothing and never throws (overflow
984 * clamps to @p N). The buffer never moves, so an instance stays a valid decode
985 * destination across every @ref IStreamImpl::feed chunk.
986 *
987 * A @b logical @b length (@ref size, @c <= @p N) is tracked separately from the
988 * capacity @p N: a blob shorter than its schema @c maxlen occupies only
989 * @ref size bytes on the wire. This is exactly why the type cannot be a plain
990 * @c std::array<std::uint8_t,N> (always length @p N) and must not reintroduce
991 * the heap of @c std::vector.
992 *
993 * @par Generator integration contract
994 * Generated code is spelled exactly as for @c std::vector<std::uint8_t>:
995 * - encode passes @ref data / @ref size to the blob write, byte-for-byte
996 * identical to the same-content vector;
997 * - decode emits @c is.readBlob(b, maxlen); — @ref IStreamImpl::readBlob picks
998 * the heap-free branch off @ref set_len / @ref capacity and rejects an
999 * over-@p N wire length as INVALID per MESSAGE_SPEC §7.1 instead of
1000 * truncating it.
1001 *
1002 * @tparam N Maximum number of bytes.
1003 */
1004 template <std::size_t N>
1006 {
1007 std::array<std::uint8_t, N> buf_{}; //!< Inline storage.
1008 std::size_t len_ = 0; //!< Current logical length (<= N).
1009
1010 public:
1011 /*! @brief Element type (mirrors @c std::vector). */
1012 using value_type = std::uint8_t;
1013 /*! @brief Size type (mirrors @c std::vector). */
1014 using size_type = std::size_t;
1015
1016 /*! @brief Construct an empty blob. */
1017 FixedBytes() noexcept = default;
1018
1019 /*!
1020 * @brief Construct from a brace-enclosed list of bytes (clamped to @p N; extra bytes are dropped).
1021 *
1022 * Providing this constructor makes @c FixedBytes a non-aggregate, so a
1023 * brace-init such as @c b = {1, 2, 3} routes through here and sets
1024 * @ref size — it cannot silently fill the buffer while leaving the logical
1025 * length at zero.
1026 *
1027 * @param init Source bytes (excess beyond @p N is dropped).
1028 */
1029 FixedBytes(std::initializer_list<std::uint8_t> init) noexcept
1030 {
1031 assign(init);
1032 }
1033
1034 /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra bytes are dropped). */
1035 FixedBytes &operator=(std::initializer_list<std::uint8_t> init) noexcept
1036 {
1037 return assign(init);
1038 }
1039
1040 /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra bytes are dropped). */
1041 FixedBytes &assign(std::initializer_list<std::uint8_t> init) noexcept
1042 {
1043 len_ = 0;
1044 for (std::uint8_t b : init)
1045 {
1046 if (len_ >= N)
1047 {
1048 break;
1049 }
1050 buf_[len_++] = b;
1051 }
1052 return *this;
1053 }
1054
1055 /*! @brief Mutable pointer to the byte buffer (decode target). */
1056 std::uint8_t *data() noexcept { return buf_.data(); }
1057 /*! @brief Const pointer to the byte buffer. */
1058 const std::uint8_t *data() const noexcept { return buf_.data(); }
1059
1060 /*! @brief Number of bytes currently stored. */
1061 std::size_t size() const noexcept { return len_; }
1062 /*! @brief True if the blob is empty. */
1063 bool empty() const noexcept { return len_ == 0; }
1064 /*! @brief Maximum number of bytes (the template parameter @p N). */
1065 static constexpr std::size_t capacity() noexcept { return N; }
1066 /*! @brief Alias of @ref capacity. */
1067 static constexpr std::size_t max_size() noexcept { return N; }
1068
1069 /*!
1070 * @brief Decode hook: set the logical length (clamped to @p N).
1071 *
1072 * Called by generated decode before binding the buffer, so @ref size
1073 * reports the field length and @ref data over that many bytes is the
1074 * fill target.
1075 *
1076 * @param n Requested logical length (clamped to @p N).
1077 */
1078 void set_len(std::size_t n) noexcept { len_ = n < N ? n : N; }
1079
1080 /*! @brief Reset to an empty blob. */
1081 void clear() noexcept { len_ = 0; }
1082
1083 /*! @brief Append one byte (no-op once at capacity @p N). */
1084 void push_back(std::uint8_t b) noexcept
1085 {
1086 if (len_ < N)
1087 {
1088 buf_[len_++] = b;
1089 }
1090 }
1091
1092 /*! @brief Access the byte at @p i (no bounds checking). */
1093 std::uint8_t &operator[](std::size_t i) noexcept { return buf_[i]; }
1094 /*! @brief Access the byte at @p i (no bounds checking). */
1095 const std::uint8_t &operator[](std::size_t i) const noexcept { return buf_[i]; }
1096
1097 /*! @brief Iterator to the first byte. */
1098 std::uint8_t *begin() noexcept { return buf_.data(); }
1099 /*! @brief Iterator past the last byte. */
1100 std::uint8_t *end() noexcept { return buf_.data() + len_; }
1101 /*! @brief Const iterator to the first byte. */
1102 const std::uint8_t *begin() const noexcept { return buf_.data(); }
1103 /*! @brief Const iterator past the last byte. */
1104 const std::uint8_t *end() const noexcept { return buf_.data() + len_; }
1105
1106 /*! @brief Content equality (same logical length and bytes). */
1107 bool operator==(const FixedBytes &o) const noexcept
1108 {
1109 if (len_ != o.len_)
1110 {
1111 return false;
1112 }
1113 for (std::size_t i = 0; i < len_; ++i)
1114 {
1115 if (buf_[i] != o.buf_[i])
1116 {
1117 return false;
1118 }
1119 }
1120 return true;
1121 }
1122
1123 /*! @brief Negated @ref operator==. */
1124 bool operator!=(const FixedBytes &o) const noexcept { return !(*this == o); }
1125 };
1126
1127 /*!
1128 * @brief Fixed-capacity, heap-free sequence of up to @p N elements of type @p T.
1129 *
1130 * The embedded-friendly counterpart of @c std::vector<T> for every array a
1131 * schema bounds with a @c count: native scalars as well as strings, blobs,
1132 * structs/unions and nested arrays. Elements live in an inline
1133 * @c std::array, so the storage never reallocates and an element being filled
1134 * across @ref IStreamImpl::feed chunks stays address-stable — strictly safer
1135 * than a @c std::vector + @c reserve.
1136 *
1137 * @ref resize is what marks this type as a resizable destination to
1138 * @ref IStreamImpl::readArray, which sizes it to the wire element count. That
1139 * count IS the array's length (MESSAGE_SPEC §3); @p N is the schema @c count,
1140 * a capacity that bounds it and never adds to it.
1141 *
1142 * A @b logical @b length (@ref size, @c <= @p N) is tracked separately from the
1143 * capacity @p N: an array shorter than its schema @c count holds only
1144 * @ref size elements. This is why the type is neither a plain
1145 * @c std::array<T,N> (always length @p N) nor a heap-backed @c std::vector.
1146 *
1147 * @warning Historically this was an aggregate with a public, default-zero
1148 * length, so a natural brace-init such as @c v = {a, b, c} silently filled the
1149 * storage while leaving the logical length at 0 — the field then encoded as
1150 * empty. The @c initializer_list constructor/assignment below make the type a
1151 * non-aggregate, so that brace-init now sets @ref size correctly instead of
1152 * corrupting the wire.
1153 *
1154 * @tparam T Element type.
1155 * @tparam N Maximum number of elements.
1156 */
1157 template <typename T, std::size_t N>
1159 {
1160 std::array<T, N> buf_{}; //!< Inline storage.
1161 std::size_t len_ = 0; //!< Current logical length (<= N).
1162
1163 public:
1164 /*! @brief Element type (mirrors @c std::vector). */
1165 using value_type = T;
1166 /*! @brief Size type (mirrors @c std::vector). */
1167 using size_type = std::size_t;
1168
1169 /*! @brief Construct an empty sequence. */
1170 InlineVector() noexcept = default;
1171
1172 /*!
1173 * @brief Construct from a brace-enclosed list of elements (clamped to @p N; extra elements are dropped).
1174 *
1175 * The presence of this constructor makes @c InlineVector a non-aggregate:
1176 * @c v = {a, b, c} routes here and sets @ref size, instead of aggregate
1177 * brace-init filling the storage while leaving the length at 0.
1178 *
1179 * @param init Source elements (excess beyond @p N is dropped).
1180 */
1181 InlineVector(std::initializer_list<T> init) noexcept
1182 {
1183 assign(init);
1184 }
1185
1186 /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra elements are dropped). */
1187 InlineVector &operator=(std::initializer_list<T> init) noexcept
1188 {
1189 return assign(init);
1190 }
1191
1192 /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra elements are dropped). */
1193 InlineVector &assign(std::initializer_list<T> init) noexcept
1194 {
1195 len_ = 0;
1196 for (const T &v : init)
1197 {
1198 if (len_ >= N)
1199 {
1200 break;
1201 }
1202 buf_[len_++] = v;
1203 }
1204 return *this;
1205 }
1206
1207 /*! @brief Number of elements currently stored. */
1208 std::size_t size() const noexcept { return len_; }
1209 /*! @brief True if the sequence is empty. */
1210 bool empty() const noexcept { return len_ == 0; }
1211 /*! @brief Maximum number of elements (the template parameter @p N). */
1212 static constexpr std::size_t capacity() noexcept { return N; }
1213 /*! @brief Alias of @ref capacity. */
1214 static constexpr std::size_t max_size() noexcept { return N; }
1215
1216 /*! @brief No-op (inline storage never reallocates); present for API parity. */
1217 void reserve(std::size_t) noexcept {}
1218 /*! @brief Reset to an empty sequence (logical length only). */
1219 void clear() noexcept { len_ = 0; }
1220
1221 /*!
1222 * @brief Set the logical length to @p n, value-initializing what changes.
1223 *
1224 * The @c std::vector member of the container API this type mirrors, and the
1225 * one @ref IStreamImpl::readArray and the wrapper-array collectors probe
1226 * for: readArray *resizes* a resizable destination and *value-initializes*
1227 * a fixed-extent one, and without this method an @c InlineVector matched
1228 * neither — it fell to the fixed-extent branch, which assigned a
1229 * default-constructed container and so set the logical length to 0. The
1230 * decode then bound an empty span and dropped the array silently. With
1231 * @ref resize present, readArray keeps ownership of the tag / bound /
1232 * reset / bind order it documents, for inline storage too.
1233 *
1234 * Slots that enter or leave the logical range are set to @c T{}, so the
1235 * elements a shorter value no longer covers cannot be observed through a
1236 * later grow. @p n above the capacity @p N is clamped to @p N — the callers
1237 * that can reject an over-capacity count do so before resizing (readArray
1238 * checks the schema `count` first), and a heap-free container has nowhere
1239 * to put the excess.
1240 *
1241 * @param n New logical length.
1242 */
1243 void resize(std::size_t n) noexcept
1244 {
1245 if (n > N)
1246 {
1247 n = N;
1248 }
1249 for (std::size_t i = n; i < len_; ++i)
1250 {
1251 buf_[i] = T{};
1252 }
1253 for (std::size_t i = len_; i < n; ++i)
1254 {
1255 buf_[i] = T{};
1256 }
1257 len_ = n;
1258 }
1259
1260 /*!
1261 * @brief Append a default-constructed element and return a reference to it.
1262 *
1263 * The next inline slot is (re)set to @c T{} and bound; once at capacity
1264 * @p N the last slot is reused so a decode never writes out of bounds.
1265 * @return Reference to the newly active element.
1266 */
1267 T &emplace_back() noexcept
1268 {
1269 std::size_t i = len_ < N ? len_++ : N - 1;
1270 buf_[i] = T{};
1271 return buf_[i];
1272 }
1273
1274 /*!
1275 * @brief Append a copy of @p v; once at capacity @p N, @p v is dropped.
1276 *
1277 * The assignment-time clamp of the static storage: elements past @p N
1278 * are left out and the ones already held are kept, so a filled container
1279 * holds the first @p N values it was given. (@ref emplace_back, the
1280 * decode-side binder, reuses the last slot instead.)
1281 */
1282 void push_back(const T &v) noexcept { if (len_ < N) buf_[len_++] = v; }
1283 /*! @brief Append @p v by move; dropped once at capacity @p N (see above). */
1284 void push_back(T &&v) noexcept { if (len_ < N) buf_[len_++] = static_cast<T &&>(v); }
1285
1286 /*! @brief Reference to the last element. */
1287 T &back() noexcept { return buf_[len_ - 1]; }
1288 /*! @brief Const reference to the last element. */
1289 const T &back() const noexcept { return buf_[len_ - 1]; }
1290
1291 /*! @brief Access the element at @p i (no bounds checking). */
1292 T &operator[](std::size_t i) noexcept { return buf_[i]; }
1293 /*! @brief Access the element at @p i (no bounds checking). */
1294 const T &operator[](std::size_t i) const noexcept { return buf_[i]; }
1295
1296 /*! @brief Mutable pointer to the underlying storage. */
1297 T *data() noexcept { return buf_.data(); }
1298 /*! @brief Const pointer to the underlying storage. */
1299 const T *data() const noexcept { return buf_.data(); }
1300
1301 /*! @brief Iterator to the first element. */
1302 T *begin() noexcept { return buf_.data(); }
1303 /*! @brief Iterator past the last element. */
1304 T *end() noexcept { return buf_.data() + len_; }
1305 /*! @brief Const iterator to the first element. */
1306 const T *begin() const noexcept { return buf_.data(); }
1307 /*! @brief Const iterator past the last element. */
1308 const T *end() const noexcept { return buf_.data() + len_; }
1309
1310 /*! @brief Content equality (same logical length and elements). */
1311 bool operator==(const InlineVector &o) const noexcept
1312 {
1313 if (len_ != o.len_)
1314 {
1315 return false;
1316 }
1317 for (std::size_t i = 0; i < len_; ++i)
1318 {
1319 if (!(buf_[i] == o.buf_[i]))
1320 {
1321 return false;
1322 }
1323 }
1324 return true;
1325 }
1326
1327 /*! @brief Negated @ref operator==. */
1328 bool operator!=(const InlineVector &o) const noexcept { return !(*this == o); }
1329 };
1330
1331 /* ---------------------------------------------------------------------- */
1332 /* OStream */
1333 /* ---------------------------------------------------------------------- */
1334
1335 class OStreamMessage;
1336
1337 /**
1338 * @brief Base of the output streams: encodes values into a caller-provided buffer.
1339 *
1340 * Holds the write cursor and the encoding logic but owns no storage itself;
1341 * the buffer is supplied by a derived class (@ref OStream, @ref OStreamInline).
1342 * When the buffer fills, the optional flush callback is invoked with the bytes
1343 * accumulated so far and the cursor rewinds, so a message may exceed the buffer
1344 * (and even RAM). Without a callback, overflow returns @ref Error::BufferFull.
1345 *
1346 * Write calls return a chainable @ref Result that latches the first error.
1347 */
1349 {
1350 /* The wire tag types are implementation detail (sofab::detail); these
1351 * aliases keep this class terse without re-exporting the names. */
1352 using Wire = detail::Wire;
1353 using Fix = detail::Fix;
1354
1355 public:
1356 /** Callback invoked with a span of finished bytes whenever the buffer flushes. */
1357 using flushCallback = std::function<void(std::span<const uint8_t>)>;
1358
1359 protected:
1360 uint8_t *buffer_ = nullptr; /**< Start of the active buffer. */
1361 uint8_t *cursor_ = nullptr; /**< Current write position. */
1362 uint8_t *end_ = nullptr; /**< One past the end of the buffer. */
1363 /**
1364 * @brief Start offset of the **current installation** (§5.1).
1365 *
1366 * Where this installation's writable region begins, so `cursor_ - (buffer_
1367 * + offset_)` is the number of *message* bytes buffered — as opposed to
1368 * @ref bytesUsed, which counts from the buffer start because the reserved
1369 * head is part of the packet a sink is handed. @ref flush uses the former:
1370 * a freshly installed buffer holding nothing but its own reservation has
1371 * nothing to drain, and must not be pushed at the sink as an empty packet.
1372 *
1373 * The offset is **consumed** by the first flush that returns without an
1374 * installation, which is why it drops to zero there alongside the cursor.
1375 */
1376 size_t offset_ = 0;
1377 flushCallback flushCallback_; /**< Invoked when the buffer fills; may be empty. */
1378 size_t seqDepth_ = 0; /**< Number of currently-open nested sequences (§4.9 @ref MAX_DEPTH). */
1379 /**
1380 * @brief The held-back sequence run: ids of the innermost open sequences
1381 * whose header has not been written yet (@ref sequenceBeginLazy).
1382 *
1383 * Always a contiguous suffix of the open sequences — writing any field
1384 * commits the whole run at once — and it is **fixed-size state**
1385 * (CORELIB_PLAN §6.6.2), sized to its full extent when the stream is
1386 * constructed: "The pending run is fixed-size state (§6.6.2): at most
1387 * `MAX_DEPTH` ids, **sized at construction**. An implementation **MUST**
1388 * hold back to the full `MAX_DEPTH` (§6.2) and is thereby canonical at
1389 * every depth." (§6.0.1, "How deep the hold-back reaches"). @ref MAX_DEPTH
1390 * is what bounds the nesting, hence the run; @ref sequenceBeginLazy
1391 * refuses past it, so the array below can never be outrun.
1392 */
1394 {
1395 /**
1396 * The whole run, inside the stream object. Deliberately **not**
1397 * value-initialized: only the first @ref n_ entries are ever read, so
1398 * zeroing a kilobyte on every stream construction would be a cost with
1399 * no observable effect (§10 — `encode: typical message` is a
1400 * three-figure instruction count, and this array is larger than it).
1401 */
1402 sofab::id ids_[static_cast<size_t>(MAX_DEPTH)];
1403 size_t n_ = 0; /**< total ids held back */
1404
1405 public:
1406 /** @return `true` while no header is held back. */
1407 [[nodiscard]] bool empty() const noexcept { return n_ == 0; }
1408 /** @return How many headers are held back. */
1409 [[nodiscard]] size_t size() const noexcept { return n_; }
1410 /** @return The @p i-th held-back id, outermost first. */
1411 [[nodiscard]] sofab::id operator[](size_t i) const noexcept { return ids_[i]; }
1412 /**
1413 * @brief Hold back one more id (the new innermost open sequence).
1414 *
1415 * Allocates nothing — the run was sized at construction. The `false`
1416 * return is kept for the caller that already handles it, but it can
1417 * only be reached by a push past @ref MAX_DEPTH, which
1418 * @ref OStreamImpl::sequenceBeginLazy rejects one step earlier.
1419 *
1420 * @return `true` if the id is held back, `false` if the run is full.
1421 */
1422 [[nodiscard]] bool push(sofab::id v) noexcept
1423 {
1424 if (n_ >= static_cast<size_t>(MAX_DEPTH)) [[unlikely]] return false;
1425 ids_[n_++] = v;
1426 return true;
1427 }
1428 /** Drop the innermost held-back id — its sequence got no content. */
1429 void pop() noexcept
1430 {
1431 if (n_ == 0) return;
1432 --n_;
1433 }
1434 /** Forget the whole run (it has just been written out). */
1435 void clear() noexcept { n_ = 0; }
1436 };
1438 /**
1439 * @brief Sticky first failure of this stream (see @ref ok, @ref error).
1440 *
1441 * @ref Error::None while the encode is healthy, and one of §6.3's codes
1442 * from the moment a write could not be honoured: @ref Error::BufferFull
1443 * on an overflow with no sink (and on a hold-back run that could not
1444 * grow), @ref Error::InvalidArgument when a buffer installation was
1445 * rejected (§5.1 — an out-of-range offset, or less than
1446 * @ref MIN_OUTPUT_BUFFER usable bytes behind a sink) or when a field the
1447 * caller asked for was refused (a field id past @ref ID_MAX, a
1448 * sub-message past @ref MAX_DEPTH, a string that is not valid UTF-8
1449 * under §6.4, an array of more than @ref ARRAY_MAX elements, a payload
1450 * past @ref FIXLEN_MAX, a negative raw-blob length past §6.2's fixlen
1451 * bound).
1452 * Only the first is kept: once condemned, the stream stays
1453 * condemned for the reason it was condemned for.
1454 *
1455 * Everything that turns this non-None goes through @ref latch, so that
1456 * the set of failures the verdict covers is the set of failures the
1457 * write path can report — §5.1's "an encoder that could not write what
1458 * it was asked to write reports it".
1459 */
1461 /**
1462 * @brief Set by @ref initBuffer, cleared right before a flush callback runs.
1463 *
1464 * This is how the stream tells the two halves of §5.1's returning-callback
1465 * contract apart: a sink that returns **without** installing a buffer
1466 * copied, and the encoder resumes in the same buffer at offset 0; a sink
1467 * that **took** the buffer installed a replacement, and that installation's
1468 * own start offset is the cursor. Without it a taking sink's offset would
1469 * be overwritten the moment the callback returned, so per-packet header
1470 * room could not be re-armed.
1471 */
1472 bool installed_ = false;
1473
1474 /** Construct an unattached stream; a derived class must call @ref initBuffer. */
1475 OStreamImpl() noexcept = default;
1476
1477 /**
1478 * @brief Record a failure in the sticky verdict and hand it straight back.
1479 *
1480 * The one place @ref failure_ is written, so every refusal the write path
1481 * can return also reaches @ref ok / @ref error. That matters because the
1482 * per-call @ref Result is routinely discarded — a generated `serialize()`
1483 * issues its writes one at a time and checks nothing — and without this
1484 * an encode that dropped a field would come back indistinguishable from a
1485 * complete one (§5.1: an encoder MUST NOT return partial output as if it
1486 * were complete).
1487 *
1488 * First failure wins: a stream stays condemned for the reason it was
1489 * condemned for, so a later overflow cannot paper over the refusal that
1490 * actually cost the message a field.
1491 *
1492 * @param e The failure to report; must not be @ref Error::None.
1493 * @return @p e, unchanged, whatever the verdict already held.
1494 */
1495 Error latch(Error e) noexcept
1496 {
1497 if (failure_ == Error::None) failure_ = e;
1498 return e;
1499 }
1500
1501 /**
1502 * @brief Point the stream at a buffer and position the write cursor.
1503 *
1504 * This is the one place a buffer is handed over, so it is where §5.1's
1505 * preconditions are checked and where a bad buffer is rejected — never
1506 * partway through a message. On rejection the stream is left **inert**
1507 * (cursor at the end, nothing writable) with @ref failure_ latched, so no
1508 * subsequent write can touch storage that cannot hold it.
1509 *
1510 * @param buffer Storage to encode into.
1511 * @param buflen Capacity of @p buffer in bytes.
1512 * @param offset Number of leading bytes to leave untouched before the cursor.
1513 */
1514 void initBuffer(uint8_t *buffer, size_t buflen, size_t offset) noexcept
1515 {
1516 installed_ = true;
1517 /* §5.1: the minimum binds a buffer installed WITH a sink and no other.
1518 * Without a sink no flush can occur, so nothing can be split and the
1519 * buffer either holds the message or reports BufferFull — a two-byte
1520 * message must still encode into a two-byte buffer. */
1521 if (offset > buflen ||
1522 (flushCallback_ && buflen - offset < MIN_OUTPUT_BUFFER))
1523 {
1524 buffer_ = cursor_ = end_ = buffer;
1525 offset_ = 0;
1527 return;
1528 }
1529 buffer_ = buffer;
1530 cursor_ = buffer + offset;
1531 end_ = buffer + buflen;
1532 offset_ = offset;
1533 }
1534
1535 /**
1536 * @brief Encode an unsigned value as a base-128 varint.
1537 * @param out Destination buffer; must hold at least 10 bytes.
1538 * @param v Value to encode.
1539 * @return Number of bytes written to @p out (1–10).
1540 */
1541 static size_t encodeVarint(uint8_t *out, uint64_t v) noexcept
1542 {
1543 /* Continuation-first: every byte but the last is unconditionally
1544 * tagged, so the loop carries one test (`more to come?`) instead of
1545 * the two a "shift, then decide whether to tag" body needs. */
1546 uint8_t *p = out;
1547 while (v >= 0x80)
1548 {
1549 *p++ = static_cast<uint8_t>(static_cast<uint8_t>(v) | 0x80u);
1550 v >>= 7;
1551 }
1552 *p++ = static_cast<uint8_t>(v);
1553 return static_cast<size_t>(p - out);
1554 }
1555
1556 /**
1557 * @brief Encode a varint into a destination with a full varint window.
1558 *
1559 * The caller must guarantee @ref detail::VARINT_MAX_BYTES writable bytes at
1560 * @p out. That buys a branch-free body: the length comes from the value's
1561 * bit width in one instruction instead of being discovered a byte at a
1562 * time, and all ten bytes are then written unconditionally, with only the
1563 * last one of the *encoded* run untagged. Bytes past the returned length
1564 * are scratch — the cursor never advances over them, so they are always
1565 * overwritten by the next value or left outside the message.
1566 *
1567 * The single-byte case is peeled off first: it is by far the most common
1568 * value in real data, and paying ten stores for it would lose more on
1569 * small-element arrays than the wide case gains.
1570 *
1571 * @param out Destination, with at least @ref detail::VARINT_MAX_BYTES bytes.
1572 * @param v Value to encode.
1573 * @return Number of meaningful bytes written (1–10).
1574 */
1575 static size_t encodeVarintPadded(uint8_t *out, uint64_t v) noexcept
1576 {
1577 if (v < 0x80)
1578 {
1579 out[0] = static_cast<uint8_t>(v);
1580 return 1;
1581 }
1582 /* The varint length is ceil(bit_width(v) / 7). Spelling the divide as
1583 * a multiply and a shift is exact for every width 1..64 — check
1584 * b = 7k and 7k+1 for k = 1..9 and it holds at both sides of every
1585 * step — and costs a few instructions instead of a division. */
1586 const size_t bits = 64u - static_cast<size_t>(std::countl_zero(v));
1587 const size_t n = (bits * 9u + 64u) >> 6;
1588 /* Bytes 0-7 carry bits 0-55 and go out as one word; bytes 8 and 9
1589 * carry what is left of a 64-bit value. Everything is tagged as a
1590 * continuation, then the last byte of the encoded run is untagged. */
1591 detail::storeLittle64(out, detail::spread7(v) | 0x8080808080808080ull);
1592 out[8] = static_cast<uint8_t>((static_cast<uint8_t>(v >> 56) & 0x7fu) | 0x80u);
1593 out[9] = static_cast<uint8_t>(v >> 63);
1594 out[n - 1] = static_cast<uint8_t>(out[n - 1] & 0x7fu);
1595 return n;
1596 }
1597
1598 /**
1599 * @brief Append a single byte, flushing first if the buffer is full.
1600 * @param b Byte to write.
1601 * @return @ref Error::None on success, or @ref Error::BufferFull if the
1602 * buffer is full and no flush callback is set.
1603 */
1604 [[nodiscard]] Error pushByte(uint8_t b) noexcept
1605 {
1606 /* A condemned stream writes nothing more. Besides keeping a truncated
1607 * encode a byte-exact prefix of the full one, this is what makes a
1608 * rejected installation safe: the inert buffer left behind by
1609 * @ref initBuffer has cursor == end, and without this test the flush
1610 * path below would fall through to the store and run off it. */
1611 if (failure_ != Error::None) [[unlikely]] return failure_;
1612 if (cursor_ == end_)
1613 {
1614 if (!flushCallback_)
1615 {
1616 // Sticky, because a caller may issue writes one at a time and
1617 // discard each Result — generated serialize() bodies do — and
1618 // then nothing would record that the output was cut short.
1619 return latch(Error::BufferFull);
1620 }
1621 /* §5.1, the returning-callback contract. The sink either copied —
1622 * it returns without installing anything, and the same buffer is
1623 * reused from offset 0 — or it took the buffer and installed a
1624 * replacement, whose own start offset is already the cursor and
1625 * must not be overwritten here. */
1626 installed_ = false;
1627 flushCallback_(std::span<const uint8_t>(buffer_, static_cast<size_t>(cursor_ - buffer_)));
1628 if (failure_ != Error::None) [[unlikely]] return failure_; /* the sink installed a rejected buffer */
1629 if (!installed_) { cursor_ = buffer_; offset_ = 0; } /* the offset is consumed */
1630 }
1631 *cursor_++ = b;
1632 return Error::None;
1633 }
1634
1635 /**
1636 * @brief Append a run of bytes.
1637 *
1638 * Uses a single `memcpy` when the payload fits the remaining buffer (the
1639 * common case); otherwise falls back to a byte-by-byte copy that flushes
1640 * across buffer boundaries.
1641 *
1642 * @param data Source bytes.
1643 * @param len Number of bytes to append.
1644 * @return @ref Error::None on success, or @ref Error::BufferFull if the
1645 * buffer fills with no flush callback set.
1646 */
1647 [[nodiscard]] Error pushBytes(const uint8_t *data, size_t len) noexcept
1648 {
1649 if (static_cast<size_t>(end_ - cursor_) >= len) [[likely]]
1650 {
1651 /* An empty string or blob passes a null @p data, and memcpy
1652 * forbids that even for a zero length (§7.1.4 [mem.req]) — which
1653 * UBSan reports on the shared-vector suite. */
1654 if (len) std::memcpy(cursor_, data, len);
1655 cursor_ += len;
1656 return Error::None;
1657 }
1658 for (size_t i = 0; i < len; ++i)
1659 if (Error e = pushByte(data[i]); e != Error::None) return e;
1660 return Error::None;
1661 }
1662
1663 /**
1664 * @brief Encode a value as a varint and append it to the buffer.
1665 * @param v Value to write.
1666 * @return @ref Error::None on success, or @ref Error::BufferFull on overflow.
1667 */
1668 [[nodiscard]] Error putVarint(uint64_t v) noexcept
1669 {
1670 uint8_t tmp[10];
1671 return pushBytes(tmp, encodeVarint(tmp, v));
1672 }
1673
1674 /**
1675 * @brief Write the sequence-end marker (§4.9) — id 0, wire type 7.
1676 *
1677 * The **only** header not composed inline by one of the five writers, and
1678 * deliberately not a general `putHeader(id, type)`: a general one would
1679 * look like the place to commit a held-back run, and it is not. It is
1680 * reached from @ref sequenceEnd and @ref sequenceEndKeep only, neither of
1681 * which may commit here — @ref sequenceEnd only gets here when the run is
1682 * already empty, and @ref sequenceEndKeep has committed it itself one line
1683 * earlier. The commit choke point is @ref beforeContent, called by the
1684 * five inline writers; see the note there.
1685 *
1686 * @return @ref Error::BufferFull on overflow, otherwise @ref Error::None.
1687 */
1688 [[nodiscard]] Error putSequenceEnd() noexcept
1689 {
1690 return putVarint(headerWord(0, Wire::SequenceEnd));
1691 }
1692
1693 /**
1694 * @brief Write out the held-back sequence headers, outermost first.
1695 *
1696 * Runs at most once per non-default sequence, never per field.
1697 *
1698 * The run is dropped even when a header write fails partway, and that is
1699 * deliberate: the only way to fail here is @ref Error::BufferFull, which
1700 * is unreachable while a flush callback is set and otherwise latches the
1701 * sticky @ref failure_ with the cursor parked at the buffer end — so every
1702 * later push fails too and @ref ok is already false. Keeping the leftover
1703 * ids could therefore only ever emit them into an output that is already
1704 * condemned. `bufferFullCondemnsTheRun()` in test/test_roundtrip.cpp
1705 * pins that: a truncated encode stays a byte-exact prefix of the full one
1706 * and reports `ok() == false`.
1707 */
1708 [[nodiscard]] Error commitPending() noexcept
1709 {
1710 Error err = Error::None;
1711 /* Safe to iterate and clear afterwards: putVarint never touches the
1712 * run (it writes bytes, it does not open or close a sequence). */
1713 const size_t n = pending_.size();
1714 for (size_t i = 0; i < n; ++i)
1715 if ((err = putVarint(headerWord(pending_[i], Wire::SequenceStart))) != Error::None)
1716 break;
1717 pending_.clear();
1718 return err;
1719 }
1720
1721 /**
1722 * @brief Commit any held-back sequence run before writing content.
1723 *
1724 * **This is the choke point** — there is no other. The five writers below
1725 * (@ref writeScalar, @ref writeFixlen, @ref writeFloatScalar,
1726 * @ref writeIntArray, @ref writeFloatArray) compose their header inline
1727 * for speed, so every field written by this library goes through one of
1728 * them and through this call, and through nothing else: dropping it from
1729 * any one of the five loses that field's frame, and each of the five has a
1730 * check in `lazySequenceFraming()` that fails when it does. A
1731 * @ref sequenceBeginLazy run is framed exactly when the first child field
1732 * appears (MESSAGE_SPEC §2).
1733 */
1734 [[nodiscard]] Error beforeContent() noexcept
1735 {
1736 return !pending_.empty() ? commitPending() : Error::None;
1737 }
1738
1739 /**
1740 * @brief Compose a field header word: the id in the high bits, the wire
1741 * type in the low three (§4.1).
1742 *
1743 * @param fieldId Field identifier.
1744 * @param w Wire type of the field that follows.
1745 * @return The header word, ready for @ref encodeVarint.
1746 */
1747 static constexpr uint64_t headerWord(sofab::id fieldId, Wire w) noexcept
1748 {
1749 return (static_cast<uint64_t>(fieldId) << 3) | static_cast<uint64_t>(w);
1750 }
1751
1752 /**
1753 * @brief Compose a fixlen word: the payload length (or element size) in
1754 * the high bits, the subtype in the low three (§4.6, §4.8).
1755 *
1756 * @param len Payload length in bytes, or the element size for an array.
1757 * @param ft Fixlen subtype.
1758 * @return The fixlen word, ready for @ref encodeVarint.
1759 */
1760 static constexpr uint64_t fixlenWord(uint64_t len, Fix ft) noexcept
1761 {
1762 return (len << 3) | static_cast<uint64_t>(ft);
1763 }
1764
1765 /**
1766 * @brief Write a scalar field: header varint plus one value varint, in a single bulk write.
1767 * @param fieldId Field identifier; must not exceed @ref ID_MAX.
1768 * @param type Wire type (@ref Wire::Unsigned or @ref Wire::Signed).
1769 * @param value Already-encoded scalar value (zig-zagged for signed fields).
1770 * @return @ref Error::InvalidArgument if @p fieldId is too large,
1771 * @ref Error::BufferFull on overflow, otherwise @ref Error::None.
1772 */
1773 [[nodiscard]] Error writeScalar(sofab::id fieldId, Wire type, uint64_t value) noexcept
1774 {
1775 if (fieldId > ID_MAX) [[unlikely]] return latch(Error::InvalidArgument);
1776 if (Error e = beforeContent(); e != Error::None) return e;
1777 /* Header and value are each at most VARINT_MAX_BYTES, so with room for
1778 * two of them the field is composed straight into the buffer: no
1779 * scratch array and no copy out of it. The checked path below still
1780 * runs at the buffer tail and across every flush boundary. */
1781 if (static_cast<size_t>(end_ - cursor_) >= 2 * detail::VARINT_MAX_BYTES) [[likely]]
1782 {
1783 uint8_t *o = cursor_;
1784 o += encodeVarintPadded(o, headerWord(fieldId, type));
1785 o += encodeVarintPadded(o, value);
1786 cursor_ = o;
1787 return Error::None;
1788 }
1789 uint8_t tmp[20];
1790 size_t n = encodeVarint(tmp, headerWord(fieldId, type));
1791 n += encodeVarint(tmp + n, value);
1792 return pushBytes(tmp, n);
1793 }
1794
1795 /**
1796 * @brief Write a length-prefixed field (string, blob or other fixlen payload).
1797 * @param fieldId Field identifier; must not exceed @ref ID_MAX.
1798 * @param ft Payload sub-type (@ref Fix::String, @ref Fix::Blob, ...).
1799 * @param data Payload bytes.
1800 * @param len Payload length in bytes; must not exceed @ref FIXLEN_MAX.
1801 * @return @ref Error::InvalidArgument if @p fieldId or @p len is too large,
1802 * @ref Error::BufferFull on overflow, otherwise @ref Error::None.
1803 */
1804 [[nodiscard]] Error writeFixlen(sofab::id fieldId, Fix ft, const uint8_t *data, size_t len) noexcept
1805 {
1806 if (fieldId > ID_MAX) [[unlikely]] return latch(Error::InvalidArgument);
1807 /* §6.2: @ref FIXLEN_MAX is a format-wide ceiling, so a longer payload
1808 * has no fixlen word a reader will take — the one this would emit is
1809 * `INVALID` for every decoder (§5.2), this library's own included.
1810 * Refused here, next to the id, and refused BEFORE @ref beforeContent
1811 * so a held-back sequence run stays held back: the field emits
1812 * nothing at all rather than a header its payload never follows. */
1813 if (len > static_cast<size_t>(FIXLEN_MAX)) [[unlikely]] return latch(Error::InvalidArgument);
1814 if (Error e = beforeContent(); e != Error::None) return e;
1815 /* As in @ref writeScalar, plus the payload. The room test is split so
1816 * it cannot overflow on a huge @p len. */
1817 const size_t room = static_cast<size_t>(end_ - cursor_);
1818 if (room >= 2 * detail::VARINT_MAX_BYTES && room - 2 * detail::VARINT_MAX_BYTES >= len) [[likely]]
1819 {
1820 uint8_t *o = cursor_;
1821 o += encodeVarintPadded(o, headerWord(fieldId, Wire::Fixlen));
1822 o += encodeVarintPadded(o, fixlenWord(len, ft));
1823 /* An empty string or blob passes a null @p data; memcpy forbids
1824 * that even for a zero length (§7.1.4 [mem.req]). */
1825 if (len) std::memcpy(o, data, len);
1826 cursor_ = o + len;
1827 return Error::None;
1828 }
1829 uint8_t tmp[20];
1830 size_t n = encodeVarint(tmp, headerWord(fieldId, Wire::Fixlen));
1831 n += encodeVarint(tmp + n, fixlenWord(len, ft));
1832 if (Error e = pushBytes(tmp, n); e != Error::None) return e;
1833 return pushBytes(data, len);
1834 }
1835
1836 /**
1837 * @brief Write a single float or double as a little-endian fixlen field.
1838 * @tparam F Floating-point type (`float` or `double`).
1839 * @param fieldId Field identifier; must not exceed @ref ID_MAX.
1840 * @param value Value to encode.
1841 * @return @ref Error::InvalidArgument if @p fieldId is too large,
1842 * @ref Error::BufferFull on overflow, otherwise @ref Error::None.
1843 */
1844 template <std::floating_point F>
1845 [[nodiscard]] Error writeFloatScalar(sofab::id fieldId, F value) noexcept
1846 {
1847 constexpr Fix ft = (sizeof(F) == 4) ? Fix::Fp32 : Fix::Fp64;
1848 if (fieldId > ID_MAX) [[unlikely]] return latch(Error::InvalidArgument);
1849 if (Error e = beforeContent(); e != Error::None) return e;
1850 auto bits = detail::floatBits(value);
1851 if (static_cast<size_t>(end_ - cursor_) >= 2 * detail::VARINT_MAX_BYTES + sizeof(F)) [[likely]]
1852 {
1853 uint8_t *o = cursor_;
1854 o += encodeVarintPadded(o, headerWord(fieldId, Wire::Fixlen));
1855 o += encodeVarintPadded(o, fixlenWord(sizeof(F), ft));
1856 detail::storeLittleBits(o, bits);
1857 cursor_ = o + sizeof(F);
1858 return Error::None;
1859 }
1860 uint8_t tmp[20];
1861 size_t n = encodeVarint(tmp, headerWord(fieldId, Wire::Fixlen));
1862 n += encodeVarint(tmp + n, fixlenWord(sizeof(F), ft));
1863 detail::storeLittleBits(tmp + n, bits);
1864 n += sizeof(F);
1865 return pushBytes(tmp, n);
1866 }
1867
1868 /**
1869 * @brief Write an array of integers as a count-prefixed run of varints.
1870 *
1871 * The wire type is chosen from the signedness of the type the elements
1872 * travel as (@ref detail::WireInt); signed elements are zig-zag encoded.
1873 *
1874 * @tparam E Integral or enumeration element type. An enumeration encodes
1875 * at its declared underlying width, converted per element; a
1876 * `bool` encodes as the unsigned `0`/`1` of §4.4.
1877 * @param fieldId Field identifier; must not exceed @ref ID_MAX.
1878 * @param elems Elements to encode, in order; at most @ref ARRAY_MAX of them.
1879 * @return @ref Error::InvalidArgument if @p fieldId is too large or
1880 * @p elems holds more than @ref ARRAY_MAX elements,
1881 * @ref Error::BufferFull on overflow, otherwise @ref Error::None.
1882 */
1883 template <typename E>
1884 requires (std::integral<E> || std::is_enum_v<E>)
1885 [[nodiscard]] Error writeIntArray(sofab::id fieldId, std::span<const E> elems) noexcept
1886 {
1887 using U = detail::WireInt_t<E>;
1888 constexpr bool isSigned = std::is_signed_v<U>;
1889 if (fieldId > ID_MAX) [[unlikely]] return latch(Error::InvalidArgument);
1890 /* §6.2/§4.7: the element count is bounded by @ref ARRAY_MAX, the same
1891 * format-wide ceiling the decoder enforces on the count word — see
1892 * @ref writeFixlen for why it is refused here and not emitted. */
1893 if (elems.size() > static_cast<size_t>(ARRAY_MAX)) [[unlikely]] return latch(Error::InvalidArgument);
1894 if (Error e = beforeContent(); e != Error::None) return e;
1895 const uint64_t head = (static_cast<uint64_t>(fieldId) << 3) |
1896 static_cast<uint64_t>(isSigned ? Wire::ArraySigned : Wire::ArrayUnsigned);
1897 if (static_cast<size_t>(end_ - cursor_) >= 2 * detail::VARINT_MAX_BYTES) [[likely]]
1898 {
1899 uint8_t *o = cursor_;
1900 o += encodeVarintPadded(o, head);
1901 o += encodeVarintPadded(o, elems.size());
1902 cursor_ = o;
1903 }
1904 else
1905 {
1906 uint8_t hdr[20];
1907 size_t hn = encodeVarint(hdr, head);
1908 hn += encodeVarint(hdr + hn, elems.size());
1909 if (Error e = pushBytes(hdr, hn); e != Error::None) return e;
1910 }
1911
1912 /* Element loop. The straightforward body — encode into a scratch
1913 * array, then pushBytes it — costs a bounds check and a variable-length
1914 * memcpy per element. Instead, ask once how many elements are
1915 * *guaranteed* to fit (each varint is at most VARINT_MAX_BYTES) and run
1916 * that many straight into the buffer with no per-element check at all.
1917 * Only the buffer tail, and every flush boundary, takes the checked
1918 * path — which is still pushBytes, so flushing behaviour is unchanged. */
1919 const auto word = [](const E &v) noexcept -> uint64_t {
1920 if constexpr (std::is_same_v<E, bool>)
1921 {
1922 /* §4.4 is canonical on encode: `true` is `1`. The element is
1923 * loaded as a byte, not as a `bool`, because generated code
1924 * may present a byte-backed member as `bool` elements (the
1925 * way it presents an enum member as its backing integer),
1926 * and a byte other than 0/1 is a representation a `bool`
1927 * lvalue has no value for. A character-type load is defined
1928 * for both, and `!= 0` keeps the wire canonical either way. */
1929 static_assert(sizeof(bool) == 1, "a bool element is stored as one byte");
1930 return reinterpret_cast<const unsigned char &>(v) != 0 ? 1u : 0u;
1931 }
1932 else
1933 {
1934 /* An enum element converts here, one at a time, as it is encoded:
1935 * the span still points at the caller's array of E and is never
1936 * reinterpreted, so there is no aliasing question and no copy. */
1937 const auto u = static_cast<U>(v);
1938 if constexpr (isSigned) return detail::zigzagEncode(static_cast<int64_t>(u));
1939 else return static_cast<uint64_t>(u);
1940 }
1941 };
1942 const size_t n = elems.size();
1943 for (size_t i = 0; i < n; )
1944 {
1945 size_t fit = static_cast<size_t>(end_ - cursor_) / detail::VARINT_MAX_BYTES;
1946 if (fit == 0) [[unlikely]]
1947 {
1948 uint8_t tmp[detail::VARINT_MAX_BYTES];
1949 size_t k = encodeVarint(tmp, word(elems[i]));
1950 if (Error e = pushBytes(tmp, k); e != Error::None) return e;
1951 ++i;
1952 continue;
1953 }
1954 if (fit > n - i) fit = n - i;
1955 uint8_t *out = cursor_;
1956 for (size_t k = 0; k < fit; ++k, ++i)
1957 out += encodeVarintPadded(out, word(elems[i]));
1958 cursor_ = out;
1959 }
1960 return Error::None;
1961 }
1962
1963 /**
1964 * @brief Write an array of floats or doubles as a count-prefixed fixlen array.
1965 *
1966 * On little-endian hosts the payload is copied in one block since the wire
1967 * layout matches native memory; on big-endian hosts each element is byte-swapped.
1968 *
1969 * @tparam F Floating-point element type (`float` or `double`).
1970 * @param fieldId Field identifier; must not exceed @ref ID_MAX.
1971 * @param elems Elements to encode, in order; at most @ref ARRAY_MAX of them.
1972 * @return @ref Error::InvalidArgument if @p fieldId is too large or
1973 * @p elems holds more than @ref ARRAY_MAX elements,
1974 * @ref Error::BufferFull on overflow, otherwise @ref Error::None.
1975 */
1976 template <std::floating_point F>
1977 [[nodiscard]] Error writeFloatArray(sofab::id fieldId, std::span<const F> elems) noexcept
1978 {
1979 constexpr Fix ft = (sizeof(F) == 4) ? Fix::Fp32 : Fix::Fp64;
1980 if (fieldId > ID_MAX) [[unlikely]] return latch(Error::InvalidArgument);
1981 /* §6.2/§4.8: as in @ref writeIntArray — the count word is bounded by
1982 * @ref ARRAY_MAX whatever the element type is. */
1983 if (elems.size() > static_cast<size_t>(ARRAY_MAX)) [[unlikely]] return latch(Error::InvalidArgument);
1984 if (Error e = beforeContent(); e != Error::None) return e;
1985 /* §4.8: a fixlen array always carries its fixlen_word, even when empty
1986 * (count == 0), so an empty fp32 and fp64 array stay distinguishable. */
1987 if (static_cast<size_t>(end_ - cursor_) >= 3 * detail::VARINT_MAX_BYTES) [[likely]]
1988 {
1989 uint8_t *o = cursor_;
1990 o += encodeVarintPadded(o, headerWord(fieldId, Wire::ArrayFixlen));
1991 o += encodeVarintPadded(o, elems.size());
1992 o += encodeVarintPadded(o, fixlenWord(sizeof(F), ft));
1993 cursor_ = o;
1994 }
1995 else
1996 {
1997 uint8_t hdr[30];
1998 size_t hn = encodeVarint(hdr, headerWord(fieldId, Wire::ArrayFixlen));
1999 hn += encodeVarint(hdr + hn, elems.size());
2000 hn += encodeVarint(hdr + hn, fixlenWord(sizeof(F), ft));
2001 if (Error e = pushBytes(hdr, hn); e != Error::None) return e;
2002 }
2003 if (elems.empty()) return Error::None; /* fixlen_word emitted; no payload */
2004
2005 if constexpr (std::endian::native == std::endian::little)
2006 {
2007 /* wire bytes == native bytes: copy the whole payload at once */
2008 return pushBytes(reinterpret_cast<const uint8_t *>(elems.data()), elems.size() * sizeof(F));
2009 }
2010 else
2011 {
2012 for (F v : elems)
2013 {
2014 uint8_t tmp[sizeof(F)];
2016 if (Error e = pushBytes(tmp, sizeof(F)); e != Error::None) return e;
2017 }
2018 return Error::None;
2019 }
2020 }
2021
2022 public:
2023 /**
2024 * @brief Chainable result of a write operation.
2025 *
2026 * Each chained call is a no-op once an error has been latched, so a
2027 * sequence of writes can be expressed fluently and the first failure
2028 * inspected at the end via @ref ok / @ref code.
2029 */
2031 {
2032 OStreamImpl &os_;
2033 Error error_;
2034 friend class OStreamImpl;
2035 Result(OStreamImpl &os, Error e) noexcept : os_(os), error_(e) {}
2036
2037 public:
2038 /**
2039 * @brief Chain another field write onto the same stream.
2040 * @tparam T Value type accepted by @ref OStreamImpl::write.
2041 * @param fieldId Field identifier.
2042 * @param value Value to encode.
2043 * @return `*this`, for further chaining.
2044 */
2045 template <typename T>
2046 Result write(sofab::id fieldId, const T &value) noexcept
2047 {
2048 if (error_ == Error::None) error_ = os_.write(fieldId, value).error_;
2049 return *this;
2050 }
2051 /**
2052 * @brief Chain a field write that only happens when @p condition holds.
2053 * @tparam T Value type accepted by @ref OStreamImpl::write.
2054 * @param fieldId Field identifier.
2055 * @param value Value to encode when @p condition is true.
2056 * @param condition Write the field only if this is true.
2057 * @return `*this`, for further chaining.
2058 */
2059 template <typename T>
2060 Result writeIf(sofab::id fieldId, const T &value, bool condition) noexcept
2061 {
2062 if (error_ == Error::None && condition) error_ = os_.write(fieldId, value).error_;
2063 return *this;
2064 }
2065 /**
2066 * @brief Chain a nested-message field write that is omitted when the
2067 * message is all-default (@ref OStreamImpl::writeLazy).
2068 * @param fieldId Field identifier of the sub-message.
2069 * @param value Nested message to encode.
2070 * @return `*this`, for further chaining.
2071 */
2072 template <typename T>
2073 Result writeLazy(sofab::id fieldId, const T &value) noexcept
2074 {
2075 if (error_ == Error::None) error_ = os_.writeLazy(fieldId, value).error_;
2076 return *this;
2077 }
2078 /**
2079 * @brief Chain a frame-keeping close (@ref OStreamImpl::sequenceEndKeep).
2080 * @return `*this`, for further chaining.
2081 */
2083 {
2084 if (error_ == Error::None) error_ = os_.sequenceEndKeep().error_;
2085 return *this;
2086 }
2087 /**
2088 * @brief Chain the opening of a nested sub-message that is framed only
2089 * if it turns out to have content (@ref
2090 * OStreamImpl::sequenceBeginLazy).
2091 * @param fieldId Field identifier of the sub-message.
2092 * @return `*this`, for further chaining.
2093 */
2095 {
2096 if (error_ == Error::None) error_ = os_.sequenceBeginLazy(fieldId).error_;
2097 return *this;
2098 }
2099 /**
2100 * @brief Chain the closing of the current nested sub-message.
2101 * @return `*this`, for further chaining.
2102 */
2104 {
2105 if (error_ == Error::None) error_ = os_.sequenceEnd().error_;
2106 return *this;
2107 }
2108 /** @return `true` if no error has been latched. */
2109 [[nodiscard]] explicit operator bool() const noexcept { return ok(); }
2110 /** @return `true` if no error has been latched. */
2111 [[nodiscard]] bool ok() const noexcept { return error_ == Error::None; }
2112 /** @return The latched status code (@ref Error::None if all writes succeeded). */
2113 [[nodiscard]] Error code() const noexcept { return error_; }
2114 /** @return `true` if the latched code equals @p e. */
2115 bool operator==(Error e) const noexcept { return error_ == e; }
2116 /** @return `true` if the latched code differs from @p e. */
2117 bool operator!=(Error e) const noexcept { return error_ != e; }
2118 };
2119
2120 OStreamImpl(const OStreamImpl &) = delete;
2122 OStreamImpl(OStreamImpl &&) noexcept = default;
2123 OStreamImpl &operator=(OStreamImpl &&) noexcept = default;
2124 /** Flushes any buffered bytes through the callback before destruction. */
2125 virtual ~OStreamImpl() noexcept { flush(); }
2126
2127 /**
2128 * @brief Hand any buffered bytes to the flush callback and rewind the cursor.
2129 *
2130 * **With no flush callback installed this is a no-op** and the buffered
2131 * message stays exactly where it is, reachable through @ref data /
2132 * @ref bytesUsed. There is nowhere to drain to, so §5.1's "drain any
2133 * remaining buffered bytes" has nothing to do, and the cursor only
2134 * returns to offset 0 after a *handover* the callback returned from —
2135 * which never happened. Rewinding here would discard the encode and drop
2136 * the installation's reserved head, so the next write would overwrite
2137 * both.
2138 *
2139 * @return Number of bytes that were buffered before the flush.
2140 */
2141 size_t flush() noexcept
2142 {
2143 const size_t used = static_cast<size_t>(cursor_ - buffer_);
2144 /* Only *message* bytes are worth draining. A buffer that was just
2145 * installed holds nothing but its own reserved head, and handing the
2146 * sink that head as a packet of its own would invent an empty packet —
2147 * which the destructor's flush would then do after every taking sink's
2148 * last handover. */
2149 if (flushCallback_ && used > offset_)
2150 {
2151 /* Same contract as in @ref pushByte: an explicit flush is a flush
2152 * like any other, so a sink that takes the buffer here installs a
2153 * replacement and that installation's offset stands. */
2154 installed_ = false;
2155 flushCallback_(std::span<const uint8_t>(buffer_, used));
2156 if (!installed_) { cursor_ = buffer_; offset_ = 0; }
2157 }
2158 return used;
2159 }
2160
2161 /** @return Number of bytes written into the buffer since the last flush. */
2162 [[nodiscard]] size_t bytesUsed() const noexcept { return static_cast<size_t>(cursor_ - buffer_); }
2163 /** @return Pointer to the start of the buffer; the first @ref bytesUsed bytes are valid. */
2164 [[nodiscard]] const uint8_t *data() const noexcept { return buffer_; }
2165
2166 /**
2167 * @brief Whether every write on this stream has succeeded.
2168 *
2169 * Sticky and independent of how the writes were issued — chained, or one
2170 * at a time with each Result discarded, which is what a generated
2171 * `serialize()` does — so it is **the** verdict to check after encoding:
2172 * §5.1 forbids handing on partial output as if it were complete, and this
2173 * is what tells the two apart.
2174 *
2175 * It turns false whenever a field the caller asked for did not reach the
2176 * output: an overflow with no flush callback set (@ref OStreamView with a
2177 * buffer smaller than the message), a rejected buffer installation, a
2178 * field id past @ref ID_MAX, a sub-message past @ref MAX_DEPTH, a string
2179 * that is not valid UTF-8 under §6.4, an array of more than
2180 * @ref ARRAY_MAX elements or a payload past @ref FIXLEN_MAX, a negative
2181 * raw-blob length, and — rarely — a
2182 * @ref sequenceBeginLazy that cannot allocate room to hold a header back.
2183 *
2184 * @return true while every write this stream was given has been honoured.
2185 */
2186 [[nodiscard]] bool ok() const noexcept { return failure_ == Error::None; }
2187
2188 /**
2189 * @brief The code behind @ref ok, latched first-failure-wins.
2190 *
2191 * @return @ref Error::BufferFull once a write has overflowed with no sink
2192 * (or a hold-back run could not grow), @ref Error::InvalidArgument
2193 * when a buffer installation was rejected (§5.1 — an out-of-range
2194 * offset, or fewer than @ref MIN_OUTPUT_BUFFER usable bytes behind
2195 * a sink) or a field was refused as unencodable (§6.2's
2196 * @ref ID_MAX, @ref ARRAY_MAX, @ref FIXLEN_MAX and
2197 * @ref MAX_DEPTH, §6.4's UTF-8 rule), else @ref Error::None.
2198 */
2199 [[nodiscard]] Error error() const noexcept { return failure_; }
2200
2201 /**
2202 * @brief Refuse the value being encoded: latch @ref Error::InvalidArgument.
2203 *
2204 * The hook a generated `serialize()` calls when a field's value is past
2205 * a bound only the schema knows -- a string or blob longer than its
2206 * `maxlen`, an array with more elements than its `count`. The corelib
2207 * holds no schema bound; it records the refusal, so that @ref ok and
2208 * @ref error report it exactly like its own §6.2 / §6.4 refusals and no
2209 * byte of the message is returned as a success (§5.1). Writes nothing
2210 * itself. The encode-side counterpart of IStreamImpl::invalidate.
2211 *
2212 * Cold and out of line: the refusal is the rare path, and keeping it
2213 * out of a generated serialize() keeps that function small enough for
2214 * GCC to go on inlining the writes into it (measured: the bench
2215 * schema's encode is 11546 Ir/op with this, 12423 with the hook
2216 * inlined at its 18 call sites, 11904 before any guard existed).
2217 *
2218 * @return A Result carrying @ref Error::InvalidArgument.
2219 */
2220 [[gnu::cold, gnu::noinline]] Result rejectArgument() noexcept
2221 {
2222 return Result{*this, latch(Error::InvalidArgument)};
2223 }
2224
2225 /**
2226 * @brief Write a field, dispatching on the value's type.
2227 *
2228 * Handles integers (signed values are zig-zag encoded), `bool`, `float`,
2229 * `double`, anything convertible to `std::string_view`, contiguous ranges
2230 * of integers, enumerations, booleans or floats (encoded as arrays), and
2231 * nested @ref sofab::OStreamMessage objects (encoded as a sub-message). An
2232 * enumeration element travels as its declared underlying type, so a
2233 * container of scoped enums needs no converted copy; a boolean element
2234 * travels as the unsigned `0`/`1` of §4.4. Unsupported types fail to
2235 * compile.
2236 *
2237 * @tparam T Deduced value type.
2238 * @param fieldId Field identifier; must not exceed @ref ID_MAX.
2239 * @param value Value to encode.
2240 * @return A @ref Result carrying @ref Error::None on success, or the first
2241 * error encountered.
2242 */
2243 template <typename T>
2244 Result write(sofab::id fieldId, const T &value) noexcept
2245 {
2246 Error err = Error::None;
2247
2248 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>)
2249 {
2250 if constexpr (std::is_unsigned_v<T>)
2251 err = writeScalar(fieldId, Wire::Unsigned, static_cast<uint64_t>(value));
2252 else
2253 err = writeScalar(fieldId, Wire::Signed, detail::zigzagEncode(static_cast<int64_t>(value)));
2254 }
2255 else if constexpr (std::is_same_v<T, bool>)
2256 {
2257 err = writeScalar(fieldId, Wire::Unsigned, value ? 1u : 0u);
2258 }
2259 else if constexpr (std::is_same_v<T, float>) { err = writeFloatScalar(fieldId, value); }
2260 else if constexpr (std::is_same_v<T, double>) { err = writeFloatScalar(fieldId, value); }
2261 else if constexpr (std::is_convertible_v<T, std::string_view>)
2262 {
2263 std::string_view sv{value};
2264#if SOFAB_STRICT_UTF8
2265 /* §6.4: a `string` value that is not valid UTF-8 is refused with
2266 * InvalidArgument — this is what enforces MESSAGE_SPEC §8's
2267 * producer-side MUST NOT. `blob` (the pointer+size overload) is
2268 * never validated. Folds away when the check is compiled out. */
2269 if (!detail::utf8Valid(sv.data(), sv.size()))
2271 else
2272#endif
2273 err = writeFixlen(fieldId, Fix::String,
2274 reinterpret_cast<const uint8_t *>(sv.data()), sv.size());
2275 }
2276 else if constexpr (std::is_base_of_v<OStreamMessage, T>)
2277 {
2278 /* The ELEMENT form: the frame is kept even when the nested message
2279 * writes nothing, because element presence carries a wrapper
2280 * array's length (MESSAGE_SPEC §5.1). A nested message FIELD, which
2281 * may vanish when all-default, is @ref writeLazy. */
2282 err = sequenceBeginLazy(fieldId).error_;
2283 if (err == Error::None) err = value.serialize(*this).error_;
2284 if (err == Error::None) err = sequenceEndKeep().error_;
2285 }
2286 else if constexpr (requires { typename T::value_type; std::span{std::declval<const T &>()}; })
2287 {
2288 using Elem = typename T::value_type;
2289 std::span<const Elem> sp{value};
2290 /* An enumeration rides the integer path at its declared width, so a
2291 * caller holding `std::vector<Gear>` needs no converted copy. */
2292 /* A container of `bool` joins it too: §4.4 lowers a boolean onto
2293 * the unsigned varint, and @ref writeIntArray emits each element
2294 * as its canonical `0`/`1`. */
2295 if constexpr (std::is_integral_v<Elem> || std::is_enum_v<Elem>)
2296 err = writeIntArray(fieldId, sp);
2297 else if constexpr (std::is_same_v<Elem, float> || std::is_same_v<Elem, double>)
2298 err = writeFloatArray(fieldId, sp);
2299 else
2300 static_assert(always_false_v<T>, "Unsupported span element type in OStream::write()");
2301 }
2302 else
2303 {
2304 static_assert(always_false_v<T>, "Unsupported type passed to OStream::write()");
2305 }
2306
2307 return Result{*this, err};
2308 }
2309
2310 /**
2311 * @brief Write a nested message **field**, omitting it when it is all-default.
2312 *
2313 * Same as @ref write for an @ref OStreamMessage, except it closes with
2314 * @ref sequenceEnd rather than @ref sequenceEndKeep: the nested `serialize`
2315 * omits every child that equals its default, so "not one child was written"
2316 * is exactly "the object equals its declared default" — evaluated per child
2317 * field, recursively — and the field is then dropped instead of emitted as
2318 * an empty frame (MESSAGE_SPEC §2).
2319 *
2320 * Use it for a `struct`/`union` **field**. Keep plain @ref write for an
2321 * array **element**: element presence carries a dynamic array's length
2322 * (§5.1), so an all-default element stays framed.
2323 *
2324 * @tparam T A type deriving from @ref OStreamMessage.
2325 * @param fieldId Field identifier; must not exceed @ref ID_MAX.
2326 * @param value Nested message to encode.
2327 * @return A @ref Result carrying @ref Error::None on success, or the error encountered.
2328 */
2329 template <typename T>
2330 requires std::is_base_of_v<OStreamMessage, T>
2331 Result writeLazy(sofab::id fieldId, const T &value) noexcept
2332 {
2333 Error err = sequenceBeginLazy(fieldId).error_;
2334 if (err == Error::None) err = value.serialize(*this).error_;
2335 if (err == Error::None) err = sequenceEnd().error_;
2336 return Result{*this, err};
2337 }
2338
2339 /**
2340 * @brief Write a raw byte blob field.
2341 *
2342 * @p size is signed for symmetry with the generated accessors, but §6.2
2343 * bounds a fixlen payload to `0 .. 2,147,483,647`: a negative length is
2344 * outside the format and is refused with @ref Error::InvalidArgument
2345 * (§6.3), emitting nothing, exactly as an unencodable `string` is. The
2346 * guard has to sit here, before the conversion — `static_cast<size_t>`
2347 * would turn `-1` into `SIZE_MAX` and the encoder would copy from
2348 * @p value until the buffer filled, reading past the caller's object.
2349 *
2350 * Like every other refusal it also reaches @ref ok / @ref error: the
2351 * field the caller asked for is not on the wire, and §5.1 does not let a
2352 * stream missing a field report success (@ref latch).
2353 *
2354 * @param fieldId Field identifier; must not exceed @ref ID_MAX.
2355 * @param value Pointer to the bytes to copy.
2356 * @param size Number of bytes to copy; must not be negative.
2357 * @return A @ref Result carrying @ref Error::None on success, or the error encountered.
2358 */
2359 Result write(sofab::id fieldId, const void *value, int32_t size) noexcept
2360 {
2361 if (size < 0) [[unlikely]] return Result{*this, latch(Error::InvalidArgument)};
2362 return Result{*this, writeFixlen(fieldId, Fix::Blob,
2363 static_cast<const uint8_t *>(value), static_cast<size_t>(size))};
2364 }
2365
2366 /**
2367 * @brief Write a field only when @p condition holds.
2368 * @tparam T Value type accepted by @ref write.
2369 * @param fieldId Field identifier.
2370 * @param value Value to encode when @p condition is true.
2371 * @param condition Write the field only if this is true.
2372 * @return The result of the write, or a success @ref Result if skipped.
2373 */
2374 template <typename T>
2375 Result writeIf(sofab::id fieldId, const T &value, bool condition) noexcept
2376 {
2377 return condition ? write(fieldId, value) : Result{*this, Error::None};
2378 }
2379
2380 /**
2381 * @brief Open a nested sub-message whose header is **held back** until the
2382 * sub-message turns out to have content.
2383 *
2384 * MESSAGE_SPEC §2 omits a sequence-typed field whose value equals its
2385 * declared default, and "not one child was written" is exactly that
2386 * condition — evaluated per child field, recursively, for free. A sequence
2387 * closed with nothing in it therefore emits **nothing** instead of a
2388 * two-byte empty frame, and an all-default message becomes the empty byte
2389 * string.
2390 *
2391 * The predicate never touches a byte image of the object, so struct padding
2392 * cannot influence it and a non-zero nested default is handled by the
2393 * caller's ordinary per-field test.
2394 *
2395 * This is the only way to open a sub-message. How it closes decides whether
2396 * a contentless one survives: @ref sequenceEnd drops it, @ref sequenceEndKeep
2397 * forces the frame out.
2398 *
2399 * The hold-back has **no depth window**: the pending run is sized at
2400 * construction to the full @ref MAX_DEPTH, so the output is canonical at
2401 * every legal depth and no nesting depth allocates (CORELIB_PLAN §6.0.1,
2402 * "How deep the hold-back reaches" — only a constrained profile may bound
2403 * the run below @ref MAX_DEPTH and frame eagerly past the bound, and this
2404 * port takes no such allowance).
2405 *
2406 * @param fieldId Field identifier of the sub-message.
2407 * @return A @ref Result carrying @ref Error::None on success,
2408 * @ref Error::InvalidArgument past @ref MAX_DEPTH or @ref ID_MAX.
2409 */
2411 {
2412 if (seqDepth_ >= static_cast<size_t>(MAX_DEPTH)) [[unlikely]]
2413 return Result{*this, latch(Error::InvalidArgument)};
2414 if (fieldId > ID_MAX) [[unlikely]]
2415 return Result{*this, latch(Error::InvalidArgument)};
2416 /* The run is MAX_DEPTH ids wide and was sized at construction — no
2417 * window, no eager fallback, no allocator call (CORELIB_PLAN §6.0.1 /
2418 * §6.6.2). The MAX_DEPTH check above is what keeps it in range, so the
2419 * push cannot fail; the branch stays because a sequence that was NOT
2420 * opened must condemn the stream (sticky @ref failure_), the caller's
2421 * matching close would otherwise end an enclosing sequence instead of
2422 * this one. */
2423 if (!pending_.push(fieldId)) [[unlikely]]
2424 return Result{*this, latch(Error::InvalidArgument)};
2425 ++seqDepth_;
2426 return Result{*this, Error::None};
2427 }
2428 /**
2429 * @brief Close the most recently opened sub-message, letting it **vanish**
2430 * if it received no content.
2431 *
2432 * Use it wherever absence encodes the same value as an empty frame: a
2433 * `struct`/`union` field, and an array field whose declared `default` is the
2434 * empty collection (MESSAGE_SPEC §2). Where the frame must be visible, close
2435 * with @ref sequenceEndKeep instead.
2436 *
2437 * @return A @ref Result carrying @ref Error::None on success, or the error encountered.
2438 */
2440 {
2441 if (seqDepth_ > 0) --seqDepth_;
2442 if (!pending_.empty())
2443 {
2444 /* The innermost open sequence is the last held-back one: drop it. */
2445 pending_.pop();
2446 return Result{*this, Error::None};
2447 }
2448 return Result{*this, putSequenceEnd()};
2449 }
2450
2451 /**
2452 * @brief Close the most recently opened sub-message, **keeping** its frame
2453 * even when it received no content.
2454 *
2455 * Behaves like a write: it first emits any held-back headers — this frame's
2456 * and every enclosing one's — and then the end marker, so an empty sequence
2457 * reaches the wire as `begin` + `end`.
2458 *
2459 * Required wherever the frame carries information beyond its contents:
2460 * - a **wrapper-array element** (`struct`/`union`/nested row): element
2461 * presence is what carries a dynamic array's length — *highest present id
2462 * + 1* (§5.1) — so dropping an all-default element would change the
2463 * decoded length, not just the bytes;
2464 * - an array field already known to **differ from a non-empty declared
2465 * `default`**: absence would reconstruct that default, so the empty frame
2466 * is the only encoding of "explicitly empty" (§2, §3).
2467 *
2468 * The two failure directions are not symmetric, which is why this is the
2469 * safe choice when in doubt: using it where @ref sequenceEnd would do costs
2470 * one non-canonical empty frame that a decoder normalizes away, while the
2471 * reverse silently changes an array's length.
2472 *
2473 * @return A @ref Result carrying @ref Error::None on success, or the error encountered.
2474 */
2476 {
2477 if (seqDepth_ > 0) --seqDepth_;
2478 if (!pending_.empty())
2479 if (Error e = commitPending(); e != Error::None)
2480 return Result{*this, e};
2481 return Result{*this, putSequenceEnd()};
2482 }
2483 };
2484
2485 /**
2486 * @brief Output stream over a caller-supplied buffer whose lifetime is shared.
2487 *
2488 * The buffer is adopted from the caller, swappable at runtime via
2489 * @ref setBuffer, and retrievable with @ref getBuffer so it may be shared with
2490 * whatever consumes the encoded bytes.
2491 *
2492 * @note This stream does **not** allocate the buffer, and no stream in this
2493 * library does: §5.1 puts every output buffer on the caller's side, so that
2494 * there is one buffer-ownership model rather than two and a heap-less profile
2495 * is the plain reading of it rather than a special case. Sizing the storage is
2496 * the job of the layer that knows the schema — the generated code, which
2497 * allocates `MAX_SIZE` and installs it without a sink for a bounded schema, or
2498 * a scratch buffer with an appending sink for an unbounded one. A caller that
2499 * simply wants a heap buffer writes
2500 * `sofab::OStream os{std::make_shared<uint8_t[]>(n), n};`.
2501 */
2502 class OStream : public OStreamImpl
2503 {
2504 protected:
2505 std::shared_ptr<uint8_t[]> bufferOwner_; /**< Caller storage, kept alive. */
2506 /** Construct without a buffer; one must be set via @ref setBuffer. */
2507 OStream() noexcept = default;
2508
2509 public:
2510 /**
2511 * @brief Construct over a caller-supplied buffer.
2512 * @param buffer Backing storage to adopt.
2513 * @param buflen Capacity of @p buffer in bytes.
2514 * @param offset Number of leading bytes to reserve before the write cursor.
2515 */
2516 OStream(std::shared_ptr<uint8_t[]> buffer, size_t buflen, size_t offset = 0) noexcept
2517 : bufferOwner_{std::move(buffer)}
2518 {
2519 initBuffer(bufferOwner_.get(), buflen, offset);
2520 }
2521 /**
2522 * @brief Construct over a caller-supplied buffer with a flush callback.
2523 * @param callback Invoked with finished bytes whenever the buffer fills.
2524 * @param buffer Backing storage to adopt.
2525 * @param buflen Capacity of @p buffer in bytes.
2526 * @param offset Number of leading bytes to reserve before the write cursor.
2527 */
2528 OStream(flushCallback callback, std::shared_ptr<uint8_t[]> buffer, size_t buflen, size_t offset = 0) noexcept
2529 : bufferOwner_{std::move(buffer)}
2530 {
2531 flushCallback_ = std::move(callback);
2532 initBuffer(bufferOwner_.get(), buflen, offset);
2533 }
2534 /**
2535 * @brief Install a buffer, mid-stream if need be (§5.1's buffer-set).
2536 *
2537 * This is what a flush sink that **takes** the buffer — hands it to a
2538 * transport, queues it for an asynchronous write, gives it to DMA — must
2539 * call before returning; returning without calling it means the sink
2540 * copied, and the encoder reuses the same buffer from offset 0.
2541 *
2542 * **The start offset belongs to this installation, not to the buffer**,
2543 * and it is consumed: passing the *same* buffer again is a new
2544 * installation like any other, which is how a sink re-arms header room in
2545 * every flushed packet where a bare return would not.
2546 *
2547 * With a sink installed the buffer must leave at least
2548 * @ref MIN_OUTPUT_BUFFER writable bytes (`buflen - offset`); an undersized
2549 * one — or an offset past @p buflen — is rejected **here** rather than
2550 * partway through a message, leaving the stream inert with @ref ok false
2551 * and @ref error reporting @ref Error::InvalidArgument.
2552 *
2553 * @param buffer New backing storage to adopt.
2554 * @param buflen Capacity of @p buffer in bytes.
2555 * @param offset Number of leading bytes to reserve before the write cursor.
2556 */
2557 void setBuffer(std::shared_ptr<uint8_t[]> buffer, size_t buflen, size_t offset = 0) noexcept
2558 {
2559 bufferOwner_ = std::move(buffer);
2560 initBuffer(bufferOwner_.get(), buflen, offset);
2561 }
2562 /** @return A shared handle to the backing buffer. */
2563 [[nodiscard]] std::shared_ptr<uint8_t[]> getBuffer() noexcept { return bufferOwner_; }
2564 };
2565
2566 /**
2567 * @brief Output stream over a buffer the caller already owns.
2568 *
2569 * Allocates no buffer and copies no payload: encoding writes straight into
2570 * @p buffer. The counterpart to @ref OStreamInline (buffer inside the object)
2571 * and @ref OStream (buffer held by a `shared_ptr`) — this is the one for a
2572 * destination that already exists, such as the `dst` of a generated
2573 * `encodeTo`, or a DMA / transport region a **taking** sink hands on
2574 * (§5.1.5). Like every stream it allocates nothing at all after
2575 * construction.
2576 *
2577 * The buffer must outlive the stream, and it is **not** restored if encoding
2578 * fails: overflow leaves the bytes written so far in place and @ref ok false.
2579 */
2581 {
2582 public:
2583 /**
2584 * @brief Construct over caller storage.
2585 * @param buffer Destination; must outlive this stream.
2586 * @param buflen Capacity of @p buffer in bytes.
2587 * @param offset Number of leading bytes to leave untouched before the cursor.
2588 */
2589 OStreamView(uint8_t *buffer, size_t buflen, size_t offset = 0) noexcept
2590 {
2591 initBuffer(buffer, buflen, offset);
2592 }
2593
2594 /**
2595 * @brief Construct over caller storage with a flush callback.
2596 * @param callback Invoked with finished bytes whenever the buffer fills.
2597 * @param buffer Destination; must outlive this stream.
2598 * @param buflen Capacity of @p buffer in bytes.
2599 * @param offset Number of leading bytes to leave untouched before the cursor.
2600 */
2601 OStreamView(flushCallback callback, uint8_t *buffer, size_t buflen,
2602 size_t offset = 0) noexcept
2603 {
2604 flushCallback_ = std::move(callback);
2605 initBuffer(buffer, buflen, offset);
2606 }
2607
2608 /**
2609 * @brief Install a different caller buffer, mid-stream.
2610 *
2611 * §5.1.1 lists "allow a new output buffer to be installed mid-stream"
2612 * among a corelib's required capabilities, and §5.1.5 puts the duty on
2613 * the **sink**: "A sink that takes the buffer MUST install a replacement
2614 * before returning." This is the call it makes. Without it a taking sink
2615 * could only be written against @ref OStream — the `shared_ptr` flavour —
2616 * which is the wrong one for the case a taking sink exists for: memory
2617 * the caller already owns and hands on (A2-0020).
2618 *
2619 * The stream keeps no reference to the buffer it gives up. The new one
2620 * must outlive the stream, and the same @ref MIN_OUTPUT_BUFFER floor
2621 * applies as at construction: behind a sink, `buflen - offset` short of
2622 * it is refused with @ref Error::InvalidArgument rather than partway
2623 * through a later field (§5.1.4).
2624 *
2625 * @param buffer New destination; must outlive this stream.
2626 * @param buflen Capacity of @p buffer in bytes.
2627 * @param offset Number of leading bytes to leave untouched before the cursor.
2628 */
2629 void setBuffer(uint8_t *buffer, size_t buflen, size_t offset = 0) noexcept
2630 {
2631 initBuffer(buffer, buflen, offset);
2632 }
2633 };
2634
2635 /**
2636 * @brief Output stream whose buffer is stored inline (the *buffer* costs no
2637 * heap allocation).
2638 *
2639 * The encoded bytes never leave the inline array, and the stream allocates
2640 * nothing at all — the held-back sequence run is fixed @ref MAX_DEPTH state
2641 * sized at construction (§6.6.2).
2642 *
2643 * Because the buffer **is** the object, this flavour admits only a
2644 * **copying** sink: there is nothing to hand over, so a sink must copy the
2645 * span it is given and return without installing anything (§5.1.5's other
2646 * half). A taking sink wants @ref OStreamView (caller memory, with
2647 * @ref OStreamView::setBuffer) or @ref OStream (`shared_ptr` memory).
2648 *
2649 * @tparam N Buffer capacity in bytes; must be greater than zero.
2650 * @tparam Offset Number of leading bytes to reserve before the cursor; must be less than @p N.
2651 */
2652 template <size_t N, size_t Offset = 0>
2654 {
2655 static_assert(N > 0, "Buffer size N must be greater than zero");
2656 static_assert(Offset < N, "Offset must be less than buffer size N");
2657 std::array<uint8_t, N> bufferOwner_{}; /**< Inline backing storage. */
2658
2659 public:
2660 /** Construct with no flush callback; overflow returns @ref Error::BufferFull. */
2661 OStreamInline() noexcept { initBuffer(bufferOwner_.data(), N, Offset); }
2662 /**
2663 * @brief Construct with a flush callback.
2664 * @param callback Invoked with finished bytes whenever the buffer fills.
2665 */
2666 explicit OStreamInline(flushCallback callback) noexcept
2667 {
2668 flushCallback_ = std::move(callback);
2669 initBuffer(bufferOwner_.data(), N, Offset);
2670 }
2671 };
2672
2673 /**
2674 * @brief Constrains a serialisable message: derives from @ref sofab::OStreamMessage
2675 * and exposes a `static constexpr std::size_t _maxSize`.
2676 * @tparam T Candidate message type.
2677 */
2678 template <class T>
2680 std::derived_from<T, OStreamMessage> &&
2681 requires { { T::_maxSize } -> std::convertible_to<std::size_t>; } &&
2682 std::is_same_v<decltype(T::_maxSize), const std::size_t>;
2683
2684 /**
2685 * @brief Base class for user-defined messages that can serialise themselves.
2686 *
2687 * Derive from this and implement @ref serialize to write the message's fields;
2688 * the object can then be passed to @ref OStreamImpl::write to be encoded as a
2689 * nested sub-message.
2690 */
2692 {
2693 protected:
2694 friend class OStreamImpl;
2695 /**
2696 * @brief Write this message's fields into @p ostream.
2697 * @param ostream Stream to encode into.
2698 * @return A @ref OStreamImpl::Result carrying the outcome.
2699 */
2700 virtual OStreamImpl::Result serialize(OStreamImpl &ostream) const noexcept = 0;
2701 };
2702
2703 /**
2704 * @brief Bundles a message with an inline output buffer sized for it.
2705 *
2706 * Combines an @ref OStreamInline buffer with an instance of @p MessageType,
2707 * so a message can be populated through `operator->` and then encoded in one
2708 * @ref serialize call without managing a separate stream and buffer.
2709 *
2710 * @tparam MessageType A type satisfying @ref sofab::OutputMessage.
2711 * @tparam N Buffer capacity in bytes; defaults to `MessageType::_maxSize`.
2712 * @tparam Offset Number of leading bytes to reserve before the cursor.
2713 */
2714 template <OutputMessage MessageType, size_t N = MessageType::_maxSize, size_t Offset = 0>
2715 class OStreamObject : public OStreamInline<N + Offset, Offset>
2716 {
2717 MessageType message_;
2718
2719 public:
2720 /** Construct with no flush callback. */
2721 OStreamObject() noexcept = default;
2722 /**
2723 * @brief Construct with a flush callback.
2724 * @param callback Invoked with finished bytes whenever the buffer fills.
2725 */
2726 explicit OStreamObject(typename OStreamImpl::flushCallback callback) noexcept
2727 : OStreamInline<N + Offset, Offset>{std::move(callback)} {}
2728
2729 /**
2730 * @brief Reach the wrapped message, so its fields are `obj->field`.
2731 *
2732 * `operator->` is re-applied to what it returns until a pointer comes
2733 * back, so this has to hand out a *pointer* to the message: returning a
2734 * reference to a type that has no `operator->` of its own is not a
2735 * member access at all, it is a compile error at every use.
2736 *
2737 * @return Pointer to the wrapped message; never null.
2738 */
2739 MessageType *operator->() noexcept { return &message_; }
2740 /** @copydoc operator->() */
2741 const MessageType *operator->() const noexcept { return &message_; }
2742
2743 /**
2744 * @brief Serialise the wrapped message into the inline buffer and flush.
2745 * @return A @ref OStreamImpl::Result carrying the outcome.
2746 */
2748 {
2749 auto result = message_.serialize(static_cast<OStreamImpl &>(*this));
2751 return result;
2752 }
2753 };
2754
2755
2756 /* ---------------------------------------------------------------------- */
2757 /* IStream — protobuf-style cursor decoder */
2758 /* ---------------------------------------------------------------------- */
2759
2760 class IStreamMessage;
2761 /**
2762 * @brief Constrains a deserialisable message: must derive from @ref sofab::IStreamMessage.
2763 * @tparam T Candidate message type.
2764 */
2765 template <typename T>
2766 concept InputMessage = std::derived_from<T, IStreamMessage>;
2767
2768 /* ---------------------------------------------------------------------- */
2769 /* Receiver-side policy */
2770 /* */
2771 /* Unlike the wire-format limits above, these are a LOCAL choice: */
2772 /* the bytes are well-formed, this receiver just declines to buffer */
2773 /* that much. Hence the separate outcome @ref Error::LimitExceeded, */
2774 /* which is not INVALID. */
2775 /* ---------------------------------------------------------------------- */
2776
2777 /**
2778 * @brief The one stream-scoped receiver cap: how many bytes a single top-level
2779 * field may span.
2780 *
2781 * @par This IS a §6.2.1 receiver cap, and is treated as one
2782 * It is configured by the **deployment**, not by the schema; it binds only a
2783 * field the schema leaves unbounded; and its breach is a **policy** rejection
2784 * on bytes that are perfectly well-formed — the same message decodes under a
2785 * looser number. That is precisely §6.3's `LimitExceeded`, and every rule
2786 * §6.2.1 states about a receiver limit therefore binds this one:
2787 *
2788 * * **the codec holds no limit of its own.** The number arrives as a
2789 * constructor argument, is the caller's, and is used for this one decode's
2790 * comparisons — §6.2.1's *"supplied per call **or per decode**, used for that
2791 * one comparison"*. An @ref IStreamObject / @ref IStreamInline **is** one
2792 * decode;
2793 * * **there is no default.** @ref Limits cannot be default-constructed and the
2794 * stream constructors do not default it, so a stream cannot come into
2795 * existence without the deployment having stated a number (§6.2.1: a codec
2796 * "**MUST NOT** supply a default for one it was not given");
2797 * * **there is no unlimited mode.** No value of this member is special-cased,
2798 * and no sentinel switches the check off. A caller that states `SIZE_MAX`
2799 * has stated the platform's own ceiling — the check still runs and simply
2800 * never fires — which is a number the *caller* chose, not a mode the codec
2801 * offers. §6.2 ceilings are never reported through @ref Error::LimitExceeded
2802 * in this library.
2803 *
2804 * @par The three `max_dyn_*` caps are not here
2805 * `max_dyn_array_count`, `max_dyn_string_len` and `max_dyn_blob_len` are
2806 * **not** members of this struct and never were the stream's to hold. Each is
2807 * a **parameter** on the call that reads the field it bounds — the `dynCap` of
2808 * @ref IStreamImpl::readStringCapped, @ref IStreamImpl::readBlobCapped,
2809 * @ref IStreamImpl::readArrayCapped and of a wrapper-array collector. They are
2810 * per **field**, so they belong on the read; this one is per **stream**,
2811 * because a field's span accrues across chunks and across a sequence's
2812 * children, where no single read exists to carry it.
2813 */
2814 struct Limits
2815 {
2816 /**
2817 * @brief Cap on how many bytes a single top-level field may span, in bytes.
2818 *
2819 * A receiver policy on the **size of a field**, not on a buffer: the
2820 * decoder holds no buffer a field could grow (§6.6). It is what bounds the
2821 * one shape the three per-read `max_dyn_*` caps cannot see — a *sequence*
2822 * whose bulk accrues field by field, which no single count or length word
2823 * announces.
2824 *
2825 * Checked the moment the size becomes known -- at the header for a fixlen
2826 * or fixlen-array payload, as it accrues for a sequence -- so an oversized
2827 * claim fails before its payload is buffered, and even if that payload
2828 * never arrives.
2829 *
2830 * It binds only a field the schema leaves **unbounded**: a declared
2831 * `maxlen`/`count` decides first, and its violation is
2832 * @ref Error::InvalidMessage rather than @ref Error::LimitExceeded
2833 * (§6.2.1/§6.3). An over-cap field is therefore still handed to the deliver
2834 * callback -- the only place that bound is known -- but with its payload
2835 * withheld, so it can be judged without being materialised.
2836 *
2837 * Bytes are never clamped or truncated; the `feed()` simply fails.
2838 */
2840
2841 /**
2842 * @brief State the cap. There is no default and no default constructor:
2843 * §6.2.1 leaves this library no number to invent.
2844 *
2845 * @param maxBufferedField The deployment's byte budget for one top-level
2846 * field. Generated code passes `SOFAB_MAX_DYN_BUFFERED_FIELD`; a
2847 * hand-written caller states its own. `SIZE_MAX` is a legal choice
2848 * and means "this receiver's budget is the platform's ceiling" — a
2849 * number the caller stated, not a mode this library offers.
2850 */
2851 constexpr explicit Limits(size_t maxBufferedField) noexcept
2852 : max_buffered_field(maxBufferedField) {}
2853 };
2854
2855 /**
2856 * @brief The value range a declared integer type admits (MESSAGE_SPEC §7.1).
2857 *
2858 * §7/§7.1 turned the declared integer width from a *storage hint* into a
2859 * **validity bound**: a wire value that does not fit the declared type is
2860 * `INVALID` alongside `M > N` and `maxlen`, and **MUST NOT** be masked to the
2861 * width, nor kept. The wire itself carries no width — every integer is a
2862 * varint read into a 64-bit accumulator — so the width is a **schema** fact
2863 * and has to reach the decoder the same way `count` and `maxlen` do
2864 * (@ref IStreamImpl::readArray, @ref IStreamImpl::readString).
2865 *
2866 * For a *scalar* a caller can range-check the value once @ref IStreamImpl::read
2867 * has returned it. An array *element* cannot be checked that way without
2868 * decoding the whole array into a wider temporary and copying it down —
2869 * precisely the cost the bulk path exists to avoid — so for arrays the bound
2870 * rides into the read and is applied where each element is decoded.
2871 *
2872 * Default-constructed it is **unarmed**, so an existing call site keeps the
2873 * behaviour it had.
2874 *
2875 * @note The range is inclusive and applied in full: an element below @ref lo
2876 * or above @ref hi makes the decode `INVALID`. For an unsigned element
2877 * type @ref lo is consulted only when positive, since a varint cannot be
2878 * negative.
2879 */
2881 {
2882 int64_t lo = 0; /**< Smallest admissible value, inclusive. */
2883 int64_t hi = 0; /**< Largest admissible value, inclusive. */
2884 bool armed = false; /**< `false`: no bound — the decode is unchanged. */
2885
2886 constexpr ElemBound() noexcept = default;
2887
2888 /** @brief An explicit inclusive range, armed. */
2889 constexpr ElemBound(int64_t low, int64_t high) noexcept
2890 : lo(low), hi(high), armed(true) {}
2891
2892 /**
2893 * @brief The bound a declared element type @p E implies.
2894 *
2895 * **Unarmed for a 64-bit type**, whose range is the accumulator's own and
2896 * therefore cannot be exceeded — so generated code may hand this in
2897 * unconditionally and a `u64`/`i64` array pays nothing for it.
2898 */
2899 template <typename E>
2900 static constexpr ElemBound of() noexcept
2901 {
2902 if constexpr (sizeof(E) >= sizeof(int64_t)) return ElemBound{};
2903 else
2904 return ElemBound{static_cast<int64_t>(std::numeric_limits<E>::min()),
2905 static_cast<int64_t>(std::numeric_limits<E>::max())};
2906 }
2907 };
2908
2909 /**
2910 * @brief Base of the input streams: decodes fields from fed bytes.
2911 *
2912 * Bytes are supplied through @ref feed, which may be called repeatedly with
2913 * chunks. A whole message handed in at once is parsed in place with no copy;
2914 * an incomplete trailing field is buffered and resumed on the next @ref feed.
2915 * Each complete top-level field is delivered to a callback, inside which
2916 * @ref read pulls the field's value out at the matching type.
2917 */
2919 {
2920 /* The wire tag types are implementation detail (sofab::detail); these
2921 * aliases keep this class terse without re-exporting the names. */
2922 using Wire = detail::Wire;
2923 using Fix = detail::Fix;
2924
2925 public:
2926 /**
2927 * @brief Three-valued outcome of a @ref feed call (spec §7).
2928 *
2929 * Carries one of @ref Error::None (`COMPLETE`), @ref Error::Incomplete
2930 * (`INCOMPLETE`) or @ref Error::InvalidMessage (`INVALID`). Read it either
2931 * as an @ref Error @ref code, as a @ref DecodeStatus via @ref status, or
2932 * through the boolean predicates @ref complete / @ref incomplete /
2933 * @ref invalid. @ref incomplete is **not** an error — the bytes merely end
2934 * mid-field and more may follow.
2935 */
2937 {
2938 Error error_;
2939 size_t skipped_ = 0;
2940 friend class IStreamImpl;
2941 explicit Result(Error e, size_t skipped = 0) noexcept : error_(e), skipped_(skipped) {}
2942 public:
2943 /**
2944 * @return Fields skipped because their wire tag contradicted the type
2945 * the callback asked for (MESSAGE_SPEC §7.3) — see
2946 * @ref IStreamImpl::skipped. A diagnostic: a non-zero count on
2947 * a `COMPLETE` result means the message was valid but did not
2948 * match this schema everywhere.
2949 */
2950 [[nodiscard]] size_t skipped() const noexcept { return skipped_; }
2951 /** @return `true` only for `COMPLETE` — the bytes end exactly at a field boundary. */
2952 [[nodiscard]] explicit operator bool() const noexcept { return ok(); }
2953 /** @return `true` only for `COMPLETE`; `false` for both @ref incomplete and @ref invalid. */
2954 [[nodiscard]] bool ok() const noexcept { return error_ == Error::None; }
2955 /**
2956 * @return The outcome as a @ref DecodeStatus, **one value per
2957 * category**. The three §5.2 wire outcomes map to
2958 * @ref DecodeStatus::Complete / @ref DecodeStatus::Incomplete /
2959 * @ref DecodeStatus::Invalid; the two non-wire refusals keep
2960 * values of their own — @ref DecodeStatus::LimitExceeded for a
2961 * receiver policy cap (§6.2.1) and
2962 * @ref DecodeStatus::InvalidArgument for a destination too
2963 * short for a well-formed value (§6.6.3).
2964 *
2965 * @note These used to fold into @ref DecodeStatus::Invalid "as a coarse
2966 * fallback", which §6.2.1 forbids outright — "An implementation
2967 * **MUST NOT** report it as `InvalidMessage` and **MUST NOT**
2968 * fold it into the `INVALID` outcome" — and `status()` is the
2969 * accessor a caller writing `switch (r.status())` reaches for
2970 * first (A2-0024).
2971 */
2972 [[nodiscard]] DecodeStatus status() const noexcept
2973 {
2974 switch (error_)
2975 {
2980 default: return DecodeStatus::Invalid;
2981 }
2982 }
2983 /** @return `true` if the consumed bytes end exactly at a field boundary (`COMPLETE`). */
2984 [[nodiscard]] bool complete() const noexcept { return error_ == Error::None; }
2985 /** @return `true` if the bytes end mid-field / with an open sequence (`INCOMPLETE`). Not an error. */
2986 [[nodiscard]] bool incomplete() const noexcept { return error_ == Error::Incomplete; }
2987 /**
2988 * @return `true` if the bytes are malformed (`INVALID`). **False** for a
2989 * @ref limitExceeded result — a policy cap is not wire malformation.
2990 */
2991 [[nodiscard]] bool invalid() const noexcept { return error_ == Error::InvalidMessage; }
2992 /** @return `true` if a receiver-side limit (§6.2.1) was exceeded. Distinct from @ref invalid. */
2993 [[nodiscard]] bool limitExceeded() const noexcept { return error_ == Error::LimitExceeded; }
2994 /**
2995 * @return `true` if a well-formed value did not fit the destination
2996 * the caller handed over (§6.3's third tier, §6.6.3). Distinct
2997 * from both @ref invalid and @ref limitExceeded.
2998 */
2999 [[nodiscard]] bool invalidArgument() const noexcept { return error_ == Error::InvalidArgument; }
3000 /** @return The status code (@ref Error::None, @ref Error::Incomplete, @ref Error::InvalidMessage, @ref Error::LimitExceeded or @ref Error::InvalidArgument). */
3001 [[nodiscard]] Error code() const noexcept { return error_; }
3002 /** @return `true` if the status code equals @p e. */
3003 bool operator==(Error e) const noexcept { return error_ == e; }
3004 /** @return `true` if the status code differs from @p e. */
3005 bool operator!=(Error e) const noexcept { return error_ != e; }
3006 };
3007
3008 protected:
3009 /**
3010 * @brief Widest prefix of a wire item that can outlive a chunk boundary,
3011 * derived from this format's own constants (§6.6).
3012 *
3013 * The parse never backs up over a payload — a `string`, a `blob` or an
3014 * array element run is written into the caller's destination piece by piece
3015 * as the pieces arrive (§6.6.2) — so what a chunk boundary can cut in half
3016 * is only ever a **small item**: a field header, the words between it and
3017 * its payload, a lone varint element, or a fixed-width scalar. The widest
3018 * of those is an `ARRAY_FIXLEN` field's prefix: the header word, the
3019 * element count and a `fixlen_word`, three varints of at most
3020 * @ref detail::VARINT_MAX_BYTES each.
3021 *
3022 * That is what makes @ref carry_ **bounded working state** in §6.6's sense
3023 * rather than an accumulator: a constant of the specification caps it, no
3024 * wire number can enlarge it, and it is sized when the decoder is
3025 * constructed.
3026 */
3027 static constexpr size_t CARRY_CAP = 3 * detail::VARINT_MAX_BYTES;
3028
3029 /**
3030 * @brief The prefix of one cut item, carried to the next @ref feed.
3031 *
3032 * This is what replaced the private reassembly accumulator §6.6.2 forbids:
3033 * "A payload split across fed chunks has to be joined somewhere. That
3034 * somewhere is storage the caller supplied — the codec copies each piece
3035 * into it as the piece arrives … A codec **MUST NOT** grow a private
3036 * accumulator instead." A fixed array of @ref CARRY_CAP bytes cannot be
3037 * grown, and a sender cannot make it larger by sending different bytes,
3038 * which is §6.6's whole test.
3039 */
3041 size_t carryLen_ = 0; /**< Live bytes of @ref carry_. */
3042
3043 /**
3044 * @brief Depth at which the parse is suspended, or -1 when nothing is.
3045 *
3046 * The decoder resumes rather than re-parses, so a field that straddles a
3047 * chunk boundary is never delivered from the beginning again. Three pieces
3048 * of fixed-size state describe where it stopped: this depth,
3049 * @ref pathId_ / @ref pathSkip_ for the sequences that are open above it,
3050 * and @ref pend_ / @ref pendDone_ for the field itself.
3051 */
3053 /** @brief Re-descending @ref pathId_ to reach @ref suspendDepth_. */
3054 bool replay_ = false;
3055 /**
3056 * @brief Id of the sequence field entered at each open level (§4.9).
3057 *
3058 * A nested sequence cannot be resumed by remembering a byte offset: the
3059 * handler chain that was descending into it lives on the C++ stack, which
3060 * a `feed` returning unwinds. What survives is the **path** — one field id
3061 * per open level — and replaying it re-enters exactly the handlers that
3062 * were open, because each level's `deserialize` dispatches on the id. At
3063 * most @ref MAX_DEPTH ids, sized at construction (§6.6).
3064 */
3066 /** @brief That level was entered by @ref skipPayload, not by a handler. */
3068 /** @brief A field at @ref suspendDepth_ is half-delivered. */
3069 bool pend_ = false;
3070 /**
3071 * @brief That field's header, kept apart from the live @ref type_ /
3072 * @ref fixLen_ / @ref count_.
3073 *
3074 * The live metadata belongs to whatever field the parser is looking at
3075 * *now*, and re-descending @ref pathId_ overwrites it with each sequence
3076 * header it replays. The suspended field's own header therefore has to be
3077 * kept separately and put back once its level is reached again — it is the
3078 * header the read will be continued under, and re-parsing it is exactly
3079 * what there are no bytes for.
3080 */
3082 Wire pendType_{}; /**< @copydoc pendId_ */
3083 Fix pendFix_{}; /**< @copydoc pendId_ */
3084 size_t pendLen_ = 0; /**< @copydoc pendId_ */
3085 size_t pendCount_ = 0; /**< @copydoc pendId_ */
3086 /** @brief ...and it was declined, so @ref skipPayload resumes it rather than the handler. */
3087 bool pendSkip_ = false;
3088 /**
3089 * @brief Progress through the pending field: payload bytes already written
3090 * into the caller's destination, or array elements already decoded.
3091 */
3092 size_t pendDone_ = 0;
3093 /** @brief Incremental UTF-8 DFA state for the `string` payload in progress (§6.4.4). */
3094 uint32_t utf8State_ = 0;
3095 /** @brief Bytes of the current top-level field consumed in earlier chunks (#26). */
3096 size_t spanCarry_ = 0;
3097 /** @brief Where that field's span continues in the window being parsed (#26). */
3098 const uint8_t *spanBase_ = nullptr;
3099 /**
3100 * @brief Is the parse currently inside a **skipped** sequence subtree
3101 * (§6.2.1, #129)?
3102 *
3103 * The accruing arm of the field-span cap (@ref beginField) is off while it
3104 * is set. A skipped subtree is walked, never materialized, so no receiver
3105 * limit governs it — the same reason @ref skipSequence suspends the
3106 * element-index bound, and set and restored in the same place, for the
3107 * same subtree.
3108 */
3109 bool spanSkip_ = false;
3110 /**
3111 * @brief Can the field-span cap provably not fire anywhere in the window
3112 * being parsed (§6.2.1, #26)? Set once per @ref parseWindow.
3113 *
3114 * Every span the cap measures in one window is at most @ref spanCarry_ plus
3115 * the window's length, and every header-declared `need` is at most
3116 * @ref CAP_NEED_MAX (the §6.2 ceilings: ARRAY_MAX elements of at most
3117 * FIXLEN_MAX bytes). When the stated budget covers both, @ref exceedsBuffer
3118 * would answer `false` for every field of the window, so asking it per
3119 * field is work with a known answer. This is not an unlimited mode: the
3120 * receiver's number is still the only input, and a budget that could be
3121 * reached keeps the per-field check exactly as before.
3122 */
3123 bool capInert_ = false;
3124 /**
3125 * @brief Bytes of the current top-level field spent on SKIPPED subtrees
3126 * (§6.2.1, #129 one level down).
3127 *
3128 * @ref spanned counts the field's raw byte span, which is what the
3129 * accruing arm of the field-span cap used to measure. Inside a sequence
3130 * this receiver DOES read, that span also contains every child it does
3131 * NOT — an unknown id, or one §7.3 declines — and those bytes are walked,
3132 * never materialized. §6.2.1: "a field the handler skips allocates
3133 * nothing", so "a decode that steps over an over-cap field it was never
3134 * going to read stays COMPLETE". @ref spanSkip_ suppresses the check
3135 * *inside* such a subtree; this discounts what the subtree cost, so the
3136 * live field AFTER it — the sequence end included — is measured against
3137 * the bulk this receiver actually took on and not against the sender's
3138 * padding. Reset with @ref spanCarry_, and carried across chunks for the
3139 * same reason it is.
3140 */
3141 size_t spanSkipped_ = 0;
3142
3143 /* cursor + current-field metadata, valid during a deliver callback */
3144 const uint8_t *p_ = nullptr; /**< Read cursor. */
3145 const uint8_t *end_ = nullptr; /**< One past the last readable byte. */
3146 Wire type_{}; /**< Wire type of the field being delivered. */
3147 Fix fixType_{}; /**< Sub-type of the current fixlen field. */
3148 size_t fixLen_ = 0; /**< Payload length (fixlen) or element size (fixlen array), in bytes. */
3149 size_t count_ = 0; /**< Element count of the current array field. */
3150 bool consumed_ = false; /**< Set once the callback has read the current field's value. */
3151 /**
3152 * @brief Sticky "this feed was refused" flag, and the **only** one the
3153 * parse loops test.
3154 *
3155 * Raised by every refusal, whichever of §6.3's three tiers it belongs to:
3156 * @ref invalidate raises it alone, @ref exceedLimit and
3157 * @ref rejectDestination raise it alongside their own category flag. That
3158 * keeps the per-field test in @ref dispatchLevel and @ref parseTopLevel a
3159 * single load — the categories are read once, by @ref feed, when the
3160 * parse has already stopped.
3161 */
3162 bool error_ = false;
3163 bool limitExceeded_ = false; /**< Category: a receiver-side limit was crossed (§6.2.1). Implies @ref error_. */
3164 /**
3165 * @brief Category: a well-formed value did not fit the destination the
3166 * caller handed over (§6.3's third refusal tier, §6.6.3). Implies
3167 * @ref error_.
3168 *
3169 * Lives for exactly one @ref feed, like @ref error_ and
3170 * @ref limitExceeded_, and is latched into @ref terminal_ as
3171 * @ref Error::InvalidArgument by the feed that saw it.
3172 */
3173 bool argError_ = false;
3174 /**
3175 * @brief The stream's latched terminal verdict, or @ref Error::None while
3176 * the stream is still usable (§5.2, §6.3).
3177 *
3178 * @ref error_, @ref limitExceeded_ and @ref argError_ live for exactly one
3179 * @ref feed; this outlives it. `INVALID` is terminal — §5.2 answers "can
3180 * more bytes change it?" with "no — terminal" — and `LimitExceeded` is "a
3181 * terminal, receiver-local policy rejection" (§6.3). `InvalidArgument`
3182 * (§6.3's third tier) is terminal for the same reason the other two are:
3183 * the field was refused rather than consumed, and letting a later chunk
3184 * "recover" it would make the verdict depend on where the chunk boundaries
3185 * fell. So once any of the three is the answer it stays the answer for
3186 * every later @ref feed, until @ref reset starts a new message. Without the
3187 * latch the verdict would depend on where the chunk boundaries fell: the
3188 * offending bytes are consumed and gone, so the next call would start from
3189 * a clean slate and resynchronize on whatever follows the fault — exactly
3190 * the divergence §7.2 item 4 forbids.
3191 */
3193 int seqDepth_ = 0; /**< Current nested-sequence depth during dispatch (§4.9 @ref MAX_DEPTH). */
3194 size_t skipped_ = 0; /**< §7.3 type-mismatch skips seen so far (@ref skipped). */
3195 bool incomplete_ = false; /**< The field being delivered needs more bytes (§7 INCOMPLETE, not malformed). */
3196 /**
3197 * @brief The tightest armed element-index bound of the wrapper sequence
3198 * being read (§5.1); -1 = none.
3199 *
3200 * A fast gate only — it answers "is any bound crossed?" in one compare.
3201 * Which of §6.3's three tiers a crossing belongs to is decided by
3202 * @ref rejectElementIndex from the three bounds below, and only once a
3203 * crossing has actually happened.
3204 */
3205 long elemBound_ = -1;
3206 long elemSchema_ = -1; /**< Schema `count` N: an id at or past it is `InvalidMessage` (§7.1). */
3207 long elemDyn_ = -1; /**< Configured `max_dyn_array_count`: `LimitExceeded` (§6.2.1). */
3208 long elemDest_ = -1; /**< The destination container's own capacity: `InvalidArgument` (§6.6.3). */
3209 int elemWire_ = -1; /**< §7.3 wire type its elements must carry (a @ref Wire as int); -1 = the collector decides the bound itself. */
3210 int elemFix_ = -1; /**< §7.3 fixlen subtype for that element type (a @ref Fix as int); -1 = the element type has none. */
3211 sofab::id fieldId_ = 0; /**< Id of the field being delivered. */
3212
3213 /**
3214 * @brief The receiver's byte budget for one top-level field
3215 * (@ref Limits::max_buffered_field), as this decode was told it.
3216 *
3217 * Deliberately **uninitialised here**: there is no value this library may
3218 * pick (§6.2.1), so the only way to reach it is through the constructor
3219 * below, which every stream has to go through.
3220 */
3222
3223 std::function<void(sofab::id, size_t, size_t)> topCallback_; /**< Delivers each top-level field. */
3224
3225 /**
3226 * @brief Construct with the receiver's @ref Limits; a derived class installs
3227 * @ref topCallback_.
3228 *
3229 * There is no default constructor. §6.2.1 leaves this codec no number to
3230 * invent, so a stream that was told none cannot be built: the omission is a
3231 * compile error rather than a decode that turns out to have been bounded by
3232 * nothing.
3233 */
3234 explicit IStreamImpl(Limits limits) noexcept
3235 : maxBufferedField_(limits.max_buffered_field)
3236 {}
3237
3238 /**
3239 * @brief Read one varint, given that a full varint window is in the buffer.
3240 *
3241 * The caller must have established that at least @ref detail::VARINT_MAX_BYTES
3242 * bytes are readable at @p p. That single fact retires both per-byte
3243 * checks the general path needs: the cursor cannot run past the end
3244 * inside ten bytes, and the first nine bytes carry at most 63 payload
3245 * bits, so only the tenth can be overlong (§4.1). With the checks gone
3246 * the first eight bytes can be taken as one word and unpacked with
3247 * @ref detail::gather7, leaving only a ninth and tenth byte to guard.
3248 *
3249 * @param[in,out] p Cursor; advanced past the varint, including on overflow.
3250 * @param[out] out Decoded value.
3251 * @param overflow Set when the varint is wider than 64 bits (INVALID, §6.3).
3252 * @return `true` on success, `false` on a > 64-bit varint.
3253 */
3254 /* Hot leaf of the decode loop. The §6.2.1/§7.3 work grew its callers past
3255 * GCC's default inline budget, at which point this stopped being inlined and
3256 * became an out-of-line call per varint — measured at +14.3%% on the
3257 * generator's cpp-cpp decode row with the body byte-identical (#133). The
3258 * attribute states the intent the budget can no longer be trusted to infer;
3259 * `finishField` above already carries it for the same reason. */
3260 [[gnu::always_inline]] static inline bool getVarintWindowed(const uint8_t *&p, uint64_t &out, bool *overflow) noexcept
3261 {
3262 /* Read the first eight bytes as one word and locate the terminator by
3263 * its clear continuation bit. Everything past it belongs to whatever
3264 * follows this varint, so it is masked away before the gather. */
3265 const uint64_t w = detail::loadLittle64(p);
3266 /* A single byte still wins on its own: one test against the gather's
3267 * dozen ALU ops. It is taken off the word already loaded rather than
3268 * from a second byte-sized load of p[0] — the load is on the critical
3269 * path either way, and one of the two was pure overhead. */
3270 if (!(w & 0x80u))
3271 {
3272 out = w & 0xffu;
3273 ++p;
3274 return true;
3275 }
3276 const uint64_t term = ~w & 0x8080808080808080ull;
3277 if (term) [[likely]]
3278 {
3279 const unsigned len = (static_cast<unsigned>(std::countr_zero(term)) >> 3) + 1u;
3280 out = detail::gather7(w & (~uint64_t{0} >> (64u - 8u * len)));
3281 p += len;
3282 return true;
3283 }
3284 /* Eight continuation bytes: 56 bits are in, and a ninth (and possibly
3285 * tenth) byte carries the rest. */
3286 uint64_t v = detail::gather7(w);
3287 const uint8_t b8 = p[8];
3288 v |= static_cast<uint64_t>(b8 & 0x7f) << 56;
3289 if (!(b8 & 0x80))
3290 {
3291 p += 9;
3292 out = v;
3293 return true;
3294 }
3295 /* Tenth byte: 63 bits are already in, so only bit 0 fits. Any higher
3296 * payload bit — or a continuation into an eleventh byte — is a varint
3297 * wider than 64 bits, which is INVALID (§4.1/§6.3). The cursor still
3298 * advances past the offending byte, exactly as the checked loop does,
3299 * so callers observe the same position either way. */
3300 const uint8_t b9 = p[9];
3301 p += 10;
3302 /* `b9 > 1` is exactly "a payload bit above bit 0, or a continuation
3303 * into an eleventh byte": the legal tenth bytes are 0x00 and 0x01 and
3304 * nothing else, so the two tests fold into one compare. */
3305 if (b9 > 1)
3306 {
3307 if (overflow) *overflow = true;
3308 return false;
3309 }
3310 v |= static_cast<uint64_t>(b9) << 63;
3311 out = v;
3312 return true;
3313 }
3314
3315 /** @brief @ref getVarintWindowed without building the value — see @ref skipVarint. */
3316 static bool skipVarintWindowed(const uint8_t *&p, bool *overflow) noexcept
3317 {
3318 const uint64_t term = ~detail::loadLittle64(p) & 0x8080808080808080ull;
3319 if (term) [[likely]]
3320 {
3321 p += (static_cast<unsigned>(std::countr_zero(term)) >> 3) + 1u;
3322 return true;
3323 }
3324 const uint8_t b8 = p[8];
3325 if (!(b8 & 0x80))
3326 {
3327 p += 9;
3328 return true;
3329 }
3330 const uint8_t b9 = p[9];
3331 p += 10;
3332 if (b9 > 1) /* see @ref getVarintWindowed */
3333 {
3334 if (overflow) *overflow = true;
3335 return false;
3336 }
3337 return true;
3338 }
3339
3340 /**
3341 * @brief Read one base-128 varint, advancing the cursor (bounds-checked).
3342 * @param[in,out] p Cursor; advanced past the varint on success.
3343 * @param end One past the last readable byte.
3344 * @param[out] out Decoded value.
3345 * @return `true` on success, `false` if the buffer ends mid-varint or it
3346 * overflows 64 bits. On overflow (a varint > 64 bits, §4.1) `*overflow`
3347 * is set: that is INVALID regardless of what follows, and callers in
3348 * callers must distinguish it from a merely-truncated tail.
3349 */
3350 /* Hot leaf of the decode loop. The §6.2.1/§7.3 work grew its callers past
3351 * GCC's default inline budget, at which point this stopped being inlined and
3352 * became an out-of-line call per varint — measured at +14.3%% on the
3353 * generator's cpp-cpp decode row with the body byte-identical (#133). The
3354 * attribute states the intent the budget can no longer be trusted to infer;
3355 * `finishField` above already carries it for the same reason. */
3356 [[gnu::always_inline]] static inline bool getVarint(const uint8_t *&p, const uint8_t *end, uint64_t &out,
3357 bool *overflow = nullptr) noexcept
3358 {
3359 /* One byte is the overwhelmingly common case away from array
3360 * payloads — every field header with an id below 16, every short
3361 * length, every small count and value — so it is tested before
3362 * anything else and costs a load and a compare. Array element runs do
3363 * not come through here at all; they drive @ref getVarintWindowed
3364 * directly under one shared bounds check (see @ref read). */
3365 if (p < end && *p < 0x80) [[likely]]
3366 {
3367 out = *p++;
3368 return true;
3369 }
3370 if (static_cast<size_t>(end - p) >= detail::VARINT_MAX_BYTES)
3371 return getVarintWindowed(p, out, overflow);
3372
3373 /* Tail: fewer than VARINT_MAX_BYTES bytes are left, so this loop runs
3374 * at most nine times and the value it builds carries at most 63 bits.
3375 * Both §4.1 overlong tests are therefore dead here — the tenth byte
3376 * that could trip them is by definition not in the buffer — and the
3377 * only way out other than a terminator byte is running dry, which is
3378 * a truncated varint (INCOMPLETE, not INVALID, so `overflow` stays
3379 * untouched). @p overflow is still taken for the fast path above. */
3380 uint64_t v = 0;
3381 int shift = 0;
3382 for (const uint8_t *q = p; q < end; )
3383 {
3384 const uint8_t b = *q++;
3385 v |= static_cast<uint64_t>(b & 0x7f) << shift;
3386 if (!(b & 0x80))
3387 {
3388 p = q;
3389 out = v;
3390 return true;
3391 }
3392 shift += 7;
3393 }
3394 /* Truncated: the cursor does NOT move. A varint cut by a chunk
3395 * boundary is bounded working state (§6.6.2) that rides in the carry
3396 * and is read again from its first byte, so every caller wants it left
3397 * where it started rather than half-consumed. */
3398 return false;
3399 }
3400 /**
3401 * @brief Advance the cursor past one varint without decoding it (bounds-checked).
3402 * @param[in,out] p Cursor; advanced past the varint on success.
3403 * @param end One past the last readable byte.
3404 * @return `true` on success, `false` if the buffer ends mid-varint or it
3405 * overflows 64 bits. As with @ref getVarint, `*overflow` is set on a
3406 * > 64-bit varint (§4.1), so an over-long varint is never mistaken
3407 * for a truncated tail.
3408 */
3409 static bool skipVarint(const uint8_t *&p, const uint8_t *end,
3410 bool *overflow = nullptr) noexcept
3411 {
3412 /* Same three-part shape as @ref getVarint, and for the same reasons. */
3413 if (p < end && *p < 0x80) [[likely]]
3414 {
3415 ++p;
3416 return true;
3417 }
3418 if (static_cast<size_t>(end - p) >= detail::VARINT_MAX_BYTES)
3419 return skipVarintWindowed(p, overflow);
3420
3421 for (const uint8_t *q = p; q < end; )
3422 if (!(*q++ & 0x80)) { p = q; return true; }
3423 return false; /* truncated: cursor unmoved, see @ref getVarint */
3424 }
3425
3426 /**
3427 * @brief Validate a single `Fixlen` field's length-and-subtype word (§4.6, §6.2).
3428 *
3429 * A well-formed word carries a defined subtype (0–3) whose length is legal
3430 * for that subtype: a `Fp32` payload is exactly 4 bytes, `Fp64` exactly 8,
3431 * and `String`/`Blob` any length up to @ref FIXLEN_MAX. Subtypes `0b100`..`0b111`
3432 * are reserved. A violation is malformed **regardless of what follows**
3433 * (spec §7 `INVALID`), so it must be rejected rather than mistaken for a
3434 * truncated (`INCOMPLETE`) field.
3435 *
3436 * @param word The decoded `fixlen_word` (`(length << 3) | subtype`).
3437 * @return `true` if the subtype/length pair is legal for a scalar fixlen field.
3438 */
3439 static bool fixlenWordValid(uint64_t word) noexcept
3440 {
3441 uint64_t len = word >> 3;
3442 switch (static_cast<Fix>(word & 0x7))
3443 {
3444 case Fix::Fp32: return len == 4;
3445 case Fix::Fp64: return len == 8;
3446 case Fix::String:
3447 case Fix::Blob: return len <= FIXLEN_MAX;
3448 default: return false; /* reserved subtype (§4.6) */
3449 }
3450 }
3451
3452 /**
3453 * @brief Validate a `ArrayFixlen` element word (§4.8, §6.2).
3454 *
3455 * A fixlen array may only carry fixed-width elements — `Fp32` (4 bytes) or
3456 * `Fp64` (8 bytes). Dynamic subtypes (`String`, `Blob`) and the reserved
3457 * subtypes are **not** permitted as array elements (§4.8); such a word is
3458 * `INVALID`.
3459 *
3460 * @param word The decoded per-element `fixlen_word`.
3461 * @return `true` if the subtype/element-size pair is legal for a fixlen array.
3462 */
3463 static bool arrayFixlenWordValid(uint64_t word) noexcept
3464 {
3465 uint64_t esize = word >> 3;
3466 switch (static_cast<Fix>(word & 0x7))
3467 {
3468 case Fix::Fp32: return esize == 4;
3469 case Fix::Fp64: return esize == 8;
3470 default: return false; /* string/blob/reserved (§4.8) */
3471 }
3472 }
3473
3474 /**
3475 * @brief Load a little-endian float or double from raw bytes.
3476 * @tparam F Floating-point type to read (`float` or `double`).
3477 * @param p Pointer to at least `sizeof(F)` readable bytes.
3478 * @return The decoded value.
3479 */
3480 template <std::floating_point F>
3481 static F loadFloat(const uint8_t *p) noexcept
3482 {
3483 using Bits = std::conditional_t<sizeof(F) == 4, uint32_t, uint64_t>;
3484 return detail::bitsFloat<F>(detail::loadLittleBits<Bits>(p));
3485 }
3486
3487 /**
3488 * @brief The §7.3 seam: does the delivered field's wire tag match the one
3489 * the caller's read declares?
3490 *
3491 * A field's *tag* is its wire type plus, for the fixlen kinds, the subtype
3492 * — the two are only meaningful together, since `fp32`, `fp64`, `string`
3493 * and `blob` all share @ref Wire::Fixlen. Every typed @ref read compares
3494 * the whole tag here, so half a comparison cannot be written.
3495 *
3496 * On a mismatch the field is left unconsumed: the parser that delivered it
3497 * — @ref parseTopLevel at the top level, @ref dispatchLevel inside a
3498 * sequence — then skips it exactly like an unknown id, which is what
3499 * MESSAGE_SPEC §7.3 requires — this is **not** an error, and never affects
3500 * the decode outcome. The skip is counted in @ref skipped_ as a diagnostic.
3501 *
3502 * A read may admit *more than one* subtype — `read(std::string&)` takes a
3503 * `string` or a `blob`, since both are fixlen payloads and a std::string
3504 * is the documented destination for either. That is what the two-subtype
3505 * overload is for: it is still one comparison of the whole tag, so a
3506 * refusal counts exactly one skip, never one per candidate.
3507 *
3508 * @param wantWire Wire type the read declares.
3509 * @param wantFix Fixlen subtype it declares; ignored unless @p wantWire is
3510 * a fixlen kind and the caller separates the subtypes.
3511 * @return `true` when the caller may consume the field.
3512 */
3513 [[nodiscard]] bool tagMatches(Wire wantWire) noexcept
3514 {
3515 if (type_ == wantWire) return true;
3516 ++skipped_;
3517 return false;
3518 }
3519
3520 [[nodiscard]] bool tagMatches(Wire wantWire, Fix wantFix) noexcept
3521 {
3522 if (type_ == wantWire && fixType_ == wantFix) return true;
3523 ++skipped_;
3524 return false;
3525 }
3526
3527 /** @copydoc tagMatches(Wire, Fix)
3528 * @param wantFix2 A second admissible fixlen subtype. */
3529 [[nodiscard]] bool tagMatches(Wire wantWire, Fix wantFix, Fix wantFix2) noexcept
3530 {
3531 if (type_ == wantWire && (fixType_ == wantFix || fixType_ == wantFix2)) return true;
3532 ++skipped_;
3533 return false;
3534 }
3535
3536 /**
3537 * @brief Deliver the current fixlen payload into the destination the
3538 * caller handed over (§6.6.3, second shape).
3539 *
3540 * The one place a `string` / `blob` payload reaches a destination, so the
3541 * §6.6 rule has one implementation and cannot hold in one read and be
3542 * missing from another. In order:
3543 *
3544 * 1. **The destination's room** (@ref detail::destRoom) against the
3545 * announced length. Too short is §6.3's third refusal tier —
3546 * @ref rejectDestination, `InvalidArgument` — because both bounds that
3547 * can speak about the *message* have already spoken: the schema
3548 * `maxlen` in the caller above, and any configured receiver cap. It is
3549 * decided from the **header alone**, before a byte of payload is
3550 * consulted, so where the chunk boundaries fall cannot change it.
3551 * 2. **Availability.** Fewer bytes than the declared length is
3552 * `INCOMPLETE`, never an error (§5.2).
3553 * 3. **UTF-8** (§6.4), for a `string` payload only, and never on skip
3554 * (§6.4.5 — this function runs only where a value is materialized).
3555 * 4. **The copy**, then the length (@ref sofab::detail::destSetLen). The
3556 * destination is written exactly once, complete (§6.6.2).
3557 *
3558 * @tparam D Destination: @ref sofab::FixedString / @ref sofab::FixedBytes
3559 * (static room) or a `std::string` / `std::vector<uint8_t>` the
3560 * caller sized.
3561 * @param value Destination.
3562 * @param validateUtf8 Whether the payload is a `string` (§6.4).
3563 * @return `true` when the payload was delivered and the field consumed.
3564 */
3565 template <typename D>
3566 bool readPayload(D &value, bool validateUtf8) noexcept
3567 {
3568 const size_t avail = static_cast<size_t>(end_ - p_);
3569 if (pendDone_ == 0 && avail >= fixLen_) [[likely]]
3570 {
3571 /* The whole payload in one piece — every un-chunked feed, and every
3572 * chunked one whose boundary did not fall inside this field. One
3573 * room test, one validation pass, one copy. */
3574 if (!roomFor(value, fixLen_)) return false;
3575#if SOFAB_STRICT_UTF8
3576 if (validateUtf8 &&
3577 !detail::utf8Valid(reinterpret_cast<const char *>(p_), fixLen_))
3578 { error_ = true; return false; }
3579#else
3580 (void)validateUtf8;
3581#endif
3582 if (fixLen_) std::memcpy(value.data(), p_, fixLen_);
3584 p_ += fixLen_;
3585 consumed_ = true;
3586 return true;
3587 }
3588 return readPayloadPiece(value, validateUtf8, avail);
3589 }
3590
3591 /**
3592 * @brief Is there room for @p need bytes in the destination the caller
3593 * handed over (§6.6.3)?
3594 *
3595 * Two kinds of destination answer differently, and the difference is a fact
3596 * the type publishes rather than a policy this read picks:
3597 *
3598 * * **static room** (`D::capacity()`) cannot change between chunks, so the
3599 * refusal is decided from the header alone — before a byte of payload is
3600 * consulted — and where the chunk boundaries fall cannot change it;
3601 * * **room the caller sized** is judged against what this delivery can
3602 * actually reach: the announced length, clamped to what has arrived. A
3603 * declared length whose payload is absent or withheld reaches nothing and
3604 * refuses nothing, so a truncated field stays `INCOMPLETE` (§5.2) instead
3605 * of being mistaken for a destination that is too small; once the last
3606 * piece is here the reach IS the announced length, and a destination
3607 * genuinely too short is refused exactly then.
3608 *
3609 * @return `false` with @ref rejectDestination raised (`InvalidArgument`).
3610 */
3611 template <typename D>
3612 bool roomFor(D &value, size_t need) noexcept
3613 {
3614 if constexpr (requires { D::capacity(); })
3615 {
3616 if (fixLen_ > D::capacity()) { rejectDestination(); return false; }
3617 }
3618 else if (need > value.size()) { rejectDestination(); return false; }
3619 return true;
3620 }
3621
3622 /**
3623 * @brief The chunk-straddling half of @ref readPayload — deliver the piece
3624 * that has arrived and remember how far the value got.
3625 *
3626 * §6.6.2: "A payload split across fed chunks has to be joined somewhere.
3627 * That somewhere is storage the caller supplied — the codec copies each
3628 * piece into it as the piece arrives … A codec **MUST NOT** grow a private
3629 * accumulator instead." So the piece goes straight where the value belongs
3630 * and only the **length** is published, once, at the end — no caller ever
3631 * sees a half-written value (§6.6.2's "written exactly once, complete").
3632 *
3633 * Cold: it runs only for a field a chunk boundary fell inside.
3634 */
3635 template <typename D>
3636 bool readPayloadPiece(D &value, bool validateUtf8, size_t avail) noexcept
3637 {
3638 const size_t done = pendDone_;
3639 const size_t take = std::min(avail, fixLen_ - done);
3640 if (!roomFor(value, done + take)) return false;
3641#if SOFAB_STRICT_UTF8
3642 /* §6.4.4 permits exactly this — "A decoder MAY validate incrementally
3643 * provided it carries validator state across `feed` calls; no assembly
3644 * buffer is required" — and requires the verdict to be taken at payload
3645 * completion, never mid-payload, so a chunk boundary cannot decide it. */
3646 if (validateUtf8) utf8State_ = detail::utf8Advance(utf8State_, p_, take);
3647#else
3648 (void)validateUtf8;
3649#endif
3650 if (take) std::memcpy(value.data() + done, p_, take);
3651 p_ += take;
3652 if (done + take < fixLen_)
3653 {
3654 pendDone_ = done + take;
3655 incomplete_ = true;
3656 return false;
3657 }
3658#if SOFAB_STRICT_UTF8
3659 if (validateUtf8 && utf8State_ != detail::UTF8_ACCEPT)
3660 { error_ = true; return false; }
3661#endif
3663 pendDone_ = 0;
3665 consumed_ = true;
3666 return true;
3667 }
3668
3669 /** @brief Upper bound of any header-declared `need` (§6.2 ceilings). */
3670 static constexpr uint64_t CAP_NEED_MAX =
3671 static_cast<uint64_t>(ARRAY_MAX) * static_cast<uint64_t>(FIXLEN_MAX);
3672
3673 /**
3674 * @brief Hoisted form of @ref exceedsBuffer for a whole window of @p n
3675 * bytes: `true` when no field of it can cross the budget.
3676 */
3677 [[nodiscard]] bool capCannotFire(size_t n) const noexcept
3678 {
3679 const uint64_t cap = static_cast<uint64_t>(maxBufferedField_);
3680 const uint64_t reach = static_cast<uint64_t>(spanCarry_) + static_cast<uint64_t>(n);
3681 if (reach < static_cast<uint64_t>(n) || reach > cap) return false;
3682 return cap - reach >= CAP_NEED_MAX;
3683 }
3684
3685 /**
3686 * @brief Would buffering this field cross @ref maxBufferedField_?
3687 *
3688 * @param consumed Bytes of the current top-level field already spanned.
3689 * @param need Further bytes the field is now known to require (a declared
3690 * payload length, array byte-span, or per-element lower bound).
3691 * @return `true` if `consumed + need` exceeds the cap. Overflow-safe: the
3692 * addition is never formed, so a caller that stated `SIZE_MAX` as
3693 * its budget gets a check that runs and never fires, rather than a
3694 * check this library switched off.
3695 */
3696 [[nodiscard]] bool exceedsBuffer(size_t consumed, uint64_t need) const noexcept
3697 {
3698 if (consumed > maxBufferedField_) return true;
3699 return need > static_cast<uint64_t>(maxBufferedField_ - consumed);
3700 }
3701
3702
3703 /**
3704 * @brief Decode fields at the current nesting level, firing @p cb for each.
3705 *
3706 * For every field the metadata members (@ref type_, @ref fixLen_,
3707 * @ref count_, ...) are set before @p cb runs; a field whose value the
3708 * callback does not @ref read is skipped automatically.
3709 *
3710 * @tparam Cb The callable's own type, so the call is direct. A
3711 * `std::function` parameter here cost a construction, a
3712 * manager-driven destruction and two indirect hops **per
3713 * sub-message read**, and the `std::function` machinery around
3714 * it accounted for ~13 % of the `decode: typical message`
3715 * profile. The two call sites pass a stateless no-op
3716 * (@ref skipPayload) and a two-pointer lambda (@ref read), so
3717 * the instantiation count is bounded and the body inlines into
3718 * both.
3719 * @param cb Callback invoked as `(fieldId, size, count)` per field.
3720 * @param stopAtEnd If `true`, return at a @ref Wire::SequenceEnd
3721 * marker (nested level); if `false`, such a marker is a decode error.
3722 */
3723 /**
3724 * @brief A non-owning reference to a level's per-field callback.
3725 *
3726 * The parse loops call their callback through a template parameter, so the
3727 * call is direct and inlines (that is deliberate — a `std::function`
3728 * parameter there cost ~13 % of `decode: typical message`). The **resume**
3729 * helpers below want the opposite: they run once per chunk boundary, never
3730 * in the loop, and compiling a copy of each of them into every one of the
3731 * dozens of `dispatchLevel` instantiations buys nothing but code size and
3732 * uncoverable lines. They take this instead — two pointers, one indirect
3733 * call on a cold path.
3734 */
3735 struct FieldCb
3736 {
3737 void *ctx;
3738 void (*fn)(void *, sofab::id, size_t, size_t);
3739 void operator()(sofab::id id, size_t size, size_t count) const noexcept
3740 {
3741 fn(ctx, id, size, count);
3742 }
3743 };
3744
3745 /** @brief Wrap a level's callback as a @ref FieldCb. */
3746 template <typename Cb>
3747 static FieldCb wrapCb(Cb &cb) noexcept
3748 {
3749 return FieldCb{&cb, [](void *p, sofab::id id, size_t size, size_t count) noexcept {
3750 (*static_cast<Cb *>(p))(id, size, count);
3751 }};
3752 }
3753
3754 /** @brief How a level is being entered (see @ref levelEntry). */
3755 enum class Entry : uint8_t
3756 {
3757 Fresh, /**< Nothing open here: parse the next field. */
3758 Descend, /**< The suspended level is deeper: replay one more id. */
3759 Resume, /**< This level is it: continue its half-delivered field. */
3760 };
3761
3762 /**
3763 * @brief Decide how this level is being entered, and clear the replay state
3764 * once the suspended level is reached.
3765 *
3766 * Non-template on purpose: every `dispatchLevel` instantiation asks the
3767 * same question, and only the answer differs.
3768 */
3770 {
3771 if (!replay_) return Entry::Fresh;
3773 replay_ = false;
3774 suspendDepth_ = -1;
3775 return pend_ ? Entry::Resume : Entry::Fresh;
3776 }
3777
3778 template <typename Cb>
3779 void dispatchLevel(Cb &&cb, bool stopAtEnd) noexcept
3780 {
3781 /* Re-enter a level the previous chunk left open, rather than parsing
3782 * its bytes again — which is the whole of §6.6.2's "MUST NOT grow a
3783 * private accumulator": there is nothing to re-parse from. */
3784 const Entry entry = levelEntry();
3785 if (entry != Entry::Fresh) [[unlikely]]
3786 {
3787 if (!reenterLevel(wrapCb(cb), entry)) return;
3788 }
3789
3790 while (p_ < end_ && !error_ && !incomplete_)
3791 {
3792 /* Everything before the delivery is the same code in every
3793 * instantiation, and it is where §7.3's element test, §5.1's index
3794 * bound and §4.6/§4.8's metadata rules all live, so it is written
3795 * once (@ref beginField) rather than copied into each.
3796 *
3797 * @c fieldStart is taken first because it is the field's FIRST
3798 * byte, not its payload's: a child this level SKIPS is discounted
3799 * from the field-span cap whole, header and all, exactly as a
3800 * declined top-level field is (§6.2.1, @ref finishField). */
3801 const uint8_t *const fieldStart = p_;
3802 const Field f = beginField(stopAtEnd);
3803 if (f == Field::Stop) return;
3804 const sofab::id fieldId = fieldId_;
3805 const uint8_t *payload = p_;
3806 /* a §7.3-skipped element is never delivered; leaving it unconsumed
3807 * runs it through the same skip as an unknown id. */
3808 if (f != Field::SkipElem) cb(fieldId, fixLen_, count_);
3809 if (!finishField(fieldStart, payload, fieldId)) return;
3810 }
3811 closeLevel(stopAtEnd);
3812 }
3813
3814 /** @brief What @ref beginField found at this level's next field. */
3815 enum class Field : uint8_t
3816 {
3817 Ready, /**< Deliver it. */
3818 SkipElem, /**< §7.3 says it is not this array's element: skip, do not deliver. */
3819 Stop, /**< The level is finished, suspended or refused. */
3820 };
3821
3822 /**
3823 * @brief Parse the next field's header and metadata at a nested level, and
3824 * apply every rule that is decided before the value.
3825 *
3826 * Split out of @ref dispatchLevel so it is compiled **once** rather than
3827 * once per callback type: the loop's callback is a template parameter so
3828 * the delivery inlines, but everything around it is the same code in every
3829 * instantiation, and a dozen copies of it are a dozen copies of the §7.3
3830 * and §5.1 rules for a reader to keep in step.
3831 *
3832 * @param stopAtEnd Whether a @ref Wire::SequenceEnd closes this level.
3833 * @return @ref Field::Stop when @ref dispatchLevel must return.
3834 */
3835 Field beginField(bool stopAtEnd) noexcept
3836 {
3837 /* #26: a sequence's own bulk accrues field by field — bound it as it
3838 * grows, catching many-small-fields that no single payload check
3839 * would trip. Not inside a skipped subtree: §6.2.1's "a skipped field
3840 * is never capped" is not about how the field's size is learnt, and a
3841 * sequence nobody asked for is the case the rule most obviously
3842 * protects — a peer adding a nested message at an id this schema does
3843 * not declare (#129). */
3845 { exceedLimit(); return Field::Stop; }
3846 const uint8_t *const fieldStart = p_;
3847 if (!parseFieldTag())
3848 {
3849 /* A cut header is backed up whole: it is at most three varints,
3850 * which is what @ref CARRY_CAP is sized for. */
3851 if (incomplete_) { p_ = fieldStart; suspendAtBoundary(); }
3852 return Field::Stop;
3853 }
3854 const sofab::id fieldId = fieldId_;
3855 /* §5.1/§7: an element index at or past the declared count is
3856 * INVALID -- but §7.3 decides first. An element header whose wire
3857 * type (or, for a fixlen element type, whose fixlen subtype)
3858 * contradicts the declared element type MUST be skipped exactly as
3859 * an unknown id is skipped, so it never becomes an element and its
3860 * id is not an array index the bound could measure. §7.4 states the
3861 * same from the other side ("an occurrence skipped under §7.3 is
3862 * not an occurrence"), and CORELIB_PLAN §4.8 gives the reason: the
3863 * field was never this array's value.
3864 *
3865 * The bound is therefore applied only to a header that survives the
3866 * §7.3 test. For a fixlen element type that is known only after the
3867 * fixlen word below, so a message ending BETWEEN the element header
3868 * and its fixlen word is INCOMPLETE, not INVALID (§5.2, the analogue
3869 * of §4.8's ruling for the fixlen array's two words). From the
3870 * fixlen word on the reject is immediate -- it never waits for
3871 * payload bytes. Format-level rejects (over-64-bit varint,
3872 * ARRAY_MAX, a reserved fixlen subtype, ...) still fire on a skipped
3873 * field's own metadata: §7.3 subordinates the SCHEMA bound only.
3874 *
3875 * A collector that publishes no element type (elemWire_ < 0) keeps
3876 * the bound to itself and enforces it in its deserialize. */
3877 bool skipElem = false; /* §7.3: not an element of this array */
3878 bool boundPending = false; /* over-index, subtype not yet known */
3879 if (elemBound_ >= 0 && elemWire_ >= 0 && type_ != Wire::SequenceEnd &&
3880 static_cast<long>(fieldId) >= elemBound_)
3881 {
3882 if (static_cast<int>(type_) != elemWire_) { skipElem = true; ++skipped_; }
3883 else if (type_ != Wire::Fixlen) { rejectElementIndex(fieldId); return Field::Stop; }
3884 else boundPending = true; /* decided at the fixlen word */
3885 }
3886
3887 if (type_ == Wire::SequenceEnd)
3888 {
3889 if (!stopAtEnd) error_ = true; /* §7: a dangling end */
3890 return Field::Stop;
3891 }
3892
3893 /* The metadata that precedes the payload — one parser, shared
3894 * with the top level (@ref parseFieldMeta). It used to be copied
3895 * out here, and the copy silently lost the §6.2 count ceiling on
3896 * a nested fixlen array until #103 put it back; a second copy of
3897 * a validating parser is a hole waiting to reopen. */
3898 if (!parseFieldMeta())
3899 {
3900 if (incomplete_) { p_ = fieldStart; suspendAtBoundary(); }
3901 return Field::Stop;
3902 }
3903
3904 /* the fixlen word is in: §7.3 first, then the §5.1/§7 bound. */
3905 if (boundPending)
3906 {
3907 if (elemFix_ >= 0 && static_cast<int>(fixType_) != elemFix_)
3908 { skipElem = true; ++skipped_; }
3909 else { rejectElementIndex(fieldId); return Field::Stop; }
3910 }
3911
3912 /* From here the field's metadata is settled, so a chunk boundary
3913 * inside it no longer costs a rewind: it suspends. The progress
3914 * counters start at zero for a field nothing has delivered yet;
3915 * @ref pend_ / @ref pendSkip_ need no reset, since every suspension
3916 * writes them (@ref suspendHere, @ref suspendAtBoundary). */
3917 pendDone_ = 0;
3918 utf8State_ = 0;
3919 consumed_ = false;
3920 return skipElem ? Field::SkipElem : Field::Ready;
3921 }
3922
3923 /**
3924 * @brief Settle a field the callback has been offered: skip it if the
3925 * callback did not want it, suspend it if its bytes ran out.
3926 *
3927 * The callback did not want this field: rewind to the payload — which the
3928 * declining read left the cursor at anyway — and skip it, resumably, so a
3929 * long payload nobody asked for is stepped over as it arrives rather than
3930 * buffered (§6.6.2).
3931 *
3932 * §7: the bytes running out INSIDE the field is a different thing. It is
3933 * unfinished, not declined, and the two must not be confused — hence the
3934 * `!incomplete_` in the test. Skipping a truncation would rewind into a
3935 * payload the callback has already parsed *into* and re-read those bytes
3936 * under the metadata of whatever innermost field the descent left behind,
3937 * reporting INVALID for a truncation (Crucible F-0056, corelib-cpp#71).
3938 *
3939 * §6.2.1: what the skip walks past is discounted from the field-span cap
3940 * — from @p fieldStart, so the skipped child's own header goes with it.
3941 * A skip that SUSPENDS discounts what this window walked and the resume
3942 * (@ref deliverPending) discounts the rest, which is what keeps the
3943 * verdict independent of the caller's chunking (§7.2 item 4).
3944 *
3945 * @param fieldStart The field's first header byte.
3946 * @param payload The field's first payload byte.
3947 * @param fieldId Its id, for the path entry a suspension records.
3948 * @return `false` when the level must return.
3949 */
3950 [[gnu::always_inline]] inline bool finishField(const uint8_t *fieldStart,
3951 const uint8_t *payload,
3952 sofab::id fieldId) noexcept
3953 {
3954 bool declined = false;
3955 if (!incomplete_ && !consumed_)
3956 {
3957 declined = true;
3958 p_ = payload;
3959 skipPayload();
3960 discountSkipped(fieldStart);
3961 }
3962 if (incomplete_)
3963 {
3964 suspendHere(fieldId, declined);
3965 return false;
3966 }
3967 return true;
3968 }
3969
3970 /**
3971 * @brief The bytes ran out with this sequence still open — `INCOMPLETE`,
3972 * not malformed (§7). The level is re-entered along @ref pathId_
3973 * once the remaining bytes arrive.
3974 */
3975 void closeLevel(bool stopAtEnd) noexcept
3976 {
3977 if (stopAtEnd && !error_ && !incomplete_)
3978 {
3979 incomplete_ = true;
3981 }
3982 }
3983
3984 /** @brief Take the @ref Entry::Descend or @ref Entry::Resume path. */
3985 bool reenterLevel(FieldCb cb, Entry entry) noexcept
3986 {
3987 if (entry == Entry::Descend) return descendResume(cb);
3989 return deliverPending(cb, pendSkip_);
3990 }
3991
3992 /**
3993 * @brief Record that this level's current field is the suspension point.
3994 *
3995 * The innermost level claims @ref suspendDepth_; every level above it then
3996 * writes its own @ref pathId_ entry as the stack unwinds, so the path is
3997 * complete by the time @ref feed sees the `INCOMPLETE`.
3998 *
3999 * @param fieldId Id of this level's field, for the @ref pathId_ entry a
4000 * level above the suspension records.
4001 * @param declined Whether the field was being skipped rather than read.
4002 */
4003 void suspendHere(sofab::id fieldId, bool declined) noexcept
4004 {
4005 if (suspendDepth_ >= 0)
4006 {
4007 /* A deeper level is the suspension point; this one is on the path
4008 * that reaches it. */
4009 pathId_[seqDepth_] = fieldId;
4010 pathSkip_[seqDepth_] = declined;
4011 return;
4012 }
4014 pend_ = true;
4015 pendSkip_ = declined;
4016 pendId_ = fieldId;
4017 pendType_ = type_;
4019 pendLen_ = fixLen_;
4021 }
4022
4023 /**
4024 * @brief Claim the suspension for this level at a **field boundary** —
4025 * nothing half-delivered, only a header cut in two or a sequence
4026 * still open.
4027 *
4028 * The ≤ @ref CARRY_CAP bytes of the cut header ride in @ref carry_ and are
4029 * parsed again from their first byte; there is no pending field, so nothing
4030 * is re-delivered.
4031 */
4032 void suspendAtBoundary() noexcept
4033 {
4034 if (suspendDepth_ >= 0) return;
4036 pend_ = false;
4037 pendSkip_ = false;
4038 }
4039
4040 /** @brief Put the suspended field's header back before continuing it. */
4041 void restorePending() noexcept
4042 {
4043 fieldId_ = pendId_;
4044 type_ = pendType_;
4046 fixLen_ = pendLen_;
4048 }
4049
4050 /**
4051 * @brief Re-deliver the half-delivered field at this level.
4052 *
4053 * Its metadata (@ref type_, @ref fixLen_, @ref count_, @ref fieldId_) is
4054 * still the state the previous chunk left, and @ref pendDone_ says how far
4055 * it got, so the read (or the skip) continues where it stopped instead of
4056 * starting over.
4057 *
4058 * @return `false` when the level must return — the field suspended again,
4059 * or the decode failed.
4060 */
4061 bool deliverPending(FieldCb cb, bool declined) noexcept
4062 {
4063 /* A descent below this field clobbers @ref fieldId_, so the id this
4064 * level would have to record is taken before the delivery. */
4065 const sofab::id id = fieldId_;
4066 consumed_ = false;
4067 const uint8_t *const from = p_;
4068 if (declined) { skipPayload(); discountSkipped(from); }
4069 else cb(id, fixLen_, count_);
4070 if (error_) return false;
4071 if (!incomplete_ && !consumed_ && !declined)
4072 {
4073 declined = true;
4074 skipPayload();
4075 discountSkipped(from);
4076 if (error_) return false;
4077 }
4078 if (incomplete_)
4079 {
4080 suspendHere(id, declined);
4081 return false;
4082 }
4083 pend_ = false;
4084 pendSkip_ = false;
4085 pendDone_ = 0;
4086 return true;
4087 }
4088
4089 /**
4090 * @brief Re-descend one recorded level of @ref pathId_ towards
4091 * @ref suspendDepth_.
4092 *
4093 * Replays the sequence field this level was inside when the chunk ran out:
4094 * either by handing its id back to @p cb — whose `deserialize` dispatches
4095 * on the id and calls `read` on the same member, re-establishing exactly the
4096 * handler that was open — or, for a level that was being **skipped**, by
4097 * re-entering the skip descent directly. Nothing is parsed here: the bytes
4098 * of the sequence header were consumed by an earlier chunk and are gone.
4099 *
4100 * @param cb This level's per-field callback.
4101 * @return `false` when the level must return.
4102 */
4103 bool descendResume(FieldCb cb) noexcept
4104 {
4105 const int d = seqDepth_;
4106 const sofab::id fieldId = pathId_[d];
4107 const bool declined = pathSkip_[d];
4108 fieldId_ = fieldId;
4109 type_ = Wire::SequenceStart;
4110 fixLen_ = 0;
4111 count_ = 0;
4112 if (declined)
4113 {
4114 if (seqDepth_ >= MAX_DEPTH) { error_ = true; return false; }
4115 /* §6.2.1, as in @ref finishField: the rest of a skipped subtree,
4116 * arriving in a later chunk, is still walked and not materialized.
4117 * Discounting it here is what makes the cap's verdict the same
4118 * whether the subtree arrived in one window or ten. */
4119 const uint8_t *const from = p_;
4120 skipSequence();
4121 discountSkipped(from);
4122 }
4123 else
4124 {
4125 consumed_ = false;
4126 cb(fieldId, size_t{0}, size_t{0});
4127 }
4128 if (error_) return false;
4129 if (incomplete_)
4130 {
4131 suspendHere(fieldId, declined);
4132 return false;
4133 }
4134 return true;
4135 }
4136
4137 /**
4138 * @brief Step over the payload of the current field, resumably.
4139 *
4140 * Called for a field the callback declined. Like every read, it never
4141 * buffers what it has not finished: a payload cut by a chunk boundary
4142 * leaves its byte (or element) progress in @ref pendDone_ and is continued
4143 * on the next @ref feed, and a **small** item cut in half — a lone varint,
4144 * an element — is backed up to its own start so the ≤ @ref CARRY_CAP bytes
4145 * of it can be carried (§6.6.2).
4146 *
4147 * Assumes the cursor sits at the payload's resume point and the field
4148 * metadata is set.
4149 */
4150 void skipPayload() noexcept
4151 {
4152 switch (type_)
4153 {
4154 case Wire::Unsigned:
4155 case Wire::Signed:
4156 {
4157 /* One varint, at most @ref detail::VARINT_MAX_BYTES bytes: cut
4158 * in half it is backed up whole rather than half-consumed, so
4159 * the carry holds it and this runs again from its first byte. */
4160 bool ovf = false;
4161 if (!skipVarint(p_, end_, &ovf))
4162 (ovf ? error_ : incomplete_) = true;
4163 break;
4164 }
4165 case Wire::Fixlen:
4166 {
4167 /* A payload of any length, stepped over as it arrives. */
4168 const size_t left = fixLen_ - pendDone_;
4169 const size_t avail = static_cast<size_t>(end_ - p_);
4170 if (avail < left)
4171 {
4172 p_ += avail;
4173 pendDone_ += avail;
4174 incomplete_ = true;
4175 break;
4176 }
4177 p_ += left;
4178 pendDone_ = 0;
4179 break;
4180 }
4181 case Wire::ArrayUnsigned:
4182 case Wire::ArraySigned:
4183 {
4184 for (size_t i = pendDone_; i < count_; ++i)
4185 {
4186 bool ovf = false;
4187 if (!skipVarint(p_, end_, &ovf))
4188 {
4189 if (ovf) { error_ = true; return; }
4190 pendDone_ = i;
4191 incomplete_ = true;
4192 return;
4193 }
4194 }
4195 pendDone_ = 0;
4196 break;
4197 }
4198 case Wire::ArrayFixlen:
4199 {
4200 const size_t bytes = count_ * fixLen_;
4201 const size_t left = bytes - pendDone_;
4202 const size_t avail = static_cast<size_t>(end_ - p_);
4203 if (avail < left)
4204 {
4205 p_ += avail;
4206 pendDone_ += avail;
4207 incomplete_ = true;
4208 break;
4209 }
4210 p_ += left;
4211 pendDone_ = 0;
4212 break;
4213 }
4214 case Wire::SequenceStart:
4215 {
4216 if (seqDepth_ >= MAX_DEPTH) /* §4.9 */
4217 {
4218 error_ = true;
4219 break;
4220 }
4221 skipSequence();
4222 break;
4223 }
4224 case Wire::SequenceEnd:
4225 break;
4226 }
4227 }
4228
4229 /**
4230 * @brief Walk a sub-sequence nobody asked for, delivering nothing.
4231 *
4232 * Split out of @ref skipPayload because a skipped sequence, like every
4233 * other construct, has to be **re-enterable**: when a chunk ends inside one
4234 * the level is recorded in @ref pathSkip_ and @ref descendResume comes back
4235 * through here, with no callback to replay.
4236 *
4237 * §7.3: this sequence is not an element of the enclosing wrapper — and the
4238 * fields INSIDE it are not that wrapper's elements either. Their ids are
4239 * child ids of a field that never became a value, not array indices, so the
4240 * element-index bound must not measure them: it is suspended for the whole
4241 * subtree and restored after. Without this a child id at or past the
4242 * wrapper's `count` would trip the §5.1/§7 reject from inside a field §7.3
4243 * says is not the array's at all (Crucible F-0051, corelib-cpp#65). The
4244 * suspension is not specific to a §7.3-mistyped element: an unknown id
4245 * skipped inside the wrapper reaches the same place and is equally not an
4246 * element. Format-level rejects (§4.9 depth, over-64-bit varint, ...) still
4247 * fire inside the subtree — §7.3 subordinates the SCHEMA bound only.
4248 */
4249 void skipSequence() noexcept
4250 {
4251 const long outerBound = elemBound_, outerSchema = elemSchema_;
4252 const long outerDyn = elemDyn_, outerDest = elemDest_;
4253 const int outerElemWire = elemWire_, outerElemFix = elemFix_;
4254 const bool outerSpanSkip = spanSkip_;
4256 elemWire_ = elemFix_ = -1;
4257 spanSkip_ = true;
4258 ++seqDepth_;
4259 dispatchLevel([](sofab::id, size_t, size_t) noexcept {}, /*stopAtEnd*/ true);
4260 --seqDepth_;
4261 elemBound_ = outerBound;
4262 elemSchema_ = outerSchema;
4263 elemDyn_ = outerDyn;
4264 elemDest_ = outerDest;
4265 elemWire_ = outerElemWire;
4266 elemFix_ = outerElemFix;
4267 spanSkip_ = outerSpanSkip;
4268 }
4269
4270 public:
4271 IStreamImpl(const IStreamImpl &) = delete;
4273 IStreamImpl(IStreamImpl &&) noexcept = default;
4274 IStreamImpl &operator=(IStreamImpl &&) noexcept = default;
4275 virtual ~IStreamImpl() = default;
4276
4277 /**
4278 * @brief Feed bytes into the decoder, delivering every complete top-level field.
4279 *
4280 * May be called repeatedly with successive chunks; a field split across
4281 * chunks is **resumed** on a later call — its pieces are written into the
4282 * caller's destination as they arrive, and only what a chunk boundary can
4283 * cut in half (a field header, the words before a payload, one varint
4284 * element — at most @ref CARRY_CAP bytes) is carried over. Every chunk is
4285 * parsed in place; nothing is copied but the value itself.
4286 *
4287 * @note A field split across chunks is therefore **delivered once per
4288 * chunk that carries part of it**, with the same id and header, and
4289 * the typed read continues where it stopped (@ref progress). The
4290 * destination has to stay put until the field completes: a member of
4291 * the message object does, a local in the callback does not.
4292 *
4293 * @param buffer Bytes to decode.
4294 * @param buflen Number of bytes in @p buffer.
4295 * @return A @ref Result carrying the three-valued §7 outcome:
4296 * @ref Error::None (`COMPLETE`) when the fed bytes end exactly at a
4297 * field boundary; @ref Error::Incomplete (`INCOMPLETE`) when they end
4298 * **inside** a field (partial varint, short fixlen/array payload) or
4299 * with an open sequence — the decoder keeps its place for the next
4300 * @ref feed and this is **not** an error; or @ref Error::InvalidMessage
4301 * (`INVALID`) when the bytes are malformed regardless of what follows.
4302 * @ref Error::LimitExceeded is the fourth, receiver-policy outcome
4303 * (§6.2.1) — well-formed bytes this receiver refuses to buffer.
4304 *
4305 * @note **INVALID and LimitExceeded are terminal.** §5.2 answers "can more
4306 * bytes change it?" with "no — terminal" for `INVALID`, and §6.3 calls
4307 * `LimitExceeded` "a terminal, receiver-local policy rejection". Once
4308 * @ref feed has returned either, the verdict is latched on the
4309 * *stream*: every later call returns the same code without parsing a
4310 * byte, no further field is delivered, and the input after the fault
4311 * is neither buffered nor inspected. @ref reset is the way back — it
4312 * is the documented start of a new message anyway. This is what makes
4313 * the outcome chunk-independent (§7.2 item 4): the same bytes fed
4314 * whole, in odd-sized chunks or one at a time all end on the same
4315 * verdict, and garbage prefixed to a valid message can never be
4316 * reported as `COMPLETE`.
4317 *
4318 * @warning **One message per destination.** Successive @ref feed calls
4319 * continue the *same* message — a decoder cannot see a message
4320 * boundary, because a message has no framing on the wire and a
4321 * zero-byte message is legal (MESSAGE_SPEC §2). Decoding a
4322 * *second* message therefore requires a destination reset: call
4323 * @ref reset (which for @ref IStreamObject also re-initialises the
4324 * wrapped message) or use a fresh stream. MESSAGE_SPEC §5.1 puts
4325 * this duty on the decoding side — "supplying a cleanly
4326 * initialised destination is the application's responsibility" —
4327 * and §2 makes it load-bearing: an all-default field is *absent*
4328 * from the bytes, so nothing runs for it and whatever the previous
4329 * message left in that member survives.
4330 */
4331 Result feed(const uint8_t *buffer, size_t buflen) noexcept
4332 {
4333 /* §5.2/§6.3: INVALID, LimitExceeded and InvalidArgument are TERMINAL.
4334 * Once the stream has returned one, no later chunk can change it — the
4335 * bytes were malformed regardless of what follows, or the receiver's
4336 * policy already refused them. */
4337 if (terminal_ != Error::None) [[unlikely]] return Result{terminal_, skipped_};
4338
4339 /* §5.2.4: an empty feed is the end-of-input probe, and the verdict is
4340 * read off the decoder's own state. It is also the empty message
4341 * (MESSAGE_SPEC §2), which is COMPLETE for every schema. */
4342 if (buflen == 0)
4343 return Result{atBoundary() ? Error::None : Error::Incomplete, skipped_};
4344
4345 error_ = false;
4346 limitExceeded_ = false;
4347 argError_ = false;
4348
4349 const uint8_t *cur = buffer;
4350 size_t left = buflen;
4351
4352 if (carryLen_) [[unlikely]]
4353 {
4354 /* An item was cut in half by the previous chunk boundary. Stitch it
4355 * back together in a window of @ref CARRY_CAP bytes on the stack —
4356 * never the whole chunk — and parse out of that; whatever of this
4357 * chunk the window did not need is then parsed in place, with no
4358 * copy at all. At most @ref CARRY_CAP bytes are ever copied,
4359 * whatever the caller's chunk size, which is the property §6.6
4360 * protects: "can a sender make this allocation bigger by sending
4361 * different bytes?" — no. */
4362 uint8_t stitch[CARRY_CAP];
4363 const size_t held = carryLen_;
4364 const size_t take = std::min(CARRY_CAP - held, left);
4365 std::memcpy(stitch, carry_, held);
4366 std::memcpy(stitch + held, cur, take);
4367 const size_t window = held + take;
4368 carryLen_ = 0;
4369 const size_t used = parseWindow(stitch, window);
4370 if (error_) return latchTerminal();
4371 if (used < held)
4372 {
4373 /* Still short of a complete item, so the parse consumed nothing
4374 * — the carry holds exactly one item's prefix — and the chunk
4375 * went in whole. */
4376 if (take < left) { error_ = true; return latchTerminal(); }
4377 std::memcpy(carry_, stitch + used, window - used);
4378 carryLen_ = window - used;
4380 }
4381 cur += used - held;
4382 left -= used - held;
4383 if (left == 0)
4384 {
4385 stash(stitch + used, window - used);
4387 skipped_};
4388 }
4389 /* Anything the window left unconsumed is still ahead of `cur` in the
4390 * caller's own chunk, so the parse below simply reaches it again. */
4391 }
4392
4393 const size_t used = parseWindow(cur, left);
4394 if (error_) return latchTerminal();
4395 stash(cur + used, left - used);
4396 if (error_) return latchTerminal();
4398 }
4399
4400 /**
4401 * @brief Drop every byte of decoder state, so the next @ref feed starts a
4402 * brand-new message.
4403 *
4404 * Discards the buffered partial field, the sticky error/limit flags, the
4405 * latched terminal verdict (§5.2/§6.3 — this is the only way to clear an
4406 * `INVALID` or `LimitExceeded` stream), the nesting depth and the §7.3
4407 * @ref skipped counter. There is no buffer to hand back: the decoder's
4408 * working state is the fixed-size carry, path and progress it was
4409 * constructed with (§6.6), so a reset is a handful of stores and the
4410 * message loop pays no allocator for it.
4411 *
4412 * **It does not touch the destination** — this class has none; it only
4413 * dispatches. @ref IStreamObject overrides this to reset the message it
4414 * owns as well, which is what a caller reusing a decoder wants. A caller
4415 * driving @ref IStreamInline owns its destinations and must clear them
4416 * itself.
4417 *
4418 * Required between messages: MESSAGE_SPEC §2 omits an all-default field
4419 * entirely, so an absent field delivers no callback and leaves the previous
4420 * message's value in place — including a wrapper-array field, whose
4421 * collector (@ref StringSeq, @ref BlobSeq, @ref MessageSeq) only clears its
4422 * destination when the wrapper sequence is actually present.
4423 */
4424 virtual void reset() noexcept
4425 {
4426 carryLen_ = 0;
4427 suspendDepth_ = -1;
4428 replay_ = false;
4429 pend_ = false;
4430 pendSkip_ = false;
4431 pendDone_ = 0;
4432 utf8State_ = 0;
4433 spanCarry_ = 0;
4434 spanBase_ = nullptr;
4435 spanSkip_ = false;
4436 spanSkipped_ = 0;
4437 p_ = end_ = nullptr;
4438 type_ = Wire{};
4439 fixType_ = Fix{};
4440 fixLen_ = 0;
4441 count_ = 0;
4442 fieldId_ = 0;
4443 consumed_ = false;
4444 error_ = false;
4445 limitExceeded_ = false;
4446 argError_ = false;
4448 incomplete_ = false;
4449 seqDepth_ = 0;
4450 skipped_ = 0;
4451 elemBound_ = -1;
4452 elemSchema_ = -1;
4453 elemDyn_ = -1;
4454 elemDest_ = -1;
4455 elemWire_ = -1;
4456 elemFix_ = -1;
4457 }
4458
4459 /**
4460 * @brief Mark the running decode INVALID from inside a deliver callback.
4461 *
4462 * Sets the sticky decode-error flag, so the surrounding @ref feed stops
4463 * dispatching further fields and returns @ref Error::InvalidMessage
4464 * (`INVALID`). For callers that detect malformed content the wire layer
4465 * cannot judge on its own — e.g. a generated message rejecting an array
4466 * whose wire element count exceeds its schema `count` capacity, which is
4467 * INVALID per spec §3/§7 (generator#100). Idempotent; a no-op outside a
4468 * @ref feed since every feed clears the flag on entry.
4469 */
4470 void invalidate() noexcept { error_ = true; }
4471
4472 /**
4473 * @brief Report a receiver-side decode-limit violation from inside a
4474 * deliver callback.
4475 *
4476 * Sets the sticky limit flag, so the surrounding @ref feed stops
4477 * dispatching further fields and returns @ref Error::LimitExceeded.
4478 * For callers enforcing *policy* caps the wire layer cannot know —
4479 * e.g. a generated message rejecting an unbounded (schema-bound-less)
4480 * array/string/blob whose claimed count/length exceeds a configured
4481 * decode limit (generator#102). Deliberately distinct from
4482 * @ref invalidate: the bytes may be perfectly well-formed; rejecting
4483 * them is receiver policy, not wire malformation (§7). Idempotent; a
4484 * no-op outside a @ref feed since every feed clears the flag on entry.
4485 */
4486 void exceedLimit() noexcept { limitExceeded_ = error_ = true; }
4487
4488 /**
4489 * @brief Refuse the current field because the caller's **destination** is
4490 * too short for it (§6.3's third refusal tier, §6.6.3).
4491 *
4492 * The sibling of @ref invalidate and @ref exceedLimit, for the one refusal
4493 * that is about neither the message nor the deployment: the value broke no
4494 * schema bound and no configured cap, and simply does not fit the storage
4495 * this caller handed over. §6.3: "`InvalidMessage` would mark a well-formed
4496 * message malformed … `LimitExceeded` would promise a limit to raise that
4497 * was never configured." The surrounding @ref feed stops dispatching and
4498 * returns @ref Error::InvalidArgument. Idempotent; a no-op outside a
4499 * @ref feed since every feed clears the flag on entry.
4500 */
4501 void rejectDestination() noexcept { argError_ = error_ = true; }
4502
4503 /**
4504 * @brief Refuse the current field because the **call** stated no bound for
4505 * it at all (§6.3's `InvalidArgument`).
4506 *
4507 * The one answer §6.2.1 leaves for a schema-unbounded field read with no
4508 * receiver cap. This codec has no limit of its own to fall back on, and
4509 * "an argument a caller may omit is an API affordance, never a licence to
4510 * decode uncapped" — so the omission is reported rather than obeyed. It is
4511 * a mistake in the *call*, exactly like a destination too short for the
4512 * value (@ref rejectDestination): the message is well-formed and the
4513 * deployment configured nothing, so neither `InvalidMessage` nor
4514 * `LimitExceeded` would say anything true about it (§6.3's three tiers).
4515 *
4516 * Reaching it from generated code means a cap was not emitted; reaching it
4517 * from a hand-written visitor means the wrong entry point was used — the
4518 * `…Capped` forms exist so the number cannot be forgotten.
4519 */
4520 void rejectUnbounded() noexcept { argError_ = error_ = true; }
4521
4522 /**
4523 * @brief Refuse a wrapper-array element whose **index** is at or past a
4524 * bound, in the category §6.3 gives that bound.
4525 *
4526 * MESSAGE_SPEC §5.1 makes a wrapper array's length *highest present id +
4527 * 1*, so the element index **is** the length and is what has to be
4528 * checked — "A limit **MUST** be enforced … before the container it
4529 * indexes into is extended" (§6.2.1). Three bounds can be armed at once
4530 * and they do not share a verdict, so they are consulted in §6.3's order:
4531 * the schema `count` first (`InvalidMessage`), then the configured
4532 * receiver cap (`LimitExceeded`), then the destination's own capacity
4533 * (`InvalidArgument`).
4534 *
4535 * @param bad The element index that crossed a bound.
4536 */
4538 {
4539 const long i = static_cast<long>(bad);
4540 if (elemSchema_ >= 0 && i >= elemSchema_) invalidate();
4541 else if (elemDyn_ >= 0 && i >= elemDyn_) exceedLimit();
4542 else rejectDestination();
4543 }
4544
4545
4546 private:
4547 /**
4548 * @brief Does the decoder sit at a clean message boundary — nothing
4549 * carried, no open sequence, no half-delivered field (§5.2.4)?
4550 *
4551 * **Internal, deliberately not public.** This is one *ingredient* of the
4552 * outcome, not the outcome: it knows the parse position and nothing about
4553 * a latched refusal, so on bytes @ref feed already rejected it still answers
4554 * `true`. Published as an accessor it was a second way to ask "where do I
4555 * stand?" that disagreed with the first — a dangling `0x07` returns
4556 * `INVALID` from @ref feed while this predicate reports a clean boundary.
4557 * CORELIB_PLAN §5.3.1 names the cost: "Every additional surface is a second
4558 * implementation of every rule in this document." The one answer is the
4559 * @ref Result that @ref feed returns (§5.2.4: "The status `feed`/`decode`
4560 * returns *is* the answer"); this helper only supplies the
4561 * `COMPLETE`-vs-`INCOMPLETE` half of it to the empty-feed path, after that
4562 * path has already ruled out a latched terminal verdict.
4563 */
4564 [[nodiscard]] bool atBoundary() const noexcept
4565 {
4566 return carryLen_ == 0 && suspendDepth_ < 0;
4567 }
4568
4569 protected:
4570 /**
4571 * @brief The bytes of the current top-level field seen so far, across every
4572 * chunk it spans (#26, @ref Limits::max_buffered_field).
4573 *
4574 * Pointer arithmetic alone stopped being enough once a field could span
4575 * chunks without being buffered: within one window the span is
4576 * `p_ - spanBase_`, and what earlier windows already consumed of the same
4577 * field is carried in @ref spanCarry_. Without that the cap would be a
4578 * property of the caller's chunking, which §7.2 item 4 forbids.
4579 */
4580 [[nodiscard]] size_t spanned() const noexcept
4581 {
4582 return spanCarry_ + static_cast<size_t>(p_ - spanBase_);
4583 }
4584
4585 /**
4586 * @brief @ref spanned less what this field spent on skipped subtrees —
4587 * the number the field-span cap is measured against (§6.2.1).
4588 *
4589 * The cap bounds what the receiver materializes, and @ref spanSkipped_ is
4590 * exactly what it did not. Saturating rather than wrapping: the two
4591 * counters are updated in different places, and a cap that ran backwards
4592 * would be a cap that never fires.
4593 */
4594 [[nodiscard]] size_t spannedLive() const noexcept
4595 {
4596 const size_t s = spanned();
4597 return s > spanSkipped_ ? s - spanSkipped_ : 0;
4598 }
4599
4600 /** @brief Discount a skipped field's bytes from the live span (§6.2.1). */
4601 void discountSkipped(const uint8_t *from) noexcept
4602 {
4603 if (p_ > from) spanSkipped_ += static_cast<size_t>(p_ - from);
4604 }
4605
4606 /** @brief Latch the refusal this feed produced, in §6.3's order of tiers. */
4614
4615 /**
4616 * @brief Hold the ≤ @ref CARRY_CAP bytes of a cut item until the next
4617 * @ref feed.
4618 */
4619 void stash(const uint8_t *p, size_t n) noexcept
4620 {
4621 if (n == 0) return;
4622 if (n > CARRY_CAP) [[unlikely]]
4623 {
4624 /* Unreachable: the parse backs up only to the start of a small
4625 * item, and @ref CARRY_CAP is derived from the widest of those.
4626 * Deliberately not silent — an item wider than this format admits
4627 * is malformed either way. */
4628 error_ = true;
4629 return;
4630 }
4631 std::memcpy(carry_, p, n);
4632 carryLen_ = n;
4633 }
4634
4635 /**
4636 * @brief Parse one window of bytes, resuming whatever the last one left
4637 * open, and report how much of it was consumed.
4638 *
4639 * @param p Window start.
4640 * @param n Window length.
4641 * @return Bytes consumed. Whatever follows is a cut item, at most
4642 * @ref CARRY_CAP bytes of it.
4643 */
4644 size_t parseWindow(const uint8_t *p, size_t n) noexcept
4645 {
4646 p_ = p;
4647 end_ = p + n;
4648 incomplete_ = false;
4649 replay_ = suspendDepth_ >= 0;
4650 spanBase_ = p_;
4652 parseTopLevel();
4653 if (incomplete_) spanCarry_ += static_cast<size_t>(p_ - spanBase_);
4654 replay_ = false;
4655 return static_cast<size_t>(p_ - p);
4656 }
4657
4658 /**
4659 * @brief Deliver every complete top-level field in the current window,
4660 * leaving @ref p_ at the first byte not consumed.
4661 *
4662 * The same shape as @ref dispatchLevel, and for the same reasons: a level
4663 * the previous window left open is **re-entered** rather than re-parsed,
4664 * either by descending @ref pathId_ to the suspended level or — when this
4665 * level is it — by continuing the field @ref pendDone_ describes.
4666 */
4667 void parseTopLevel() noexcept
4668 {
4669 sofab::id fieldId = 0;
4670 bool declined = false;
4671
4672 const Entry entry = levelEntry();
4673 if (entry != Entry::Fresh) [[unlikely]]
4674 {
4675 if (!reenterLevel(wrapCb(topCallback_), entry)) return;
4676 }
4677
4678 const uint8_t *const end = end_;
4679 while (p_ < end)
4680 {
4681 /* Header-first: parse the field's header and metadata, then deliver
4682 * immediately. The callback's typed read decides the tag (§7.3), the
4683 * schema bound (§7.1/§5.2) and finally whether the payload is here —
4684 * in that order, so a bound rejection wins over a truncation without
4685 * anyone having to know the schema up front. */
4686 const uint8_t *fieldStart = p_;
4687 spanCarry_ = 0;
4688 spanBase_ = p_;
4689 spanSkipped_ = 0;
4690 incomplete_ = false;
4691 declined = false;
4692 if (!parseFieldHeader())
4693 {
4694 /* error_ or incomplete_ set. A cut header is backed up whole:
4695 * it is at most three varints, which is what @ref CARRY_CAP is
4696 * sized for. */
4697 if (incomplete_) { p_ = fieldStart; suspendAtBoundary(); }
4698 return;
4699 }
4700 fieldId = fieldId_;
4701 pendDone_ = 0;
4702 utf8State_ = 0;
4703 if (!capInert_ && exceedsBufferAtHeader()) [[unlikely]]
4704 {
4705 /* §6.2.1/§6.3: a receiver-side cap "MUST NOT be applied to a
4706 * field the schema already bounds" — there the schema governs
4707 * and an over-bound claim is INVALID, which is why §6.3 says
4708 * LimitExceeded is "never raised for a field the schema bounds"
4709 * (#86) — and, by the same section's closing rule, it MUST NOT
4710 * be applied to a field the handler SKIPS: "a field the handler
4711 * skips allocates nothing — it is walked, not materialized", so
4712 * "a decode that steps over an over-cap field it was never going
4713 * to read stays COMPLETE" (#129).
4714 *
4715 * Both facts are the callback's, not this codec's: only it knows
4716 * the declared maxlen/count, and only it knows whether this id
4717 * and this wire type are a field it reads at all. So the field is
4718 * offered to it first with its payload WITHHELD: end_ sits at the
4719 * payload's first byte, so a typed read still settles the tag
4720 * (§7.3) and the bound (§7.1) — both decided before a byte is
4721 * copied — and then reports INCOMPLETE instead of materialising
4722 * anything. Nothing is copied and nothing is allocated; the only
4723 * verdict that can come out of it is the INVALID the same bytes
4724 * get on an uncapped stream.
4725 *
4726 * What the offer answers, then, is which of three the field is:
4727 * refused by the schema (return the INVALID), read (the cap is
4728 * this field's and fires), or declined (walk it, and the cap
4729 * never applied). */
4731 {
4732 consumed_ = false;
4733 const uint8_t *const withheld = p_;
4734 const uint8_t *held = end_;
4735 end_ = p_;
4737 end_ = held;
4738 /* The one question a withheld offer exists to answer: did the
4739 * callback ENGAGE with this field? A typed read against the
4740 * withheld payload reaches no bytes and reports INCOMPLETE
4741 * (or refuses the destination, or consumes an empty
4742 * payload); a callback that declines — an id it does not
4743 * declare, or a §7.3 wire-type contradiction, which
4744 * `tagMatches` answers before anything else — touches none
4745 * of the three. That is the same test the ordinary delivery
4746 * below makes, on the same two flags, so a field cannot be
4747 * "skipped" on one path and "read" on the other. */
4748 const bool engaged = incomplete_ || consumed_ || error_;
4749 incomplete_ = false;
4750 pendDone_ = 0;
4751 /* The schema bound spoke first — and so does a receiver cap
4752 * the callback applied itself. An ARGUMENT refusal does not:
4753 * §6.3 puts the configured cap ahead of the caller's
4754 * destination, and the cap enforced below is one. */
4755 if (error_ && !argError_) return;
4756 error_ = false;
4757 argError_ = false;
4758 if (!engaged)
4759 {
4760 /* Walked, not materialized. The cap is not consulted
4761 * again on the way through — neither here nor on a
4762 * resume, where `deliverPending` re-enters the skip
4763 * directly — so a field that spans more than the cap is
4764 * stepped over at any chunk size, exactly as it is on an
4765 * uncapped stream. */
4766 p_ = withheld;
4767 declined = true;
4768 skipPayload();
4769 if (error_) return;
4770 if (incomplete_) { suspendHere(fieldId, declined); return; }
4771 continue;
4772 }
4773 }
4774 exceedLimit();
4775 return;
4776 }
4777
4778 consumed_ = false;
4779 const uint8_t *payload = p_;
4781 if (error_) return;
4782 if (!incomplete_ && !consumed_)
4783 {
4784 declined = true;
4785 p_ = payload;
4786 skipPayload();
4787 if (error_) return;
4788 }
4789 /* Not enough bytes yet: the field keeps its place. What it has
4790 * already delivered stays delivered — @ref pendDone_ says how much —
4791 * so nothing is re-read and nothing is buffered (§6.6.2). */
4792 if (incomplete_)
4793 {
4794 suspendHere(fieldId, declined);
4795 return;
4796 }
4797 }
4798 }
4799
4800 /**
4801 * @brief Parse a field header word into @ref fieldId_ and @ref type_ (§4.3).
4802 *
4803 * The **only** place a `(id << 3) | wire_type` word is taken apart. Both
4804 * parse loops — @ref parseTopLevel through @ref parseFieldHeader, and
4805 * @ref dispatchLevel inside a sequence — come through here, so the
4806 * @ref ID_MAX ceiling (§6.2) cannot be present in one and missing from
4807 * the other.
4808 *
4809 * @return `true` when a whole header word was read and its id is legal.
4810 * On `false` either @ref error_ (a > 64-bit varint, or an id past
4811 * @ref ID_MAX) or @ref incomplete_ (the word is cut short) is set.
4812 */
4813 [[gnu::always_inline]] inline bool parseFieldTag() noexcept
4814 {
4815 uint64_t header;
4816 bool ovf = false;
4817 if (!getVarint(p_, end_, header, &ovf))
4818 {
4819 (ovf ? error_ : incomplete_) = true;
4820 return false;
4821 }
4822 if ((header >> 3) > ID_MAX) /* §6.2/§7 */
4823 {
4824 error_ = true;
4825 return false;
4826 }
4827 fieldId_ = static_cast<sofab::id>(header >> 3);
4828 type_ = static_cast<Wire>(header & 0x7);
4829 return true;
4830 }
4831
4832 /**
4833 * @brief Parse the word(s) between a field header and its payload —
4834 * the fixlen word (§4.6), the array count (§4.7) or both (§4.8).
4835 *
4836 * Shared by the two parse loops for the same reason as @ref parseFieldTag:
4837 * this is where §4.6's subtype/length pairing, §4.8's element-subtype rule
4838 * and §6.2's @ref ARRAY_MAX ceiling are enforced, and a second copy of it
4839 * is a place for one of them to go missing — which is exactly how the
4840 * nested path lost the @ref ARRAY_MAX check on a fixlen array until #103.
4841 * A varint or sequence header states no metadata, so it falls through.
4842 *
4843 * @return `true` when the metadata is complete and well-formed, with
4844 * @ref fixLen_, @ref count_ and @ref fixType_ set. On `false`
4845 * either @ref error_ or @ref incomplete_ is set.
4846 */
4847 [[gnu::always_inline]] inline bool parseFieldMeta() noexcept
4848 {
4849 fixLen_ = 0; count_ = 0;
4850 bool ovf = false;
4851 switch (type_)
4852 {
4853 case Wire::Fixlen:
4854 {
4855 uint64_t sub;
4856 if (!getVarint(p_, end_, sub, &ovf))
4857 {
4858 (ovf ? error_ : incomplete_) = true;
4859 return false;
4860 }
4861 if (!fixlenWordValid(sub)) /* §4.6/§7 */
4862 {
4863 error_ = true;
4864 return false;
4865 }
4866 fixLen_ = static_cast<size_t>(sub >> 3);
4867 fixType_ = static_cast<Fix>(sub & 0x7);
4868 return true;
4869 }
4870 case Wire::ArrayUnsigned:
4871 case Wire::ArraySigned:
4872 {
4873 uint64_t n;
4874 if (!getVarint(p_, end_, n, &ovf))
4875 {
4876 (ovf ? error_ : incomplete_) = true;
4877 return false;
4878 }
4879 if (n > ARRAY_MAX) /* §6.2/§7 */
4880 {
4881 error_ = true;
4882 return false;
4883 }
4884 count_ = static_cast<size_t>(n);
4885 return true;
4886 }
4887 case Wire::ArrayFixlen:
4888 {
4889 uint64_t n;
4890 if (!getVarint(p_, end_, n, &ovf))
4891 {
4892 (ovf ? error_ : incomplete_) = true;
4893 return false;
4894 }
4895 /* §4.8 step 1: the FORMAT ceiling fires on the count word
4896 * whatever the subtype turns out to be, so an absurd count is
4897 * rejected before anything is sized from it. Without it the
4898 * `count_ * fixLen_` byte-span computed downstream wraps
4899 * size_t — a count of 2^62 with 4-byte elements wraps to zero
4900 * and the array is skipped as if it were empty, so a message
4901 * that must be INVALID decodes COMPLETE (#103). */
4902 if (n > ARRAY_MAX) /* §6.2/§7 */
4903 {
4904 error_ = true;
4905 return false;
4906 }
4907 count_ = static_cast<size_t>(n);
4908 /* §4.8: the fixlen_word is present even for an empty array. */
4909 uint64_t sub;
4910 if (!getVarint(p_, end_, sub, &ovf))
4911 {
4912 (ovf ? error_ : incomplete_) = true;
4913 return false;
4914 }
4915 if (!arrayFixlenWordValid(sub)) /* §4.8/§7 */
4916 {
4917 error_ = true;
4918 return false;
4919 }
4920 fixLen_ = static_cast<size_t>(sub >> 3); /* element size */
4921 fixType_ = static_cast<Fix>(sub & 0x7);
4922 return true;
4923 }
4924 default:
4925 return true; /* varint and sequence headers carry no metadata */
4926 }
4927 }
4928
4929 /**
4930 * @brief Parse one **top-level** field header plus the metadata that
4931 * precedes its payload, into the current-field members.
4932 *
4933 * @ref parseFieldTag + @ref parseFieldMeta, with the one rule that is the
4934 * top level's own: a @ref Wire::SequenceEnd here closes a sequence that
4935 * was never opened, which is `INVALID` (§7). Inside a sequence the same
4936 * marker is the close, which is why @ref dispatchLevel puts its own test
4937 * between the two calls.
4938 *
4939 * @return `true` when the header is complete and well-formed. On `false`
4940 * either @ref error_ (malformed) or @ref incomplete_ (more bytes
4941 * needed) is set.
4942 */
4943 bool parseFieldHeader() noexcept
4944 {
4945 if (!parseFieldTag()) return false;
4946 if (type_ == Wire::SequenceEnd) /* §7: dangling end at the root */
4947 {
4948 error_ = true;
4949 return false;
4950 }
4951 return parseFieldMeta();
4952 }
4953
4954 /**
4955 * @brief Does this wire type's header state a size the schema can bound?
4956 *
4957 * True for the length-prefixed payload (`maxlen`) and the three array kinds
4958 * (`count`) — exactly the fields whose §7.1 verdict outranks the field-size
4959 * cap (#86), and exactly the ones @ref exceedsBufferAtHeader derives a size
4960 * from. A sequence states no size of its own (it accrues in
4961 * @ref dispatchLevel) and a varint carries no length word at all.
4962 *
4963 * @param w The delivered field's wire type.
4964 * @return `true` when a declared `maxlen`/`count` could reject this field.
4965 */
4966 [[nodiscard]] static constexpr bool schemaBoundsHeader(Wire w) noexcept
4967 {
4968 return w == Wire::Fixlen || w == Wire::ArrayUnsigned ||
4969 w == Wire::ArraySigned || w == Wire::ArrayFixlen;
4970 }
4971
4972 /**
4973 * @brief Would this field cross @ref maxBufferedField_, judged from its
4974 * header alone (#26)?
4975 *
4976 * The header states the size exactly for a fixlen or fixlen-array payload;
4977 * a varint array's count is a lower bound on its bytes. A sequence accrues
4978 * instead, and is bounded field by field in @ref dispatchLevel.
4979 *
4980 * @return `true` when the field must be rejected before its payload is
4981 * read.
4982 */
4983 [[nodiscard]] bool exceedsBufferAtHeader() noexcept
4984 {
4985 const size_t seen = spanned();
4986 uint64_t need = 0;
4987 switch (type_)
4988 {
4989 case Wire::Fixlen: need = fixLen_; break;
4990 case Wire::ArrayFixlen: need = static_cast<uint64_t>(count_) * fixLen_; break;
4991 case Wire::ArrayUnsigned:
4992 case Wire::ArraySigned: need = count_; break;
4993 default: need = 0; break;
4994 }
4995 return exceedsBuffer(seen, need);
4996 }
4997
4998 /**
4999 * @brief Decode the current integer-array payload: @ref count_ varint
5000 * elements, the first `sp.size()` of them into @p sp.
5001 *
5002 * The tag is already known to match (§7.3) and the cursor sits at the first
5003 * element. On success the field is @ref consumed_; on failure the stream's
5004 * @ref error_ / @ref incomplete_ says which.
5005 *
5006 * @tparam Bounded Apply @p b, the declared element type's value range
5007 * (§7.1): an element outside it makes the decode `INVALID` —
5008 * never masked down to @p Elem, never kept. `false` instantiates
5009 * the plain decode, which is what @ref read alone can do: it sees
5010 * the destination's width, and a destination width is not a
5011 * declared width. The two are separate instantiations, so an
5012 * unbounded array carries no test for a bound it does not have.
5013 * @param sp Destination for the leading elements; the rest of @ref count_
5014 * is still parsed, to stay framed.
5015 * @param b The element range, when @p Bounded.
5016 */
5017 template <bool Bounded, typename Elem>
5018 bool readIntElements(std::span<Elem> sp, ElemBound b = {}) noexcept
5019 {
5020 const size_t n = sp.size();
5021 /* §7.1: an element outside the declared range is INVALID. Both
5022 * alternatives are forbidden by name — masking it to Elem (what a bare
5023 * static_cast does) and keeping it — so the reject happens before the
5024 * store, through the same sticky flag as @ref invalidate. */
5025 auto admits = [b](uint64_t raw) noexcept -> bool {
5026 if constexpr (std::is_unsigned_v<Elem>)
5027 return raw <= static_cast<uint64_t>(b.hi) &&
5028 (b.lo <= 0 || raw >= static_cast<uint64_t>(b.lo));
5029 else
5030 {
5031 const int64_t v = detail::zigzagDecode(raw);
5032 return v >= b.lo && v <= b.hi;
5033 }
5034 };
5035 auto store = [&](size_t i, uint64_t raw) noexcept -> bool {
5036 if constexpr (Bounded)
5037 if (!admits(raw)) { error_ = true; return false; }
5038 if constexpr (std::is_same_v<Elem, bool>)
5039 {
5040 /* §4.4, tolerant on decode: every non-zero element is `true`
5041 * and is normalized on store, whatever its width. The store
5042 * goes through an `unsigned char` lvalue, not a `bool` one:
5043 * generated code may present a byte-backed member as `bool`
5044 * elements, and a character-type store is well-defined for
5045 * that and for a real `bool` object alike. */
5046 static_assert(sizeof(bool) == 1, "a bool element is stored as one byte");
5047 reinterpret_cast<unsigned char &>(sp[i]) = raw != 0 ? 1u : 0u;
5048 }
5049 else if constexpr (std::is_unsigned_v<Elem>) sp[i] = static_cast<Elem>(raw);
5050 else sp[i] = static_cast<Elem>(detail::zigzagDecode(raw));
5051 return true;
5052 };
5053 /* Two loops rather than one with an `i < n` test inside: the
5054 * elements that reach the destination and the surplus that is
5055 * parsed only to stay framed are separate runs, so neither
5056 * pays for the other's branch. The unbounded surplus skips the value
5057 * accumulation too — skipVarint applies the identical §4.1
5058 * length and overflow rules, it just does not build the
5059 * number it is about to discard. A BOUNDED surplus is decoded
5060 * instead: §7.1 makes an over-width element INVALID whether or not
5061 * it had a destination to be stored in. */
5062 /* Elements already decoded by an earlier chunk (§6.6.2): the run
5063 * continues where it stopped. What it never does is start over — the
5064 * bytes of the elements already delivered are gone. */
5065 size_t i = pendDone_;
5066 while (i < n)
5067 {
5068 /* One bounds check for a whole run: with R bytes readable,
5069 * R / VARINT_MAX_BYTES elements are decodable without any
5070 * further test, since each consumes at most that many
5071 * bytes. The windowed decoder then carries no per-byte
5072 * bookkeeping at all. Only the last few bytes of the
5073 * buffer — where a varint may really be cut short — fall
5074 * back to the fully checked path. */
5075 size_t fit = static_cast<size_t>(end_ - p_) / detail::VARINT_MAX_BYTES;
5076 if (fit == 0) [[unlikely]]
5077 {
5078 uint64_t raw;
5079 bool ovf = false;
5080 if (!getVarint(p_, end_, raw, &ovf))
5081 {
5082 if (ovf) { error_ = true; return false; }
5083 /* The cut element is left at its first byte: the carry
5084 * holds it and the run resumes at element `i`. */
5085 pendDone_ = i;
5086 incomplete_ = true;
5087 return false;
5088 }
5089 if (!store(i, raw)) return false;
5090 ++i;
5091 continue;
5092 }
5093 if (fit > n - i) fit = n - i;
5094 for (size_t k = 0; k < fit; ++k, ++i)
5095 {
5096 uint64_t raw;
5097 if (!getVarintWindowed(p_, raw, nullptr))
5098 {
5099 error_ = true; /* only a > 64-bit varint can fail here */
5100 return false;
5101 }
5102 if (!store(i, raw)) return false;
5103 }
5104 }
5105 while (i < count_)
5106 {
5107 size_t fit = static_cast<size_t>(end_ - p_) / detail::VARINT_MAX_BYTES;
5108 bool ovf = false;
5109 if (fit == 0) [[unlikely]]
5110 {
5111 bool cut = false;
5112 if constexpr (Bounded)
5113 {
5114 uint64_t raw;
5115 if (!getVarint(p_, end_, raw, &ovf)) cut = true;
5116 else if (!admits(raw)) { error_ = true; return false; }
5117 }
5118 else if (!skipVarint(p_, end_, &ovf)) cut = true;
5119 if (cut)
5120 {
5121 if (ovf) { error_ = true; return false; }
5122 pendDone_ = i;
5123 incomplete_ = true;
5124 return false;
5125 }
5126 ++i;
5127 continue;
5128 }
5129 if (fit > count_ - i) fit = count_ - i;
5130 for (size_t k = 0; k < fit; ++k, ++i)
5131 {
5132 if constexpr (Bounded)
5133 {
5134 uint64_t raw;
5135 if (!getVarintWindowed(p_, raw, &ovf))
5136 {
5137 error_ = true; /* only a > 64-bit varint can fail here */
5138 return false;
5139 }
5140 if (!admits(raw)) { error_ = true; return false; }
5141 }
5142 else if (!skipVarintWindowed(p_, &ovf))
5143 {
5144 error_ = true; /* only a > 64-bit varint can fail here */
5145 return false;
5146 }
5147 }
5148 }
5149 consumed_ = true;
5150 pendDone_ = 0;
5151 return true;
5152 }
5153
5154 public:
5155
5156 /**
5157 * @brief Number of fields skipped this stream because their wire tag
5158 * contradicted the type the callback asked for (MESSAGE_SPEC §7.3).
5159 *
5160 * A diagnostic only — it never influences the decode outcome. A non-zero
5161 * count on an otherwise `COMPLETE` message means the peer's schema and
5162 * this one disagree about a field's type (or a hand-written callback
5163 * asked for the wrong one).
5164 *
5165 * Monotonic over the stream's lifetime — unlike the sticky error flags it
5166 * is **not** cleared per @ref feed, so a message dribbled in chunk by
5167 * chunk still reports every skip it caused. @ref Result::skipped carries
5168 * the same value out of a one-shot decode.
5169 */
5170 [[nodiscard]] size_t skipped() const noexcept { return skipped_; }
5171
5172 /**
5173 * @brief Read the current field's value, dispatching on @p value's type.
5174 *
5175 * Call from inside a deliver callback. Handles integers (signed values are un-zig-zagged),
5176 * `bool`, `float`, `double`, `std::string`, nested @ref sofab::IStreamMessage
5177 * objects, and writable contiguous ranges of integers, booleans or floats
5178 * (excess wire elements past the span's capacity are read and discarded).
5179 * A `bool` scalar or element reads every non-zero value as `true` and is
5180 * bounded by no width (§4.4). On a malformed or truncated field the
5181 * stream's error flag is set.
5182 *
5183 * Every destination **owns** what it receives. There is deliberately no
5184 * borrowing destination: a fed chunk is the caller's for the duration of
5185 * @ref feed only (CORELIB_PLAN §6), so a decoded value must survive the
5186 * caller reusing, overwriting or freeing that memory the moment `feed`
5187 * returns.
5188 *
5189 * @tparam T Type to decode into.
5190 * @param[out] value Destination for the decoded value.
5191 */
5192 template <typename T>
5193 bool read(T &value) noexcept
5194 {
5195 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>)
5196 {
5197 constexpr Wire want = std::is_unsigned_v<T> ? Wire::Unsigned : Wire::Signed;
5198 if (!tagMatches(want)) return false; /* §7.3 */
5199 uint64_t raw;
5200 bool ovf = false;
5201 if (!getVarint(p_, end_, raw, &ovf))
5202 {
5203 /* A varint cut by a chunk boundary stays where it is (§6.6.2's
5204 * "partial varint"): its ≤ 9 bytes ride in the carry and the
5205 * field is continued, not re-parsed from its header. */
5206 (ovf ? error_ : incomplete_) = true;
5207 return false;
5208 }
5209 if constexpr (std::is_unsigned_v<T>) value = static_cast<T>(raw);
5210 else value = static_cast<T>(detail::zigzagDecode(raw));
5211 consumed_ = true;
5212 }
5213 else if constexpr (std::is_same_v<T, bool>)
5214 {
5215 /* §4.4: bool travels as an unsigned varint; any non-zero is true. */
5216 if (!tagMatches(Wire::Unsigned)) return false; /* §7.3 */
5217 uint64_t raw;
5218 bool ovf = false;
5219 if (!getVarint(p_, end_, raw, &ovf))
5220 {
5221 (ovf ? error_ : incomplete_) = true;
5222 return false;
5223 }
5224 value = (raw != 0);
5225 consumed_ = true;
5226 }
5227 else if constexpr (std::is_same_v<T, float> || std::is_same_v<T, double>)
5228 {
5229 constexpr Fix want = std::is_same_v<T, float> ? Fix::Fp32 : Fix::Fp64;
5230 if (!tagMatches(Wire::Fixlen, want)) return false; /* §7.3 */
5231 if (static_cast<size_t>(end_ - p_) < sizeof(T))
5232 {
5233 incomplete_ = true;
5234 return false;
5235 }
5236 value = loadFloat<T>(p_);
5237 p_ += sizeof(T);
5238 consumed_ = true;
5239 }
5240 else if constexpr (std::is_same_v<T, std::string_view>)
5241 {
5242 /* Rejected on purpose, and rejected HERE so the diagnostic names
5243 * the replacement instead of surfacing as a span-deduction failure
5244 * further down (std::string_view satisfies the contiguous-range
5245 * branch below, whose error message would explain nothing).
5246 *
5247 * This destination used to exist and handed back a view into the
5248 * bytes just parsed. CORELIB_PLAN §6 borrows a fed chunk for the
5249 * duration of `feed` only: the caller may reuse or free it the
5250 * moment `feed` returns, and the decoded message MUST NOT be
5251 * affected — so a decoder that binds a `string`/`blob` destination
5252 * to chunk memory has to copy out before returning. The spec
5253 * exempts a one-shot `decode(buffer)`, where the caller keeps the
5254 * whole buffer alive across the call; this port has no such
5255 * separate entry point — `feed` is the only way in, and a one-shot
5256 * decode is just a single `feed` — so the exemption never applies
5257 * and there is no configuration in which the view is safe. */
5258 static_assert(always_false_v<T>,
5259 "IStream::read() does not decode into std::string_view: a fed chunk is "
5260 "borrowed only for the duration of feed() (CORELIB_PLAN §6), so a view "
5261 "into it dangles as soon as feed() returns. Read into an owning "
5262 "destination instead — std::string, std::vector<uint8_t>, "
5263 "sofab::FixedString<N>, sofab::FixedBytes<N> — via read(), readString() "
5264 "or readBlob().");
5265 }
5266 else if constexpr (std::is_same_v<T, std::string>)
5267 {
5268 /* §7.3: a std::string destination declares a fixlen *payload* —
5269 * `string` or `blob`. Both are byte payloads a std::string owns
5270 * verbatim, so either may be read into one (readString/readBlob
5271 * are how a caller narrows it to exactly one). `fp32` and `fp64`
5272 * share Wire::Fixlen with them but are not payloads: comparing
5273 * the wire type alone admitted them and materialised their four
5274 * or eight raw value bytes as text — and, since the UTF-8 gate
5275 * below is on the subtype, without even validating them. They
5276 * are skipped like an unknown id instead. */
5277 if (!tagMatches(Wire::Fixlen, Fix::String, Fix::Blob))
5278 return false; /* §7.3, see the view branch */
5279 /* §6.6.3: the destination is what the caller handed over, and a
5280 * payload longer than its room is refused rather than grown into
5281 * — see @ref readPayload. */
5282 if (!readPayload(value, fixType_ == Fix::String)) return false;
5283 }
5284 else if constexpr (InputMessage<T>)
5285 {
5286 if (!tagMatches(Wire::SequenceStart)) return false; /* §7.3 */
5287 /* §7.4: a wrapper sequence IS the array's value, so a repeated field
5288 * id REPLACES it whole. The reset that implements that must run only
5289 * once the tag is known to match — an occurrence skipped under §7.3
5290 * is not an occurrence and must not wipe a valid earlier one. A
5291 * collector that needs the reset says so by declaring prepare();
5292 * plain struct/union targets do not and pay nothing, since this is a
5293 * template and the call disappears at compile time. */
5294 /* ...and only on the FIRST entry. A sequence re-entered along
5295 * @ref pathId_ after a chunk boundary is the SAME occurrence, so
5296 * resetting the collector here would throw away the elements that
5297 * already arrived with the earlier chunks. */
5298 if (!replay_)
5299 if constexpr (requires { value.prepare(); }) value.prepare();
5300 /* §5.1: in a wrapper sequence the element id IS its index, so the
5301 * bound belongs to the stream rather than to the collector, where a
5302 * truncated element would outrun it. A collector declares it by
5303 * carrying `cap`, and declares the element type the bound is
5304 * conditional on (§7.3, see @ref dispatchLevel) by carrying the
5305 * static `elemWire` / `elemFix`. Both are picked up by the same
5306 * detection; a collector that publishes `cap` without an element
5307 * type keeps the bound and applies it in its own deserialize. */
5308 const long outerBound = elemBound_;
5309 const int outerElemWire = elemWire_, outerElemFix = elemFix_;
5310 /* consumed_ tracks the field at THIS level. A successful inner read
5311 * would otherwise make a still-open sequence look taken, and its
5312 * caller would not expect the re-delivery that follows. */
5313 const bool outerConsumed = consumed_;
5314 consumed_ = false;
5315 /* Three bounds, three categories (§6.3), one fast gate. A
5316 * collector declares the schema `count` as `cap`, the configured
5317 * receiver cap as `dynCap` (§6.2.1's `max_dyn_array_count` — the
5318 * INDEX is what it binds, a wrapper array having no count header
5319 * to bind) and the destination's own capacity as the static
5320 * `elemDestCap`. @ref elemBound_ is the tightest armed one, so the
5321 * per-element test stays a single compare; @ref rejectElementIndex
5322 * sorts out which tier spoke, and only when one has. */
5323 const long outerSchema = elemSchema_, outerDyn = elemDyn_, outerDest = elemDest_;
5324 if constexpr (requires { value.cap; }) elemSchema_ = value.cap;
5325 else elemSchema_ = -1;
5326 /* No fallback, and no way to omit it either: a collector that
5327 * publishes a schema `cap` MUST publish a `dynCap` beside it. The
5328 * two are the array's two possible index bounds and exactly one of
5329 * them can apply (§6.2.1), so a collector carrying only the first
5330 * used to leave the second silently at "no cap" — a duck-typing
5331 * miss nothing diagnosed. The stream has no limit of its own to
5332 * lend it (§6.2.1 — the codec "MUST NOT supply a default for one it
5333 * was not given"), so the omission is a compile error instead. */
5334 static_assert(!(requires { value.cap; }) || (requires { value.dynCap; }),
5335 "A wrapper-array collector that publishes a schema `cap` must also "
5336 "publish a receiver `dynCap` (CORELIB_PLAN 6.2.1): without it a "
5337 "schema-unbounded array would be bounded by nothing.");
5338 if constexpr (requires { value.dynCap; }) elemDyn_ = value.dynCap;
5339 else elemDyn_ = -1;
5340 if constexpr (requires { T::elemDestCap; }) elemDest_ = static_cast<long>(T::elemDestCap);
5341 else elemDest_ = -1;
5342 /* §6.2.1: a receiver limit "MUST NOT be applied to a field the
5343 * schema already bounds. There the schema bound governs and its
5344 * violation is INVALID." */
5345 if (elemSchema_ >= 0) elemDyn_ = -1;
5346 elemBound_ = -1;
5347 for (long b : {elemSchema_, elemDyn_, elemDest_})
5348 if (b >= 0 && (elemBound_ < 0 || b < elemBound_)) elemBound_ = b;
5349 if constexpr (requires { T::elemWire; }) elemWire_ = static_cast<int>(T::elemWire);
5350 else elemWire_ = -1;
5351 if constexpr (requires { T::elemFix; }) elemFix_ = static_cast<int>(T::elemFix);
5352 else elemFix_ = -1;
5353 /* descend into a nested sequence */
5354 if (seqDepth_ >= MAX_DEPTH) /* §4.9 */
5355 {
5356 error_ = true;
5357 return false;
5358 }
5359 ++seqDepth_;
5360 dispatchLevel([this, &value](sofab::id i, size_t s, size_t c) {
5361 value.deserialize(*this, i, s, c);
5362 }, /*stopAtEnd*/ true);
5363 elemBound_ = outerBound;
5364 elemSchema_ = outerSchema;
5365 elemDyn_ = outerDyn;
5366 elemDest_ = outerDest;
5367 elemWire_ = outerElemWire;
5368 elemFix_ = outerElemFix;
5369 --seqDepth_;
5370 /* A sequence cut short is NOT consumed: the whole field is
5371 * delivered again once its remaining bytes arrive. */
5372 if (incomplete_)
5373 {
5374 consumed_ = outerConsumed;
5375 return false;
5376 }
5377 consumed_ = true;
5378 }
5379 else if constexpr (requires { typename T::value_type; std::span{std::declval<T &>()}; } &&
5380 !std::is_const_v<typename T::value_type>)
5381 {
5382 using Elem = typename T::value_type;
5383 std::span<Elem> sp{value};
5384 size_t n = std::min(sp.size(), count_);
5385 if constexpr (std::is_integral_v<Elem> && !std::is_same_v<Elem, bool>)
5386 {
5387 /* §7.3: the element kind selects the array wire type. */
5388 constexpr Wire want = std::is_unsigned_v<Elem> ? Wire::ArrayUnsigned : Wire::ArraySigned;
5389 if (!tagMatches(want)) return false;
5390 /* No declared element width here: read() is handed a
5391 * destination, not a schema. The bounded form is reached
5392 * through readArray, which is handed both. */
5393 if (!readIntElements<false>(sp.first(n))) return false;
5394 }
5395 else if constexpr (std::is_same_v<Elem, bool>)
5396 {
5397 /* Kept apart from the integral branch above on purpose: a
5398 * boolean rides the unsigned varint array form (§4.4), but is
5399 * not an integer. Every non-zero element is `true`, is
5400 * normalized on store, and is bounded by nothing -- `256` and
5401 * `2^64-1` are `true`, not INVALID -- so this read is never the
5402 * bounded instantiation, whatever the caller declared. */
5403 if (!tagMatches(Wire::ArrayUnsigned)) return false; /* §7.3 */
5404 if (!readIntElements<false>(sp.first(n))) return false;
5405 }
5406 else if constexpr (std::is_same_v<Elem, float> || std::is_same_v<Elem, double>)
5407 {
5408 constexpr Fix want = std::is_same_v<Elem, float> ? Fix::Fp32 : Fix::Fp64;
5409 if (!tagMatches(Wire::ArrayFixlen, want)) return false; /* §7.3 */
5410 const size_t bytes = count_ * sizeof(Elem);
5411 if (pendDone_ == 0 &&
5412 static_cast<size_t>(end_ - p_) >= bytes) [[likely]]
5413 {
5414 /* The whole payload in one piece: one bulk move, which is
5415 * what the fixlen array's wire form exists for. */
5416 if constexpr (std::endian::native == std::endian::little)
5417 {
5418 /* An empty destination span has a null data(), which
5419 * memcpy forbids even for a zero length. */
5420 if (n) std::memcpy(sp.data(), p_, n * sizeof(Elem)); /* wire == native */
5421 }
5422 else
5423 for (size_t i = 0; i < n; ++i)
5424 sp[i] = loadFloat<Elem>(p_ + i * sizeof(Elem));
5425 p_ += bytes;
5426 }
5427 else
5428 {
5429 /* Split across feeds: element by element into the caller's
5430 * destination as each one lands (§6.6.2). A part-arrived
5431 * element is left where it is — at most seven bytes, which
5432 * the carry holds. */
5433 size_t i = pendDone_;
5434 while (i < count_)
5435 {
5436 if (static_cast<size_t>(end_ - p_) < sizeof(Elem))
5437 {
5438 pendDone_ = i;
5439 incomplete_ = true;
5440 return false;
5441 }
5442 if (i < n) sp[i] = loadFloat<Elem>(p_);
5443 p_ += sizeof(Elem);
5444 ++i;
5445 }
5446 pendDone_ = 0;
5447 }
5448 consumed_ = true;
5449 }
5450 else
5451 {
5452 static_assert(always_false_v<T>, "Unsupported span element type in IStream::read()");
5453 }
5454 }
5455 else
5456 {
5457 static_assert(always_false_v<T>, "Unsupported type passed to IStream::read()");
5458 }
5459 return true;
5460 }
5461
5462 /**
5463 * @brief Read the current field as a `string`, or skip it (§7.3).
5464 *
5465 * `fp32`, `fp64`, `string` and `blob` all share @ref Wire::Fixlen, so a
5466 * plain @ref read cannot tell which one the caller declared. This overload
5467 * states it: the value is read only when the wire subtype is
5468 * @ref Fix::String, otherwise the field is left unconsumed — the decoder
5469 * then skips it exactly like an unknown id, and @ref skipped counts it.
5470 *
5471 * The destination is either a growable one (`std::string`) or a heap-free
5472 * @ref FixedString, told apart by @ref FixedString::set_len rather than by
5473 * name, so a caller's own type works too. Both spell the call identically;
5474 * only where the bytes land differs.
5475 *
5476 * @par The three ways this refuses (§6.3), in the only correct order
5477 * 1. The wire subtype contradicts `string` → the field is **skipped**
5478 * (§7.3), and neither bound below is applied to it: "a skipped field
5479 * is never capped" (§6.2.1).
5480 * 2. @p bound is declared and the announced length exceeds it →
5481 * `InvalidMessage` (MESSAGE_SPEC §7.1). The schema calls these bytes
5482 * invalid.
5483 * 3. @p bound is negative — the schema declares none — and the announced
5484 * length exceeds @p dynCap → @ref Error::LimitExceeded (§6.2.1). The
5485 * bytes are well-formed; this receiver declines to hold that much.
5486 *
5487 * All three are decided **at the length header**, before the destination is
5488 * sized (§6.2.1's enforcement point, §5.2.3): @ref sofab::readString, the
5489 * helper that sizes a growable destination, applies the identical gate
5490 * before it grows anything.
5491 *
5492 * @par Two entry points, so a number cannot be forgotten
5493 * This overload is the **schema-bounded** read and takes the declared
5494 * `maxlen` only; @ref readStringCapped is the **schema-unbounded** one and
5495 * takes the §6.2.1 receiver cap only. Exactly one of the two numbers can
5496 * ever apply — a receiver limit "**MUST NOT** be applied to a field the
5497 * schema already bounds" — so the choice belongs in the call's *name*
5498 * rather than in a pair of arguments where either may be left out. Neither
5499 * has a default, and neither reads a negative value as "unlimited": a
5500 * @p bound below zero is not a schema-unbounded read, it is a call that
5501 * stated no bound at all, and it answers @ref Error::InvalidArgument
5502 * through @ref rejectUnbounded.
5503 *
5504 * @par The bound is passed in, never held
5505 * §6.2.1 leaves this corelib "the report and the category" and puts the
5506 * *numbers* in generated code, so @p bound is the caller's, used for this
5507 * one comparison and not retained. There is no stream-wide fallback of any
5508 * kind. Passing the number here rather than testing it in front of the call
5509 * is what keeps case 1 above true: the tag test is inside, so a field the
5510 * decoder must skip never meets the ceiling.
5511 *
5512 * @param[out] value Destination for the decoded text.
5513 * @param bound Declared `maxlen`. **Required and non-negative**; a
5514 * schema-unbounded field is read through
5515 * @ref readStringCapped instead.
5516 * @return `true` when the value was read; `false` when the field was left
5517 * for the decoder to skip.
5518 */
5519 template <typename S, typename Sizer = detail::NoSizer>
5520 bool readString(S &value, long bound, Sizer sizer = {}) noexcept
5521 {
5522 if (bound < 0) { rejectUnbounded(); return false; }
5523 return readStringGated(value, bound, -1, sizer);
5524 }
5525
5526 /**
5527 * @brief Read the current field as a schema-**unbounded** `string` under
5528 * the receiver's `max_dyn_string_len` (§6.2.1).
5529 *
5530 * The counterpart of @ref readString for a field whose schema declares no
5531 * `maxlen`. It refuses in the same order — tag (§7.3), then the cap
5532 * (@ref Error::LimitExceeded) — and the cap is the caller's, used for this
5533 * one comparison and not retained.
5534 *
5535 * It exists as its own entry point rather than as a defaulted argument
5536 * because a defaulted one can be left out, and a schema-unbounded read with
5537 * no cap is the sender choosing how much this process holds. There is
5538 * nothing to default to: §6.2.1 forbids this codec a limit of its own.
5539 *
5540 * @param[out] value Destination for the decoded text.
5541 * @param dynCap The caller's `max_dyn_string_len`. **Required and
5542 * non-negative**; a negative value is a call that stated no
5543 * cap and answers @ref Error::InvalidArgument.
5544 * @return `true` when the value was read; `false` when the field was left
5545 * for the decoder to skip.
5546 */
5547 template <typename S, typename Sizer = detail::NoSizer>
5548 bool readStringCapped(S &value, long dynCap, Sizer sizer = {}) noexcept
5549 {
5550 if (dynCap < 0) { rejectUnbounded(); return false; }
5551 return readStringGated(value, -1, dynCap, sizer);
5552 }
5553
5554 protected:
5555 /**
5556 * @brief The body both `string` reads share, so the two cannot answer
5557 * differently. Exactly one of @p bound / @p dynCap is non-negative.
5558 *
5559 * **Not an entry point.** It carries no check that a number was stated —
5560 * that is the job of @ref readString and @ref readStringCapped, which is
5561 * why this is not public: a `(-1, -1)` call is the fail-open shape §6.2.1
5562 * forbids, and there is deliberately no way to spell it.
5563 */
5564 template <typename S, typename Sizer>
5565 bool readStringGated(S &value, long bound, long dynCap, Sizer sizer) noexcept
5566 {
5567 if (!tagMatches(Wire::Fixlen, Fix::String)) return false; /* §7.3 */
5568 if (bound >= 0 && fixLen_ > static_cast<size_t>(bound)) /* §7.1/§5.2 */
5569 { error_ = true; return false; }
5570 /* §6.2.1: consulted only where the schema declares no bound — a
5571 * receiver limit "MUST NOT be applied to a field the schema already
5572 * bounds". */
5573 if (bound < 0 && dynCap >= 0 && fixLen_ > static_cast<size_t>(dynCap))
5574 { exceedLimit(); return false; }
5575 /* One delivery path for both storage modes (§6.6.3): the destination
5576 * is refused when it is shorter than the announced payload, never
5577 * grown to fit it. Which of the two a destination is — static room or
5578 * room the caller sized — is a fact @ref detail::destRoom reads off
5579 * the type, not a policy this read picks. */
5580 /* The caller's sizer (the free read's fitDest) runs here — after
5581 * §7.3 and the bound, before the room test — so those checks are
5582 * made once, not once in front of this read and again inside it. */
5583 sizer(value, std::min(fixLen_, pendDone_ + static_cast<size_t>(end_ - p_)));
5584 return readPayload(value, /*validateUtf8*/ true);
5585 }
5586
5587 public:
5588 /**
5589 * @brief Read the current field as a `blob`, or skip it (§7.3).
5590 *
5591 * The @ref Fix::Blob counterpart of @ref readString; reads straight into
5592 * the byte container, with no intermediate `std::string`. Takes a growable
5593 * `std::vector<uint8_t>` or a heap-free @ref FixedBytes, on the same
5594 * @ref FixedBytes::set_len test.
5595 *
5596 * Refuses in the same three ways, in the same order, as
5597 * @ref readString — and takes its own §6.2.1 cap the same way. `blob` and
5598 * `string` are separate limits, so the caller passes
5599 * `max_dyn_blob_len` here.
5600 *
5601 * Split into two entry points on the same terms as @ref readString: this
5602 * one takes the declared `maxlen`, @ref readBlobCapped takes the receiver
5603 * cap, and neither has a default.
5604 *
5605 * @param[out] value Destination for the decoded bytes.
5606 * @param bound Declared `maxlen`. **Required and non-negative**; a
5607 * schema-unbounded field is read through @ref readBlobCapped.
5608 * @return `true` when the value was read; `false` when the field was left
5609 * for the decoder to skip.
5610 */
5611 template <typename B, typename Sizer = detail::NoSizer>
5612 bool readBlob(B &value, long bound, Sizer sizer = {}) noexcept
5613 {
5614 if (bound < 0) { rejectUnbounded(); return false; }
5615 return readBlobGated(value, bound, -1, sizer);
5616 }
5617
5618 /**
5619 * @brief Read the current field as a schema-**unbounded** `blob` under the
5620 * receiver's `max_dyn_blob_len` (§6.2.1).
5621 *
5622 * The `blob` counterpart of @ref readStringCapped; see it for why the
5623 * capped read is its own entry point. `blob` and `string` are separate
5624 * limits, so the caller passes `max_dyn_blob_len` here.
5625 *
5626 * @param[out] value Destination for the decoded bytes.
5627 * @param dynCap The caller's `max_dyn_blob_len`. **Required and
5628 * non-negative**; a negative value answers
5629 * @ref Error::InvalidArgument.
5630 * @return `true` when the value was read; `false` when the field was left
5631 * for the decoder to skip.
5632 */
5633 template <typename B, typename Sizer = detail::NoSizer>
5634 bool readBlobCapped(B &value, long dynCap, Sizer sizer = {}) noexcept
5635 {
5636 if (dynCap < 0) { rejectUnbounded(); return false; }
5637 return readBlobGated(value, -1, dynCap, sizer);
5638 }
5639
5640 protected:
5641 /** @brief The body both `blob` reads share. @copydetails readStringGated */
5642 template <typename B, typename Sizer>
5643 bool readBlobGated(B &value, long bound, long dynCap, Sizer sizer) noexcept
5644 {
5645 if (!tagMatches(Wire::Fixlen, Fix::Blob)) return false;
5646 if (bound >= 0 && fixLen_ > static_cast<size_t>(bound)) /* §7.1 */
5647 {
5648 error_ = true;
5649 return false;
5650 }
5651 if (bound < 0 && dynCap >= 0 && fixLen_ > static_cast<size_t>(dynCap)) /* §6.2.1 */
5652 {
5653 exceedLimit();
5654 return false;
5655 }
5656 /* §6.6.3, as in readString — one delivery path, refuse rather than
5657 * grow. A `blob` is never UTF-8 validated (§6.4). */
5658 /* The caller's sizer (the free read's fitDest) runs here — after
5659 * §7.3 and the bound, before the room test — so those checks are
5660 * made once, not once in front of this read and again inside it. */
5661 sizer(value, std::min(fixLen_, pendDone_ + static_cast<size_t>(end_ - p_)));
5662 return readPayload(value, /*validateUtf8*/ false);
5663 }
5664
5665 public:
5666 /**
5667 * @brief Read a count-prefixed native array, applying every receiver-side
5668 * decision at the one word that decides it.
5669 *
5670 * Folds what a caller previously had to spell out in four steps — check the
5671 * wire tag, check the schema `count`, check a configured policy cap, reset
5672 * the destination — into one call, in the only order that is correct:
5673 *
5674 * 1. **Tag** (§7.3). A contradicting array kind is skipped like an unknown
5675 * id; nothing else runs, so neither bound below can be applied to a field
5676 * that is not this field's value.
5677 * 2. **Schema `count`** (§7.1/§5.2) → `INVALID`. Malformed input.
5678 * 3. **Configured receiver cap** (@p dynCap, §6.2.1) → `LimitExceeded`.
5679 * Deliberately *not* INVALID: the bytes are fine and the same message
5680 * decodes under a looser cap.
5681 * 3b. **The destination's own capacity**, for a destination that publishes
5682 * one → `InvalidArgument` (§6.3's third tier, §6.6.3): a count it cannot
5683 * hold is refused instead of silently truncated into it (MESSAGE_SPEC
5684 * §3), and by this point neither the schema nor the deployment has
5685 * anything left to object to — only this caller's storage.
5686 * 4. **Reset, then fill.** The destination is resized (dynamic container) or
5687 * value-initialized (fixed extent) only now, so an occurrence skipped at
5688 * step 1 cannot wipe a valid earlier one (§7.4). A destination pre-sized
5689 * to a declared `count: N` keeps the element default in the slots past
5690 * the wire count `M`, which is the array's length — there is no
5691 * fill-to-`N` and no trailing elision to undo (§3).
5692 * 5. **Declared element width** (@p elem, §7.1) → `INVALID`, per element as
5693 * it is decoded. The sibling of the `count` bound at step 2: the same
5694 * class of schema fact, arriving through the same call, and the reason it
5695 * is applied *here* rather than by the caller — an element cannot be
5696 * range-checked after the fact without a wide temporary copy of the whole
5697 * array. Unarmed by default, so an omitted bound decodes exactly as before.
5698 *
5699 * @param[out] dst Destination range (fixed extent or resizable).
5700 * @param schemaCount Declared `count: N`, or negative when unbounded.
5701 * Split into two entry points on the same terms as @ref readString: this
5702 * one takes the declared `count`, @ref readArrayCapped takes the receiver
5703 * cap, and neither has a default.
5704 *
5705 * @param elem Declared element range (@ref ElemBound), e.g.
5706 * `ElemBound::of<std::uint8_t>()` for `items: u8`.
5707 * Ignored for a float element type, which has no
5708 * narrowing to reject: `fp32`/`fp64` are carried at
5709 * their own width on the wire. Ignored for a `bool`
5710 * element too, which §4.4 bounds by no width at all:
5711 * every non-zero element is `true`.
5712 * @param schemaCount Declared `count: N`. **Required and non-negative**;
5713 * a schema-unbounded array is read through
5714 * @ref readArrayCapped.
5715 * @return `true` when the array was read; `false` when it was skipped (§7.3)
5716 * or rejected, with the outcome already recorded on the stream.
5717 */
5718 template <typename T, typename Sizer = detail::NoSizer>
5719 bool readArray(T &dst, long schemaCount, ElemBound elem = {}, Sizer sizer = {}) noexcept
5720 {
5721 if (schemaCount < 0) { rejectUnbounded(); return false; }
5722 return readArrayGated(dst, schemaCount, -1, elem, sizer);
5723 }
5724
5725 /**
5726 * @brief Read a schema-**unbounded** count-prefixed array under the
5727 * receiver's `max_dyn_array_count` (§6.2.1).
5728 *
5729 * The counterpart of @ref readArray for an array whose schema declares no
5730 * `count`. Step 2 of the order above drops out and step 3 decides; the cap
5731 * is the caller's, used for that one comparison and not retained.
5732 *
5733 * @param[out] dst Destination range (fixed extent or resizable).
5734 * @param dynCap The caller's `max_dyn_array_count`. **Required and
5735 * non-negative**; a negative value answers
5736 * @ref Error::InvalidArgument.
5737 * @param elem Declared element range (@ref ElemBound).
5738 * @return `true` when the array was read.
5739 */
5740 template <typename T, typename Sizer = detail::NoSizer>
5741 bool readArrayCapped(T &dst, long dynCap, ElemBound elem = {}, Sizer sizer = {}) noexcept
5742 {
5743 if (dynCap < 0) { rejectUnbounded(); return false; }
5744 return readArrayGated(dst, -1, dynCap, elem, sizer);
5745 }
5746
5747 protected:
5748 /** @brief The body both array reads share. @copydetails readStringGated */
5749 template <typename T, typename Sizer>
5750 bool readArrayGated(T &dst, long schemaCount, long dynCap, ElemBound elem, Sizer sizer) noexcept
5751 {
5752 using Elem = typename T::value_type;
5753 if constexpr (std::is_same_v<Elem, float> || std::is_same_v<Elem, double>)
5754 {
5755 constexpr Fix want = std::is_same_v<Elem, float> ? Fix::Fp32 : Fix::Fp64;
5756 if (!tagMatches(Wire::ArrayFixlen, want)) return false;
5757 }
5758 else
5759 {
5760 constexpr Wire want = std::is_unsigned_v<Elem> ? Wire::ArrayUnsigned : Wire::ArraySigned;
5761 if (!tagMatches(want)) return false;
5762 }
5763 if (schemaCount >= 0 && count_ > static_cast<size_t>(schemaCount))
5764 {
5765 error_ = true;
5766 return false;
5767 }
5768 /* §6.2.1: consulted only where the schema declares no `count` — a
5769 * receiver limit "MUST NOT be applied to a field the schema already
5770 * bounds", which is the same gate the wrapper-array collectors apply
5771 * to their own index cap. */
5772 if (schemaCount < 0 && dynCap >= 0 && count_ > static_cast<size_t>(dynCap))
5773 {
5774 exceedLimit();
5775 return false;
5776 }
5777 /* Step 3's second ceiling: the destination's own capacity. MESSAGE_SPEC
5778 * §3 has a decoder materialize exactly the M elements the wire carries,
5779 * "the same value on a pre-sized target and on a growable one", so a
5780 * count a heap-free destination cannot hold is rejected here rather
5781 * than truncated into it. Nothing downstream can catch it: an
5782 * InlineVector's resize clamps to N and the fill then binds
5783 * min(size, count) elements, parsing the surplus only to stay framed —
5784 * the field is consumed and the decode reports COMPLETE with elements
5785 * silently missing (issue #81). The same gate readString / readBlob
5786 * already apply to a FixedString / FixedBytes payload.
5787 *
5788 * The category is §6.3's THIRD tier, and it does not depend on where
5789 * the ceiling came from: both bounds that speak about the *message*
5790 * have already spoken by the time this runs — the schema `count` at
5791 * step 2 and the configured cap at step 3 — so what is left is a
5792 * destination too short for a value both of them admit. That is
5793 * `InvalidArgument`: "The third is a mistake in the **call**, not a
5794 * property of the message or of the deployment, and the other two
5795 * codes each say something untrue about it." (§6.3). This used to
5796 * report INVALID under a declared `count` and LimitExceeded without
5797 * one — two answers, neither of them this one (A2-0022). */
5798 if constexpr (constexpr long destCap = detail::destCapacity<T>(); destCap >= 0)
5799 {
5800 /* A **static** capacity cannot change between chunks, so the
5801 * refusal is pulled forward to the header: the destination is
5802 * judged before a byte of payload is read, and the verdict cannot
5803 * depend on where the chunk boundaries fell. */
5804 if (count_ > static_cast<size_t>(destCap))
5805 {
5807 return false;
5808 }
5809 }
5810 else if constexpr (requires { dst.resize(size_t{}); })
5811 {
5812 /* Room the caller sized (§6.6.3) — the branch §6.6 is about, since
5813 * this is the destination the codec used to grow. It is compared
5814 * against what this delivery can actually **reach**: the announced
5815 * count, clamped to the elements the bytes in hand could carry (a
5816 * varint element is at least one byte, a fixlen one exactly
5817 * @ref fixLen_).
5818 *
5819 * Clamping is what keeps a hostile count from deciding anything: a
5820 * declared 2^31 elements whose payload is absent or withheld reaches
5821 * nothing, so it neither refuses a sound destination nor asks anyone
5822 * to size one — which is also what lets the field-size cap withhold
5823 * an over-cap payload while the schema `count` above still gets to
5824 * speak (#86). When the payload is complete the reach IS `count_`, so
5825 * a destination genuinely too short is refused exactly then, and
5826 * refused rather than silently truncated into (MESSAGE_SPEC §3,
5827 * issue #81). */
5828 const uint64_t readable = static_cast<uint64_t>(end_ - p_);
5829 const uint64_t fillable = type_ == Wire::ArrayFixlen
5830 ? (fixLen_ ? readable / fixLen_ : uint64_t{0})
5831 : readable;
5832 const size_t reach = static_cast<size_t>(
5833 std::min<uint64_t>(static_cast<uint64_t>(count_),
5834 static_cast<uint64_t>(pendDone_) + fillable));
5835 sizer(dst, reach); /* the caller's fitDest, after the checks above */
5836 if (reach > dst.size())
5837 {
5839 return false;
5840 }
5841 }
5842 /* A destination of fixed extent that publishes neither a capacity nor a
5843 * resize (`std::array`, a bound span) is @ref read's low-level contract
5844 * and not this tier's business: it cannot be grown, so §6.6 has nothing
5845 * to say about it, and the leading elements land in it while the rest is
5846 * parsed only to stay framed. */
5847 /* §7.4's reset, and the destination's length, in the one order each
5848 * kind admits:
5849 *
5850 * * **static room** (@ref InlineVector): the storage is already the
5851 * caller's in full, so setting the length to `M` is a length store
5852 * and nothing is allocated. It happens **before** the fill, because
5853 * the span the fill binds is the destination's *current* length;
5854 * * **fixed extent with no length** (`std::array`, a bound span): put
5855 * back to the element default here — the slots past `M` are what
5856 * §7.4 would otherwise leave from an earlier message;
5857 * * **room the caller sized**: the fill writes the `M` elements it was
5858 * given room for, and the length is published **after**, as a shrink
5859 * (below). Growing it here is exactly what §6.6 forbids. */
5860 if (pendDone_ == 0)
5861 {
5862 /* Only on the FIRST delivery: a field resumed from an earlier chunk
5863 * already holds the elements that arrived with it, and resetting
5864 * here would throw them away (§6.6.2 — the destination is written
5865 * as the pieces arrive, not from scratch each feed). */
5866 if constexpr (detail::destCapacity<T>() >= 0) detail::destSetLen(dst, count_);
5867 else if constexpr (!requires { dst.resize(size_t{}); }) dst = T{};
5868 }
5869 const bool ok = [&]() noexcept {
5870 if constexpr (std::is_integral_v<Elem> && !std::is_same_v<Elem, bool>)
5871 {
5872 if (elem.armed)
5873 {
5874 /* The tag is already settled above, so the bounded decode is
5875 * entered directly rather than through read(). */
5876 std::span<Elem> sp{dst};
5877 return readIntElements<true>(sp.first(std::min(sp.size(), count_)), elem);
5878 }
5879 }
5880 return read(dst);
5881 }();
5882 if (!ok) return false;
5883 if constexpr (detail::destCapacity<T>() < 0) detail::destSetLen(dst, count_);
5884 return true;
5885 }
5886
5887 public:
5888 /**
5889 * @brief Read the current blob field into a caller buffer.
5890 *
5891 * Copies up to @p maxlen bytes; the field is consumed regardless of how
5892 * much fit. Call from inside a deliver callback.
5893 *
5894 * Declares a `blob` like @ref readBlob, so it compares the whole tag first
5895 * (§7.3): any other field — an integer, a sequence, an array, or another
5896 * fixlen subtype — is left for the decoder to skip, with @p dst untouched.
5897 * That check is what keeps the cursor sane, because @ref fixLen_ only means
5898 * "payload length" for a scalar fixlen field: it is 0 for a varint field and
5899 * the per-ELEMENT width for a fixlen array, so consuming on those tags left
5900 * the parser standing inside the payload and re-reading it as field headers
5901 * (issue #80).
5902 *
5903 * @param dst Destination buffer.
5904 * @param maxlen Capacity of @p dst in bytes.
5905 * @return Number of bytes copied (`min(maxlen, payload length)`), or 0 when
5906 * the field was not consumed. Zero is therefore ambiguous on its own —
5907 * a zero-length blob also copies nothing, and so does a skipped
5908 * mismatch — so a caller that needs to tell them apart consults
5909 * @ref consumed().
5910 */
5911 size_t read(void *dst, size_t maxlen) noexcept
5912 {
5913 if (!tagMatches(Wire::Fixlen, Fix::Blob)) return 0; /* §7.3 */
5914 const size_t done = pendDone_;
5915 const size_t avail = static_cast<size_t>(end_ - p_);
5916 const size_t take = std::min(avail, fixLen_ - done);
5917 /* The piece that lands inside the caller's buffer is copied; the rest of
5918 * the payload is stepped over, exactly as the truncating contract above
5919 * says. Both halves resume, so a blob split across feeds needs no buffer
5920 * of the decoder's own (§6.6.2). */
5921 if (done < maxlen && take)
5922 std::memcpy(static_cast<uint8_t *>(dst) + done, p_,
5923 std::min(take, maxlen - done));
5924 p_ += take;
5925 if (done + take < fixLen_)
5926 {
5927 /* The payload has not fully arrived. That is INCOMPLETE, not an
5928 * error: more bytes may complete it, and the field is continued
5929 * once they do. Setting error_ here made a truncated blob INVALID
5930 * and — because the run is then condemned — unrecoverable even
5931 * after the remaining bytes arrived. Matches @ref readBlob and
5932 * @ref readString, which guard the identical condition. */
5933 pendDone_ = done + take;
5934 incomplete_ = true;
5935 return 0;
5936 }
5937 pendDone_ = 0;
5938 consumed_ = true;
5939 return std::min(maxlen, fixLen_);
5940 }
5941
5942 /**
5943 * @return `true` when a read in this delivery consumed the field. `false`
5944 * means the field was declined (skipped) or its payload has not
5945 * arrived yet, in which case the field is delivered again with the
5946 * next chunk and the read continues where it stopped.
5947 */
5948 [[nodiscard]] bool consumed() const noexcept { return consumed_; }
5949
5950 /**
5951 * @brief Wire type of the field currently being delivered.
5952 *
5953 * Valid inside a deliver callback. Introspection only: the typed reads
5954 * compare the tag themselves and skip a contradicting field (§7.3), so a
5955 * caller does not need this to be correct — it is here for diagnostics and
5956 * for code that wants to branch on the delivered form. The type it returns
5957 * lives in @ref sofab::detail. Reads no bytes and does not consume the
5958 * field.
5959 *
5960 * @return The delivered field's @ref Wire.
5961 */
5962 [[nodiscard]] Wire wire() const noexcept { return type_; }
5963
5964 /**
5965 * @brief Fixlen sub-type of the field currently being delivered.
5966 *
5967 * Only meaningful when @ref wire is a fixlen kind. Introspection only,
5968 * like @ref wire: `readString` / `readBlob` state the declared subtype and
5969 * the stream compares it. Reads no bytes and does not consume the field.
5970 *
5971 * @return The delivered field's @ref Fix.
5972 */
5973 [[nodiscard]] Fix fixType() const noexcept { return fixType_; }
5974
5975 /**
5976 * @brief The payload length the current field's header announces — a
5977 * `string`/`blob` byte count, or a fixlen array's **element** width.
5978 *
5979 * §6.6.3's "after being told the announced count": the number the caller
5980 * sizes its destination from before handing it back. Identical to the
5981 * `size` argument of the deliver callback, reachable from a helper that
5982 * was not handed it (@ref sofab::readString and friends).
5983 */
5984 [[nodiscard]] size_t announcedSize() const noexcept { return fixLen_; }
5985
5986 /**
5987 * @brief The element count the current array field's header announces.
5988 * @copydetails announcedSize
5989 */
5990 [[nodiscard]] size_t announcedCount() const noexcept { return count_; }
5991
5992 /**
5993 * @brief Bytes of this field readable right now, in the chunk being parsed.
5994 *
5995 * What lets a helper sizing a destination clamp an announced count to what
5996 * the bytes in hand could ever fill, so a hostile count never decides an
5997 * allocation — the same clamp @ref readArray applies to its own refusal.
5998 */
5999 [[nodiscard]] size_t available() const noexcept
6000 {
6001 return static_cast<size_t>(end_ - p_);
6002 }
6003
6004 /**
6005 * @brief How much of the current field earlier chunks already delivered —
6006 * payload bytes written, or array elements decoded.
6007 *
6008 * Zero on a field's first delivery. A field split across `feed` calls is
6009 * **continued**, not re-parsed (§6.6.2), so a helper sizing the destination
6010 * has to add what is already in it to what has just arrived; sizing from
6011 * this chunk alone would ask the codec to fit a value into less room than it
6012 * has already used.
6013 */
6014 [[nodiscard]] size_t progress() const noexcept { return pendDone_; }
6015
6016 /**
6017 * @brief `true` when this delivery **re-enters a sequence** an earlier
6018 * `feed` left open, rather than announcing a new field.
6019 *
6020 * A nested sequence cut by a chunk boundary cannot be resumed from a byte
6021 * offset — the handler chain that was inside it lives on the C++ stack, and
6022 * a `feed` returning unwinds it. The decoder therefore replays the field ids
6023 * of the open levels, so each handler is asked for the same member again and
6024 * the chain is rebuilt exactly as it was. Nothing about the field is new: the
6025 * id, the sequence and everything already decoded inside it are the ones the
6026 * previous chunks produced.
6027 *
6028 * A handler that only dispatches on the id — every generated `deserialize`,
6029 * and any handler written the same way — needs this for nothing: reading the
6030 * same member again is precisely right, and the codec continues where it
6031 * stopped. It exists for a handler that keeps a **position** of its own
6032 * rather than a schema, which must not advance it twice.
6033 *
6034 * Distinct from @ref progress, which is about the bytes of one field.
6035 */
6036 [[nodiscard]] bool resumed() const noexcept { return replay_; }
6037
6038 /**
6039 * @brief The §7.3 and §7.1 decisions @ref readString makes, taken **before
6040 * a destination exists**.
6041 *
6042 * For a caller that has to place an element before it can offer a
6043 * destination — @ref StringSeq puts an element at its index, and growing
6044 * the container for a field that turns out not to be an element would
6045 * change the array's length (§5.1/§7.4). It answers the same two questions
6046 * @ref readString answers first, in the same order and through the same
6047 * seam, so the skip is counted exactly once: the tag (§7.3) and then the
6048 * declared `maxlen` (§7.1).
6049 *
6050 * It takes the §6.2.1 receiver cap on the same terms as @ref readString —
6051 * passed in, never held, and consulted only where @p bound is negative —
6052 * so the two seams cannot answer differently.
6053 *
6054 * It splits into a bounded and a capped form for the same reason
6055 * @ref readString does, and refuses a call that states neither the same
6056 * way (@ref rejectUnbounded).
6057 *
6058 * @param bound Declared `maxlen`. **Required and non-negative**;
6059 * @ref acceptsStringCapped is the schema-unbounded form.
6060 * @return `true` when a destination may be placed and handed to
6061 * @ref readString.
6062 */
6063 [[nodiscard]] bool acceptsString(long bound) noexcept
6064 {
6065 if (bound < 0) { rejectUnbounded(); return false; }
6066 return acceptsStringGated(bound, -1);
6067 }
6068
6069 /**
6070 * @brief @ref acceptsString for a schema-unbounded element, under the
6071 * receiver's `max_dyn_string_len` (§6.2.1).
6072 * @param dynCap The caller's cap. **Required and non-negative.**
6073 */
6074 [[nodiscard]] bool acceptsStringCapped(long dynCap) noexcept
6075 {
6076 if (dynCap < 0) { rejectUnbounded(); return false; }
6077 return acceptsStringGated(-1, dynCap);
6078 }
6079
6080 protected:
6081 /** @brief The body both `string` accepts share. */
6082 [[nodiscard]] bool acceptsStringGated(long bound, long dynCap) noexcept
6083 {
6084 if (!tagMatches(Wire::Fixlen, Fix::String)) return false; /* §7.3 */
6085 if (bound >= 0 && fixLen_ > static_cast<size_t>(bound)) /* §7.1 */
6086 { error_ = true; return false; }
6087 if (bound < 0 && dynCap >= 0 && fixLen_ > static_cast<size_t>(dynCap)) /* §6.2.1 */
6088 { exceedLimit(); return false; }
6089 return true;
6090 }
6091
6092 public:
6093 /** @copydoc acceptsString */
6094 [[nodiscard]] bool acceptsBlob(long bound) noexcept
6095 {
6096 if (bound < 0) { rejectUnbounded(); return false; }
6097 return acceptsBlobGated(bound, -1);
6098 }
6099
6100 /** @copydoc acceptsStringCapped */
6101 [[nodiscard]] bool acceptsBlobCapped(long dynCap) noexcept
6102 {
6103 if (dynCap < 0) { rejectUnbounded(); return false; }
6104 return acceptsBlobGated(-1, dynCap);
6105 }
6106
6107 protected:
6108 /** @brief The body both `blob` accepts share. */
6109 [[nodiscard]] bool acceptsBlobGated(long bound, long dynCap) noexcept
6110 {
6111 if (!tagMatches(Wire::Fixlen, Fix::Blob)) return false; /* §7.3 */
6112 if (bound >= 0 && fixLen_ > static_cast<size_t>(bound)) /* §7.1 */
6113 { error_ = true; return false; }
6114 if (bound < 0 && dynCap >= 0 && fixLen_ > static_cast<size_t>(dynCap)) /* §6.2.1 */
6115 { exceedLimit(); return false; }
6116 return true;
6117 }
6118 };
6119
6120 /**
6121 * @brief Input stream that delivers each top-level field to a user callback.
6122 *
6123 * The lightweight way to decode: supply a callback, then drive bytes through
6124 * @ref feed and pull values out with @ref read inside the callback.
6125 */
6127 {
6128 public:
6129 /** Callback type invoked per top-level field as `(fieldId, size, count)`. */
6130 using fieldCallback = std::function<void(sofab::id, size_t, size_t)>;
6131
6132 /**
6133 * @brief Construct with the per-field callback and the receiver's decode
6134 * limits.
6135 * @param callback Invoked for each complete top-level field.
6136 * @param limits The receiver's field-span budget (see @ref Limits).
6137 * **Required**: §6.2.1 gives this library no number to default to.
6138 */
6139 explicit IStreamInline(fieldCallback callback, Limits limits) noexcept
6140 : IStreamImpl(limits)
6141 {
6142 topCallback_ = std::move(callback);
6143 }
6144 };
6145
6146 /**
6147 * @brief Base class for user-defined messages that can deserialise themselves.
6148 *
6149 * Derive from this and implement @ref deserialize to read the message's fields;
6150 * the type can then be decoded directly (e.g. via @ref IStreamObject or by
6151 * reading a nested sub-message with @ref IStreamImpl::read).
6152 */
6154 {
6155 template <InputMessage MessageType>
6156 friend class IStreamObject;
6157
6158 public:
6159 /**
6160 * @brief Consume one of this message's fields from @p istream.
6161 *
6162 * Invoked once per field of the message; use @p id to dispatch and
6163 * @ref IStreamImpl::read to pull the value.
6164 *
6165 * @param istream Stream positioned at the field's value.
6166 * @param id Identifier of the field being delivered.
6167 * @param size Payload length (fixlen) or element size (fixlen array), in bytes.
6168 * @param count Element count for array fields, otherwise 0.
6169 */
6170 virtual void deserialize(IStreamImpl &istream, sofab::id id, size_t size, size_t count) noexcept = 0;
6171 virtual ~IStreamMessage() = default;
6172 };
6173
6174 /**
6175 * @brief A message that both encodes and decodes: exactly
6176 * @ref OStreamMessage + @ref IStreamMessage.
6177 *
6178 * Almost every message is both, so spelling out the pair at every declaration
6179 * is noise. This is an empty intermediate base — no storage, no vtable slot of
6180 * its own, identical layout to inheriting the two directly — so it is a naming
6181 * convenience and nothing else:
6182 *
6183 * ```cpp
6184 * struct Telemetry : sofab::Message {
6185 * sofab::OStreamImpl::Result serialize(sofab::OStreamImpl &os) const noexcept override;
6186 * void deserialize(sofab::IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override;
6187 * };
6188 * ```
6189 *
6190 * Both @ref sofab::InputMessage and @ref sofab::OutputMessage are satisfied
6191 * through it. Inherit a single side directly when a type really is one-way.
6192 */
6194 {
6195 };
6196
6197
6198 /**
6199 * @brief Holds a message and routes decoded top-level fields into it.
6200 *
6201 * Owns a @p MessageType instance and wires its @ref sofab::IStreamMessage::deserialize
6202 * as the per-field callback, so feeding bytes populates the message directly.
6203 * The decoded message is reached through `operator->` / `operator*`.
6204 *
6205 * @warning **One message per object, unless you @ref reset.** The wrapped
6206 * message is populated *in place* across every @ref IStreamImpl::feed,
6207 * and MESSAGE_SPEC §2 omits an all-default field from the bytes
6208 * altogether — so decoding a second message into the same object
6209 * leaves the first message's value in every field the second one does
6210 * not carry. That is true of a scalar field (it keeps the old number)
6211 * and, since §2, of a wrapper-array field too: its collector clears
6212 * the destination only when the wrapper sequence is present, so an
6213 * absent array field keeps the previous decode's elements instead of
6214 * reading as the empty array §2 requires. Call @ref reset between
6215 * messages — it re-initialises the message and the decoder together.
6216 *
6217 * @tparam MessageType A type satisfying @ref sofab::InputMessage.
6218 */
6219 template <InputMessage MessageType>
6221 {
6222 MessageType data_;
6223
6224 public:
6225 /**
6226 * Construct and route each top-level field into the wrapped message.
6227 * @param limits The receiver's field-span budget (see @ref Limits).
6228 * **Required**: §6.2.1 gives this library no number to default to.
6229 */
6230 explicit IStreamObject(Limits limits) noexcept
6231 : IStreamImpl(limits)
6232 {
6233 topCallback_ = [this](sofab::id id, size_t size, size_t count) {
6234 data_.deserialize(*this, id, size, count);
6235 };
6236 }
6237
6238 /**
6239 * @brief Reset the decoder **and** the wrapped message, ready for the next
6240 * message.
6241 *
6242 * Extends @ref IStreamImpl::reset by value-initialising the owned
6243 * @p MessageType — the destination side of the contract, which the base
6244 * class cannot do because it does not own a destination. Its address is
6245 * unchanged, so the field callback installed at construction stays valid.
6246 *
6247 * This is the supported way to decode more than one message with one
6248 * object; see the class warning for what goes wrong without it.
6249 */
6250 void reset() noexcept override
6251 {
6253 std::destroy_at(&data_);
6254 std::construct_at(&data_);
6255 }
6256
6257 /** @return The wrapped message (mutable access). */
6258 MessageType &operator->() noexcept { return data_; }
6259 /** @return The wrapped message (const access). */
6260 const MessageType &operator->() const noexcept { return data_; }
6261 /** @return Reference to the wrapped message (mutable access). */
6262 MessageType &operator*() noexcept { return data_; }
6263 /** @return Reference to the wrapped message (const access). */
6264 const MessageType &operator*() const noexcept { return data_; }
6265 };
6266
6267 /**
6268 * @brief Decoder that decodes into a message instance the CALLER owns.
6269 *
6270 * @ref IStreamObject with the instance taken out: it routes each top-level
6271 * field into the message handed to the constructor instead of one it holds
6272 * itself. That is the whole difference — same callback, same dispatch — and
6273 * it is what a caller who already has a destination needs, which is every
6274 * generated `try_decode` (sofa-buffers/generator#744). The alternative, a
6275 * hand-written @ref IStreamInline whose callback forwards to the
6276 * destination, needs the stream inside its own callback and so cannot
6277 * capture it; this class is that shape without the knot.
6278 *
6279 * @warning **One message per stream, unless the destination is put back.**
6280 * Everything @ref IStreamObject warns about applies here, for the
6281 * same reason — the message is populated in place and MESSAGE_SPEC
6282 * §2 leaves an all-default field out of the bytes, so a field the
6283 * next message does not carry keeps the previous one's value. The
6284 * difference is who clears it: the destination is the caller's, so
6285 * @ref reset here resets the DECODER only and the caller puts the
6286 * message back (generated code calls the message's own `reset()`,
6287 * which keeps the buffers it has already paid for — the reason to
6288 * hand a destination in at all). A rejected input likewise leaves
6289 * the fields decoded before the error in it.
6290 *
6291 * The message must outlive the stream.
6292 *
6293 * ```cpp
6294 * Telemetry msg; // kept across messages
6295 * msg.reset();
6296 * sofab::IStreamInto<Telemetry> in{msg, limits};
6297 * auto r = in.feed(bytes, len);
6298 * ```
6299 *
6300 * @tparam MessageType A type satisfying @ref sofab::InputMessage.
6301 */
6302 template <InputMessage MessageType>
6304 {
6305 MessageType *data_;
6306
6307 public:
6308 /**
6309 * Bind @p message and route each top-level field into it.
6310 * @param message The destination; must outlive the stream.
6311 * @param limits The receiver's field-span budget (see @ref Limits).
6312 * **Required**: §6.2.1 gives this library no number to default to.
6313 */
6314 explicit IStreamInto(MessageType &message, Limits limits) noexcept
6315 : IStreamImpl(limits), data_{&message}
6316 {
6317 topCallback_ = [this](sofab::id id, size_t size, size_t count) {
6318 data_->deserialize(*this, id, size, count);
6319 };
6320 }
6321 };
6322
6323 /* ---------------------------------------------------------------------- */
6324 /* The static helper layer (§6.6.1) */
6325 /* */
6326 /* Everything from here to the end of the file is the HELPER layer, not */
6327 /* the codec. CORELIB_PLAN §6.6.1 draws the line by ownership: "A helper */
6328 /* is part of the corelib -- it ships in the repository and is built with */
6329 /* it -- but the codec never uses one directly. Either the caller invokes */
6330 /* it, or it is reached from inside a callback the codec made. It may */
6331 /* allocate, because whatever it takes belongs to whoever called it." */
6332 /* */
6333 /* Nothing in IStreamImpl above calls anything below. These functions are */
6334 /* what the GENERATED layer calls instead of the codec's own read*: they */
6335 /* size the destination each field lands in -- "the generated object knows */
6336 /* the schema, sizes and owns the storage each field lands in, then drives */
6337 /* the codec over it like any other caller" (§6.6.1) -- and then hand it */
6338 /* to the codec, which refuses a destination too short rather than growing */
6339 /* one (§6.6.3). */
6340 /* ---------------------------------------------------------------------- */
6341
6342 namespace detail
6343 {
6344 /**
6345 * @brief Give @p dst room for @p want, if it is a destination the caller
6346 * has to size.
6347 *
6348 * Helper layer: this is the allocator call §6.6 moved out of the codec, and
6349 * it is here rather than there because the storage belongs to whoever
6350 * called this. A destination with **static room** (`T::capacity()`) needs
6351 * nothing — it already holds what it can ever hold — and one of fixed
6352 * extent with no `resize` cannot be sized at all.
6353 *
6354 * Only ever grows: a destination the caller deliberately sized larger keeps
6355 * its room, and the decoded length is published by
6356 * @ref sofab::detail::destSetLen when the value is in.
6357 *
6358 * @param dst Destination.
6359 * @param want Room the announced value needs, already clamped by the caller
6360 * to what the bytes in hand could fill.
6361 */
6362 /**
6363 * @brief Is @p D a destination the **caller** has to size?
6364 *
6365 * True only for heap-growable storage: it can be resized and publishes no
6366 * static capacity. A @ref sofab::FixedString / @ref sofab::FixedBytes /
6367 * @ref sofab::InlineVector
6368 * already holds everything it can hold, and a `std::array` or a bound span
6369 * cannot be sized at all — for those the whole helper below compiles away
6370 * and generated code pays nothing for calling it.
6371 */
6372 template <typename D>
6373 concept sizable = requires(D &d) { d.resize(size_t{}); } && !requires { D::capacity(); };
6374
6375 template <typename D>
6376 void fitDest(D &dst, size_t want) noexcept
6377 {
6378 if constexpr (requires { D::capacity(); }) { (void)dst; (void)want; }
6379 else if constexpr (requires { dst.resize(size_t{}); })
6380 {
6381 if (dst.size() < want) dst.resize(want);
6382 }
6383 }
6384
6385 /**
6386 * @brief @ref fitDest as the sizer a typed read runs between its checks
6387 * and its delivery, so the free reads below state the §7.3 tag,
6388 * the bound and the reach once — inside the read — instead of
6389 * re-deriving them in front of it.
6390 */
6391 struct FitDest
6392 {
6393 template <typename D>
6394 [[gnu::always_inline]] void operator()(D &dst, size_t want) const noexcept { fitDest(dst, want); }
6395 };
6396
6397 /**
6398 * @brief Elements of the announced array the bytes in hand could still
6399 * carry, clamped to the count itself.
6400 *
6401 * The same clamp @ref IStreamImpl::readArray applies to its own refusal, so
6402 * the helper never sizes a destination the codec would then refuse, and an
6403 * announced 2^31 whose payload is absent or withheld sizes nothing.
6404 */
6405 [[nodiscard]] inline size_t arrayReach(const IStreamImpl &is) noexcept
6406 {
6407 const uint64_t readable = static_cast<uint64_t>(is.available());
6408 const uint64_t fillable = is.wire() == Wire::ArrayFixlen
6409 ? (is.announcedSize()
6410 ? readable / is.announcedSize()
6411 : uint64_t{0})
6412 : readable;
6413 return static_cast<size_t>(
6414 std::min<uint64_t>(static_cast<uint64_t>(is.announcedCount()),
6415 static_cast<uint64_t>(is.progress()) + fillable));
6416 }
6417
6418 /** @brief Does the delivered tag match the array kind @p Elem declares (§7.3)? */
6419 template <typename Elem>
6420 [[nodiscard]] inline bool arrayTagMatches(const IStreamImpl &is) noexcept
6421 {
6422 if constexpr (std::is_same_v<Elem, float>)
6423 return is.wire() == Wire::ArrayFixlen && is.fixType() == Fix::Fp32;
6424 else if constexpr (std::is_same_v<Elem, double>)
6425 return is.wire() == Wire::ArrayFixlen && is.fixType() == Fix::Fp64;
6426 else if constexpr (std::is_unsigned_v<Elem>)
6427 return is.wire() == Wire::ArrayUnsigned;
6428 else
6429 return is.wire() == Wire::ArraySigned;
6430 }
6431 } // namespace detail
6432
6433 /**
6434 * @brief Read the current field as a `string` into a destination this call
6435 * sizes — the generated layer's @ref IStreamImpl::readString.
6436 *
6437 * Sizes @p dst for the announced payload and then hands it to the codec, which
6438 * refuses a destination too short rather than growing one (§6.6.3). For a
6439 * destination with static room (@ref FixedString) it adds nothing and compiles
6440 * away; for a `std::string` it is the one place the allocation happens.
6441 *
6442 * The sizing runs only once **every** gate @ref IStreamImpl::readString applies
6443 * has admitted the field — the tag (§7.3), the declared `maxlen` (§7.1) **and**
6444 * the configured receiver cap @p dynCap (§6.2.1) — so a mistyped, an over-long
6445 * or an over-cap occurrence leaves @p dst exactly as it was (§7.4). Sizing on
6446 * a subset of them would defeat the point of a receiver cap: §6.2.1 puts the
6447 * check "before the allocation it is meant to prevent", and this call *is* that
6448 * allocation. A schema-unbounded field sized here from the wire-announced
6449 * length is precisely the sender dictating the receiver's allocation.
6450 *
6451 * @par No number can be left out
6452 * This helper holds no limit and invents none (§6.2.1: a codec "MUST NOT supply
6453 * a default for one it was not given, MUST NOT read an omitted argument as
6454 * *unlimited*"), so it does not offer an argument that may be omitted at all.
6455 * There are two entry points, one per bound that can apply, neither defaulted:
6456 * ```cpp
6457 * sofab::readString(is, name, 32); // maxlen: 32
6458 * sofab::readStringCapped(is, name, SOFAB_MAX_DYN_STRING_LEN); // no maxlen
6459 * ```
6460 * Sizing @p dst from the wire with neither number stated is precisely the
6461 * sender dictating the receiver's allocation, so a negative one is refused
6462 * with @ref Error::InvalidArgument rather than obeyed.
6463 *
6464 * @param is Stream delivering the field.
6465 * @param dst Destination for the decoded text.
6466 * @param maxlen Declared `maxlen`. **Required and non-negative.**
6467 * @return `true` when the value was read.
6468 */
6469 template <typename S>
6470 bool readString(IStreamImpl &is, S &dst, long maxlen) noexcept
6471 {
6472 if constexpr (detail::sizable<S>) return is.readString(dst, maxlen, detail::FitDest{});
6473 else return is.readString(dst, maxlen);
6474 }
6475
6476 /**
6477 * @brief The schema-unbounded @ref sofab::readString: sizes @p dst only once
6478 * the §6.2.1 receiver cap has admitted the field.
6479 * @param is Stream delivering the field.
6480 * @param dst Destination for the decoded text.
6481 * @param dynCap The caller's `max_dyn_string_len`. **Required and
6482 * non-negative.**
6483 */
6484 template <typename S>
6485 bool readStringCapped(IStreamImpl &is, S &dst, long dynCap) noexcept
6486 {
6487 if constexpr (detail::sizable<S>) return is.readStringCapped(dst, dynCap, detail::FitDest{});
6488 else return is.readStringCapped(dst, dynCap);
6489 }
6490
6491 /**
6492 * @brief The `blob` counterpart of @ref sofab::readString.
6493 * @copydetails sofab::readString
6494 */
6495 template <typename B>
6496 bool readBlob(IStreamImpl &is, B &dst, long maxlen) noexcept
6497 {
6498 if constexpr (detail::sizable<B>) return is.readBlob(dst, maxlen, detail::FitDest{});
6499 else return is.readBlob(dst, maxlen);
6500 }
6501
6502 /**
6503 * @brief The `blob` counterpart of @ref sofab::readStringCapped.
6504 * @copydetails sofab::readStringCapped
6505 */
6506 template <typename B>
6507 bool readBlobCapped(IStreamImpl &is, B &dst, long dynCap) noexcept
6508 {
6509 if constexpr (detail::sizable<B>) return is.readBlobCapped(dst, dynCap, detail::FitDest{});
6510 else return is.readBlobCapped(dst, dynCap);
6511 }
6512
6513 /**
6514 * @brief Read the current count-prefixed array into a destination this call
6515 * sizes — the generated layer's @ref IStreamImpl::readArray.
6516 *
6517 * Sizes @p dst for the announced element count, clamped to what the bytes in
6518 * hand could fill, and only once the tag (§7.3), the schema `count` (§7.1) and
6519 * the configured receiver cap (§6.2.1) all admit the field — so neither a
6520 * mistyped occurrence nor a hostile count reaches an allocator. The codec then
6521 * fills what it was given room for and refuses a destination shorter than the
6522 * array actually is (§6.6.3).
6523 *
6524 * Two entry points, neither defaulted, exactly as for @ref sofab::readString.
6525 *
6526 * @param is Stream delivering the field.
6527 * @param dst Destination range.
6528 * @param schemaCount Declared `count: N`. **Required and non-negative.**
6529 * @param elem Declared element range (@ref ElemBound).
6530 * @return `true` when the array was read.
6531 */
6532 template <typename T>
6533 bool readArray(IStreamImpl &is, T &dst, long schemaCount, ElemBound elem = {}) noexcept
6534 {
6535 if constexpr (detail::sizable<T>) return is.readArray(dst, schemaCount, elem, detail::FitDest{});
6536 else return is.readArray(dst, schemaCount, elem);
6537 }
6538
6539 /**
6540 * @brief The schema-unbounded @ref sofab::readArray: sizes @p dst only once the
6541 * §6.2.1 receiver cap has admitted the count.
6542 * @param is Stream delivering the field.
6543 * @param dst Destination range.
6544 * @param dynCap The caller's `max_dyn_array_count`. **Required and
6545 * non-negative.**
6546 * @param elem Declared element range (@ref ElemBound).
6547 */
6548 template <typename T>
6549 bool readArrayCapped(IStreamImpl &is, T &dst, long dynCap, ElemBound elem = {}) noexcept
6550 {
6551 if constexpr (detail::sizable<T>) return is.readArrayCapped(dst, dynCap, elem, detail::FitDest{});
6552 else return is.readArrayCapped(dst, dynCap, elem);
6553 }
6554
6555 /**
6556 * @brief @ref IStreamImpl::read with the destination sized first — the
6557 * generated layer's untyped read.
6558 *
6559 * Dispatches like @ref IStreamImpl::read and adds nothing for a scalar or a
6560 * sub-message, whose destinations hold no room to size. A `std::string` payload
6561 * destination and a contiguous element range are sized here, so the codec never
6562 * has to grow one.
6563 */
6564 template <typename T>
6565 bool read(IStreamImpl &is, T &dst) noexcept
6566 {
6567 if constexpr (std::is_same_v<T, std::string>)
6568 {
6569 if (is.wire() == detail::Wire::Fixlen &&
6570 (is.fixType() == detail::Fix::String || is.fixType() == detail::Fix::Blob))
6571 detail::fitDest(dst, std::min(is.announcedSize(),
6572 is.progress() + is.available()));
6573 }
6574 else if constexpr (requires(T &d) {
6575 typename T::value_type;
6576 std::span{d};
6577 requires !std::is_const_v<typename T::value_type>;
6578 requires !InputMessage<T>;
6579 })
6580 {
6581 if constexpr (detail::sizable<T>)
6582 if (detail::arrayTagMatches<typename T::value_type>(is))
6583 detail::fitDest(dst, detail::arrayReach(is));
6584 }
6585 return is.read(dst);
6586 }
6587
6588 /* ---------------------------------------------------------------------- */
6589 /* Wrapper-sequence collectors and encode helpers */
6590 /* ---------------------------------------------------------------------- */
6591
6592 namespace detail
6593 {
6594 /**
6595 * @brief Admit or refuse a wrapper-array element **index**, in §6.3's
6596 * categories, before the container it indexes into is extended.
6597 *
6598 * MESSAGE_SPEC §5.1 makes the array's length *highest present id + 1*, so
6599 * the index **is** the length: "for a **sequence array** it surfaces the
6600 * **index** of the element in hand … there being no count header to
6601 * check", and "A limit **MUST** be enforced … before the container it
6602 * indexes into is extended" (§6.2.1).
6603 *
6604 * The three bounds do not share a verdict, so they are consulted in
6605 * §6.3's order. A schema `count` shuts the receiver cap out entirely —
6606 * a receiver limit "**MUST NOT** be applied to a field the schema already
6607 * bounds" (§6.2.1).
6608 *
6609 * The stream applies the same three bounds one step earlier, at the
6610 * element header (@ref IStreamImpl::rejectElementIndex), which is where a
6611 * truncated element cannot outrun them. This is the second gate, for a
6612 * `deserialize` reached directly — it is a public entry point — and for a
6613 * collector that publishes no element type for the stream to key on.
6614 *
6615 * @param is Stream to record the refusal on.
6616 * @param id The element index in hand.
6617 * @param cap Schema `count` N, or negative.
6618 * @param dynCap The caller's `max_dyn_array_count` (§6.2.1), or
6619 * negative when the caller supplied none — in which case
6620 * **no** index cap applies, because there is none to fall
6621 * back on.
6622 * @param destCap The destination container's capacity, or negative.
6623 * @return `true` when the index may be placed.
6624 *
6625 * @par A collector that states no bound at all is refused, not obeyed
6626 * A wrapper array's length is its highest index, so an unbounded array
6627 * whose collector carries neither a schema `count` nor a receiver cap grows
6628 * to whatever index the sender picks — the amplification §6.2.1 exists to
6629 * stop, from a ~9-byte field. There is nothing to fall back on (§6.2.1
6630 * forbids this codec a limit of its own), so the call is refused with
6631 * @ref Error::InvalidArgument. A destination that **cannot grow** is the
6632 * one exemption: its capacity already bounds the allocation, so no cap is
6633 * needed for the sender not to choose it.
6634 */
6635 inline bool seqIndexAdmitted(IStreamImpl &is, sofab::id id, long cap, long dynCap,
6636 long destCap) noexcept
6637 {
6638 const long i = static_cast<long>(id);
6639 const long dyn = dynCap; /* no stream-wide fallback (§6.2.1) */
6640 if (cap < 0 && dyn < 0 && destCap < 0)
6641 {
6642 is.rejectUnbounded(); /* §6.3 — a mistake in the call */
6643 return false;
6644 }
6645 if (cap >= 0)
6646 {
6647 if (i >= cap) { is.invalidate(); return false; } /* §7.1 */
6648 }
6649 else if (dyn >= 0 && i >= dyn)
6650 {
6651 is.exceedLimit(); /* §6.2.1 — policy, never INVALID */
6652 return false;
6653 }
6654 if (destCap >= 0 && i >= destCap)
6655 {
6656 is.rejectDestination(); /* §6.3's third tier */
6657 return false;
6658 }
6659 return true;
6660 }
6661 } // namespace detail
6662
6663 /**
6664 * @brief Collects the elements of a `string` wrapper-sequence array.
6665 *
6666 * MESSAGE_SPEC §5 lowers an array of strings to a sequence whose child ids are
6667 * the element indices, so an element is *placed* at its id rather than
6668 * appended: a default (empty) element is omitted on the wire (§2), and the gap
6669 * it leaves is filled with the element default.
6670 *
6671 * The schema bounds ride into the read, so a mis-typed element is skipped
6672 * under §7.3 instead of being measured against bounds that are not its own,
6673 * and an over-index element that survives that test is rejected by the stream
6674 * — at the element header for an element type the header settles, and at the
6675 * fixlen word for a fixlen one, which is where a `string` element's subtype
6676 * becomes known.
6677 *
6678 * @tparam C Destination container. `std::vector<std::string>` for the growable
6679 * storage mode, `InlineVector<FixedString<M>, N>` for the heap-free
6680 * one; anything with `clear`/`size`/`emplace_back`/`operator[]` whose
6681 * `value_type` @ref readString accepts will do. Class template
6682 * argument deduction makes the spelling identical either way:
6683 * `sofab::StringSeq s{dst, count, maxlen}`.
6684 */
6685 template <typename C = std::vector<std::string>>
6687 {
6689 long cap;
6690 long emax;
6691 /**
6692 * @brief The configured receiver cap on the element **index**
6693 * (`max_dyn_array_count`, §6.2.1); negative means none.
6694 *
6695 * A wrapper array carries no count header, so there is no count word for a
6696 * cap to bind: "for a **sequence array** it surfaces the **index** of the
6697 * element in hand — a wrapper array's length is *highest present id + 1*
6698 * (MESSAGE_SPEC §5.1), so the index is what has to be checked, there being
6699 * no count header to check." An id at or past this is
6700 * @ref Error::LimitExceeded, decided **before** @ref out is extended, so an
6701 * announced index never becomes an allocation.
6702 *
6703 * Deliberately **not** @ref StringSeq::cap — `cap` is the schema `count` and its
6704 * breach is `InvalidMessage` — the bytes contradict the schema both peers
6705 * agreed on — while this is a *policy* rejection the same bytes survive
6706 * under a looser cap, and §6.2.1 forbids folding the two. It is also
6707 * ignored while `cap` is armed, since a receiver limit "MUST NOT be
6708 * applied to a field the schema already bounds". The number itself is
6709 * generated code's to supply (§6.2.1: "The numbers and the allocation are
6710 * not the codec's"). There is **no default**: the constructor takes it,
6711 * and a collector built without one does not compile. (corelib-cpp#124)
6712 */
6714
6715 /**
6716 * @brief The §6.2.1 receiver cap on one ELEMENT's length, or -1 when the
6717 * caller supplied none.
6718 *
6719 * @ref dynCap bounds how many elements the array may have; this bounds how
6720 * long each may be. Both are needed: an array of two elements a gigabyte
6721 * each is under any index cap. It is consulted only where @ref emax is -1
6722 * — a receiver limit "MUST NOT be applied to a field the schema already
6723 * bounds" — and, like every cap here, it is passed in and never held.
6724 * There is no default: a negative value means the caller stated no cap,
6725 * and an element read under one answers @ref Error::InvalidArgument
6726 * rather than being read unbounded.
6727 */
6729
6730 /**
6731 * @brief The destination's own capacity, or -1 for a growable container.
6732 *
6733 * §6.3's third tier: an index the container cannot hold, with neither the
6734 * schema nor the deployment objecting, is @ref Error::InvalidArgument. For
6735 * a fixed-capacity container this is also what keeps the placement loop
6736 * below terminating — @ref InlineVector::emplace_back reuses the last slot
6737 * once full, so `out.size()` would never pass a large id.
6738 */
6739 static constexpr long elemDestCap = detail::destCapacity<C>();
6740
6741 /**
6742 * @brief The declared element type, published to the stream (§7.3).
6743 *
6744 * The §5.1/§7 over-index reject applies only to an element whose header
6745 * agrees with this — one that contradicts it is not this array's element at
6746 * all and is skipped like an unknown id, bound or no bound. The stream
6747 * picks these up exactly as it picks up @ref cap; they are compile-time
6748 * constants, so no constructor signature changes.
6749 */
6750 static constexpr int elemWire = static_cast<int>(detail::Wire::Fixlen);
6751 /** @copydoc elemWire */
6752 static constexpr int elemFix = static_cast<int>(detail::Fix::String);
6753
6754 /**
6755 * @param o Destination vector; elements are placed at their index id.
6756 * @param capacity Schema `count` N, or -1 for an unbounded array. An
6757 * element id at or past N is INVALID (§5.1/§7) once the
6758 * element has passed the §7.3 type test, rejected before
6759 * the container grows — which also bounds an over-index
6760 * allocation.
6761 * @param elemMax Element `maxlen`, or -1. A longer element is INVALID
6762 * (§7.1), never truncated.
6763 * @param indexCap The caller's `max_dyn_array_count` (@ref dynCap), or -1
6764 * when none was supplied — there is no fallback, so no
6765 * index cap then applies. An element id at or past it is
6766 * @ref Error::LimitExceeded, decided before the container
6767 * grows.
6768 * @param elemLenCap The caller's `max_dyn_string_len` / `max_dyn_blob_len`
6769 * for one element (@ref elemDynCap), or -1 when none was
6770 * supplied. Consulted only where @p elemMax is -1.
6771 */
6772 explicit StringSeq(C &o, long capacity, long elemMax,
6773 long indexCap, long elemLenCap) noexcept
6774 : out(o), cap(capacity), emax(elemMax), dynCap(indexCap),
6775 elemDynCap(elemLenCap) {}
6776
6777 /**
6778 * §7.4: the sequence IS the array's value, so a repeated field id replaces
6779 * it whole. @ref IStreamImpl::read calls this once the SequenceStart tag
6780 * matched, so a §7.3-skipped occurrence cannot wipe a valid earlier one.
6781 *
6782 * @warning It runs only when the wrapper sequence is **present**. Since
6783 * MESSAGE_SPEC §2 omits an all-default array field, an *absent*
6784 * field reaches no collector at all and @p out is left exactly as
6785 * it was — so a destination reused across messages must be reset
6786 * by its owner first (@ref IStreamObject::reset, §5.1 "supplying a
6787 * cleanly initialised destination is the application's
6788 * responsibility"). This is not the collector's call to make: it
6789 * never learns that the field was absent.
6790 */
6791 void prepare() noexcept { out.clear(); }
6792
6793 void deserialize(IStreamImpl &is, sofab::id id, size_t size, size_t) noexcept override
6794 {
6795 /* readString decides both, in the order §5.2 needs and before the
6796 * payload: the declared subtype (§7.3 -- a mis-typed element is not
6797 * this array's) and then the element maxlen (§7.1). The over-index
6798 * reject (§5.1) is enforced by the stream, from `cap` above, and only
6799 * on an element that passed the same §7.3 test first: at the fixlen
6800 * word, where the subtype is known. From that word on it is immediate,
6801 * so a truncated element still cannot outrun it -- only a message
6802 * ending between the element header and its fixlen word is INCOMPLETE
6803 * rather than INVALID, since there the subtype, and with it whether the
6804 * field is an element at all, is not yet decidable. */
6805 (void)size;
6806 /* Decide first, place second, read into the placed element last.
6807 *
6808 * A §7.3-skipped or §7.1-rejected element must leave the destination
6809 * untouched — growing the container for a field that is not an element
6810 * would change the array's length (§5.1, highest present id + 1) — so
6811 * both decisions are taken through @ref IStreamImpl::acceptsString,
6812 * before there is a destination at all. It is the same seam
6813 * @ref IStreamImpl::readString takes them at, in the same order, so the
6814 * §7.3 skip is counted exactly once.
6815 *
6816 * The element is then read **in place** rather than into a temporary
6817 * that is moved in. A payload split across chunks is written into the
6818 * caller's destination piece by piece (§6.6.2), and a temporary would
6819 * not survive the `feed` that carries the first half. */
6820 /* The element's own bound picks the entry point, exactly as it does
6821 * for a scalar field: the declared `maxlen` where the schema stated
6822 * one, the receiver cap where it did not. Never both (§6.2.1). */
6823 if (emax >= 0 ? !is.acceptsString(emax) : !is.acceptsStringCapped(elemDynCap))
6824 return;
6825 if (!detail::seqIndexAdmitted(is, id, cap, dynCap, elemDestCap)) return;
6826 while (out.size() <= static_cast<size_t>(id)) out.emplace_back();
6827 auto &slot = out[static_cast<size_t>(id)];
6828 if (emax >= 0) (void)sofab::readString(is, slot, emax);
6829 else (void)sofab::readStringCapped(is, slot, elemDynCap);
6830 }
6831 };
6832
6833 /**
6834 * The `blob` counterpart of @ref StringSeq; see it for the placement and bound
6835 * rules.
6836 *
6837 * @tparam C Destination container — `std::vector<std::vector<uint8_t>>` or
6838 * `InlineVector<FixedBytes<M>, N>`; deduced from the constructor.
6839 */
6840 template <typename C = std::vector<std::vector<uint8_t>>>
6842 {
6844 long cap;
6845 long emax;
6846 /** @copydoc StringSeq::dynCap */
6848 /** @copydoc StringSeq::elemDestCap */
6849 static constexpr long elemDestCap = detail::destCapacity<C>();
6850
6851 /** @copydoc StringSeq::elemWire */
6852 static constexpr int elemWire = static_cast<int>(detail::Wire::Fixlen);
6853 /** @copydoc StringSeq::elemWire */
6854 static constexpr int elemFix = static_cast<int>(detail::Fix::Blob);
6855
6856 /** @copydoc StringSeq::elemDynCap */
6858
6859 /** @copydoc StringSeq::StringSeq */
6860 explicit BlobSeq(C &o, long capacity, long elemMax,
6861 long indexCap, long elemLenCap) noexcept
6862 : out(o), cap(capacity), emax(elemMax), dynCap(indexCap),
6863 elemDynCap(elemLenCap) {}
6864
6865 /** @copydoc StringSeq::prepare */
6866 void prepare() noexcept { out.clear(); }
6867
6868 void deserialize(IStreamImpl &is, sofab::id id, size_t size, size_t) noexcept override
6869 {
6870 (void)size;
6871 /* Decide, place, read in place -- see StringSeq::deserialize. */
6872 /* @copydetails StringSeq::deserialize -- the element's own bound picks
6873 * the entry point. */
6874 if (emax >= 0 ? !is.acceptsBlob(emax) : !is.acceptsBlobCapped(elemDynCap))
6875 return; /* §7.3 + §7.1 + §6.2.1 */
6876 if (!detail::seqIndexAdmitted(is, id, cap, dynCap, elemDestCap)) return;
6877 while (out.size() <= static_cast<size_t>(id)) out.emplace_back();
6878 auto &slot = out[static_cast<size_t>(id)];
6879 if (emax >= 0) (void)sofab::readBlob(is, slot, emax);
6880 else (void)sofab::readBlobCapped(is, slot, elemDynCap);
6881 }
6882 };
6883
6884 namespace detail
6885 {
6886 /**
6887 * @brief Whether a @ref MessageSeq template argument names the destination
6888 * **container** rather than the element type.
6889 *
6890 * @ref MessageSeq is templated on the container, exactly as @ref StringSeq
6891 * is, which is what lets it collect into an @ref InlineVector as well as a
6892 * @c std::vector. It used to be templated on the ELEMENT, with
6893 * `std::vector<T>` hard-wired as the destination, and that spelling keeps
6894 * working: the two readings are told apart here, from the argument alone.
6895 *
6896 * An argument names a container when its `value_type` is something this
6897 * collector reads as an element — a message, or a row container. The two
6898 * readings can only collide for an argument whose `value_type` is itself
6899 * one of those two, i.e. an element that is a sequence of messages or a row
6900 * of rows; under the element reading such an element is handed to
6901 * @ref IStreamImpl::read, which has no overload for it, so what the
6902 * container reading takes over is code that never compiled.
6903 */
6904 template <typename A>
6905 constexpr bool namesSeqContainer() noexcept
6906 {
6907 if constexpr (requires { typename A::value_type; })
6908 {
6909 using V = typename A::value_type;
6910 return std::is_base_of_v<IStreamMessage, V> || requires { typename V::value_type; };
6911 }
6912 else
6913 {
6914 return false;
6915 }
6916 }
6917 } // namespace detail
6918
6919 /**
6920 * @brief Collects a struct/union or nested-array wrapper sequence into the
6921 * container it is handed.
6922 *
6923 * One element is placed and read per child: @ref IStreamImpl::read descends
6924 * into a struct/union element's own sub-sequence, and a native-scalar row goes
6925 * through @ref IStreamImpl::readArray — exactly as a top-level field of that
6926 * type would be read.
6927 *
6928 * The target is held by pointer rather than a bound reference so one instance
6929 * can serve several fields.
6930 *
6931 * @tparam A Destination **container**, as @ref StringSeq takes it:
6932 * `std::vector<T>` for the growable storage mode,
6933 * `InlineVector<T, N>` for the heap-free one; its `value_type` is the
6934 * element type. The older ELEMENT spelling `MessageSeq<T>`, which
6935 * always collected into a `std::vector<T>`, still compiles — see
6936 * @ref detail::namesSeqContainer for how the two are told apart.
6937 */
6938 template <typename A>
6940 {
6941 /** Destination container: @p A itself, or `std::vector<A>` for the element spelling. */
6942 using Container = std::conditional_t<detail::namesSeqContainer<A>(), A, std::vector<A>>;
6943 /** Element type — an @ref IStreamMessage, or a container for a nested-array row. */
6944 using Elem = typename Container::value_type;
6945
6946 Container *out = nullptr; /**< Destination; a null one collects nothing. */
6947
6948 /**
6949 * @brief Schema `count` N, or -1; an id at or past N is
6950 * @ref Error::InvalidMessage (§5.1/§7.1).
6951 *
6952 * It used to default to the destination's own capacity, which bounded a
6953 * heap-free container but reported the wrong category for it: a
6954 * destination too short is neither a malformed message nor a configured
6955 * limit. That bound now lives in @ref elemDestCap, in §6.3's third
6956 * category, and this member carries only what the **schema** said.
6957 */
6958 long cap = -1;
6959 /**
6960 * @copydoc StringSeq::dynCap
6961 *
6962 * @note This collector is an **aggregate** — callers fill it field by
6963 * field — so a member cannot be made mandatory the way
6964 * @ref StringSeq's constructor argument is. The sentinel is
6965 * therefore still spellable here, and it is **diagnosed** rather
6966 * than obeyed: an array with neither a schema `cap` nor a `dynCap`
6967 * nor a fixed-capacity destination is refused with
6968 * @ref Error::InvalidArgument at its first element
6969 * (@ref detail::seqIndexAdmitted). "No cap stated" is never read as
6970 * "unlimited" (§6.2.1).
6971 */
6972 long dynCap = -1;
6973 /**
6974 * @brief The ROW's schema `count` N, or -1 — the second axis of a native
6975 * nested row (`array<array<u32>>`), and the inner array's own §7.1
6976 * bound (corelib-cpp#124).
6977 *
6978 * A matrix has two axes and each needs its own pair of numbers. @ref cap /
6979 * @ref dynCap bound the row **id**, which is the outer array's length
6980 * (§5.1). These two bound the row's **element count**, which the row
6981 * announces as a real count header because a row IS a native array — and
6982 * that header is the enforcement point §6.2.1 names, "before the
6983 * allocation it is meant to prevent".
6984 *
6985 * Reusing @ref dynCap for the row was wrong in both directions. Where the
6986 * OUTER array carries a schema `count`, ARCHITECTURE §9.5 has generated
6987 * code state no receiver cap at all — caps govern only what the schema
6988 * left unbounded — so the row was read under `-1` and every row was
6989 * refused @ref Error::InvalidArgument. Where the outer array was
6990 * unbounded, a row past the inner `count:` was accepted under the OUTER
6991 * array's element cap, which is a §7.1 `INVALID` gone missing and, had it
6992 * fired, the wrong category for it.
6993 *
6994 * Set it when the schema declares the inner `count`; leave it -1 and set
6995 * @ref rowDynCap when it does not. Both -1 is refused, not obeyed, exactly
6996 * as on the id axis.
6997 */
6998 long rowCap = -1;
6999 /**
7000 * @brief The ROW's receiver cap (`max_dyn_array_count`), or -1 — the
7001 * row-axis twin of @ref dynCap.
7002 *
7003 * Consulted only where @ref rowCap is absent, and its breach is
7004 * @ref Error::LimitExceeded: the bytes are well-formed and the same row
7005 * decodes for a receiver configured with a larger cap (§6.2.1, §6.3). A
7006 * row the schema bounds answers to @ref rowCap alone — §6.2.1 forbids
7007 * applying a receiver cap to a field the schema already bounds.
7008 */
7009 long rowDynCap = -1;
7010 /** @copydoc StringSeq::elemDestCap */
7011 static constexpr long elemDestCap = detail::destCapacity<Container>();
7012
7013 /**
7014 * @brief The declared element type, published to the stream (§7.3), as
7015 * @ref StringSeq::elemWire is.
7016 *
7017 * A struct/union element arrives as a sequence; a nested-array row arrives
7018 * as the array wire type its element kind selects — the same choice
7019 * @ref IStreamImpl::read makes when it reads the row. `-1` for a row type
7020 * neither rule covers, which leaves the bound to the check below.
7021 */
7022 static constexpr int elemWire = []() constexpr -> int {
7023 if constexpr (std::is_base_of_v<IStreamMessage, Elem>)
7024 return static_cast<int>(detail::Wire::SequenceStart);
7025 else if constexpr (requires { typename Elem::value_type; })
7026 {
7027 using RowElem = typename Elem::value_type;
7028 /* A `bool` row lands in the unsigned arm: §4.4 lowers a boolean
7029 * onto the unsigned varint, and `std::is_unsigned_v<bool>` holds. */
7030 if constexpr (std::is_integral_v<RowElem>)
7031 return static_cast<int>(std::is_unsigned_v<RowElem> ? detail::Wire::ArrayUnsigned
7032 : detail::Wire::ArraySigned);
7033 else if constexpr (std::is_same_v<RowElem, float> || std::is_same_v<RowElem, double>)
7034 return static_cast<int>(detail::Wire::ArrayFixlen);
7035 else
7036 return -1;
7037 }
7038 else
7039 return -1;
7040 }();
7041
7042 /** §7.4 replace-whole, and absent ⇒ never called: @copydoc StringSeq::prepare */
7043 void prepare() noexcept { if (out) out->clear(); }
7044
7045 void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override
7046 {
7047 if (!out) return;
7048 /* §7.3 first, in the same order the stream uses, so the two entry points
7049 * cannot disagree: an element whose wire type contradicts @ref elemWire
7050 * is not this array's element at all. It is skipped like an unknown id,
7051 * which means the destination has to be left exactly as it was -- so the
7052 * decision comes before the placement below -- and an id that is not an
7053 * index cannot breach the index bound either. Coming through
7054 * @ref IStreamImpl::read the same test has already run one step earlier
7055 * whenever this collector publishes a bound; it is kept here because
7056 * `deserialize` is public and an unbounded array publishes none. */
7057 if constexpr (elemWire >= 0)
7058 {
7059 if (static_cast<int>(is.wire()) != elemWire) return; /* §7.3 */
7060 }
7061 /* §5.1/§6.2.1 over-index reject, decided from the id alone and before
7062 * the container grows, which is also what keeps an announced index from
7063 * becoming an allocation — and, for a fixed-capacity container, what
7064 * keeps the gap fill below terminating at all, its `emplace_back`
7065 * stopping at the capacity so `out->size()` would never reach the id.
7066 * Three bounds, three categories (§6.3). */
7067 if (!detail::seqIndexAdmitted(is, id, cap, dynCap, elemDestCap)) return;
7068 /* §5.1: the element id IS the array index, so an element is PLACED at
7069 * `dest[id]`, never appended. The ids may contain gaps -- a decoder
7070 * MUST accept them and recover a dynamic array's length as *highest
7071 * present id + 1*, leaving every absent id at the element default.
7072 * Appending instead would silently SHORTEN the array by the size of
7073 * the gap: wire `06 0005 07 16 0009 07` (elements at id 0 and id 2,
7074 * id 1 absent) is the 3-element array `[5, 0, 9]`, not `[5, 9]`.
7075 * Same placement rule as @ref StringSeq / @ref BlobSeq. */
7076 while (out->size() <= static_cast<size_t>(id)) (void)out->emplace_back();
7077 Elem &row = (*out)[static_cast<size_t>(id)];
7078 if constexpr (std::is_base_of_v<IStreamMessage, Elem>)
7079 {
7080 is.read(row); /* the element's own sub-sequence */
7081 }
7082 else if constexpr (requires { row.resize(size_t{}); })
7083 {
7084 /* A native-scalar row is sized by the wire count, and
7085 * @ref IStreamImpl::readArray is what owns that: it settles the
7086 * row's array tag, refuses a count the row cannot hold instead of
7087 * truncating into it (§3), and grows only as far as the bytes in
7088 * hand could ever fill -- so an announced count of 2^31 never
7089 * becomes an allocation. A bare `resize(count)` here got all three
7090 * wrong. A heap-free row's capacity IS the schema `count` it was
7091 * generated for, so it is passed as one and a row past it is the
7092 * INVALID of §7.1 rather than a receiver-side LimitExceeded. */
7093 if constexpr (detail::destCapacity<Elem>() >= 0)
7094 (void)sofab::readArray(is, row, detail::destCapacity<Elem>());
7095 else if (rowCap >= 0)
7096 /* A GROWABLE row has no capacity of its own to be bounded by,
7097 * so the row axis states its own bounds (@ref rowCap /
7098 * @ref rowDynCap, corelib-cpp#124). The schema `count` first:
7099 * a row past it contradicts the schema both peers agreed on,
7100 * which is §7.1's `INVALID`, and §6.2.1 forbids a receiver cap
7101 * on an axis the schema already bounds -- so @ref rowDynCap is
7102 * not consulted here even when it is set. */
7103 (void)sofab::readArray(is, row, rowCap);
7104 else
7105 /* Row unbounded by the schema: the receiver's own
7106 * `max_dyn_array_count`, whose breach is the POLICY category.
7107 * It is required, like every other cap here: a row read with
7108 * none answers @ref Error::InvalidArgument rather than letting
7109 * the wire count decide how long the row is (§6.2.1, "no unset
7110 * state and no unlimited mode"). */
7111 (void)sofab::readArrayCapped(is, row, rowDynCap);
7112 }
7113 else
7114 {
7115 /* A fixed-extent row (`std::array`, a bound span) publishes no
7116 * resize: read()'s low-level contract fills what it holds. */
7117 is.read(row);
7118 }
7119 }
7120 };
7121
7122 /**
7123 * @brief Collects a wrapper sequence whose elements are **rows the stream
7124 * cannot read on its own** — a row that is itself a wrapper sequence
7125 * (`array<array<string>>`, `array<array<struct>>`, deeper), or a row
7126 * that must bind through a view of its elements (an `enum` or
7127 * `boolean` row).
7128 *
7129 * @ref MessageSeq hands each element to @ref IStreamImpl::read, which reads
7130 * a message or a span of native scalars and nothing else. A row of strings
7131 * is neither, so its read has to be stated by the caller: that is
7132 * @p Reader, and it is the only part of a row collector that differs
7133 * between schemas. Everything else is the wrapper-array rule every collector
7134 * here applies, in the same order:
7135 *
7136 * 1. **§7.3 first.** An element whose wire type contradicts the row's is
7137 * not an element of this array at all. It is skipped like an unknown id,
7138 * before the index bound — so it cannot breach it — and before the
7139 * placement, so the destination is left exactly as it was. The row's wire
7140 * type is published as @ref elemWire, so the stream runs the same test
7141 * one step earlier, at the element header, and applies the bound only to
7142 * an element that survives it.
7143 * 2. **§5.1 index bound**, in §6.3's three categories
7144 * (@ref detail::seqIndexAdmitted): the schema `count` (`cap`,
7145 * `InvalidMessage`), else the receiver cap (`dynCap`, `LimitExceeded`),
7146 * and the destination's own capacity (@ref elemDestCap).
7147 * 3. **Placement.** The element id IS the index: the container is grown with
7148 * default rows up to it and the row is read in place at `dest[id]`.
7149 * 4. **§7.4.** A repeated field id replaces the array whole, via
7150 * @ref prepare.
7151 *
7152 * @tparam C Destination container of rows — `std::vector<Row>` or
7153 * `InlineVector<Row, N>`; deduced from the constructor.
7154 * @tparam Reader The row read, one level down. A default-constructible type
7155 * with
7156 * - `static constexpr detail::Wire wire()`, the wire type a
7157 * row of this schema arrives with — @c SequenceStart for a
7158 * row that is a wrapper sequence, the array wire type of the
7159 * backing integer for an enum or boolean row; and
7160 * - `void operator()(IStreamImpl &, typename C::value_type &)`,
7161 * reading the row that was placed.
7162 *
7163 * `wire()` is a function rather than a constant because a
7164 * local class — which is where generated code declares the
7165 * reader, next to the field it reads — may not have static
7166 * data members.
7167 *
7168 * @par Example
7169 * @code
7170 * // array<array<string>>: outer count 2, row count 3, element maxlen 8
7171 * struct Row {
7172 * static constexpr sofab::detail::Wire wire() noexcept { return sofab::detail::Wire::SequenceStart; }
7173 * void operator()(sofab::IStreamImpl &is, std::vector<std::string> &row) const noexcept {
7174 * sofab::StringSeq c{row, 3, 8, -1, -1}; sofab::read(is, c);
7175 * }
7176 * };
7177 * sofab::RowSeq c{grid, 2, -1, Row{}}; sofab::read(is, c);
7178 * @endcode
7179 */
7180 template <typename C, typename Reader>
7182 {
7183 /** Destination container. */
7184 using Container = C;
7185 /** Row type: the container's element. */
7186 using Elem = typename C::value_type;
7187
7189 /** Schema `count` N, or -1; an id at or past N is INVALID (§5.1/§7.1). */
7190 long cap;
7191 /** @copydoc StringSeq::dynCap */
7193 /** The row read (@p Reader). */
7194 [[no_unique_address]] Reader readRow;
7195
7196 /** @copydoc StringSeq::elemDestCap */
7197 static constexpr long elemDestCap = detail::destCapacity<C>();
7198
7199 /** @brief The row's wire type, published to the stream (§7.3), as
7200 * @ref StringSeq::elemWire is. */
7201 static constexpr int elemWire = static_cast<int>(Reader::wire());
7202
7203 /**
7204 * @param o Destination; rows are placed at their index id.
7205 * @param capacity Schema `count` N, or -1 for an unbounded array.
7206 * @param indexCap The caller's `max_dyn_array_count` (@ref dynCap), or -1
7207 * when none was supplied. Mandatory, as on @ref StringSeq:
7208 * a schema-unbounded growable array with neither is
7209 * refused with @ref Error::InvalidArgument, never read as
7210 * unlimited (§6.2.1).
7211 * @param reader The row read.
7212 */
7213 explicit RowSeq(C &o, long capacity, long indexCap, Reader reader = {}) noexcept
7214 : out(o), cap(capacity), dynCap(indexCap), readRow(reader) {}
7215
7216 /** §7.4 replace-whole, and absent ⇒ never called: @copydoc StringSeq::prepare */
7217 void prepare() noexcept { out.clear(); }
7218
7219 void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override
7220 {
7221 /* Decide, place, read in place -- see MessageSeq::deserialize. The
7222 * §7.3 test is repeated here although the stream has already run it
7223 * for a bounded array: `deserialize` is public, and an unbounded array
7224 * publishes no bound for the stream to key on. */
7225 if (static_cast<int>(is.wire()) != elemWire) return; /* §7.3 */
7226 if (!detail::seqIndexAdmitted(is, id, cap, dynCap, elemDestCap)) return;
7227 while (out.size() <= static_cast<size_t>(id)) (void)out.emplace_back();
7228 readRow(is, out[static_cast<size_t>(id)]);
7229 }
7230 };
7231
7232 /* No encode-side trailing-default trim helper lives here, deliberately.
7233 *
7234 * A `trimTail` used to, narrowing a container to its non-default prefix
7235 * before encode — the fill-to-`N` reading of MESSAGE_SPEC §3 that
7236 * count-is-capacity superseded. Under the rule as it stands, a `count: N` is
7237 * a capacity and the wire count `M` IS the array's length, so §3 states the
7238 * opposite: "A default-valued element stays on the wire, trailing ones
7239 * included — `M` is the length, so eliding one would shorten the array:
7240 * `[1, 2, 3, 0, 0]` and `[1, 2, 3]` are different values and encode
7241 * differently (`M = 5` and `M = 3`)." Trimming was therefore not a size
7242 * optimization but silent data loss, and @ref OStreamImpl::write emitting the
7243 * whole container it is handed is exactly right. The shared vector
7244 * `array_unsigned_trailing_defaults` and trailingDefaultsStayOnTheWire() in
7245 * test/test_roundtrip.cpp pin this; the latter also fails if such a helper is
7246 * ever reintroduced into this namespace. */
7247
7248} // namespace sofab
7249
7250/** @} */ // end of defgroup
7251
7252#endif // SOFAB_HPP
Bit-pattern equality for float arrays (sofab::bitsEqual).
Fixed-capacity, heap-free byte blob of up to N bytes.
Definition sofab.hpp:1006
bool empty() const noexcept
True if the blob is empty.
Definition sofab.hpp:1063
void set_len(std::size_t n) noexcept
Decode hook: set the logical length (clamped to N).
Definition sofab.hpp:1078
std::size_t size_type
Size type (mirrors std::vector).
Definition sofab.hpp:1014
std::size_t size() const noexcept
Number of bytes currently stored.
Definition sofab.hpp:1061
void clear() noexcept
Reset to an empty blob.
Definition sofab.hpp:1081
static constexpr std::size_t capacity() noexcept
Maximum number of bytes (the template parameter N).
Definition sofab.hpp:1065
std::uint8_t value_type
Element type (mirrors std::vector).
Definition sofab.hpp:1012
const std::uint8_t * end() const noexcept
Const iterator past the last byte.
Definition sofab.hpp:1104
bool operator!=(const FixedBytes &o) const noexcept
Negated operator==.
Definition sofab.hpp:1124
bool operator==(const FixedBytes &o) const noexcept
Content equality (same logical length and bytes).
Definition sofab.hpp:1107
const std::uint8_t * begin() const noexcept
Const iterator to the first byte.
Definition sofab.hpp:1102
FixedBytes & operator=(std::initializer_list< std::uint8_t > init) noexcept
Replace the contents from a brace-enclosed list (clamped to N; extra bytes are dropped).
Definition sofab.hpp:1035
const std::uint8_t & operator[](std::size_t i) const noexcept
Access the byte at i (no bounds checking).
Definition sofab.hpp:1095
void push_back(std::uint8_t b) noexcept
Append one byte (no-op once at capacity N).
Definition sofab.hpp:1084
static constexpr std::size_t max_size() noexcept
Alias of capacity.
Definition sofab.hpp:1067
std::uint8_t * end() noexcept
Iterator past the last byte.
Definition sofab.hpp:1100
FixedBytes() noexcept=default
Construct an empty blob.
const std::uint8_t * data() const noexcept
Const pointer to the byte buffer.
Definition sofab.hpp:1058
std::uint8_t & operator[](std::size_t i) noexcept
Access the byte at i (no bounds checking).
Definition sofab.hpp:1093
FixedBytes & assign(std::initializer_list< std::uint8_t > init) noexcept
Replace the contents from a brace-enclosed list (clamped to N; extra bytes are dropped).
Definition sofab.hpp:1041
std::uint8_t * begin() noexcept
Iterator to the first byte.
Definition sofab.hpp:1098
std::uint8_t * data() noexcept
Mutable pointer to the byte buffer (decode target).
Definition sofab.hpp:1056
Fixed-capacity, heap-free string of up to N characters.
Definition sofab.hpp:800
char * end() noexcept
Iterator past the last character.
Definition sofab.hpp:929
bool operator!=(std::string_view rhs) const noexcept
Inequality against any string view-like operand.
Definition sofab.hpp:972
const char * end() const noexcept
Const iterator past the last character.
Definition sofab.hpp:933
FixedString & operator=(const char *s) noexcept
Assign from a NUL-terminated C string (clamped to N, see assign).
Definition sofab.hpp:841
static constexpr std::size_t max_size() noexcept
Alias of capacity.
Definition sofab.hpp:919
void clear() noexcept
Reset to an empty string.
Definition sofab.hpp:936
std::string_view view() const noexcept
Non-owning view over the current characters.
Definition sofab.hpp:943
const char * data() const noexcept
Const pointer to the character buffer.
Definition sofab.hpp:906
FixedString(const std::string &s) noexcept
Construct from a std::string (the easy on-ramp; truncated to N).
Definition sofab.hpp:835
char & operator[](std::size_t i) noexcept
Access the character at i (no bounds checking).
Definition sofab.hpp:922
const char * c_str() const noexcept
NUL-terminated view of the contents.
Definition sofab.hpp:908
const char * begin() const noexcept
Const iterator to the first character.
Definition sofab.hpp:931
char * begin() noexcept
Iterator to the first character.
Definition sofab.hpp:927
FixedString & assign(std::string_view sv) noexcept
Replace the contents with sv, clamped to N bytes.
Definition sofab.hpp:874
FixedString & operator=(std::string_view sv) noexcept
Assign from a string view (clamped to N, see assign).
Definition sofab.hpp:848
std::string str() const
Copy the contents into an owning std::string (allocates).
Definition sofab.hpp:960
const char & operator[](std::size_t i) const noexcept
Access the character at i (no bounds checking).
Definition sofab.hpp:924
FixedString(std::string_view sv) noexcept
Construct from a string view (clamped to N, see assign).
Definition sofab.hpp:826
bool empty() const noexcept
True if the string is empty.
Definition sofab.hpp:915
static constexpr std::size_t capacity() noexcept
Maximum number of characters (the template parameter N).
Definition sofab.hpp:917
char * data() noexcept
Mutable pointer to the character buffer (decode target).
Definition sofab.hpp:904
std::size_t length() const noexcept
Alias of size.
Definition sofab.hpp:913
std::size_t size() const noexcept
Number of characters currently stored.
Definition sofab.hpp:911
char value_type
Character type (mirrors std::string).
Definition sofab.hpp:806
bool operator==(std::string_view rhs) const noexcept
Equality against any string view-like operand.
Definition sofab.hpp:966
std::size_t size_type
Size type (mirrors std::string).
Definition sofab.hpp:808
void set_len(std::size_t n) noexcept
Decode hook: set the logical length and (re)place the trailing NUL.
Definition sofab.hpp:897
FixedString() noexcept=default
Construct an empty string.
FixedString & operator=(const std::string &s) noexcept
Assign from a std::string (clamped to N, see assign).
Definition sofab.hpp:855
Three-valued outcome of a feed call (spec §7).
Definition sofab.hpp:2937
bool ok() const noexcept
Definition sofab.hpp:2954
bool invalid() const noexcept
Definition sofab.hpp:2991
bool operator==(Error e) const noexcept
Definition sofab.hpp:3003
bool incomplete() const noexcept
Definition sofab.hpp:2986
bool operator!=(Error e) const noexcept
Definition sofab.hpp:3005
bool invalidArgument() const noexcept
Definition sofab.hpp:2999
Error code() const noexcept
Definition sofab.hpp:3001
DecodeStatus status() const noexcept
Definition sofab.hpp:2972
bool complete() const noexcept
Definition sofab.hpp:2984
bool limitExceeded() const noexcept
Definition sofab.hpp:2993
size_t skipped() const noexcept
Definition sofab.hpp:2950
Base of the input streams: decodes fields from fed bytes.
Definition sofab.hpp:2919
bool readIntElements(std::span< Elem > sp, ElemBound b={}) noexcept
Decode the current integer-array payload: count_ varint elements, the first sp.size() of them into sp...
Definition sofab.hpp:5018
void discountSkipped(const uint8_t *from) noexcept
Discount a skipped field's bytes from the live span (§6.2.1).
Definition sofab.hpp:4601
Wire pendType_
That field's header, kept apart from the live type_ / fixLen_ / count_.
Definition sofab.hpp:3082
size_t maxBufferedField_
The receiver's byte budget for one top-level field (Limits::max_buffered_field), as this decode was t...
Definition sofab.hpp:3221
bool capCannotFire(size_t n) const noexcept
Hoisted form of exceedsBuffer for a whole window of n bytes: true when no field of it can cross the b...
Definition sofab.hpp:3677
size_t skipped() const noexcept
Number of fields skipped this stream because their wire tag contradicted the type the callback asked ...
Definition sofab.hpp:5170
size_t spanned() const noexcept
The bytes of the current top-level field seen so far, across every chunk it spans (#26,...
Definition sofab.hpp:4580
bool capInert_
Can the field-span cap provably not fire anywhere in the window being parsed (§6.2....
Definition sofab.hpp:3123
bool readPayload(D &value, bool validateUtf8) noexcept
Deliver the current fixlen payload into the destination the caller handed over (§6....
Definition sofab.hpp:3566
size_t available() const noexcept
Bytes of this field readable right now, in the chunk being parsed.
Definition sofab.hpp:5999
uint8_t carry_[CARRY_CAP]
The prefix of one cut item, carried to the next feed.
Definition sofab.hpp:3040
void invalidate() noexcept
Mark the running decode INVALID from inside a deliver callback.
Definition sofab.hpp:4470
static FieldCb wrapCb(Cb &cb) noexcept
Wrap a level's callback as a FieldCb.
Definition sofab.hpp:3747
static constexpr bool schemaBoundsHeader(Wire w) noexcept
Does this wire type's header state a size the schema can bound?
Definition sofab.hpp:4966
size_t pendDone_
Progress through the pending field: payload bytes already written into the caller's destination,...
Definition sofab.hpp:3092
int suspendDepth_
Depth at which the parse is suspended, or -1 when nothing is.
Definition sofab.hpp:3052
Fix fixType_
Sub-type of the current fixlen field.
Definition sofab.hpp:3147
bool error_
Sticky "this feed was refused" flag, and the only one the parse loops test.
Definition sofab.hpp:3162
Result latchTerminal() noexcept
Latch the refusal this feed produced, in §6.3's order of tiers.
Definition sofab.hpp:4607
size_t parseWindow(const uint8_t *p, size_t n) noexcept
Parse one window of bytes, resuming whatever the last one left open, and report how much of it was co...
Definition sofab.hpp:4644
std::function< void(sofab::id, size_t, size_t)> topCallback_
Delivers each top-level field.
Definition sofab.hpp:3223
bool acceptsBlobGated(long bound, long dynCap) noexcept
The body both blob accepts share.
Definition sofab.hpp:6109
bool reenterLevel(FieldCb cb, Entry entry) noexcept
Take the Entry::Descend or Entry::Resume path.
Definition sofab.hpp:3985
int seqDepth_
Current nested-sequence depth during dispatch (§4.9 MAX_DEPTH).
Definition sofab.hpp:3193
bool readStringCapped(S &value, long dynCap, Sizer sizer={}) noexcept
Read the current field as a schema-**unbounded** string under the receiver's max_dyn_string_len (§6....
Definition sofab.hpp:5548
bool deliverPending(FieldCb cb, bool declined) noexcept
Re-deliver the half-delivered field at this level.
Definition sofab.hpp:4061
const uint8_t * p_
Read cursor.
Definition sofab.hpp:3144
bool acceptsString(long bound) noexcept
The §7.3 and §7.1 decisions readString makes, taken before a destination exists.
Definition sofab.hpp:6063
void skipPayload() noexcept
Step over the payload of the current field, resumably.
Definition sofab.hpp:4150
size_t fixLen_
Payload length (fixlen) or element size (fixlen array), in bytes.
Definition sofab.hpp:3148
const uint8_t * spanBase_
Where that field's span continues in the window being parsed (#26).
Definition sofab.hpp:3098
bool parseFieldMeta() noexcept
Parse the word(s) between a field header and its payload — the fixlen word (§4.6),...
Definition sofab.hpp:4847
void suspendAtBoundary() noexcept
Claim the suspension for this level at a field boundary — nothing half-delivered, only a header cut i...
Definition sofab.hpp:4032
Wire wire() const noexcept
Wire type of the field currently being delivered.
Definition sofab.hpp:5962
long elemDyn_
Configured max_dyn_array_count: LimitExceeded (§6.2.1).
Definition sofab.hpp:3207
IStreamImpl & operator=(const IStreamImpl &)=delete
bool read(T &value) noexcept
Read the current field's value, dispatching on value's type.
Definition sofab.hpp:5193
size_t announcedCount() const noexcept
The element count the current array field's header announces.
Definition sofab.hpp:5990
void stash(const uint8_t *p, size_t n) noexcept
Hold the ≤ CARRY_CAP bytes of a cut item until the next feed.
Definition sofab.hpp:4619
size_t carryLen_
Live bytes of carry_.
Definition sofab.hpp:3041
size_t progress() const noexcept
How much of the current field earlier chunks already delivered — payload bytes written,...
Definition sofab.hpp:6014
void restorePending() noexcept
Put the suspended field's header back before continuing it.
Definition sofab.hpp:4041
sofab::id pathId_[MAX_DEPTH+1]
Id of the sequence field entered at each open level (§4.9).
Definition sofab.hpp:3065
bool descendResume(FieldCb cb) noexcept
Re-descend one recorded level of pathId_ towards suspendDepth_.
Definition sofab.hpp:4103
void rejectElementIndex(sofab::id bad) noexcept
Refuse a wrapper-array element whose index is at or past a bound, in the category §6....
Definition sofab.hpp:4537
void skipSequence() noexcept
Walk a sub-sequence nobody asked for, delivering nothing.
Definition sofab.hpp:4249
bool resumed() const noexcept
true when this delivery re-enters a sequence an earlier feed left open, rather than announcing a new ...
Definition sofab.hpp:6036
bool acceptsStringCapped(long dynCap) noexcept
acceptsString for a schema-unbounded element, under the receiver's max_dyn_string_len (§6....
Definition sofab.hpp:6074
bool pend_
A field at suspendDepth_ is half-delivered.
Definition sofab.hpp:3069
size_t spanCarry_
Bytes of the current top-level field consumed in earlier chunks (#26).
Definition sofab.hpp:3096
long elemDest_
The destination container's own capacity: InvalidArgument (§6.6.3).
Definition sofab.hpp:3208
bool readStringGated(S &value, long bound, long dynCap, Sizer sizer) noexcept
The body both string reads share, so the two cannot answer differently.
Definition sofab.hpp:5565
bool readBlob(B &value, long bound, Sizer sizer={}) noexcept
Read the current field as a blob, or skip it (§7.3).
Definition sofab.hpp:5612
Result feed(const uint8_t *buffer, size_t buflen) noexcept
Feed bytes into the decoder, delivering every complete top-level field.
Definition sofab.hpp:4331
Wire type_
Wire type of the field being delivered.
Definition sofab.hpp:3146
bool consumed_
Set once the callback has read the current field's value.
Definition sofab.hpp:3150
void dispatchLevel(Cb &&cb, bool stopAtEnd) noexcept
Definition sofab.hpp:3779
Entry
How a level is being entered (see levelEntry).
Definition sofab.hpp:3756
@ Descend
The suspended level is deeper: replay one more id.
@ Resume
This level is it: continue its half-delivered field.
@ Fresh
Nothing open here: parse the next field.
bool acceptsStringGated(long bound, long dynCap) noexcept
The body both string accepts share.
Definition sofab.hpp:6082
bool exceedsBufferAtHeader() noexcept
Would this field cross maxBufferedField_, judged from its header alone (#26)?
Definition sofab.hpp:4983
bool readArrayCapped(T &dst, long dynCap, ElemBound elem={}, Sizer sizer={}) noexcept
Read a schema-**unbounded** count-prefixed array under the receiver's max_dyn_array_count (§6....
Definition sofab.hpp:5741
Field
What beginField found at this level's next field.
Definition sofab.hpp:3816
@ Stop
The level is finished, suspended or refused.
@ SkipElem
§7.3 says it is not this array's element: skip, do not deliver.
void parseTopLevel() noexcept
Deliver every complete top-level field in the current window, leaving p_ at the first byte not consum...
Definition sofab.hpp:4667
bool tagMatches(Wire wantWire, Fix wantFix) noexcept
Definition sofab.hpp:3520
bool parseFieldTag() noexcept
Parse a field header word into fieldId_ and type_ (§4.3).
Definition sofab.hpp:4813
bool limitExceeded_
Category: a receiver-side limit was crossed (§6.2.1).
Definition sofab.hpp:3163
static bool skipVarint(const uint8_t *&p, const uint8_t *end, bool *overflow=nullptr) noexcept
Advance the cursor past one varint without decoding it (bounds-checked).
Definition sofab.hpp:3409
Fix fixType() const noexcept
Fixlen sub-type of the field currently being delivered.
Definition sofab.hpp:5973
void suspendHere(sofab::id fieldId, bool declined) noexcept
Record that this level's current field is the suspension point.
Definition sofab.hpp:4003
bool parseFieldHeader() noexcept
Parse one top-level field header plus the metadata that precedes its payload, into the current-field ...
Definition sofab.hpp:4943
void rejectUnbounded() noexcept
Refuse the current field because the call stated no bound for it at all (§6.3's InvalidArgument).
Definition sofab.hpp:4520
static bool getVarint(const uint8_t *&p, const uint8_t *end, uint64_t &out, bool *overflow=nullptr) noexcept
Read one base-128 varint, advancing the cursor (bounds-checked).
Definition sofab.hpp:3356
bool replay_
Re-descending pathId_ to reach suspendDepth_.
Definition sofab.hpp:3054
static bool arrayFixlenWordValid(uint64_t word) noexcept
Validate a ArrayFixlen element word (§4.8, §6.2).
Definition sofab.hpp:3463
void rejectDestination() noexcept
Refuse the current field because the caller's destination is too short for it (§6....
Definition sofab.hpp:4501
bool spanSkip_
Is the parse currently inside a skipped sequence subtree (§6.2.1, #129)?
Definition sofab.hpp:3109
size_t spanSkipped_
Bytes of the current top-level field spent on SKIPPED subtrees (§6.2.1, #129 one level down).
Definition sofab.hpp:3141
size_t pendCount_
That field's header, kept apart from the live type_ / fixLen_ / count_.
Definition sofab.hpp:3085
bool readString(S &value, long bound, Sizer sizer={}) noexcept
Read the current field as a string, or skip it (§7.3).
Definition sofab.hpp:5520
size_t announcedSize() const noexcept
The payload length the current field's header announces — a string/blob byte count,...
Definition sofab.hpp:5984
bool acceptsBlobCapped(long dynCap) noexcept
acceptsString for a schema-unbounded element, under the receiver's max_dyn_string_len (§6....
Definition sofab.hpp:6101
bool readBlobCapped(B &value, long dynCap, Sizer sizer={}) noexcept
Read the current field as a schema-**unbounded** blob under the receiver's max_dyn_blob_len (§6....
Definition sofab.hpp:5634
const uint8_t * end_
One past the last readable byte.
Definition sofab.hpp:3145
virtual void reset() noexcept
Drop every byte of decoder state, so the next feed starts a brand-new message.
Definition sofab.hpp:4424
IStreamImpl(const IStreamImpl &)=delete
bool argError_
Category: a well-formed value did not fit the destination the caller handed over (§6....
Definition sofab.hpp:3173
bool pendSkip_
...and it was declined, so skipPayload resumes it rather than the handler.
Definition sofab.hpp:3087
bool readArrayGated(T &dst, long schemaCount, long dynCap, ElemBound elem, Sizer sizer) noexcept
The body both array reads share.
Definition sofab.hpp:5750
size_t spannedLive() const noexcept
spanned less what this field spent on skipped subtrees — the number the field-span cap is measured ag...
Definition sofab.hpp:4594
bool exceedsBuffer(size_t consumed, uint64_t need) const noexcept
Would buffering this field cross maxBufferedField_?
Definition sofab.hpp:3696
static bool getVarintWindowed(const uint8_t *&p, uint64_t &out, bool *overflow) noexcept
Read one varint, given that a full varint window is in the buffer.
Definition sofab.hpp:3260
bool finishField(const uint8_t *fieldStart, const uint8_t *payload, sofab::id fieldId) noexcept
Settle a field the callback has been offered: skip it if the callback did not want it,...
Definition sofab.hpp:3950
bool readPayloadPiece(D &value, bool validateUtf8, size_t avail) noexcept
The chunk-straddling half of readPayload — deliver the piece that has arrived and remember how far th...
Definition sofab.hpp:3636
bool incomplete_
The field being delivered needs more bytes (§7 INCOMPLETE, not malformed).
Definition sofab.hpp:3195
Entry levelEntry() noexcept
Decide how this level is being entered, and clear the replay state once the suspended level is reache...
Definition sofab.hpp:3769
bool readBlobGated(B &value, long bound, long dynCap, Sizer sizer) noexcept
The body both blob reads share.
Definition sofab.hpp:5643
bool acceptsBlob(long bound) noexcept
The §7.3 and §7.1 decisions readString makes, taken before a destination exists.
Definition sofab.hpp:6094
uint32_t utf8State_
Incremental UTF-8 DFA state for the string payload in progress (§6.4.4).
Definition sofab.hpp:3094
bool readArray(T &dst, long schemaCount, ElemBound elem={}, Sizer sizer={}) noexcept
Read a count-prefixed native array, applying every receiver-side decision at the one word that decide...
Definition sofab.hpp:5719
size_t skipped_
§7.3 type-mismatch skips seen so far (skipped).
Definition sofab.hpp:3194
static bool fixlenWordValid(uint64_t word) noexcept
Validate a single Fixlen field's length-and-subtype word (§4.6, §6.2).
Definition sofab.hpp:3439
Fix pendFix_
That field's header, kept apart from the live type_ / fixLen_ / count_.
Definition sofab.hpp:3083
void closeLevel(bool stopAtEnd) noexcept
The bytes ran out with this sequence still open — INCOMPLETE, not malformed (§7).
Definition sofab.hpp:3975
bool pathSkip_[MAX_DEPTH+1]
That level was entered by skipPayload, not by a handler.
Definition sofab.hpp:3067
int elemFix_
§7.3 fixlen subtype for that element type (a Fix as int); -1 = the element type has none.
Definition sofab.hpp:3210
IStreamImpl(Limits limits) noexcept
Construct with the receiver's Limits; a derived class installs topCallback_.
Definition sofab.hpp:3234
sofab::id fieldId_
Id of the field being delivered.
Definition sofab.hpp:3211
static bool skipVarintWindowed(const uint8_t *&p, bool *overflow) noexcept
getVarintWindowed without building the value — see skipVarint.
Definition sofab.hpp:3316
static constexpr size_t CARRY_CAP
Widest prefix of a wire item that can outlive a chunk boundary, derived from this format's own consta...
Definition sofab.hpp:3027
Error terminal_
The stream's latched terminal verdict, or Error::None while the stream is still usable (§5....
Definition sofab.hpp:3192
size_t read(void *dst, size_t maxlen) noexcept
Read the current blob field into a caller buffer.
Definition sofab.hpp:5911
void exceedLimit() noexcept
Report a receiver-side decode-limit violation from inside a deliver callback.
Definition sofab.hpp:4486
long elemSchema_
Schema count N: an id at or past it is InvalidMessage (§7.1).
Definition sofab.hpp:3206
size_t pendLen_
That field's header, kept apart from the live type_ / fixLen_ / count_.
Definition sofab.hpp:3084
bool tagMatches(Wire wantWire) noexcept
The §7.3 seam: does the delivered field's wire tag match the one the caller's read declares?
Definition sofab.hpp:3513
bool roomFor(D &value, size_t need) noexcept
Is there room for need bytes in the destination the caller handed over (§6.6.3)?
Definition sofab.hpp:3612
Field beginField(bool stopAtEnd) noexcept
Parse the next field's header and metadata at a nested level, and apply every rule that is decided be...
Definition sofab.hpp:3835
static constexpr uint64_t CAP_NEED_MAX
Upper bound of any header-declared need (§6.2 ceilings).
Definition sofab.hpp:3670
int elemWire_
§7.3 wire type its elements must carry (a Wire as int); -1 = the collector decides the bound itself.
Definition sofab.hpp:3209
sofab::id pendId_
That field's header, kept apart from the live type_ / fixLen_ / count_.
Definition sofab.hpp:3081
static F loadFloat(const uint8_t *p) noexcept
Load a little-endian float or double from raw bytes.
Definition sofab.hpp:3481
IStreamImpl(IStreamImpl &&) noexcept=default
size_t count_
Element count of the current array field.
Definition sofab.hpp:3149
long elemBound_
The tightest armed element-index bound of the wrapper sequence being read (§5.1); -1 = none.
Definition sofab.hpp:3205
bool tagMatches(Wire wantWire, Fix wantFix, Fix wantFix2) noexcept
Definition sofab.hpp:3529
bool consumed() const noexcept
Definition sofab.hpp:5948
Input stream that delivers each top-level field to a user callback.
Definition sofab.hpp:6127
IStreamInline(fieldCallback callback, Limits limits) noexcept
Construct with the per-field callback and the receiver's decode limits.
Definition sofab.hpp:6139
std::function< void(sofab::id, size_t, size_t)> fieldCallback
Callback type invoked per top-level field as (fieldId, size, count).
Definition sofab.hpp:6130
Decoder that decodes into a message instance the CALLER owns.
Definition sofab.hpp:6304
IStreamInto(MessageType &message, Limits limits) noexcept
Bind message and route each top-level field into it.
Definition sofab.hpp:6314
Base class for user-defined messages that can deserialise themselves.
Definition sofab.hpp:6154
virtual void deserialize(IStreamImpl &istream, sofab::id id, size_t size, size_t count) noexcept=0
Consume one of this message's fields from istream.
virtual ~IStreamMessage()=default
Holds a message and routes decoded top-level fields into it.
Definition sofab.hpp:6221
IStreamObject(Limits limits) noexcept
Construct and route each top-level field into the wrapped message.
Definition sofab.hpp:6230
MessageType & operator*() noexcept
Definition sofab.hpp:6262
MessageType & operator->() noexcept
Definition sofab.hpp:6258
void reset() noexcept override
Reset the decoder and the wrapped message, ready for the next message.
Definition sofab.hpp:6250
const MessageType & operator->() const noexcept
Definition sofab.hpp:6260
const MessageType & operator*() const noexcept
Definition sofab.hpp:6264
Fixed-capacity, heap-free sequence of up to N elements of type T.
Definition sofab.hpp:1159
void push_back(T &&v) noexcept
Append v by move; dropped once at capacity N (see above).
Definition sofab.hpp:1284
InlineVector & operator=(std::initializer_list< T > init) noexcept
Replace the contents from a brace-enclosed list (clamped to N; extra elements are dropped).
Definition sofab.hpp:1187
static constexpr std::size_t capacity() noexcept
Maximum number of elements (the template parameter N).
Definition sofab.hpp:1212
std::size_t size_type
Size type (mirrors std::vector).
Definition sofab.hpp:1167
void push_back(const T &v) noexcept
Append a copy of v; once at capacity N, v is dropped.
Definition sofab.hpp:1282
T & operator[](std::size_t i) noexcept
Access the element at i (no bounds checking).
Definition sofab.hpp:1292
const T * begin() const noexcept
Const iterator to the first element.
Definition sofab.hpp:1306
bool empty() const noexcept
True if the sequence is empty.
Definition sofab.hpp:1210
T value_type
Element type (mirrors std::vector).
Definition sofab.hpp:1165
T * begin() noexcept
Iterator to the first element.
Definition sofab.hpp:1302
const T & back() const noexcept
Const reference to the last element.
Definition sofab.hpp:1289
void reserve(std::size_t) noexcept
No-op (inline storage never reallocates); present for API parity.
Definition sofab.hpp:1217
bool operator==(const InlineVector &o) const noexcept
Content equality (same logical length and elements).
Definition sofab.hpp:1311
void resize(std::size_t n) noexcept
Set the logical length to n, value-initializing what changes.
Definition sofab.hpp:1243
InlineVector() noexcept=default
Construct an empty sequence.
T & back() noexcept
Reference to the last element.
Definition sofab.hpp:1287
static constexpr std::size_t max_size() noexcept
Alias of capacity.
Definition sofab.hpp:1214
void clear() noexcept
Reset to an empty sequence (logical length only).
Definition sofab.hpp:1219
const T * data() const noexcept
Const pointer to the underlying storage.
Definition sofab.hpp:1299
const T & operator[](std::size_t i) const noexcept
Access the element at i (no bounds checking).
Definition sofab.hpp:1294
bool operator!=(const InlineVector &o) const noexcept
Negated operator==.
Definition sofab.hpp:1328
const T * end() const noexcept
Const iterator past the last element.
Definition sofab.hpp:1308
T & emplace_back() noexcept
Append a default-constructed element and return a reference to it.
Definition sofab.hpp:1267
T * end() noexcept
Iterator past the last element.
Definition sofab.hpp:1304
T * data() noexcept
Mutable pointer to the underlying storage.
Definition sofab.hpp:1297
std::size_t size() const noexcept
Number of elements currently stored.
Definition sofab.hpp:1208
InlineVector & assign(std::initializer_list< T > init) noexcept
Replace the contents from a brace-enclosed list (clamped to N; extra elements are dropped).
Definition sofab.hpp:1193
The held-back sequence run: ids of the innermost open sequences whose header has not been written yet...
Definition sofab.hpp:1394
void clear() noexcept
Forget the whole run (it has just been written out).
Definition sofab.hpp:1435
sofab::id operator[](size_t i) const noexcept
Definition sofab.hpp:1411
void pop() noexcept
Drop the innermost held-back id — its sequence got no content.
Definition sofab.hpp:1429
bool empty() const noexcept
Definition sofab.hpp:1407
size_t size() const noexcept
Definition sofab.hpp:1409
bool push(sofab::id v) noexcept
Hold back one more id (the new innermost open sequence).
Definition sofab.hpp:1422
Chainable result of a write operation.
Definition sofab.hpp:2031
Result sequenceEndKeep() noexcept
Chain a frame-keeping close (OStreamImpl::sequenceEndKeep).
Definition sofab.hpp:2082
Result write(sofab::id fieldId, const T &value) noexcept
Chain another field write onto the same stream.
Definition sofab.hpp:2046
Result writeIf(sofab::id fieldId, const T &value, bool condition) noexcept
Chain a field write that only happens when condition holds.
Definition sofab.hpp:2060
bool operator==(Error e) const noexcept
Definition sofab.hpp:2115
Result sequenceEnd() noexcept
Chain the closing of the current nested sub-message.
Definition sofab.hpp:2103
Result sequenceBeginLazy(sofab::id fieldId) noexcept
Chain the opening of a nested sub-message that is framed only if it turns out to have content (OStrea...
Definition sofab.hpp:2094
bool operator!=(Error e) const noexcept
Definition sofab.hpp:2117
Result writeLazy(sofab::id fieldId, const T &value) noexcept
Chain a nested-message field write that is omitted when the message is all-default (OStreamImpl::writ...
Definition sofab.hpp:2073
Error code() const noexcept
Definition sofab.hpp:2113
bool ok() const noexcept
Definition sofab.hpp:2111
Base of the output streams: encodes values into a caller-provided buffer.
Definition sofab.hpp:1349
OStreamImpl() noexcept=default
Construct an unattached stream; a derived class must call initBuffer.
Result write(sofab::id fieldId, const void *value, int32_t size) noexcept
Write a raw byte blob field.
Definition sofab.hpp:2359
Error commitPending() noexcept
Write out the held-back sequence headers, outermost first.
Definition sofab.hpp:1708
Error error() const noexcept
The code behind ok, latched first-failure-wins.
Definition sofab.hpp:2199
Result sequenceEnd() noexcept
Close the most recently opened sub-message, letting it vanish if it received no content.
Definition sofab.hpp:2439
Result writeIf(sofab::id fieldId, const T &value, bool condition) noexcept
Write a field only when condition holds.
Definition sofab.hpp:2375
Error writeIntArray(sofab::id fieldId, std::span< const E > elems) noexcept
Write an array of integers as a count-prefixed run of varints.
Definition sofab.hpp:1885
bool installed_
Set by initBuffer, cleared right before a flush callback runs.
Definition sofab.hpp:1472
Error latch(Error e) noexcept
Record a failure in the sticky verdict and hand it straight back.
Definition sofab.hpp:1495
Result rejectArgument() noexcept
Refuse the value being encoded: latch Error::InvalidArgument.
Definition sofab.hpp:2220
Result write(sofab::id fieldId, const T &value) noexcept
Write a field, dispatching on the value's type.
Definition sofab.hpp:2244
flushCallback flushCallback_
Invoked when the buffer fills; may be empty.
Definition sofab.hpp:1377
static constexpr uint64_t fixlenWord(uint64_t len, Fix ft) noexcept
Compose a fixlen word: the payload length (or element size) in the high bits, the subtype in the low ...
Definition sofab.hpp:1760
const uint8_t * data() const noexcept
Definition sofab.hpp:2164
OStreamImpl(OStreamImpl &&) noexcept=default
Error pushByte(uint8_t b) noexcept
Append a single byte, flushing first if the buffer is full.
Definition sofab.hpp:1604
Error pushBytes(const uint8_t *data, size_t len) noexcept
Append a run of bytes.
Definition sofab.hpp:1647
size_t flush() noexcept
Hand any buffered bytes to the flush callback and rewind the cursor.
Definition sofab.hpp:2141
size_t bytesUsed() const noexcept
Definition sofab.hpp:2162
uint8_t * buffer_
Start of the active buffer.
Definition sofab.hpp:1360
OStreamImpl & operator=(const OStreamImpl &)=delete
Error putVarint(uint64_t v) noexcept
Encode a value as a varint and append it to the buffer.
Definition sofab.hpp:1668
Error writeFloatArray(sofab::id fieldId, std::span< const F > elems) noexcept
Write an array of floats or doubles as a count-prefixed fixlen array.
Definition sofab.hpp:1977
size_t seqDepth_
Number of currently-open nested sequences (§4.9 MAX_DEPTH).
Definition sofab.hpp:1378
Result sequenceEndKeep() noexcept
Close the most recently opened sub-message, keeping its frame even when it received no content.
Definition sofab.hpp:2475
size_t offset_
Start offset of the current installation (§5.1).
Definition sofab.hpp:1376
bool ok() const noexcept
Whether every write on this stream has succeeded.
Definition sofab.hpp:2186
static size_t encodeVarint(uint8_t *out, uint64_t v) noexcept
Encode an unsigned value as a base-128 varint.
Definition sofab.hpp:1541
static size_t encodeVarintPadded(uint8_t *out, uint64_t v) noexcept
Encode a varint into a destination with a full varint window.
Definition sofab.hpp:1575
static constexpr uint64_t headerWord(sofab::id fieldId, Wire w) noexcept
Compose a field header word: the id in the high bits, the wire type in the low three (§4....
Definition sofab.hpp:1747
uint8_t * end_
One past the end of the buffer.
Definition sofab.hpp:1362
Error putSequenceEnd() noexcept
Write the sequence-end marker (§4.9) — id 0, wire type 7.
Definition sofab.hpp:1688
PendingRun pending_
Definition sofab.hpp:1437
OStreamImpl(const OStreamImpl &)=delete
Error beforeContent() noexcept
Commit any held-back sequence run before writing content.
Definition sofab.hpp:1734
Error writeFixlen(sofab::id fieldId, Fix ft, const uint8_t *data, size_t len) noexcept
Write a length-prefixed field (string, blob or other fixlen payload).
Definition sofab.hpp:1804
Error writeScalar(sofab::id fieldId, Wire type, uint64_t value) noexcept
Write a scalar field: header varint plus one value varint, in a single bulk write.
Definition sofab.hpp:1773
Result sequenceBeginLazy(sofab::id fieldId) noexcept
Open a nested sub-message whose header is held back until the sub-message turns out to have content.
Definition sofab.hpp:2410
uint8_t * cursor_
Current write position.
Definition sofab.hpp:1361
std::function< void(std::span< const uint8_t >)> flushCallback
Callback invoked with a span of finished bytes whenever the buffer flushes.
Definition sofab.hpp:1357
Result writeLazy(sofab::id fieldId, const T &value) noexcept
Write a nested message field, omitting it when it is all-default.
Definition sofab.hpp:2331
Error failure_
Sticky first failure of this stream (see ok, error).
Definition sofab.hpp:1460
void initBuffer(uint8_t *buffer, size_t buflen, size_t offset) noexcept
Point the stream at a buffer and position the write cursor.
Definition sofab.hpp:1514
Error writeFloatScalar(sofab::id fieldId, F value) noexcept
Write a single float or double as a little-endian fixlen field.
Definition sofab.hpp:1845
Output stream whose buffer is stored inline (the buffer costs no heap allocation).
Definition sofab.hpp:2654
OStreamInline() noexcept
Construct with no flush callback; overflow returns Error::BufferFull.
Definition sofab.hpp:2661
OStreamInline(flushCallback callback) noexcept
Construct with a flush callback.
Definition sofab.hpp:2666
Base class for user-defined messages that can serialise themselves.
Definition sofab.hpp:2692
virtual OStreamImpl::Result serialize(OStreamImpl &ostream) const noexcept=0
Write this message's fields into ostream.
Bundles a message with an inline output buffer sized for it.
Definition sofab.hpp:2716
OStreamObject() noexcept=default
Construct with no flush callback.
MessageType * operator->() noexcept
Reach the wrapped message, so its fields are obj->field.
Definition sofab.hpp:2739
OStreamImpl::Result serialize() noexcept
Serialise the wrapped message into the inline buffer and flush.
Definition sofab.hpp:2747
const MessageType * operator->() const noexcept
Reach the wrapped message, so its fields are obj->field.
Definition sofab.hpp:2741
Output stream over a buffer the caller already owns.
Definition sofab.hpp:2581
OStreamView(uint8_t *buffer, size_t buflen, size_t offset=0) noexcept
Construct over caller storage.
Definition sofab.hpp:2589
OStreamView(flushCallback callback, uint8_t *buffer, size_t buflen, size_t offset=0) noexcept
Construct over caller storage with a flush callback.
Definition sofab.hpp:2601
void setBuffer(uint8_t *buffer, size_t buflen, size_t offset=0) noexcept
Install a different caller buffer, mid-stream.
Definition sofab.hpp:2629
Output stream over a caller-supplied buffer whose lifetime is shared.
Definition sofab.hpp:2503
OStream() noexcept=default
Construct without a buffer; one must be set via setBuffer.
std::shared_ptr< uint8_t[]> getBuffer() noexcept
Definition sofab.hpp:2563
OStream(flushCallback callback, std::shared_ptr< uint8_t[]> buffer, size_t buflen, size_t offset=0) noexcept
Construct over a caller-supplied buffer with a flush callback.
Definition sofab.hpp:2528
std::shared_ptr< uint8_t[]> bufferOwner_
Caller storage, kept alive.
Definition sofab.hpp:2505
void setBuffer(std::shared_ptr< uint8_t[]> buffer, size_t buflen, size_t offset=0) noexcept
Install a buffer, mid-stream if need be (§5.1's buffer-set).
Definition sofab.hpp:2557
Constrains a deserialisable message: must derive from sofab::IStreamMessage.
Definition sofab.hpp:2766
Constrains a serialisable message: derives from sofab::OStreamMessage and exposes a static constexpr ...
Definition sofab.hpp:2679
Give dst room for want, if it is a destination the caller has to size.
Definition sofab.hpp:6373
std::size_t utf8Prefix(std::string_view sv, std::size_t n) noexcept
Length of the longest prefix of sv that is at most n bytes and does not end inside a UTF-8 character;...
Definition sofab.hpp:759
size_t arrayReach(const IStreamImpl &is) noexcept
Elements of the announced array the bytes in hand could still carry, clamped to the count itself.
Definition sofab.hpp:6405
constexpr uint32_t utf8Advance(uint32_t state, const uint8_t *d, size_t len) noexcept
Step the UTF-8 DFA over len bytes and return the state.
Definition sofab.hpp:552
void storeLittleBits(uint8_t *out, U bits) noexcept
Store the object representation of a 4- or 8-byte value as little-endian bytes.
Definition sofab.hpp:374
constexpr uint64_t gather7(uint64_t w) noexcept
Inverse of spread7: pack eight bytes' low 7 bits into one value.
Definition sofab.hpp:352
constexpr uint32_t UTF8_REJECT
Definition sofab.hpp:527
constexpr F bitsFloat(U bits) noexcept
Reconstruct a floating-point value from its raw bits.
Definition sofab.hpp:479
constexpr uint8_t utf8Dfa[]
Validate that [data, data+len) is well-formed UTF-8.
Definition sofab.hpp:509
bool seqIndexAdmitted(IStreamImpl &is, sofab::id id, long cap, long dynCap, long destCap) noexcept
Admit or refuse a wrapper-array element index, in §6.3's categories, before the container it indexes ...
Definition sofab.hpp:6635
Wire
Wire type stored in the low 3 bits of every field header.
Definition sofab.hpp:264
@ ArrayUnsigned
Count-prefixed array of unsigned varints.
@ Fixlen
Length-prefixed payload (float, string or blob).
@ Signed
Signed integer, zig-zag encoded as a varint.
@ ArraySigned
Count-prefixed array of zig-zag varints.
@ Unsigned
Unsigned integer encoded as a varint.
@ ArrayFixlen
Count-prefixed array of fixed-size elements.
@ SequenceStart
Opens a nested sub-message.
@ SequenceEnd
Closes the most recently opened sub-message.
constexpr int64_t zigzagDecode(uint64_t u) noexcept
Inverse of zigzagEncode.
Definition sofab.hpp:430
constexpr bool utf8Valid(const char *data, size_t len) noexcept
Definition sofab.hpp:560
constexpr void destSetLen(D &d, size_t n) noexcept
Publish the decoded length in a destination that already had the room — the one container operation t...
Definition sofab.hpp:703
constexpr size_t destRoom(const D &d) noexcept
Room a decode destination already holds — bytes for a payload, elements for an array (CORELIB_PLAN §6...
Definition sofab.hpp:677
constexpr bool namesSeqContainer() noexcept
Whether a MessageSeq template argument names the destination container rather than the element type.
Definition sofab.hpp:6905
bool arrayTagMatches(const IStreamImpl &is) noexcept
Does the delivered tag match the array kind Elem declares (§7.3)?
Definition sofab.hpp:6420
typename WireInt< E >::type WireInt_t
Alias for WireInt.
Definition sofab.hpp:457
void fitDest(D &dst, size_t want) noexcept
Definition sofab.hpp:6376
constexpr uint32_t UTF8_ACCEPT
The DFA's ACCEPT and REJECT states (see utf8Dfa).
Definition sofab.hpp:526
constexpr long destCapacity() noexcept
The element ceiling a decode destination T publishes, or -1 when it publishes none.
Definition sofab.hpp:641
constexpr uint64_t spread7(uint64_t v) noexcept
Spread the low 56 bits of v into eight 7-bit groups, one per byte.
Definition sofab.hpp:325
void storeLittle64(uint8_t *out, uint64_t w) noexcept
Store a 64-bit word as eight little-endian bytes.
Definition sofab.hpp:306
uint64_t loadLittle64(const uint8_t *in) noexcept
Load eight little-endian bytes as a 64-bit word (see storeLittle64).
Definition sofab.hpp:400
constexpr size_t VARINT_MAX_BYTES
Widest base-128 varint: ceil(64/7) == 10 bytes (§4.1).
Definition sofab.hpp:296
constexpr uint64_t zigzagEncode(int64_t v) noexcept
Map a signed integer to an unsigned one with the zig-zag scheme.
Definition sofab.hpp:421
Fix
Sub-type of a length-prefixed (Fixlen) payload, stored in the low 3 bits of its length word.
Definition sofab.hpp:282
@ String
UTF-8 text.
@ Fp32
32-bit IEEE-754 float.
@ Fp64
64-bit IEEE-754 double.
@ Blob
Opaque byte string.
constexpr auto floatBits(F v) noexcept
Reinterpret a float/double as the unsigned integer holding its bits.
Definition sofab.hpp:466
U loadLittleBits(const uint8_t *in) noexcept
Inverse of storeLittleBits.
Definition sofab.hpp:385
DecodeStatus
Three-valued decode outcome of a sofab::IStreamImpl::feed call (spec §7).
Definition sofab.hpp:217
@ LimitExceeded
A configured receiver-side limit (§6.2.1) was exceeded on a schema-**unbounded** field.
@ InvalidArgument
The value broke neither the schema bound nor a receiver cap, but does not fit the destination this ca...
@ Incomplete
Consumed bytes end inside a field or with an open sequence.
@ Invalid
Bytes are malformed regardless of what follows.
@ Complete
Consumed bytes end exactly at a field boundary — a valid message.
constexpr int API_VERSION
Version of the SofaBuffers public API implemented by this header.
Definition sofab.hpp:79
constexpr size_t MIN_OUTPUT_BUFFER
Smallest output buffer this port accepts for streaming (§5.1).
Definition sofab.hpp:134
bool readArray(IStreamImpl &is, T &dst, long schemaCount, ElemBound elem={}) noexcept
Read the current count-prefixed array into a destination this call sizes — the generated layer's IStr...
Definition sofab.hpp:6533
constexpr uint32_t FIXLEN_MAX
Largest fixlen payload byte-length (INT32_MAX).
Definition sofab.hpp:100
constexpr bool always_false_v
Always-false trait used to trigger static_assert in the otherwise-unreachable branch of an if constex...
Definition sofab.hpp:147
uint32_t id
Field identifier on the wire.
Definition sofab.hpp:247
bool read(IStreamImpl &is, T &dst) noexcept
IStreamImpl::read with the destination sized first — the generated layer's untyped read.
Definition sofab.hpp:6565
bool readString(IStreamImpl &is, S &dst, long maxlen) noexcept
Read the current field as a string into a destination this call sizes — the generated layer's IStream...
Definition sofab.hpp:6470
constexpr int MAX_DEPTH
Maximum nested-sequence depth (§4.9).
Definition sofab.hpp:110
bool readBlobCapped(IStreamImpl &is, B &dst, long dynCap) noexcept
The blob counterpart of sofab::readStringCapped.
Definition sofab.hpp:6507
constexpr uint32_t ID_MAX
Largest valid field id (INT32_MAX).
Definition sofab.hpp:94
constexpr uint32_t ARRAY_MAX
Largest array element count (INT32_MAX).
Definition sofab.hpp:105
bool readBlob(IStreamImpl &is, B &dst, long maxlen) noexcept
The blob counterpart of sofab::readString.
Definition sofab.hpp:6496
constexpr bool utf8_valid(std::string_view bytes) noexcept
Public UTF-8 validity primitive (spec CORELIB_PLAN §6.4).
Definition sofab.hpp:722
Error
Status codes returned by the encode/decode API; None signals success.
Definition sofab.hpp:151
@ BufferFull
Encode-only: the encoder ran out of room.
@ LimitExceeded
Decode-only: a receiver-configured cap (§6.2.1) was exceeded on a field the schema leaves unbounded —...
@ InvalidArgument
An argument was out of range (e.g.
@ Incomplete
Decode-only: the fed bytes end inside a field — a partial varint (§4.1), a fixlen/array payload short...
@ None
Operation succeeded (decode: COMPLETE, §7).
@ InvalidMessage
The input bytes are malformed (decode: INVALID, §7).
bool readStringCapped(IStreamImpl &is, S &dst, long dynCap) noexcept
The schema-unbounded sofab::readString: sizes dst only once the §6.2.1 receiver cap has admitted the ...
Definition sofab.hpp:6485
bool readArrayCapped(IStreamImpl &is, T &dst, long dynCap, ElemBound elem={}) noexcept
The schema-unbounded sofab::readArray: sizes dst only once the §6.2.1 receiver cap has admitted the c...
Definition sofab.hpp:6549
The blob counterpart of StringSeq; see it for the placement and bound rules.
Definition sofab.hpp:6842
long elemDynCap
The §6.2.1 receiver cap on one ELEMENT's length, or -1 when the caller supplied none.
Definition sofab.hpp:6857
BlobSeq(C &o, long capacity, long elemMax, long indexCap, long elemLenCap) noexcept
Definition sofab.hpp:6860
long dynCap
The configured receiver cap on the element index (max_dyn_array_count, §6.2.1); negative means none.
Definition sofab.hpp:6847
void prepare() noexcept
§7.4: the sequence IS the array's value, so a repeated field id replaces it whole.
Definition sofab.hpp:6866
void deserialize(IStreamImpl &is, sofab::id id, size_t size, size_t) noexcept override
Consume one of this message's fields from istream.
Definition sofab.hpp:6868
The value range a declared integer type admits (MESSAGE_SPEC §7.1).
Definition sofab.hpp:2881
int64_t lo
Smallest admissible value, inclusive.
Definition sofab.hpp:2882
int64_t hi
Largest admissible value, inclusive.
Definition sofab.hpp:2883
constexpr ElemBound() noexcept=default
bool armed
false: no bound — the decode is unchanged.
Definition sofab.hpp:2884
static constexpr ElemBound of() noexcept
The bound a declared element type E implies.
Definition sofab.hpp:2900
Decode fields at the current nesting level, firing cb for each.
Definition sofab.hpp:3736
void operator()(sofab::id id, size_t size, size_t count) const noexcept
Definition sofab.hpp:3739
void(* fn)(void *, sofab::id, size_t, size_t)
Definition sofab.hpp:3738
The one stream-scoped receiver cap: how many bytes a single top-level field may span.
Definition sofab.hpp:2815
size_t max_buffered_field
Cap on how many bytes a single top-level field may span, in bytes.
Definition sofab.hpp:2839
constexpr Limits(size_t maxBufferedField) noexcept
State the cap.
Definition sofab.hpp:2851
Collects a struct/union or nested-array wrapper sequence into the container it is handed.
Definition sofab.hpp:6940
void prepare() noexcept
§7.4 replace-whole, and absent ⇒ never called:
Definition sofab.hpp:7043
typename Container::value_type Elem
Element type — an IStreamMessage, or a container for a nested-array row.
Definition sofab.hpp:6944
std::conditional_t< detail::namesSeqContainer< A >(), A, std::vector< A > > Container
Destination container: A itself, or std::vector<A> for the element spelling.
Definition sofab.hpp:6942
void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override
Consume one of this message's fields from istream.
Definition sofab.hpp:7045
A message that both encodes and decodes: exactly OStreamMessage + IStreamMessage.
Definition sofab.hpp:6194
Collects a wrapper sequence whose elements are rows the stream cannot read on its own — a row that is...
Definition sofab.hpp:7182
long cap
Schema count N, or -1; an id at or past N is INVALID (§5.1/§7.1).
Definition sofab.hpp:7190
void prepare() noexcept
§7.4 replace-whole, and absent ⇒ never called:
Definition sofab.hpp:7217
Reader readRow
The row read (Reader).
Definition sofab.hpp:7194
long dynCap
The configured receiver cap on the element index (max_dyn_array_count, §6.2.1); negative means none.
Definition sofab.hpp:7192
RowSeq(C &o, long capacity, long indexCap, Reader reader={}) noexcept
Definition sofab.hpp:7213
C Container
Destination container.
Definition sofab.hpp:7184
typename C::value_type Elem
Row type: the container's element.
Definition sofab.hpp:7186
void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override
Consume one of this message's fields from istream.
Definition sofab.hpp:7219
Collects the elements of a string wrapper-sequence array.
Definition sofab.hpp:6687
StringSeq(C &o, long capacity, long elemMax, long indexCap, long elemLenCap) noexcept
Definition sofab.hpp:6772
long dynCap
The configured receiver cap on the element index (max_dyn_array_count, §6.2.1); negative means none.
Definition sofab.hpp:6713
long elemDynCap
The §6.2.1 receiver cap on one ELEMENT's length, or -1 when the caller supplied none.
Definition sofab.hpp:6728
void prepare() noexcept
§7.4: the sequence IS the array's value, so a repeated field id replaces it whole.
Definition sofab.hpp:6791
void deserialize(IStreamImpl &is, sofab::id id, size_t size, size_t) noexcept override
Consume one of this message's fields from istream.
Definition sofab.hpp:6793
fitDest as the sizer a typed read runs between its checks and its delivery, so the free reads below s...
Definition sofab.hpp:6392
void operator()(D &dst, size_t want) const noexcept
Definition sofab.hpp:6394
The "size nothing" sizer: what a typed read does with the caller's destination between its checks and...
Definition sofab.hpp:613
constexpr void operator()(D &, size_t) const noexcept
Definition sofab.hpp:615
std::underlying_type_t< E > type
Definition sofab.hpp:454
The integer type an element travels as on the wire.
Definition sofab.hpp:451