SofaBuffers C/C++ 0.12.0
API Documentation
Loading...
Searching...
No Matches
sofab.hpp
Go to the documentation of this file.
1/*!
2 * @file sofab.hpp
3 * @brief SofaBuffers C++ - Input and output stream decoder for Sofab messages.
4 *
5 * SPDX-License-Identifier: MIT
6 */
7
8#ifndef SOFAB_HPP
9#define SOFAB_HPP
10
11/**
12 * @defgroup cpp_api C++ API
13 * @{
14 */
15
16/* includes *******************************************************************/
17/*
18 * Freestanding split. The per-target toolchain files build C++ with
19 * -ffreestanding (utils/cortex-m/toolchain-arm-none-eabi.cmake), where libstdc++
20 * offers only a subset of the library: <string> and <vector> refuse to be
21 * included at all, and <memory>/<functional> include but do not define
22 * std::shared_ptr or std::function (both allocate). Everything below the split
23 * is available in either mode, so only the hosted convenience layer is gated —
24 * see SOFAB_CPP_HAVE_HOSTED.
25 */
26#include <array>
27#include <concepts>
28#include <cstdint>
29#include <cstring>
30#include <functional>
31#include <memory>
32#include <span>
33#include <string_view>
34#include <type_traits>
35
36/*! @brief 1 if the hosted standard library is available, else 0.
37 *
38 * Gates the convenience layer that needs an allocator: the @c std::string /
39 * @c std::vector overloads, @ref OStream (a @c std::shared_ptr buffer owner) and
40 * the @c std::function callback typedefs. Every gated entity has a heap-free
41 * counterpart that stays available freestanding — @ref FixedString,
42 * @ref FixedBytes, @ref InlineVector, @ref OStreamInline, @ref OStreamView and
43 * plain function pointers — so the wire API is complete in both modes.
44 *
45 * Defaults to the compiler's own answer (@c __STDC_HOSTED__ is 0 under
46 * @c -ffreestanding, 1 otherwise) and can be forced either way with
47 * @c -DSOFAB_CPP_HAVE_HOSTED=0/1. */
48#if !defined(SOFAB_CPP_HAVE_HOSTED)
49# define SOFAB_CPP_HAVE_HOSTED __STDC_HOSTED__
50#endif
51
52#if SOFAB_CPP_HAVE_HOSTED
53# include <string>
54# include <vector>
55#endif
56
57#include "sofab/istream.h"
58#include "sofab/ostream.h"
59
60/* feature-flag consistency with the C core ***********************************/
61/*
62 * The C core can be built with capabilities removed via its SOFAB_DISABLE_*
63 * switches. Because this wrapper is header-only and calls the C API directly,
64 * it must honour the same switches or it would emit calls to functions the core
65 * no longer declares (an opaque "sofab_... was not declared" error). The
66 * capabilities split into two groups:
67 *
68 * Type-dispatch capabilities (FP64, INT64, ARRAY) are reachable only through
69 * the templated write()/read() via `if constexpr`. When one is disabled the
70 * matching branch turns into a clear static_assert, so code that never uses
71 * that type still compiles, while code that does gets a readable diagnostic.
72 *
73 * Structural capabilities (FIXLEN, SEQUENCE, LAZY_SEQ) underpin concrete
74 * methods and the whole nested-message API (strings, blobs, floats,
75 * sequences, message objects) — i.e. most of the C++ surface. The wrapper
76 * cannot offer a coherent object API without them, so building the C++ layer
77 * with any of them disabled is rejected outright; use the C API directly for
78 * such configs. LAZY_SEQ is structural for the same reason: the wrapper's
79 * nested-message writes are defined in terms of the hold-back framing of
80 * MESSAGE_SPEC §2, and sequenceBeginLazy()/sequenceEndKeep() have no eager
81 * substitute that would produce the same bytes.
82 */
83#if defined(SOFAB_DISABLE_FIXLEN_SUPPORT)
84# error "sofab C++ wrapper requires FIXLEN support (strings, blobs, floats). Do not define SOFAB_DISABLE_FIXLEN_SUPPORT when building the C++ API; use the C API directly for fixlen-less builds."
85#endif
86#if defined(SOFAB_DISABLE_SEQUENCE_SUPPORT)
87# error "sofab C++ wrapper requires SEQUENCE support (nested messages, variable-length array reads). Do not define SOFAB_DISABLE_SEQUENCE_SUPPORT when building the C++ API; use the C API directly for sequence-less builds."
88#endif
89#if defined(SOFAB_DISABLE_LAZY_SEQ_SUPPORT)
90# error "sofab C++ wrapper requires LAZY_SEQ support (an all-default nested message is omitted, not framed empty — MESSAGE_SPEC §2). Do not define SOFAB_DISABLE_LAZY_SEQ_SUPPORT when building the C++ API; it is a footprint switch for pure-C consumers, which encode through sofab_object_encode()."
91#endif
92
93/*! @brief 1 if the wrapper exposes 64-bit float (double) fields, else 0
94 * (mirrors @c SOFAB_DISABLE_FP64_SUPPORT in the C core). */
95#if defined(SOFAB_DISABLE_FP64_SUPPORT)
96# define SOFAB_CPP_HAVE_FP64 0
97#else
98# define SOFAB_CPP_HAVE_FP64 1
99#endif
100/*! @brief 1 if the wrapper exposes 64-bit integer fields, else 0
101 * (mirrors @c SOFAB_DISABLE_INT64_SUPPORT in the C core). */
102#if defined(SOFAB_DISABLE_INT64_SUPPORT)
103# define SOFAB_CPP_HAVE_INT64 0
104#else
105# define SOFAB_CPP_HAVE_INT64 1
106#endif
107/*! @brief 1 if the wrapper exposes array/span fields, else 0
108 * (mirrors @c SOFAB_DISABLE_ARRAY_SUPPORT in the C core). */
109#if defined(SOFAB_DISABLE_ARRAY_SUPPORT)
110# define SOFAB_CPP_HAVE_ARRAY 0
111#else
112# define SOFAB_CPP_HAVE_ARRAY 1
113#endif
114
115/*! @brief 1 if generated code refuses an over-bound value at encode, else 0.
116 *
117 * A value past a bound only the schema knows -- a string or blob longer than
118 * its @c maxlen, an array with more elements than its @c count -- is refused by
119 * the generated @c serialize() through @ref sofab::OStreamImpl::rejectArgument.
120 * Each such check is written @c if (sofab::ENCODE_BOUNDS && ...), so defining
121 * @c SOFAB_DISABLE_ENCODE_BOUNDS removes all of them from the image: a
122 * footprint switch for a caller that guarantees its values fit. The decode-side
123 * bound checks are not affected. */
124#if defined(SOFAB_DISABLE_ENCODE_BOUNDS)
125# define SOFAB_CPP_HAVE_ENCODE_BOUNDS 0
126#else
127# define SOFAB_CPP_HAVE_ENCODE_BOUNDS 1
128#endif
129
130/* types **********************************************************************/
131namespace sofab
132{
133 /*! @brief SofaBuffers C++ API version (mirrors @ref SOFAB_API_VERSION). */
134 inline constexpr int API_VERSION = 1;
135
136 /*! @brief Whether generated encode refuses an over-bound value
137 * (@ref SOFAB_CPP_HAVE_ENCODE_BOUNDS; off with @c SOFAB_DISABLE_ENCODE_BOUNDS). */
138 inline constexpr bool ENCODE_BOUNDS = SOFAB_CPP_HAVE_ENCODE_BOUNDS != 0;
139
140 /*! @brief Always-false trait used to trigger a dependent static_assert in a
141 * discarded @c if @c constexpr branch (so it only fires when instantiated). */
142 template <typename>
143 inline constexpr bool always_false_v = false;
144
145 /*! @brief The integer type an element travels as on the wire: identity for an
146 * integer, the declared underlying type for an enumeration.
147 *
148 * An enum's declared width is what picks the signed or unsigned array wire
149 * type and the zig-zag transform (MESSAGE_SPEC §1). The enumeration itself
150 * cannot answer that: @c std::is_signed_v and @c std::is_unsigned_v are
151 * both false for *every* enumeration type, so a rule keyed off the element
152 * would call every enum array unsigned and quietly drop the transform from
153 * each negative constant.
154 *
155 * The partial specialization is what keeps it lazy. @c std::conditional_t
156 * would instantiate @c std::underlying_type_t<E> for a plain integer too,
157 * and that has no @c type — every existing integer array would stop
158 * compiling. */
159 template <typename E, bool = std::is_enum_v<E>>
160 struct wire_int { using type = E; };
161 /*! @brief Enumeration case of @ref wire_int: the declared underlying type. */
162 template <typename E>
163 struct wire_int<E, true> { using type = std::underlying_type_t<E>; };
164 /*! @brief Alias for @ref wire_int. */
165 template <typename E>
167
168 /*! @brief Result/error code returned by the stream APIs (wraps @ref sofab_ret_t). */
169 enum class Error
170 {
171 // Non-error outcomes first — kept low-numbered and contiguous, ahead of
172 // the error codes. Incomplete is a valid (partial) result, not a failure.
173 None = SOFAB_RET_OK, //!< Success (a complete message boundary).
174 Incomplete = SOFAB_RET_INCOMPLETE, //!< Consumed bytes end inside a field or with an
175 //!< open sequence: a valid but partial decode. NOT
176 //!< an error — the caller owns end-of-input and may
177 //!< feed more bytes. Distinct from @c None (complete)
178 //!< and @c InvalidMessage (malformed).
179 // Error codes follow.
180 BufferFull = SOFAB_RET_E_BUFFER_FULL, //!< Output buffer overflowed during encoding.
181 InvalidArgument = SOFAB_RET_E_ARGUMENT, //!< A field id out of range, a scalar width that is
182 //!< not 1/2/4/8 — or a **destination too short for
183 //!< the value it was handed** (§6.6.3): the third of
184 //!< the three ways a value can be refused, and the
185 //!< one that is a mistake in the *call*. See
186 //!< @ref IStreamImpl::readString.
187 InvalidMessage = SOFAB_RET_E_INVALID_MSG, //!< Malformed message encountered while decoding.
188 LimitExceeded = SOFAB_RET_E_LIMIT_EXCEEDED //!< A configured receiver limit (§6.2.1) was
189 //!< exceeded on a schema-**unbounded** field. The
190 //!< bytes are well-formed and decode under a looser
191 //!< limit, so this is deliberately **not**
192 //!< @c InvalidMessage: it means "raise my limit, or
193 //!< the sender must send less", where
194 //!< @c InvalidMessage means "these bytes are
195 //!< broken". Terminal, like @c InvalidMessage.
196 //!<
197 //!< **This corelib never decides it.** §6.2.1 gives
198 //!< the limits to generated code — "the visitor
199 //!< decides. The codec never invents a limit of its
200 //!< own and never clamps to one" — and leaves the
201 //!< codec "the report and the category". This
202 //!< enumerator is the category; the report is the
203 //!< @c size / @c count the field callback already
204 //!< carries. A handler that finds an announced
205 //!< length past its configured cap calls
206 //!< @ref IStreamImpl::exceedLimit and returns
207 //!< without binding a destination.
208 };
209
210
211
212 /*! @brief Field identifier type (alias of @ref sofab_id_t). */
213 using id = sofab_id_t;
214
215 /*!
216 * @brief Wire type of a decoded field (the 3-bit type tag of its header).
217 *
218 * Part of the public API: returned by @ref IStreamImpl::wire. The enumerator
219 * values are the wire tags themselves, so this mirrors @ref sofab_type_t while
220 * exposing the same @c sofab::Wire surface as the sibling @c corelib-cpp — a
221 * generator emits one @ref IStreamImpl::wire guard shape for both.
222 */
223 enum class Wire : uint8_t
224 {
225 Unsigned = SOFAB_TYPE_VARINT_UNSIGNED, //!< Unsigned integer encoded as a varint.
226 Signed = SOFAB_TYPE_VARINT_SIGNED, //!< Signed integer, zig-zag encoded as a varint.
227 Fixlen = SOFAB_TYPE_FIXLEN, //!< Length-prefixed payload (float, string or blob).
228 ArrayUnsigned = SOFAB_TYPE_VARINTARRAY_UNSIGNED, //!< Count-prefixed array of unsigned varints.
229 ArraySigned = SOFAB_TYPE_VARINTARRAY_SIGNED, //!< Count-prefixed array of zig-zag varints.
230 ArrayFixlen = SOFAB_TYPE_FIXLENARRAY, //!< Count-prefixed array of fixed-size elements.
231 SequenceStart = SOFAB_TYPE_SEQUENCE_START, //!< Opens a nested sub-message.
232 SequenceEnd = SOFAB_TYPE_SEQUENCE_END, //!< Closes the most recently opened sub-message.
233 };
234
235 /*!
236 * @brief Sub-type of a length-prefixed (@ref Wire::Fixlen) payload.
237 *
238 * Part of the public API: returned by @ref IStreamImpl::fixType. MESSAGE_SPEC
239 * §7.3 bounds the decode-side type check at wire type *plus* this subtype,
240 * since @c fp32 / @c fp64 / @c string / @c blob all share the
241 * @ref Wire::Fixlen wire type. Mirrors @ref sofab_fixlentype_t and matches
242 * @c corelib-cpp's @c sofab::Fix.
243 */
244 enum class Fix : uint8_t
245 {
246 Fp32 = SOFAB_FIXLENTYPE_FP32, //!< 32-bit IEEE-754 float.
247 Fp64 = SOFAB_FIXLENTYPE_FP64, //!< 64-bit IEEE-754 double.
248 String = SOFAB_FIXLENTYPE_STRING, //!< UTF-8 text.
249 Blob = SOFAB_FIXLENTYPE_BLOB, //!< Opaque byte string.
250 };
251
252 /*******************/
253 /*** FixedString ***/
254 /*******************/
255
256 namespace detail
257 {
258 /*!
259 * @brief Length of the longest prefix of @p sv that is at most @p n bytes
260 * and does not end inside a UTF-8 character; @p sv is longer
261 * than @p n.
262 *
263 * The over-long half of @ref FixedString's assignment-time clamp, one
264 * copy for every capacity: the cut moves back while the first byte left
265 * out is a continuation byte (10xxxxxx), so a valid UTF-8 @p sv keeps a
266 * valid UTF-8 prefix. The common case -- the value fits -- stays inline
267 * in @ref FixedString::assign, where a literal's length folds away.
268 */
269 inline std::size_t utf8Prefix(std::string_view sv, std::size_t n) noexcept
270 {
271 while (n > 0 && (static_cast<unsigned char>(sv[n]) & 0xC0u) == 0x80u)
272 {
273 --n;
274 }
275 return n;
276 }
277 } // namespace detail
278
279 /*!
280 * @brief Fixed-capacity, heap-free string of up to @p N characters.
281 *
282 * A drop-in, embedded-friendly stand-in for @c std::string on both the encode
283 * and decode paths. The characters live in an inline @c std::array, so an
284 * instance allocates nothing, never throws (an over-long value is clamped to
285 * @p N bytes at a UTF-8 character boundary, see @ref assign), and
286 * compiles cleanly under @c -fno-exceptions / @c -fno-rtti. Because the buffer
287 * never moves, an instance is a valid address-stable decode target for the
288 * deferred @ref IStreamImpl decoder (bytes bound now, filled by a later
289 * @ref IStreamImpl::feed pass).
290 *
291 * The storage is @c N+1 bytes: one extra slot always holds a trailing NUL so
292 * @ref c_str and the @c std::string_view encode path remain valid even at full
293 * length @p N. The buffer is zero-initialised, so the NUL is present from
294 * construction and is re-placed by every length-changing operation.
295 *
296 * @par Generator integration contract
297 * Generated code mirrors the @c std::string path exactly, so this type keeps a
298 * stable surface for it:
299 * - decode emits @c s.set_len(_size); if (_size) is.read(s); — @ref set_len
300 * fixes the logical length (and terminating NUL) before the read binds the
301 * buffer, and @ref IStreamImpl::read fills @c data() over @c size() bytes;
302 * - encode emits @c os.write(id, s); — the implicit @ref operator std::string_view
303 * routes it through the existing string encode branch, byte-for-byte
304 * identical to the same-content @c std::string.
305 *
306 * @tparam N Maximum number of characters (excluding the reserved NUL slot).
307 */
308 template <std::size_t N>
310 {
311 std::array<char, N + 1> buf_{}; //!< Inline storage (+1 for the NUL).
312 std::size_t len_ = 0; //!< Current logical length (<= N).
313
314 public:
315 /*! @brief Character type (mirrors @c std::string). */
317 /*! @brief Size type (mirrors @c std::string). */
318 using size_type = std::size_t;
319
320 /*! @brief Construct an empty string. */
322
323 /*!
324 * @brief Construct from a NUL-terminated C string (clamped to @p N, see @ref assign).
325 * @param s Source string, or @c nullptr for an empty string.
326 */
328 {
329 assign(s ? std::string_view{s} : std::string_view{});
330 }
331
332 /*!
333 * @brief Construct from a string view (clamped to @p N, see @ref assign).
334 * @param sv Source characters (may contain embedded NULs).
335 */
336 FixedString(std::string_view sv) noexcept
337 {
338 assign(sv);
339 }
340
341#if SOFAB_CPP_HAVE_HOSTED
342 /*!
343 * @brief Construct from a @c std::string (the easy on-ramp; clamped to @p N, see @ref assign).
344 * @param s Source string.
345 *
346 * Hosted only; freestanding builds take the @c std::string_view overload
347 * above, which a @c std::string converts to implicitly anyway.
348 */
349 FixedString(const std::string &s) noexcept
350 {
351 assign(std::string_view{s});
352 }
353#endif
354
355 /*! @brief Assign from a NUL-terminated C string (clamped to @p N, see @ref assign). */
356 FixedString &operator=(const char *s) noexcept
357 {
358 assign(s ? std::string_view{s} : std::string_view{});
359 return *this;
360 }
361
362 /*! @brief Assign from a string view (clamped to @p N, see @ref assign). */
363 FixedString &operator=(std::string_view sv) noexcept
364 {
365 assign(sv);
366 return *this;
367 }
368
369#if SOFAB_CPP_HAVE_HOSTED
370 /*! @brief Assign from a @c std::string (clamped to @p N, see @ref assign). Hosted only. */
371 FixedString &operator=(const std::string &s) noexcept
372 {
373 assign(std::string_view{s});
374 return *this;
375 }
376#endif
377
378 /*!
379 * @brief Replace the contents with @p sv, clamped to @p N bytes.
380 *
381 * The assignment-time clamp is a documented contract of the static
382 * storage (the generator's `allow_dynamic: false`): a value longer than
383 * @p N is cut, not refused, before any encoder sees it. The cut never
384 * lands inside a UTF-8 character -- it moves back to the start of the
385 * character that would not fit whole, so the kept prefix is valid UTF-8
386 * whenever @p sv is.
387 *
388 * @param sv Source characters (may contain embedded NULs).
389 * @return Reference to @c *this.
390 */
391 FixedString &assign(std::string_view sv) noexcept
392 {
393 len_ = sv.size() <= N ? sv.size() : detail::utf8Prefix(sv, N);
394 for (std::size_t i = 0; i < len_; ++i)
395 {
396 buf_[i] = sv[i];
397 }
398 buf_[len_] = '\0';
399 return *this;
400 }
401
402 /*!
403 * @brief Decode hook: set the logical length and (re)place the trailing NUL.
404 *
405 * Called by generated decode before binding the buffer: it fixes
406 * @c size() to the field length (clamped to @p N) and writes the NUL at
407 * @c buf_[len_]. The subsequent @ref IStreamImpl::read binds exactly
408 * @c size() bytes via @c sofab_istream_read_string_noterm, which fills
409 * @c [0, size()) and never touches @c buf_[len_], so the NUL survives and
410 * @ref c_str stays valid. Re-decoding a shorter value re-terminates here.
411 *
412 * @param n Requested logical length (clamped to @p N).
413 */
414 void set_len(std::size_t n) noexcept
415 {
416 len_ = n > N ? N : n;
417 buf_[len_] = '\0';
418 }
419
420 /*! @brief Mutable pointer to the character buffer (decode target). */
421 char *data() noexcept { return buf_.data(); }
422 /*! @brief Const pointer to the character buffer. */
423 const char *data() const noexcept { return buf_.data(); }
424 /*! @brief NUL-terminated view of the contents. */
425 const char *c_str() const noexcept { return buf_.data(); }
426
427 /*! @brief Number of characters currently stored. */
428 std::size_t size() const noexcept { return len_; }
429 /*! @brief Alias of @ref size. */
430 std::size_t length() const noexcept { return len_; }
431 /*! @brief True if the string is empty. */
432 bool empty() const noexcept { return len_ == 0; }
433 /*! @brief Maximum number of characters (the template parameter @p N). */
434 static constexpr std::size_t capacity() noexcept { return N; }
435 /*! @brief Alias of @ref capacity. */
436 static constexpr std::size_t max_size() noexcept { return N; }
437
438 /*! @brief Access the character at @p i (no bounds checking). */
439 char &operator[](std::size_t i) noexcept { return buf_[i]; }
440 /*! @brief Access the character at @p i (no bounds checking). */
441 const char &operator[](std::size_t i) const noexcept { return buf_[i]; }
442
443 /*! @brief Iterator to the first character. */
444 char *begin() noexcept { return buf_.data(); }
445 /*! @brief Iterator past the last character. */
446 char *end() noexcept { return buf_.data() + len_; }
447 /*! @brief Const iterator to the first character. */
448 const char *begin() const noexcept { return buf_.data(); }
449 /*! @brief Const iterator past the last character. */
450 const char *end() const noexcept { return buf_.data() + len_; }
451
452 /*! @brief Reset to an empty string. */
454 {
455 len_ = 0;
456 buf_[0] = '\0';
457 }
458
459 /*! @brief Non-owning view over the current characters. */
460 std::string_view view() const noexcept
461 {
462 return std::string_view{buf_.data(), len_};
463 }
464
465 /*!
466 * @brief Implicit conversion to @c std::string_view.
467 *
468 * Gives a cheap non-owning view and makes the existing string encode
469 * branch (@c OStreamImpl::write) match a @c FixedString automatically.
470 */
471 operator std::string_view() const noexcept
472 {
473 return view();
474 }
475
476#if SOFAB_CPP_HAVE_HOSTED
477 /*! @brief Copy the contents into an owning @c std::string (allocates).
478 * Hosted only — it is the one member of this type that needs a heap. */
479 std::string str() const
480 {
481 return std::string{buf_.data(), len_};
482 }
483#endif
484
485 /*! @brief Equality against any string view-like operand. */
486 bool operator==(std::string_view rhs) const noexcept
487 {
488 return view() == rhs;
489 }
490
491 /*! @brief Inequality against any string view-like operand. */
492 bool operator!=(std::string_view rhs) const noexcept
493 {
494 return view() != rhs;
495 }
496 };
497
498 /*! @brief Trait: true only for @ref FixedString specializations. */
499 template <typename>
500 struct is_fixed_string : std::false_type { };
501 template <std::size_t N>
502 struct is_fixed_string<FixedString<N>> : std::true_type { };
503 /*! @brief Convenience value for @ref is_fixed_string. */
504 template <typename T>
505 inline constexpr bool is_fixed_string_v =
507
508 /******************/
509 /*** FixedBytes ***/
510 /******************/
511
512 /*!
513 * @brief Fixed-capacity, heap-free byte blob of up to @p N bytes.
514 *
515 * The embedded-friendly counterpart of @c std::vector<std::uint8_t> for blob
516 * fields, mirroring @ref FixedString for bytes. The payload lives in an inline
517 * @c std::array, so an instance allocates nothing and never throws (overflow
518 * clamps to @p N). Because the buffer never moves, an instance is a valid
519 * address-stable decode target for the deferred @ref IStreamImpl decoder.
520 *
521 * A @b logical @b length (@ref size, @c <= @p N) is tracked separately from the
522 * capacity @p N: a blob shorter than its schema @c maxlen occupies only
523 * @ref size bytes on the wire. This is exactly why the type cannot be a plain
524 * @c std::array<std::uint8_t,N> (always length @p N) and must not reintroduce
525 * the heap of @c std::vector.
526 *
527 * @par Generator integration contract
528 * Generated code mirrors the @c std::vector<std::uint8_t> path:
529 * - encode passes @ref data / @ref size to the blob write, byte-for-byte
530 * identical to the same-content vector;
531 * - decode emits @c b.set_len(_size); if (_size) is.read(b); — @ref set_len
532 * fixes the logical length (clamped to @p N) before the read binds the
533 * inline buffer over @ref size bytes. Binding the container this way (not a
534 * bare @c is.read(b.data(), _size)) lets the decoder reject an over-@p N
535 * wire length as INVALID per MESSAGE_SPEC §7.1 instead of truncating it.
536 *
537 * @tparam N Maximum number of bytes.
538 */
539 template <std::size_t N>
541 {
542 std::array<std::uint8_t, N> buf_{}; //!< Inline storage.
543 std::size_t len_ = 0; //!< Current logical length (<= N).
544
545 public:
546 /*! @brief Element type (mirrors @c std::vector). */
547 using value_type = std::uint8_t;
548 /*! @brief Size type (mirrors @c std::vector). */
549 using size_type = std::size_t;
550
551 /*! @brief Construct an empty blob. */
553
554 /*!
555 * @brief Construct from a brace-enclosed list of bytes (clamped to @p N; extra bytes are dropped).
556 *
557 * Providing this constructor makes @c FixedBytes a non-aggregate, so a
558 * brace-init such as @c b = {1, 2, 3} routes through here and sets
559 * @ref size — it cannot silently fill the buffer while leaving the logical
560 * length at zero.
561 *
562 * @param init Source bytes (excess beyond @p N is dropped).
563 */
568
569 /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra bytes are dropped). */
570 FixedBytes &operator=(std::initializer_list<std::uint8_t> init) noexcept
571 {
572 return assign(init);
573 }
574
575 /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra bytes are dropped). */
576 FixedBytes &assign(std::initializer_list<std::uint8_t> init) noexcept
577 {
578 len_ = 0;
579 for (std::uint8_t b : init)
580 {
581 if (len_ >= N)
582 {
583 break;
584 }
585 buf_[len_++] = b;
586 }
587 return *this;
588 }
589
590 /*! @brief Mutable pointer to the byte buffer (decode target). */
591 std::uint8_t *data() noexcept { return buf_.data(); }
592 /*! @brief Const pointer to the byte buffer. */
593 const std::uint8_t *data() const noexcept { return buf_.data(); }
594
595 /*! @brief Number of bytes currently stored. */
596 std::size_t size() const noexcept { return len_; }
597 /*! @brief True if the blob is empty. */
598 bool empty() const noexcept { return len_ == 0; }
599 /*! @brief Maximum number of bytes (the template parameter @p N). */
600 static constexpr std::size_t capacity() noexcept { return N; }
601 /*! @brief Alias of @ref capacity. */
602 static constexpr std::size_t max_size() noexcept { return N; }
603
604 /*!
605 * @brief Decode hook: set the logical length (clamped to @p N).
606 *
607 * Called by generated decode before binding the buffer, so @ref size
608 * reports the field length and @ref data over that many bytes is the
609 * fill target.
610 *
611 * @param n Requested logical length (clamped to @p N).
612 */
613 void set_len(std::size_t n) noexcept { len_ = n < N ? n : N; }
614
615 /*! @brief Reset to an empty blob. */
616 void clear() noexcept { len_ = 0; }
617
618 /*! @brief Append one byte (no-op once at capacity @p N). */
619 void push_back(std::uint8_t b) noexcept
620 {
621 if (len_ < N)
622 {
623 buf_[len_++] = b;
624 }
625 }
626
627 /*! @brief Access the byte at @p i (no bounds checking). */
628 std::uint8_t &operator[](std::size_t i) noexcept { return buf_[i]; }
629 /*! @brief Access the byte at @p i (no bounds checking). */
630 const std::uint8_t &operator[](std::size_t i) const noexcept { return buf_[i]; }
631
632 /*! @brief Iterator to the first byte. */
633 std::uint8_t *begin() noexcept { return buf_.data(); }
634 /*! @brief Iterator past the last byte. */
635 std::uint8_t *end() noexcept { return buf_.data() + len_; }
636 /*! @brief Const iterator to the first byte. */
637 const std::uint8_t *begin() const noexcept { return buf_.data(); }
638 /*! @brief Const iterator past the last byte. */
639 const std::uint8_t *end() const noexcept { return buf_.data() + len_; }
640
641 /*! @brief Content equality (same logical length and bytes). */
642 bool operator==(const FixedBytes &o) const noexcept
643 {
644 if (len_ != o.len_)
645 {
646 return false;
647 }
648 for (std::size_t i = 0; i < len_; ++i)
649 {
650 if (buf_[i] != o.buf_[i])
651 {
652 return false;
653 }
654 }
655 return true;
656 }
657
658 /*! @brief Negated @ref operator==. */
659 bool operator!=(const FixedBytes &o) const noexcept { return !(*this == o); }
660 };
661
662 /*! @brief Trait: true only for @ref FixedBytes specializations. */
663 template <typename>
664 struct is_fixed_bytes : std::false_type { };
665 template <std::size_t N>
666 struct is_fixed_bytes<FixedBytes<N>> : std::true_type { };
667 /*! @brief Convenience value for @ref is_fixed_bytes. */
668 template <typename T>
669 inline constexpr bool is_fixed_bytes_v =
671
672 /********************/
673 /*** InlineVector ***/
674 /********************/
675
676 /*!
677 * @brief Fixed-capacity, heap-free sequence of up to @p N elements of type @p T.
678 *
679 * The embedded-friendly counterpart of @c std::vector<T> for the sequence
680 * fields the fixed-capacity profile lowers without a heap: arrays of strings,
681 * blobs, structs/unions or nested arrays. Elements live in an inline
682 * @c std::array, so the storage never reallocates and a bound-then-filled
683 * element (the deferred @ref IStreamImpl decoder) stays address-stable —
684 * strictly safer than a @c std::vector + @c reserve.
685 *
686 * A @b logical @b length (@ref size, @c <= @p N) is tracked separately from the
687 * capacity @p N: an array shorter than its schema @c count holds only
688 * @ref size elements. This is why the type is neither a plain
689 * @c std::array<T,N> (always length @p N) nor a heap-backed @c std::vector.
690 *
691 * @warning Historically this was an aggregate with a public, default-zero
692 * length, so a natural brace-init such as @c v = {a, b, c} silently filled the
693 * storage while leaving the logical length at 0 — the field then encoded as
694 * empty. The @c initializer_list constructor/assignment below make the type a
695 * non-aggregate, so that brace-init now sets @ref size correctly instead of
696 * corrupting the wire.
697 *
698 * @tparam T Element type.
699 * @tparam N Maximum number of elements.
700 */
701 template <typename T, std::size_t N>
703 {
704 std::array<T, N> buf_{}; //!< Inline storage.
705 std::size_t len_ = 0; //!< Current logical length (<= N).
706
707 public:
708 /*! @brief Element type (mirrors @c std::vector). */
709 using value_type = T;
710 /*! @brief Size type (mirrors @c std::vector). */
711 using size_type = std::size_t;
712
713 /*! @brief Construct an empty sequence. */
715
716 /*!
717 * @brief Construct from a brace-enclosed list of elements (clamped to @p N; extra elements are dropped).
718 *
719 * The presence of this constructor makes @c InlineVector a non-aggregate:
720 * @c v = {a, b, c} routes here and sets @ref size, instead of aggregate
721 * brace-init filling the storage while leaving the length at 0.
722 *
723 * @param init Source elements (excess beyond @p N is dropped).
724 */
729
730 /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra elements are dropped). */
731 InlineVector &operator=(std::initializer_list<T> init) noexcept
732 {
733 return assign(init);
734 }
735
736 /*! @brief Replace the contents from a brace-enclosed list (clamped to @p N; extra elements are dropped). */
737 InlineVector &assign(std::initializer_list<T> init) noexcept
738 {
739 len_ = 0;
740 for (const T &v : init)
741 {
742 if (len_ >= N)
743 {
744 break;
745 }
746 buf_[len_++] = v;
747 }
748 return *this;
749 }
750
751 /*! @brief Number of elements currently stored. */
752 std::size_t size() const noexcept { return len_; }
753 /*! @brief True if the sequence is empty. */
754 bool empty() const noexcept { return len_ == 0; }
755 /*! @brief Maximum number of elements (the template parameter @p N). */
756 static constexpr std::size_t capacity() noexcept { return N; }
757 /*! @brief Alias of @ref capacity. */
758 static constexpr std::size_t max_size() noexcept { return N; }
759
760 /*! @brief No-op (inline storage never reallocates); present for API parity. */
761 void reserve(std::size_t) noexcept {}
762 /*! @brief Reset to an empty sequence (logical length only). */
763 void clear() noexcept { len_ = 0; }
764
765 /*!
766 * @brief Set the logical length to @p n, value-initializing what changes.
767 *
768 * The @c std::vector member of the container API this type mirrors, and the
769 * one @ref IStreamImpl::readArray and the wrapper-array collectors probe
770 * for: readArray *resizes* a resizable destination and *value-initializes*
771 * a fixed-extent one, and without this method an @c InlineVector matched
772 * neither — it fell to the fixed-extent branch, which assigned a
773 * default-constructed container and so set the logical length to 0. The
774 * decode then bound an empty span and dropped the array silently. With
775 * @ref resize present, readArray keeps ownership of the tag / bound /
776 * reset / bind order it documents, for inline storage too.
777 *
778 * Slots that enter or leave the logical range are set to @c T{}, so the
779 * elements a shorter value no longer covers cannot be observed through a
780 * later grow. @p n above the capacity @p N is clamped to @p N — the callers
781 * that can reject an over-capacity count do so before resizing (readArray
782 * checks the schema `count` first), and a heap-free container has nowhere
783 * to put the excess.
784 *
785 * @param n New logical length.
786 */
787 void resize(std::size_t n) noexcept
788 {
789 if (n > N)
790 {
791 n = N;
792 }
793 for (std::size_t i = n; i < len_; ++i)
794 {
795 buf_[i] = T{};
796 }
797 for (std::size_t i = len_; i < n; ++i)
798 {
799 buf_[i] = T{};
800 }
801 len_ = n;
802 }
803
804 /*!
805 * @brief Append a default-constructed element and return a reference to it.
806 *
807 * The next inline slot is (re)set to @c T{} and bound; once at capacity
808 * @p N the last slot is reused so a decode never writes out of bounds.
809 * @return Reference to the newly active element.
810 */
812 {
813 std::size_t i = len_ < N ? len_++ : N - 1;
814 buf_[i] = T{};
815 return buf_[i];
816 }
817
818 /*!
819 * @brief Append a copy of @p v; once at capacity @p N, @p v is dropped.
820 *
821 * The assignment-time clamp of the static storage: elements past @p N
822 * are left out and the ones already held are kept, so a filled container
823 * holds the first @p N values it was given. (@ref emplace_back, the
824 * decode-side binder, reuses the last slot instead.)
825 */
826 void push_back(const T &v) noexcept { if (len_ < N) buf_[len_++] = v; }
827 /*! @brief Append @p v by move; dropped once at capacity @p N (see above). */
828 void push_back(T &&v) noexcept { if (len_ < N) buf_[len_++] = static_cast<T &&>(v); }
829
830 /*! @brief Reference to the last element. */
831 T &back() noexcept { return buf_[len_ - 1]; }
832 /*! @brief Const reference to the last element. */
833 const T &back() const noexcept { return buf_[len_ - 1]; }
834
835 /*! @brief Access the element at @p i (no bounds checking). */
836 T &operator[](std::size_t i) noexcept { return buf_[i]; }
837 /*! @brief Access the element at @p i (no bounds checking). */
838 const T &operator[](std::size_t i) const noexcept { return buf_[i]; }
839
840 /*! @brief Mutable pointer to the underlying storage. */
841 T *data() noexcept { return buf_.data(); }
842 /*! @brief Const pointer to the underlying storage. */
843 const T *data() const noexcept { return buf_.data(); }
844
845 /*! @brief Iterator to the first element. */
846 T *begin() noexcept { return buf_.data(); }
847 /*! @brief Iterator past the last element. */
848 T *end() noexcept { return buf_.data() + len_; }
849 /*! @brief Const iterator to the first element. */
850 const T *begin() const noexcept { return buf_.data(); }
851 /*! @brief Const iterator past the last element. */
852 const T *end() const noexcept { return buf_.data() + len_; }
853
854 /*! @brief Content equality (same logical length and elements). */
855 bool operator==(const InlineVector &o) const noexcept
856 {
857 if (len_ != o.len_)
858 {
859 return false;
860 }
861 for (std::size_t i = 0; i < len_; ++i)
862 {
863 if (!(buf_[i] == o.buf_[i]))
864 {
865 return false;
866 }
867 }
868 return true;
869 }
870
871 /*! @brief Negated @ref operator==. */
872 bool operator!=(const InlineVector &o) const noexcept { return !(*this == o); }
873 };
874
875 /***************/
876 /*** OStream ***/
877 /***************/
878
879 class OStreamMessage;
880
881 /*!
882 * @brief Base output stream: encodes fields into a caller-provided buffer.
883 *
884 * Thin C++ facade over @ref sofab_ostream_t. The @c write() overloads deduce
885 * the wire encoding from the C++ type, and each returns a @ref Result that
886 * can be chained fluently. Concrete buffer ownership is added by the derived
887 * @ref OStream / @ref OStreamInline classes; this base is not constructed
888 * directly.
889 */
891 {
892 public:
893 /*! @brief Callback invoked with the bytes to flush (buffer full or on flush()).
894 *
895 * A @c std::function hosted, a plain function pointer freestanding (where
896 * @c std::function is not available — it type-erases onto the heap). Both
897 * spellings are contextually convertible to @c bool and callable, which is
898 * all this class asks of the type. The freestanding form accepts a
899 * captureless lambda or a free function; carry state through a global or
900 * through the object the stream lives in. */
901#if SOFAB_CPP_HAVE_HOSTED
902 using flushCallback = std::function<void(std::span<const uint8_t>)>;
903#else
904 using flushCallback = void (*)(std::span<const uint8_t>);
905#endif
906
907 protected:
908 sofab_ostream_t ctx_; //!< Underlying C output stream context.
909 uint8_t *buffer_; //!< Pointer to the active encode buffer.
910 // Value-initialised: empty for std::function, and null rather than
911 // indeterminate for the freestanding function pointer, which
912 // onFlushCallback() tests before calling.
913 flushCallback flushCallback_{}; //!< Optional user flush callback.
914 uint8_t failed_ = 0; //!< Sticky: first failing write's sofab_ret_t
915 //!< (0 = none). See @ref ok.
916
917 /*! @brief Invoke the user flush callback (if any) with @p len buffered bytes. */
918 void onFlushCallback(size_t len) noexcept
919 {
920 if (flushCallback_)
921 {
922 flushCallback_(std::span<const uint8_t>(buffer_, len));
923 }
924 }
925
926 /*! @brief C-ABI flush trampoline: forwards to onFlushCallback() via @p usrptr. */
929 const uint8_t *data,
930 size_t len,
931 void *usrptr) noexcept
932 {
933 (void)ctx;
934 (void)data;
935
936 OStreamImpl *self = static_cast<OStreamImpl*>(usrptr);
938 }
939
941
942 public:
943 /*!
944 * @brief Outcome of an encode operation, supporting fluent chaining.
945 *
946 * Returned by every @ref OStreamImpl write/sequence call. The first
947 * error is sticky: once set, subsequent chained calls become no-ops and
948 * the original error is preserved, so a chain can be checked once at the
949 * end. Convertible to @c bool (true on success).
950 */
952 {
953 private:
954 OStreamImpl &ostream_;
955 Error error_ = Error::None;
956
957 friend class OStreamImpl;
959 : ostream_(ostream)
960 , error_(static_cast<Error>(retval))
961 { }
962
963 sofab_ret_t rawCode() const noexcept
964 {
965 return static_cast<sofab_ret_t>(error_);
966 }
967
968 public:
969 /*!
970 * @brief Chained write of a field (no-op if a prior call failed).
971 * @param id Field identifier.
972 * @param value Value to encode; the wire type is deduced from @p T.
973 * @return This Result, carrying the first error encountered (if any).
974 */
975 template <typename T>
976 Result write(sofab_id_t id, const T &value) noexcept
977 {
978 if (error_ != Error::None)
979 {
980 return *this;
981 }
982
983 auto res = ostream_.write(id, value);
984 if (!res.ok())
985 {
986 error_ = res.code();
987 }
988
989 return *this;
990 }
991
992 /*!
993 * @brief Chained conditional write (no-op if a prior call failed).
994 * @param id Field identifier.
995 * @param value Value to encode; the wire type is deduced from @p T.
996 * @param condition Write the field only when true.
997 * @return This Result, carrying the first error encountered (if any).
998 */
999 template <typename T>
1000 Result writeIf(sofab_id_t id, const T &value, bool condition) noexcept
1001 {
1002 if (error_ != Error::None)
1003 {
1004 return *this;
1005 }
1006
1007 auto res = ostream_.writeIf(id, value, condition);
1008 if (!res.ok())
1009 {
1010 error_ = res.code();
1011 }
1012
1013 return *this;
1014 }
1015
1016 /*!
1017 * @brief Chained nested-message field write that is omitted when the
1018 * message is all-default (no-op if a prior call failed).
1019 * @param id Field identifier.
1020 * @param value Nested message to encode.
1021 * @return This Result, carrying the first error encountered (if any).
1022 * @see OStreamImpl::writeLazy
1023 */
1024 template <typename T>
1025 Result writeLazy(sofab_id_t id, const T &value) noexcept
1026 {
1027 if (error_ != Error::None)
1028 {
1029 return *this;
1030 }
1031
1032 auto res = ostream_.writeLazy(id, value);
1033 if (!res.ok())
1034 {
1035 error_ = res.code();
1036 }
1037
1038 return *this;
1039 }
1040
1041 /*!
1042 * @brief Chained frame-keeping sequence-end (no-op if a prior call failed).
1043 * @return This Result, carrying the first error encountered (if any).
1044 * @see OStreamImpl::sequenceEndKeep
1045 */
1047 {
1048 if (error_ != Error::None)
1049 {
1050 return *this;
1051 }
1052
1053 auto res = ostream_.sequenceEndKeep();
1054 if (!res.ok())
1055 {
1056 error_ = res.code();
1057 }
1058
1059 return *this;
1060 }
1061
1062 /*!
1063 * @brief Chained lazy sequence-begin (no-op if a prior call failed).
1064 * @param id Field identifier of the nested sequence.
1065 * @return This Result, carrying the first error encountered (if any).
1066 * @see OStreamImpl::sequenceBeginLazy
1067 */
1069 {
1070 if (error_ != Error::None)
1071 {
1072 return *this;
1073 }
1074
1075 auto res = ostream_.sequenceBeginLazy(id);
1076 if (!res.ok())
1077 {
1078 error_ = res.code();
1079 }
1080
1081 return *this;
1082 }
1083
1084 /*!
1085 * @brief Chained sequence-end marker (no-op if a prior call failed).
1086 * @return This Result, carrying the first error encountered (if any).
1087 */
1089 {
1090 if (error_ != Error::None)
1091 {
1092 return *this;
1093 }
1094
1095 auto res = ostream_.sequenceEnd();
1096 if (!res.ok())
1097 {
1098 error_ = res.code();
1099 }
1100
1101 return *this;
1102 }
1103
1104 /*! @brief True if no error occurred (same as ok()). */
1105 explicit operator bool() const noexcept
1106 {
1107 return ok();
1108 }
1109
1110 /*! @brief Compare the held error code to @p e. */
1111 bool operator==(Error e) const noexcept
1112 {
1113 return error_ == e;
1114 }
1115
1116 /*! @brief Negated operator==(). */
1117 bool operator!=(Error e) const noexcept
1118 {
1119 return !(*this == e);
1120 }
1121
1122 /*! @brief True if the operation (and the chain so far) succeeded. */
1124 {
1125 return error_ == Error::None;
1126 }
1127
1128 /*! @brief The first @ref Error encountered in the chain. */
1130 {
1131 return error_;
1132 }
1133 };
1134
1135 /*! @brief Copy construction is deleted (the context owns raw buffer pointers). */
1136 OStreamImpl(const OStreamImpl&) = delete;
1137 /*! @brief Copy assignment is deleted (the context owns raw buffer pointers). */
1139
1140 /*! @brief Move construction (transfers the underlying context). */
1142 /*! @brief Move assignment (transfers the underlying context). */
1144
1145 /*! @brief Destructor; flushes any buffered bytes. */
1147 {
1148 flush();
1149 }
1150
1151 /*!
1152 * @brief Flush buffered bytes through the flush callback (if any).
1153 * @return Number of bytes flushed.
1154 */
1156 {
1157 return sofab_ostream_flush(&ctx_);
1158 }
1159
1160 /*!
1161 * @brief Number of bytes written to the active buffer since the last flush.
1162 * @return Bytes currently used in the buffer.
1163 */
1165 {
1167 }
1168
1169 /*!
1170 * @brief Pointer to the start of the active encode buffer.
1171 * @return Read-only pointer to the buffer (valid for @ref bytesUsed bytes).
1172 */
1174 {
1175 return buffer_;
1176 }
1177
1178 /*!
1179 * @brief Encode a single field, deducing the wire type from @p T.
1180 *
1181 * Supports integers, @c bool, @c float, @c double, string-like types
1182 * (@c std::string / @c std::string_view / C strings), contiguous ranges
1183 * (arrays/vectors/spans) of integers, enumerations or floats, and nested
1184 * @ref OStreamMessage objects. An enumeration element travels as its
1185 * declared underlying type, so a container of scoped enums needs no
1186 * converted copy. Using a type whose capability was compiled out of the
1187 * C core is a compile-time error (see the @c SOFAB_DISABLE_* notes at
1188 * the top).
1189 *
1190 * @param id Field identifier.
1191 * @param value Value to encode.
1192 * @return @ref Result for fluent chaining and error inspection.
1193 */
1194 template <typename T>
1195 Result write(sofab_id_t id, const T &value) noexcept
1196 {
1198
1199 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>)
1200 {
1201#if !SOFAB_CPP_HAVE_INT64
1202 static_assert(sizeof(T) <= 4,
1203 "64-bit integer fields require INT64 support, disabled via "
1204 "SOFAB_DISABLE_INT64_SUPPORT");
1205#endif
1206 if constexpr (std::is_unsigned_v<T>)
1207 {
1209 &ctx_, id, static_cast<sofab_unsigned_t>(value));
1210 }
1211 else
1212 {
1214 &ctx_, id, static_cast<sofab_signed_t>(value));
1215 }
1216 }
1217 else if constexpr (std::is_same_v<T, bool>)
1218 {
1219 ret = sofab_ostream_write_boolean(&ctx_, id, value);
1220 }
1221 else if constexpr (std::is_same_v<T, float>)
1222 {
1223 ret = sofab_ostream_write_fp32(&ctx_, id, value);
1224 }
1225 else if constexpr (std::is_same_v<T, double>)
1226 {
1227#if SOFAB_CPP_HAVE_FP64
1228 ret = sofab_ostream_write_fp64(&ctx_, id, value);
1229#else
1230 static_assert(always_false_v<T>,
1231 "double (FP64) fields require FP64 support, disabled via "
1232 "SOFAB_DISABLE_FP64_SUPPORT");
1233#endif
1234 }
1235 else if constexpr (std::is_convertible_v<T, std::string_view>)
1236 {
1237 /* The view carries its own length, so use it. Routing this
1238 * through sofab_ostream_write_string() would derive the length
1239 * with strlen() instead, which is wrong in both directions: a
1240 * std::string_view need not be NUL-terminated, so strlen()
1241 * reads past the caller's buffer; and a value holding an
1242 * embedded U+0000 would be truncated there, though §4.6 frames
1243 * a string by length with no terminator and §6.4.3 makes
1244 * embedded U+0000 valid. The C convenience wrapper stays what
1245 * it is — the entry point for a genuinely NUL-terminated
1246 * const char*, which reaches this branch already converted. */
1247 std::string_view sv{value};
1248 if (sv.size() > static_cast<size_t>(INT32_MAX))
1249 {
1250 /* Longer than the int32_t the C entry point takes, so the
1251 * cast below would wrap and hand it a negative length. A
1252 * caller mistake, hence §6.3's InvalidArgument.
1253 *
1254 * Only this bound is checked here. SOFAB_FIXLEN_MAX is the
1255 * C core's and it enforces it (ostream.c), on exactly the
1256 * profile where it can bind -- one lowered per §6.2. Where
1257 * it is not lowered it equals INT32_MAX and this IS that
1258 * comparison; repeating it would be a second implementation
1259 * of one bound. */
1261 }
1262 else
1263 {
1265 &ctx_, id, sv.data(),
1266 static_cast<int32_t>(sv.size()),
1268 }
1269 }
1270 else if constexpr (std::is_base_of_v<OStreamMessage, T>)
1271 {
1272 /* The frame-KEEPING form: it survives even when the nested
1273 * message writes nothing. That is what a wrapper array's LAST
1274 * element needs -- the array carries no length, so *highest present
1275 * id + 1* is what recovers it and the final element may never be
1276 * elided (MESSAGE_SPEC §2/§5.1). A nested message that MAY vanish
1277 * when all-default -- a struct/union FIELD, and equally an INTERIOR
1278 * array element, which since §3 made `count` a capacity is omitted
1279 * exactly like a default leaf element -- is @ref writeLazy.
1280 *
1281 * The closer runs even when the nested serialize() fails, so the
1282 * sequence this call opened is always the sequence this call
1283 * closes. A failing serialize() is reachable on a perfectly
1284 * healthy stream -- write_fixlen rejects invalid UTF-8 with
1285 * E_ARGUMENT before emitting a byte under SOFAB_ENABLE_STRICT_UTF8
1286 * -- and leaving the frame open would put an unterminated sequence
1287 * on the wire and strand a slot of the bounded hold-back window.
1288 * The first failure is what the caller sees. */
1289 ret = sequenceBeginLazy(id).rawCode();
1290 if (ret == SOFAB_RET_OK)
1291 {
1292 ret = value.serialize(static_cast<OStreamImpl&>(*this)).rawCode();
1293 sofab_ret_t cret = sequenceEndKeep().rawCode();
1294 if (ret == SOFAB_RET_OK)
1295 {
1296 ret = cret;
1297 }
1298 }
1299 }
1300 else if constexpr (
1301 requires {
1302 typename T::value_type;
1303 std::span{ std::declval<const T&>() };
1304 })
1305 {
1306#if SOFAB_CPP_HAVE_ARRAY
1307 using Elem = typename T::value_type;
1308 std::span<const Elem> span{value};
1309
1310 /* An enumeration rides the integer path at its declared width, so
1311 * a caller holding `std::vector<Gear>` (the shape the generator
1312 * stores an `enum` array in, MESSAGE_SPEC §1) needs no converted
1313 * copy. The element type changes nothing that leaves here: the
1314 * entry point and the element width are the same two facts as for
1315 * the integer behind it, `span.data()` reaches `const void *` by
1316 * the ordinary implicit conversion, and this side casts nothing.
1317 *
1318 * The C core then loads each element at element_size through a
1319 * typed lvalue (`_write_varint_array` in ostream.c) rather than
1320 * copying it out. For an enum array that load is formally covered
1321 * only at width 1, via `unsigned char`; wider elements rest on
1322 * `enum class E : U` having the size, alignment and value
1323 * representation of U, which the standard does guarantee. Written
1324 * down rather than glossed over, because the alternative is worse
1325 * on the axis this corelib exists for: making the C core copy out
1326 * with memcpy instead costs .text in the element loop of EVERY
1327 * array, integer ones included, and -mno-unaligned-access turns
1328 * that copy into byte loads on the ARMv6-M targets. */
1329 if constexpr ((std::is_integral_v<Elem> || std::is_enum_v<Elem>) &&
1330 !std::is_same_v<Elem, bool>)
1331 {
1332 /* What the elements travel as. Signedness comes from this and
1333 * never from Elem -- see @ref wire_int. sizeof is the same
1334 * either way, but element_size stays the ELEMENT's size: it is
1335 * what the C side strides the caller's array by. */
1336 using U = wire_int_t<Elem>;
1337#if !SOFAB_CPP_HAVE_INT64
1338 static_assert(sizeof(U) <= 4,
1339 "64-bit integer arrays require INT64 support, disabled "
1340 "via SOFAB_DISABLE_INT64_SUPPORT");
1341#endif
1342 if constexpr (std::is_unsigned_v<U>)
1343 {
1345 &ctx_, id,
1346 span.data(),
1347 static_cast<int32_t>(span.size()),
1348 sizeof(Elem));
1349 }
1350 else
1351 {
1353 &ctx_, id,
1354 span.data(),
1355 static_cast<int32_t>(span.size()),
1356 sizeof(Elem));
1357 }
1358 }
1359 else if constexpr (std::is_same_v<Elem, bool>)
1360 {
1361 /* A boolean array travels as an unsigned varint array, and
1362 * needs no normalizing step of its own: §4.4 is canonical on
1363 * encode, and these elements are `bool` objects, which hold
1364 * 0 or 1 and are that form already. Only a decode sees
1365 * foreign bytes, which is why only the read normalizes. */
1367 &ctx_, id,
1368 span.data(),
1369 static_cast<int32_t>(span.size()),
1370 sizeof(bool));
1371 }
1372 else if constexpr (std::is_same_v<Elem, float>)
1373 {
1375 &ctx_, id,
1376 span.data(),
1377 static_cast<int32_t>(span.size()));
1378 }
1379 else if constexpr (std::is_same_v<Elem, double>)
1380 {
1381#if SOFAB_CPP_HAVE_FP64
1383 &ctx_, id,
1384 span.data(),
1385 static_cast<int32_t>(span.size()));
1386#else
1387 static_assert(always_false_v<T>,
1388 "double (FP64) arrays require FP64 support, disabled "
1389 "via SOFAB_DISABLE_FP64_SUPPORT");
1390#endif
1391 }
1392 else
1393 {
1394 static_assert(always_false_v<T>,
1395 "Unsupported span element type in OStream::write()");
1396 }
1397#else
1398 static_assert(always_false_v<T>,
1399 "array/span fields require ARRAY support, disabled via "
1400 "SOFAB_DISABLE_ARRAY_SUPPORT");
1401#endif
1402 }
1403 else
1404 {
1405 static_assert(always_false_v<T>,
1406 "Unsupported type passed to OStream::write()");
1407 }
1408
1409 return result(ret);
1410 }
1411
1412 /*!
1413 * @brief Encode a nested message **field**, omitting it when all-default.
1414 *
1415 * Same as @ref write for an @ref OStreamMessage, except it closes with
1416 * @ref sequenceEnd rather than @ref sequenceEndKeep: the nested @c serialize
1417 * omits every child
1418 * that equals its default, so "not one child was written" is exactly "the
1419 * object equals its declared default" -- evaluated per child field,
1420 * recursively -- and the field is then dropped instead of emitted as an
1421 * empty frame (MESSAGE_SPEC §2).
1422 *
1423 * Use it for a @c struct / @c union **field**. Keep plain @ref write for an
1424 * array **element**: element presence carries a dynamic array's length
1425 * (§5.1), so an all-default element stays framed.
1426 *
1427 * As in @ref write, the closer runs even when the nested @c serialize
1428 * fails (a strict-UTF-8 rejection does that on an otherwise healthy
1429 * stream), so the sequence never stays open and the hold-back window never
1430 * strands a slot. The first failure is the one returned.
1431 *
1432 * @param id Field identifier.
1433 * @param value Nested message to encode.
1434 * @return @ref Result for fluent chaining and error inspection.
1435 */
1436 template <typename T>
1437 Result writeLazy(sofab_id_t id, const T &value) noexcept
1438 {
1439 static_assert(std::is_base_of_v<OStreamMessage, T>,
1440 "writeLazy() takes a nested message; plain write() covers every other type");
1441 sofab_ret_t ret = sequenceBeginLazy(id).rawCode();
1442 if (ret == SOFAB_RET_OK)
1443 {
1444 ret = value.serialize(static_cast<OStreamImpl&>(*this)).rawCode();
1445 sofab_ret_t cret = sequenceEnd().rawCode();
1446 if (ret == SOFAB_RET_OK)
1447 {
1448 ret = cret;
1449 }
1450 }
1451
1452 return result(ret);
1453 }
1454
1455 /*!
1456 * @brief Encode a raw binary blob field.
1457 * @param id Field identifier.
1458 * @param value Pointer to the bytes to write.
1459 * @param size Number of bytes at @p value.
1460 * @return @ref Result for fluent chaining and error inspection.
1461 */
1462 Result write(sofab_id_t id, const void *value, int32_t size) noexcept
1463 {
1464 return result(sofab_ostream_write_blob(&ctx_, id, value, size));
1465 }
1466
1467 /*!
1468 * @brief Encode a field only when @p condition is true.
1469 * @param id Field identifier.
1470 * @param value Value to encode; the wire type is deduced from @p T.
1471 * @param condition Write the field only when true; otherwise a success no-op.
1472 * @return @ref Result for fluent chaining and error inspection.
1473 */
1474 template <typename T>
1475 Result writeIf(sofab_id_t id, const T &value, bool condition) noexcept
1476 {
1477 if (condition)
1478 {
1479 return write(id, value);
1480 }
1481
1482 return result(SOFAB_RET_OK);
1483 }
1484
1485
1486 /*!
1487 * @brief Open a nested sequence whose header is held back until it turns
1488 * out to have content.
1489 *
1490 * MESSAGE_SPEC §2 omits a sequence-typed field whose value equals its
1491 * declared default, and "not one child was written" is exactly that
1492 * condition -- evaluated per child field, recursively, for free. Closing
1493 * such a sequence with nothing in it emits **nothing** instead of a
1494 * two-byte empty frame, so an all-default message becomes the empty byte
1495 * string. The predicate never touches a byte image, so struct padding
1496 * cannot influence it.
1497 *
1498 * Where an empty frame carries meaning, close with @ref sequenceEndKeep
1499 * instead: the **last element** of a wrapper array (§5.1 — the interior is
1500 * sparse and drops like any default field), the §4.9 empty-sequence
1501 * primitive itself, and the explicitly empty array of a field that declares
1502 * a non-empty default (§2, §3). The wrapper deliberately exposes no eager
1503 * opener — the frame-or-not decision belongs to the closer, which is the
1504 * one call site that knows the position in the schema. (The C core keeps
1505 * @c sofab_ostream_write_sequence_begin() for @c sofab_object_encode().)
1506 *
1507 * **Bounded**: at most @c SOFAB_LAZY_SEQ_DEPTH (default 8) headers are
1508 * held back at once; a sequence opened deeper than that is framed eagerly
1509 * and keeps an empty frame it could have dropped — well-formed and
1510 * value-identical, but not canonical. See @c SOFAB_LAZY_SEQ_DEPTH in
1511 * @c sofab/ostream.h.
1512 *
1513 * @param id Field identifier of the sequence.
1514 * @return @ref Result for fluent chaining and error inspection.
1515 */
1517 {
1518 return result(sofab_ostream_write_sequence_begin_lazy(&ctx_, id));
1519 }
1520
1521 /*!
1522 * @brief Close the current nested sequence, letting it vanish if it got no
1523 * content (MESSAGE_SPEC §2).
1524 * @return @ref Result for fluent chaining and error inspection.
1525 */
1527 {
1528 return result(sofab_ostream_write_sequence_end(&ctx_));
1529 }
1530
1531 /*!
1532 * @brief Close the current nested sequence, keeping its frame even without
1533 * content.
1534 *
1535 * Emits the held-back headers -- this frame's and every enclosing one's --
1536 * and then the end marker, so an empty sequence reaches the wire as
1537 * begin + end. Required wherever the frame carries information beyond its
1538 * contents: a wrapper-array ELEMENT (presence carries a dynamic array's
1539 * length, MESSAGE_SPEC §5.1), and an array field already known to differ
1540 * from a non-empty declared default (§2, §3).
1541 *
1542 * @return @ref Result for fluent chaining and error inspection.
1543 */
1548
1549 private:
1550 /*! @brief Wrap a C return code in a @ref Result bound to this stream. */
1551 inline Result result(sofab_ret_t ret) noexcept
1552 {
1553 // Remember the first failure. A caller may chain writes and read the
1554 // verdict off the returned Result, but generated serialize() bodies
1555 // issue each write on its own and discard the result, so without this
1556 // a full buffer would leave no trace anywhere.
1557 if (failed_ == 0 && ret != SOFAB_RET_OK)
1558 {
1559 failed_ = (uint8_t)ret;
1560 }
1561
1562 return Result{*this, ret};
1563 }
1564
1565 public:
1566 /*!
1567 * @brief Whether every write on this stream has succeeded.
1568 *
1569 * Sticky and independent of how the writes were issued — chained or one
1570 * at a time with the result discarded. The usual reason it turns false is
1571 * @ref Error::BufferFull on a stream over caller storage
1572 * (@ref OStreamView), where the destination can be smaller than the
1573 * message.
1574 *
1575 * @return true while no write has failed.
1576 */
1577 [[nodiscard]] bool ok() const noexcept { return failed_ == 0; }
1578
1579 /*!
1580 * @brief The first failure this stream saw, or @ref Error::None.
1581 * @return The error code of the first failing write.
1582 */
1584 {
1585 return static_cast<Error>(failed_);
1586 }
1587
1588 /*!
1589 * @brief Refuse the value being encoded: latch @ref Error::InvalidArgument.
1590 *
1591 * The hook a generated @c serialize() calls when a field's value is past
1592 * a bound only the schema knows -- a string or blob longer than its
1593 * @c maxlen, an array with more elements than its @c count. The corelib
1594 * holds no schema bound; it records the refusal (first failure wins), so
1595 * that @ref ok and @ref error report it like any other failed write and
1596 * no byte of the message is returned as a success. Writes nothing
1597 * itself. Generated code tests @ref ENCODE_BOUNDS first, so
1598 * @c SOFAB_DISABLE_ENCODE_BOUNDS compiles every such check away.
1599 *
1600 * Cold and out of line: every guard in a generated serialize() then
1601 * shares one call instead of its own inlined latch (measured on
1602 * ARMv6-m: 202 B instead of 300 B of .text for the 18 guards of the
1603 * bench schema), and the rare path stays out of the hot one.
1604 *
1605 * @return A Result carrying @ref Error::InvalidArgument.
1606 */
1607 [[gnu::cold, gnu::noinline]] Result rejectArgument() noexcept
1608 {
1609 return result(SOFAB_RET_E_ARGUMENT);
1610 }
1611
1612 protected:
1613 };
1614
1615#if SOFAB_CPP_HAVE_HOSTED
1616 /*!
1617 * @brief Output stream backed by a heap buffer (@c std::shared_ptr).
1618 *
1619 * Owns (or shares) a dynamically allocated buffer. With a flush callback the
1620 * buffer can be swapped mid-encoding via @ref setBuffer to stream in chunks.
1621 *
1622 * Hosted only: @c std::shared_ptr is unavailable freestanding. The heap-free
1623 * counterparts are @ref OStreamInline (buffer inside the object) and
1624 * @ref OStreamView (buffer supplied by the caller), which cover every
1625 * embedded use of this class.
1626 */
1627 class OStream : public OStreamImpl
1628 {
1629 protected:
1630 std::shared_ptr<uint8_t[]> bufferOwner_; //!< Shared owner of the encode buffer.
1631
1633
1634 public:
1635 /*!
1636 * @brief Construct with a freshly allocated buffer.
1637 * @param buflen Buffer size in bytes.
1638 * @param offset Initial write offset within the buffer (default 0).
1639 */
1640 OStream(size_t buflen, size_t offset = 0) noexcept
1641 {
1642 bufferOwner_ = std::make_shared<uint8_t[]>(buflen);
1643 buffer_ = bufferOwner_.get();
1644 sofab_ostream_init(&ctx_, buffer_, buflen, offset, nullptr, nullptr);
1645 }
1646
1647 /*!
1648 * @brief Construct over a caller-provided shared buffer.
1649 * @param buffer Shared buffer to encode into.
1650 * @param buflen Usable size of @p buffer in bytes.
1651 * @param offset Initial write offset within the buffer (default 0).
1652 */
1653 OStream(
1654 std::shared_ptr<uint8_t[]> buffer, size_t buflen,
1655 size_t offset = 0) noexcept
1656 : bufferOwner_{buffer}
1657 {
1658 buffer_ = bufferOwner_.get();
1659 sofab_ostream_init(&ctx_, buffer_, buflen, offset, nullptr, nullptr);
1660 }
1661
1662 /*!
1663 * @brief Construct with a flush callback for chunked streaming.
1664 * @param callback Invoked with buffered bytes when the buffer fills or on flush().
1665 * @param buffer Shared buffer to encode into.
1666 * @param buflen Usable size of @p buffer in bytes.
1667 * @param offset Initial write offset within the buffer (default 0).
1668 */
1669 OStream(
1670 flushCallback callback,
1671 std::shared_ptr<uint8_t[]> buffer, size_t buflen,
1672 size_t offset = 0) noexcept
1673 : bufferOwner_{buffer}
1674 {
1675 flushCallback_ = callback;
1676 buffer_ = bufferOwner_.get();
1677 sofab_ostream_init(&ctx_, buffer_, buflen, offset, static_flush_callback, this);
1678 }
1679
1680 /*!
1681 * @brief Replace the active buffer (typically from within a flush callback).
1682 * @param buffer New shared buffer to continue encoding into.
1683 * @param buflen Usable size of @p buffer in bytes.
1684 * @param offset Initial write offset within the new buffer (default 0).
1685 */
1686 void setBuffer(
1687 std::shared_ptr<uint8_t[]> buffer, size_t buflen,
1688 size_t offset = 0) noexcept
1689 {
1690 bufferOwner_ = buffer;
1691 buffer_ = bufferOwner_.get();
1692 sofab_ostream_buffer_set(&ctx_, buffer_, buflen, offset);
1693 }
1694
1695 /*!
1696 * @brief Access the currently owned buffer.
1697 * @return Shared pointer to the active buffer.
1698 */
1699 std::shared_ptr<uint8_t[]> getBuffer() noexcept
1700 {
1701 return bufferOwner_;
1702 }
1703 };
1704#endif /* SOFAB_CPP_HAVE_HOSTED */
1705
1706 /*!
1707 * @brief Output stream backed by an inline, fixed-size buffer.
1708 *
1709 * Stores the @c N-byte buffer inside the object (no heap allocation), making
1710 * it well suited to embedded use.
1711 *
1712 * @tparam N Total buffer size in bytes (must be > 0).
1713 * @tparam Offset Initial write offset within the buffer (must be < @c N).
1714 */
1715 template <size_t N, size_t Offset = 0>
1717 {
1718 static_assert(N > 0, "Buffer size N must be greater than zero");
1719 static_assert(Offset < N, "Offset must be less than buffer size N");
1720 std::array<uint8_t, N> bufferOwner_ = {}; //!< Inline encode buffer.
1721
1722 public:
1723 /*! @brief Construct with no flush callback. */
1725 {
1726 buffer_ = bufferOwner_.data();
1727 sofab_ostream_init(&ctx_, buffer_, N, Offset, nullptr, nullptr);
1728 }
1729
1730 /*!
1731 * @brief Construct with a flush callback.
1732 * @param callback Invoked with buffered bytes when the buffer fills or on flush().
1733 */
1735 {
1736 buffer_ = bufferOwner_.data();
1739 }
1740 };
1741
1742 /*!
1743 * @brief Output stream over a buffer the caller already owns.
1744 *
1745 * Neither allocates nor copies: encoding writes straight into @p buffer. The
1746 * counterpart to @ref OStreamInline (buffer inside the object) and @ref
1747 * OStream (buffer held by a @c shared_ptr) — this is the one to use when the
1748 * destination already exists: a DMA or radio frame, a slot in a ring buffer,
1749 * or the @c dst of a generated @c encodeTo.
1750 *
1751 * The buffer must outlive the stream, and it is @b not restored if encoding
1752 * fails: a write past @p buflen ends in @ref Error::BufferFull with the bytes
1753 * written so far already in place. That is the price of not staging the
1754 * output elsewhere first — a caller needing all-or-nothing encodes into
1755 * scratch storage and copies on success.
1756 */
1758 {
1759 public:
1760 /*!
1761 * @brief Construct over caller storage.
1762 * @param buffer Destination; must outlive this stream.
1763 * @param buflen Usable size of @p buffer in bytes.
1764 * @param offset Initial write offset within the buffer (default 0).
1765 */
1766 OStreamView(uint8_t *buffer, size_t buflen, size_t offset = 0) noexcept
1767 {
1768 buffer_ = buffer;
1769 sofab_ostream_init(&ctx_, buffer_, buflen, offset, nullptr, nullptr);
1770 }
1771
1772 /*!
1773 * @brief Construct over caller storage with a flush callback.
1774 * @param callback Invoked with buffered bytes when the buffer fills or on flush().
1775 * @param buffer Destination; must outlive this stream.
1776 * @param buflen Usable size of @p buffer in bytes.
1777 * @param offset Initial write offset within the buffer (default 0).
1778 */
1780 flushCallback callback, uint8_t *buffer, size_t buflen,
1781 size_t offset = 0) noexcept
1782 {
1783 buffer_ = buffer;
1786 }
1787 };
1788
1789 class OStreamMessage;
1790
1791 /*! @brief Detects the CORELIB_PLAN §6.1.1 spelling of the worst-case size. */
1792 template <class T>
1793 concept HasMaxSize =
1794 requires { { T::MAX_SIZE } -> std::convertible_to<std::size_t>; } &&
1795 std::is_same_v<decltype(T::MAX_SIZE), const std::size_t>;
1796
1797 /*! @brief Detects the pre-0.11 spelling. Deprecated; see @ref OutputMessage. */
1798 template <class T>
1800 requires { { T::_maxSize } -> std::convertible_to<std::size_t>; } &&
1801 std::is_same_v<decltype(T::_maxSize), const std::size_t>;
1802
1803 /*!
1804 * @brief The worst-case encoded size of a generated message, whichever
1805 * spelling it declares. Prefers `MAX_SIZE`.
1806 */
1807 template <class T>
1808 inline constexpr size_t max_size_v = [] () constexpr -> size_t
1809 {
1810 if constexpr (HasMaxSize<T>) { return T::MAX_SIZE; }
1811 else { return T::_maxSize; }
1812 }();
1813
1814 /*!
1815 * @brief Concept: a serializable message type usable with @ref OStreamObject.
1816 *
1817 * Derives from @ref OStreamMessage and declares its worst-case encoded size.
1818 *
1819 * CORELIB_PLAN §6.1.1 closes the generated-object name set and puts
1820 * **`MAX_SIZE`** in it, permitting "only casing/idiom …, never the words".
1821 * This concept required `_maxSize`, an underscore-prefixed private-marker
1822 * spelling that is past casing — and because the concept is a hard
1823 * requirement, it fixed that name for every generated type built against this
1824 * corelib. (The C side was never affected: generated C emits
1825 * `MESSAGE_<NAME>_MAX_SIZE`, an idiomatic C macro spelling.)
1826 *
1827 * Both spellings are accepted so the rename is not a flag day: a generated
1828 * tree built against 0.10 keeps compiling while the `cpp` backend switches
1829 * over. `_maxSize` is deprecated and will be dropped once no emitter uses it.
1830 */
1831 template <class T>
1833 std::derived_from<T, OStreamMessage> &&
1835
1836 /*!
1837 * @brief Base class for serializable message objects.
1838 *
1839 * Derive from this and implement @ref serialize to define how the message's
1840 * fields are written. Use with @ref OStreamObject to encode instances.
1841 */
1843 {
1844 protected:
1845 /*!
1846 * @brief Serialize this message's fields into @p _ostream.
1847 * @param _ostream Output stream to write the fields to.
1848 * @return The encode @ref OStreamImpl::Result.
1849 */
1850 virtual OStreamImpl::Result
1851 serialize(OStreamImpl &_ostream) const noexcept = 0;
1852 };
1853
1854 /*!
1855 * @brief Self-contained encoder that owns a message and an inline buffer.
1856 *
1857 * Bundles a @ref OStreamMessage instance with an @ref OStreamInline buffer
1858 * sized from the message's worst-case size, so a message can be populated and
1859 * encoded in one object.
1860 *
1861 * @tparam MessageType An @ref OutputMessage type.
1862 * @tparam N Buffer size in bytes (defaults to the message's
1863 * @c MAX_SIZE, or its deprecated @c _maxSize).
1864 * @tparam Offset Initial write offset within the buffer.
1865 */
1866 template <OutputMessage MessageType, size_t N = max_size_v<MessageType>, size_t Offset = 0>
1867 class OStreamObject : public OStreamInline<N + Offset, Offset>
1868 {
1869 MessageType message_; //!< The owned message instance.
1870
1871 public:
1872 /*! @brief Construct with no flush callback. */
1874 /*!
1875 * @brief Construct with a flush callback.
1876 * @param callback Invoked with buffered bytes when the buffer fills or on flush().
1877 */
1878 // The typedef comes from OStreamImpl, the base this type actually derives
1879 // from through OStreamInline — not from the heap-backed OStream, which is
1880 // unrelated to it and absent in a freestanding build.
1884
1885 /*! @brief Member-access to the owned message (e.g. @c obj->field = ...). */
1886 MessageType& operator->() noexcept
1887 {
1888 return message_;
1889 }
1890
1891 /*!
1892 * @brief Serialize the owned message and flush.
1893 * @return The encode @ref OStreamImpl::Result.
1894 */
1896 {
1897 auto result = message_.serialize(static_cast<OStreamImpl&>(*this));
1899
1900 return result;
1901 }
1902 };
1903
1904 /*!
1905 * @brief @ref OStreamObject variant parameterized by offset only.
1906 *
1907 * Convenience alias-like class fixing @c N to the message's worst-case size while
1908 * letting the caller choose a leading @p Offset (e.g. to reserve a header).
1909 *
1910 * @tparam MessageType An @ref OutputMessage type.
1911 * @tparam Offset Initial write offset within the buffer.
1912 */
1913 template <OutputMessage MessageType, size_t Offset = 0>
1914 class OStreamObjectOffset : public OStreamObject<MessageType, max_size_v<MessageType>, Offset>
1915 {
1916 };
1917
1918
1919 /***************/
1920 /*** IStream ***/
1921 /***************/
1922
1923 class IStreamMessage;
1924 /*! @brief Concept: a decodable message type usable with @ref IStreamObject
1925 * and the nested-message @c IStreamImpl::read() overload. */
1926 template <typename T>
1927 concept InputMessage = std::derived_from<T, IStreamMessage>;
1928
1929 /*! @brief Detects a container that states its own fixed capacity: the
1930 * condition behind @c fixed_capacity_v.
1931 *
1932 * Named, rather than written inline where it is used, because the natural
1933 * spelling of @c fixed_capacity_v -- an immediately-invoked constexpr
1934 * lambda with a requires-expression in its body -- segfaults Clang 17 on
1935 * instantiation, in @c Sema::BuildExprRequirement reached through
1936 * @c TransformRequiresExpr inside @c TransformLambdaExpr inside
1937 * @c InstantiateVariableInitializer. That form is valid C++20 and GCC and
1938 * current Clang both accept it; the crash is an upstream Clang 17 bug,
1939 * reproduced on stock 17.0.6 rather than only on the Renesas fork the RL78
1940 * job builds with. What matters is where the requires-expression sits: it
1941 * is fine in a named concept, so @c max_size_v above keeps its lambda,
1942 * and fine in an @c if @c constexpr inside a function template, so
1943 * @c arrayRoom_ keeps its inline one. This was the only place that put a
1944 * requires-expression in a lambda body, and the only one that had to move.
1945 * test/cpp-freestanding/freestanding.cpp pins this with a static_assert,
1946 * because that file is the only C++ the RL78 job compiles. */
1947 template <typename C>
1949 requires { { C::capacity() } -> std::convertible_to<std::size_t>; };
1950
1951 /*!
1952 * @brief Compile-time capacity a heap-free container publishes, or -1.
1953 *
1954 * @ref InlineVector, @ref FixedString and @ref FixedBytes all declare
1955 * @c capacity() @c static @c constexpr, which is what tells them apart from
1956 * @c std::vector — whose @c capacity() is a per-object, runtime quantity and
1957 * so cannot be called on the type.
1958 *
1959 * @par Two readings, and which one applies is decided by the caller
1960 * A heap-free container is usually generated for a schema `count` /
1961 * `maxlen`, so its capacity is numerically that bound. Whether it is *read*
1962 * as that bound depends on whether the caller was told the bound some other
1963 * way, and the two callers in this header differ:
1964 *
1965 * - **the reads** — @ref IStreamImpl::readString, @ref IStreamImpl::readBlob
1966 * and @ref IStreamImpl::readArray take the schema bound as a parameter, so
1967 * the capacity is *not* what states it to them. What the capacity means to
1968 * a read is how much storage the caller offered — §6.3's **third** tier,
1969 * and a value the schema and the cap both admit but the destination cannot
1970 * hold is @ref Error::InvalidArgument, never @ref Error::InvalidMessage.
1971 * A read passed no bound is told nothing about the schema and can only
1972 * apply that third tier — which is why a capacity of -1 there, with no
1973 * bound and no cap, leaves the read with **no** ceiling at all and is
1974 * refused outright (@ref IStreamImpl::refuseUnbounded);
1975 * - **the fixed-storage collectors** — @ref FixedMessageSeq and the fixed
1976 * string/blob sequences take no `cap` at all, by design: their
1977 * @c static_assert says the container's capacity *is* the schema bound
1978 * they were generated for, because there is no other channel to state it
1979 * on. For them it is §6.3's **first** tier, and an element past it is
1980 * @ref Error::InvalidMessage (MESSAGE_SPEC §7.1).
1981 *
1982 * Both are correct, and the difference is not about the number — it is about
1983 * which channel states it. A collector generated *for* a bound carries it in
1984 * the only place it has; a read is told it outright, and applies it through
1985 * @ref IStreamImpl::refuseSchema (or @ref IStreamImpl::refuseCap, on the
1986 * `…Capped` entry point) before it sizes anything.
1987 *
1988 * @tparam C Container type.
1989 */
1990 template <typename C>
1991 inline constexpr long fixed_capacity_v = -1;
1992
1993 template <HasFixedCapacity C>
1994 inline constexpr long fixed_capacity_v<C> = static_cast<long>(C::capacity());
1995
1996
1997 /*!
1998 * @brief A CORELIB_PLAN §6.2.1 receiver cap, exactly as the caller states it.
1999 *
2000 * §6.2.1 draws a line this type exists to make unforgeable: the **provenance**
2001 * of a receiver limit is generated code's, and "there is no unset state and no
2002 * unlimited mode". A codec "**MUST NOT** hold a limit of its own, **MUST NOT**
2003 * supply a default for one it was not given, **MUST NOT** read an omitted
2004 * argument as *unlimited*".
2005 *
2006 * A `long dynCap = -1` parameter breaks the last of those by construction: the
2007 * sentinel *is* an omitted argument, and reading it as "no ceiling" is the
2008 * unlimited mode the clause forbids. This type has no such spelling.
2009 *
2010 * - a value is stated by constructing from an unsigned count — @c DynCap{64};
2011 * - a default-constructed @c DynCap is **unstated**, which is not "unlimited"
2012 * but *missing*. Reaching it on a schema-unbounded field is an error in the
2013 * **call** — the caller stated neither a schema bound nor a cap — and is
2014 * reported as @ref Error::InvalidArgument (§6.3), never decoded uncapped;
2015 * - a signed argument does not compile, so the old `-1` cannot be smuggled in
2016 * as @c SIZE_MAX, which would be the unlimited mode wearing a new type.
2017 *
2018 * The number is still never held past the comparison it was passed for: a
2019 * @c DynCap lives in the caller's collector or on the caller's stack, and this
2020 * header only reads it.
2021 */
2023 {
2024 std::size_t value_ = 0;
2025 bool stated_ = false;
2026
2027 public:
2028 /*! @brief The **unstated** cap: missing, not unlimited. */
2029 constexpr DynCap() noexcept = default;
2030
2031 /*! @brief State the cap. @p v is a maximum: @c n @c > @c v is refused. */
2032 constexpr explicit DynCap(std::size_t v) noexcept : value_(v), stated_(true) {}
2033
2034 /*! @brief Deleted: a signed cap would let `-1` re-enter as an unlimited mode. */
2035 template <typename T>
2036 requires std::is_signed_v<T>
2037 constexpr explicit DynCap(T) = delete;
2038
2039 /*! @brief Whether the caller stated a number at all. */
2040 [[nodiscard]] constexpr bool stated() const noexcept { return stated_; }
2041
2042 /*! @brief The stated maximum. Meaningless unless @ref stated. */
2043 [[nodiscard]] constexpr std::size_t value() const noexcept { return value_; }
2044 };
2045
2046
2047 /*!
2048 * @brief Base input stream: incrementally decodes fed bytes into bound targets.
2049 *
2050 * Thin C++ facade over @ref sofab_istream_t. Bytes are supplied via
2051 * @ref feed; inside a field callback (or a message's @c deserialize) the
2052 * matching @c read() overload binds the destination for the current field.
2053 * Decoding is lazy — a bound target is filled by subsequent @ref feed calls,
2054 * so targets must stay alive and address-stable until decoding completes.
2055 */
2057 {
2058 protected:
2059 sofab_istream_t ctx_; //!< Underlying C input stream context.
2060
2061 // Persistent decoder for variable-length-element array reads (see the
2062 // std::vector read() overloads below). The C decoder is deferred: a
2063 // read_sequence() only registers this decoder, and its per-element
2064 // callbacks fire later as feed() advances. It must therefore outlive the
2065 // field callback that started the array, so it lives in the stream object
2066 // rather than on the caller's stack.
2067 //
2068 // One member supports one active variable-length array at a time, which
2069 // covers all realistic schemas: array elements here are scalars (string /
2070 // blob), and sibling or nested-message array fields decode sequentially.
2071 // Genuinely nested variable-length arrays (e.g. vector<vector<string>>)
2072 // would need a decoder stack and are intentionally not supported.
2074
2075 // The category of a refusal a *callback* made, latched at the first one
2076 // and held until the stream is re-initialized.
2077 //
2078 // The C core has one sticky verdict, SOFAB_RET_E_INVALID_MSG, and that is
2079 // the whole of what it needs: it cannot be handed an unbounded field
2080 // (every C read carries its destination's size), so it can neither be
2081 // told of a breached receiver cap nor be handed a destination the caller
2082 // sized wrong. The wrapper can be both, so it keeps its own category
2083 // beside the core's flag: sofab_istream_invalidate() stops the decode and
2084 // makes it terminal, and this says which of §6.3's three refusals it was.
2085 // SOFAB_RET_OK means "no callback refusal" — then feed() reports whatever
2086 // the core decided.
2087 //
2088 // First-wins, because a decode is sequential: the first field to be
2089 // refused is the one that ended the message, and a later field in the same
2090 // fed chunk must not overwrite that verdict (the core keeps dispatching
2091 // within a feed after a callback rejects).
2093
2095
2096 // Latch a callback-side refusal and stop the decode. The category is
2097 // recorded here; the stop is the core's own sticky INVALID flag, which is
2098 // what keeps the rejection terminal across feeds (§5.2 / §6.3).
2100 {
2101 if (refusal_ == SOFAB_RET_OK)
2102 {
2103 refusal_ = static_cast<uint8_t>(category);
2104 }
2106 }
2107
2108 /*!
2109 * @brief Clear a latched refusal, for a subclass that re-initialises the
2110 * stream itself.
2111 *
2112 * @ref invalidate documents the verdict as cleared by re-initialising the
2113 * stream, and the C core's own sticky flag is. This one is not: it is a
2114 * member, so it survives a bare `sofab_istream_init()` on the embedded
2115 * context and would report a stale category on the next message. The
2116 * library never hits that — `sofab_istream_init` is called from the
2117 * constructors — but a subclass that re-inits to reuse one object (as
2118 * `bench/cpp` does) must call this in the same breath.
2119 */
2121 {
2123 }
2124
2125 // Count a §7.3 skip the C core cannot see. The core counts a skip when a
2126 // bound read contradicts the wire; the reads that must check the type
2127 // *before* they touch their destination (readString, readBlob,
2128 // readSequence) decline without ever binding, so from the core's side
2129 // they are indistinguishable from a callback that simply was not
2130 // interested. Counting here keeps sofab_istream_skipped meaning the same
2131 // thing whichever side detected the contradiction. Saturating, like the
2132 // core's own increment.
2134 {
2135#if SOFAB_SKIP_COUNTER
2136 if (ctx_.skipped < 0xFF)
2137 {
2138 ctx_.skipped++;
2139 }
2140#endif
2141 }
2142
2143 // sofab_istream_read_field's bind, returning the MESSAGE_SPEC §7.3 tag
2144 // test the stream applies to it after the callback: on entry target_opt
2145 // still holds the DELIVERED wire type (bits 0-2) and fixlen subtype
2146 // (bits 3-5), and this is _call_field_callback_masked's own 0x3F
2147 // comparison, taken before the bind overwrites it. A contradicting bind
2148 // is unbound again, and counted, by the stream -- as for any read.
2149 //
2150 // Out of line on purpose, and here rather than in istream.c: every
2151 // readMatch call shares this one copy of the comparison, and a program
2152 // that never calls readMatch -- every one without a tagged union, and
2153 // every pure-C one -- carries none of it, not even in the library.
2154 // `(diff << 26) == 0` is `(diff & 0x3F) == 0`, 2-4 bytes smaller on
2155 // ARMv6-m/ARMv7-m.
2156 [[gnu::noinline]] bool bindMatch_(void *var, size_t len, uint8_t opt) noexcept
2157 {
2158 uint8_t *const target_opt = &ctx_.target_opt;
2159 const uint32_t diff = static_cast<uint32_t>(*target_opt ^ opt);
2160
2161 ctx_.target_ptr = static_cast<uint8_t *>(var);
2163 *target_opt = opt;
2164
2165 return (diff << 26) == 0u;
2166 }
2167
2168 // ---- the bodies the capped and uncapped read entry points share ------
2169 //
2170 // §6.2.1 asks for ONE implementation of the rule wherever it runs, and the
2171 // two entry points differ only in WHICH ceiling they were handed: the
2172 // schema's, or the receiver's. Everything after that verdict -- the third
2173 // tier, the sizing, the bind -- is identical, so it lives here once rather
2174 // than being copied into the *Capped twin, where the two could drift.
2175
2176 // Third tier, then size and bind a string/blob destination.
2177 template <typename T>
2178 void bindString_(T &value, size_t size) noexcept
2179 {
2180 if (refuse(size, fixed_capacity_v<T>))
2181 {
2182 return;
2183 }
2184
2185 if constexpr (requires { value.set_len(size); })
2186 {
2187 value.set_len(size);
2188 }
2189 else
2190 {
2191 value.resize(size);
2192 }
2193
2194 // a zero-length string binds no target: there is nothing to fill
2195 if (value.size())
2196 {
2197 read(value);
2198 }
2199 }
2200
2201 template <typename T>
2202 void bindBlob_(T &value, size_t size) noexcept
2203 {
2204 if (refuse(size, fixed_capacity_v<T>))
2205 {
2206 return;
2207 }
2208
2209 if constexpr (requires { value.set_len(size); })
2210 {
2211 value.set_len(size);
2212 }
2213 else
2214 {
2215 value.resize(size);
2216 }
2217
2218 // Bind the destination's own size, not the wire length: a wire length
2219 // beyond the declared bound is then rejected as INVALID by the C
2220 // decoder rather than silently truncated (MESSAGE_SPEC §7.1).
2221 read(value.data(), value.size());
2222 }
2223
2224 // MESSAGE_SPEC §7.3 for an array: does the delivered tag match the
2225 // destination's element type?
2226 template <typename C>
2228 {
2229 using Elem = typename C::value_type;
2230
2231 if constexpr (std::is_same_v<Elem, float>)
2232 {
2233 return wire() == Wire::ArrayFixlen && fixType() == Fix::Fp32;
2234 }
2235 else if constexpr (std::is_same_v<Elem, double>)
2236 {
2237 return wire() == Wire::ArrayFixlen && fixType() == Fix::Fp64;
2238 }
2239 else if constexpr (std::is_signed_v<Elem>)
2240 {
2241 return wire() == Wire::ArraySigned;
2242 }
2243 else
2244 {
2245 return wire() == Wire::ArrayUnsigned;
2246 }
2247 }
2248
2249 // What the destination can hold. A heap-free container publishes it as a
2250 // static capacity(); a std::array publishes it as its (fixed) size(); a
2251 // resizable container publishes none and takes whatever the message-side
2252 // ceiling admits.
2253 template <typename C>
2254 [[nodiscard]] static long arrayRoom_(C &out, size_t wireCount) noexcept
2255 {
2256 if constexpr (fixed_capacity_v<C> < 0 && !requires { out.resize(wireCount); })
2257 {
2258 (void)wireCount;
2259 return static_cast<long>(out.size());
2260 }
2261 else
2262 {
2263 (void)out;
2264 (void)wireCount;
2265 return fixed_capacity_v<C>;
2266 }
2267 }
2268
2269 // Third tier, then size and bind an array destination.
2270 template <typename C>
2271 void bindArray_(C &out, size_t wireCount, long room) noexcept
2272 {
2273 if (refuse(wireCount, room))
2274 {
2275 return;
2276 }
2277
2278 if constexpr (requires { out.resize(wireCount); })
2279 {
2280 out.resize(wireCount);
2281 }
2282 else
2283 {
2284 out = C{};
2285 }
2286
2287 read(out);
2288 }
2289
2290
2291 public:
2292 /*!
2293 * @brief Outcome of a @ref feed call.
2294 *
2295 * Convertible to @c bool (true on success) and comparable to @ref Error.
2296 */
2298 {
2299 private:
2300 Error error_ = Error::None;
2301
2302 friend class IStreamImpl;
2304 : error_(static_cast<Error>(retval))
2305 { }
2306
2307 sofab_ret_t rawCode() const noexcept
2308 {
2309 return static_cast<sofab_ret_t>(error_);
2310 }
2311
2312 public:
2313 /*! @brief True if the feed reached a complete message boundary
2314 * (same as ok()). An @ref Error::Incomplete partial decode is
2315 * neither complete nor an error, so this is false — use
2316 * @ref incomplete() to tell it apart from a genuine error. */
2317 explicit operator bool() const noexcept
2318 {
2319 return ok();
2320 }
2321
2322 /*! @brief Compare the held error code to @p e. */
2323 bool operator==(Error e) const noexcept
2324 {
2325 return error_ == e;
2326 }
2327
2328 /*! @brief Negated operator==(). */
2329 bool operator!=(Error e) const noexcept
2330 {
2331 return !(*this == e);
2332 }
2333
2334 /*! @brief True if the consumed bytes end exactly on a field boundary
2335 * (a complete message so far). False for both a partial decode
2336 * (@ref incomplete()) and a genuine decode error. */
2338 {
2339 return error_ == Error::None;
2340 }
2341
2342 /*! @brief True if the consumed bytes end mid-field or with an open
2343 * sequence: a valid but partial decode (@ref Error::Incomplete).
2344 * Not an error — the caller owns end-of-input and may feed more
2345 * bytes to continue. Distinct from both ok() and a decode error. */
2347 {
2348 return error_ == Error::Incomplete;
2349 }
2350
2351 /*! @brief True if the bytes are malformed (@ref Error::InvalidMessage).
2352 * Deliberately false for @ref limitExceeded(): a receiver limit is a
2353 * policy rejection on well-formed bytes (§6.2.1/§6.3), and the two
2354 * must stay distinguishable to the caller. */
2356 {
2357 return error_ == Error::InvalidMessage;
2358 }
2359
2360 /*! @brief True if a configured receiver limit was exceeded on a
2361 * schema-unbounded field (@ref Error::LimitExceeded, §6.2.1).
2362 *
2363 * Means *"raise my limit, or the sender must send less"* — the same
2364 * bytes decode on a receiver configured more loosely. Terminal, like
2365 * @ref invalid(), but never the same answer. */
2367 {
2368 return error_ == Error::LimitExceeded;
2369 }
2370
2371 /*! @brief The @ref Error result of the feed. */
2373 {
2374 return error_;
2375 }
2376 };
2377
2378 /*! @brief Copy construction is deleted (the context owns raw pointers). */
2379 IStreamImpl(const IStreamImpl&) = delete;
2380 /*! @brief Copy assignment is deleted (the context owns raw pointers). */
2382
2383 /*! @brief Move construction (transfers the underlying context). */
2385 /*! @brief Move assignment (transfers the underlying context). */
2387
2388 /*!
2389 * @brief Feed raw encoded bytes to the decoder.
2390 *
2391 * May be called repeatedly with arbitrary chunk boundaries; field
2392 * callbacks fire as complete field headers are parsed.
2393 *
2394 * The outcome is three-valued (no separate finalize step): the returned
2395 * @ref Result is @c ok() when the consumed bytes end on a field boundary
2396 * (a complete message), @ref Result::incomplete() when they end mid-field
2397 * or with an open sequence (a valid but partial decode — feed more bytes
2398 * to continue), and carries @ref Error::InvalidMessage when malformed.
2399 *
2400 * A callback may end the decode itself — @ref invalidate,
2401 * @ref exceedLimit or @ref refuseArgument — and the category it chose is
2402 * what this reports, in place of the core's plain
2403 * @ref Error::InvalidMessage. All three are terminal: every later feed
2404 * repeats the same answer until the stream is re-initialized.
2405 *
2406 * @param buffer Pointer to the bytes to decode.
2407 * @param buflen Number of bytes at @p buffer.
2408 * @return @ref Result: complete (ok), incomplete, or a decode error.
2409 */
2411 {
2413 if (refusal_ != SOFAB_RET_OK)
2414 {
2415 ret = static_cast<sofab_ret_t>(refusal_);
2416 }
2417 return Result{ret};
2418 }
2419
2420 /*!
2421 * @brief Reject the message in progress as **malformed**, from within a
2422 * field callback (§6.3's first tier).
2423 *
2424 * The bytes broke a bound the *schema* declares — a `maxlen`, a `count`,
2425 * an element index at or beyond a fixed-count array's capacity — which is
2426 * a statement about the message's *validity* (MESSAGE_SPEC §7.1), so it is
2427 * `INVALID`. Sticky: this @ref feed and every subsequent one report
2428 * @ref Error::InvalidMessage until the stream is re-initialized.
2429 *
2430 * Not for a receiver limit (@ref exceedLimit) and not for a destination
2431 * that is merely too small (@ref refuseArgument): §6.2.1 forbids folding
2432 * either into the `INVALID` outcome.
2433 */
2438
2439 /*!
2440 * @brief Reject the message because a configured receiver limit was
2441 * exceeded (§6.3's second tier, §6.2.1).
2442 *
2443 * For a **schema-unbounded** field only: the bytes are well-formed and the
2444 * same message decodes on a receiver configured more loosely, so this
2445 * reports @ref Error::LimitExceeded and never @ref Error::InvalidMessage.
2446 * Terminal, like @ref invalidate.
2447 *
2448 * @ref readStringCapped, @ref readBlobCapped, @ref readArrayCapped and the
2449 * growable wrapper-array collectors call it for you, at the length/count
2450 * header and before the destination is sized. Call it directly when a
2451 * callback enforces a limit those cannot see.
2452 */
2457
2458 /*!
2459 * @brief Reject the message because the **destination this caller handed
2460 * over** cannot hold the value (§6.3's third tier, §6.6.3).
2461 *
2462 * Neither bound that speaks about the *message* has anything left to
2463 * object to — the schema admits the value and so does the configured
2464 * limit — and what does not fit is the storage. That is a mistake in the
2465 * *call*, so it is @c Error::InvalidArgument. @ref Error::InvalidMessage
2466 * would mark a well-formed message malformed, and @ref Error::LimitExceeded
2467 * would promise a limit to raise that was never configured. Terminal, like
2468 * @ref invalidate.
2469 */
2474
2475 /*!
2476 * @brief Refuse an announced length or element count the caller's own
2477 * destination cannot hold.
2478 *
2479 * This is the **only** bound the codec judges. CORELIB_PLAN §6.2.1 gives
2480 * the receiver caps to generated code — "the visitor decides. The codec
2481 * never invents a limit of its own and never clamps to one" — and
2482 * MESSAGE_SPEC §7 gives it the schema bounds, because "the corelib cannot
2483 * know the schema". Both are measured by the handler, at the `size` /
2484 * `count` this corelib reports to it in the field callback, before it
2485 * binds a destination at all.
2486 *
2487 * What is left here is not a limit but the caller's storage: §6.6.3
2488 * requires "the codec refusing a destination too short rather than growing
2489 * it. That refusal is **`InvalidArgument`**: the message is well-formed and
2490 * within every bound it declares — what does not fit is the storage this
2491 * caller offered."
2492 *
2493 * Called before the destination is written, and terminal. Rejected, never
2494 * clamped — a short write with a `COMPLETE` verdict is the data corruption
2495 * §6.2.1 calls "a safety jacket".
2496 *
2497 * @param n The announced length in bytes, or element count.
2498 * @param room What the destination can actually hold, or -1 for a growable
2499 * one, which this corelib never bounds.
2500 * @return `true` when the value was refused, in which case the caller must
2501 * return without touching the destination.
2502 */
2503 [[nodiscard]] [[gnu::always_inline]] bool refuse(size_t n, long room) noexcept
2504 {
2505 if (room >= 0 && n > static_cast<size_t>(room))
2506 {
2508 return true;
2509 }
2510
2511 return false;
2512 }
2513
2514 /*!
2515 * @brief §6.3's **first** tier: the bound the *schema* declares.
2516 *
2517 * A value past a declared `maxlen` / `count` is a statement about the
2518 * message's validity, so it is @ref Error::InvalidMessage (MESSAGE_SPEC
2519 * §7.1). The number is the **caller's**, passed in for this one comparison
2520 * and not kept: §6.2.1 leaves the codec "the report and the category" and
2521 * forbids it to *invent* or *store* a bound, which is not the same as
2522 * forbidding it to compare against one it was handed. Passing it here
2523 * rather than testing it before the call is what keeps a §7.3-skipped
2524 * field unjudged — every caller of this runs the tag test first, so a
2525 * header contradicting the declared type has already returned.
2526 *
2527 * @param n The announced length in bytes, or element count.
2528 * @param schemaBound Schema `maxlen`/`count`, or -1 when the schema
2529 * declares none, in which case nothing is refused here
2530 * and the field is the receiver cap's business instead.
2531 * @return `true` when the value was refused, in which case the caller
2532 * must return without touching the destination.
2533 */
2534 [[nodiscard]] [[gnu::always_inline]] bool refuseSchema(size_t n, long schemaBound) noexcept
2535 {
2536 if (schemaBound >= 0 && n > static_cast<size_t>(schemaBound))
2537 {
2538 invalidate();
2539 return true;
2540 }
2541 return false;
2542 }
2543
2544 /*!
2545 * @brief §6.3's **second** tier: the receiver cap on a schema-unbounded
2546 * field (§6.2.1).
2547 *
2548 * The bytes are well-formed — the same message decodes on a receiver
2549 * configured more loosely — so a breach is @ref Error::LimitExceeded and
2550 * never @ref Error::InvalidMessage. Rejected, never clamped.
2551 *
2552 * @ref DynCap is the parameter type on purpose: a cap this corelib was not
2553 * given has no spelling here, so there is no omitted-argument path that
2554 * could be read as *unlimited* (§6.2.1). The value is used for this one
2555 * comparison and not retained.
2556 *
2557 * @param n The announced length in bytes, or element count.
2558 * @param dynCap The caller's cap. A maximum: `n > dynCap` is refused.
2559 * @return `true` when the value was refused.
2560 */
2561 [[nodiscard]] [[gnu::always_inline]] bool refuseCap(size_t n, size_t dynCap) noexcept
2562 {
2563 if (n > dynCap) { exceedLimit(); return true; }
2564 return false;
2565 }
2566
2567 /*!
2568 * @brief Refuse a read that was given **no ceiling of any kind**.
2569 *
2570 * The gap corelib-c-cpp#152 was filed for, and the one a `long dynCap = -1`
2571 * parameter used to swallow. A read of a field the schema does not bound,
2572 * into a destination that publishes no capacity, with no receiver cap
2573 * stated, sizes the caller's storage from a number the **sender** chose.
2574 * §6.2.1 forbids treating that as *unlimited*: "there is no unset state and
2575 * no unlimited mode", and a format ceiling reached because no cap was
2576 * stated "is the FORMAT's bound and MUST NOT be presented as a receiver
2577 * cap".
2578 *
2579 * So it is diagnosed instead. Nothing about the message is wrong and no
2580 * limit was configured to raise, which rules out the other two categories:
2581 * the mistake is in the **call**, and §6.3 gives that
2582 * @ref Error::InvalidArgument. The fix at the call site is to state one of
2583 * the two ceilings — pass the schema bound, or use the `…Capped` entry
2584 * point with the receiver cap.
2585 *
2586 * A heap-free destination needs neither: its capacity is a ceiling the
2587 * sender cannot move, so `room >= 0` passes here and an over-capacity value
2588 * is refused by @ref refuse as the third tier.
2589 *
2590 * @param schemaBound Schema `maxlen`/`count`, or -1 for none.
2591 * @param room The destination's static capacity, or -1 for a
2592 * growable one.
2593 * @return `true` when the read must not proceed.
2594 */
2595 [[nodiscard]] [[gnu::always_inline]] bool refuseUnbounded(long schemaBound, long room) noexcept
2596 {
2597 if (schemaBound < 0 && room < 0) { refuseArgument(); return true; }
2598 return false;
2599 }
2600
2601 /*!
2602 * @brief The two **message-side** refusals of §6.3 in one call, in the
2603 * order §6.2.1 fixes: the schema first, the receiver cap only where
2604 * the schema declared nothing — and a **diagnosis** where neither
2605 * was stated.
2606 *
2607 * @ref refuse is the third tier and answers a different question — that one
2608 * is about the caller's storage, these two are about the message.
2609 *
2610 * This is the collectors' entry point (@ref seqRefuse). A growable wrapper
2611 * array has no capacity to fall back on, so "the schema declared nothing
2612 * and no cap was stated" is not a decode without a ceiling: it is
2613 * @ref Error::InvalidArgument, exactly as in @ref refuseUnbounded.
2614 *
2615 * @param n The announced length in bytes, or element index + 1.
2616 * @param schemaBound Schema `maxlen`/`count`, or -1 when the schema
2617 * declares none — which is what arms @p dynCap.
2618 * @param dynCap The §6.2.1 receiver cap for a schema-unbounded field.
2619 * An unstated one is refused, never read as unlimited.
2620 * @return `true` when the value was refused, in which case the caller
2621 * must return without touching the destination.
2622 */
2623 [[nodiscard]] [[gnu::always_inline]] bool refuseBound(size_t n, long schemaBound, DynCap dynCap) noexcept
2624 {
2625 if (schemaBound >= 0)
2626 {
2627 // Schema-bounded: its violation is INVALID (MESSAGE_SPEC §7.1),
2628 // and §6.2.1 forbids the cap from reaching this field at all.
2629 return refuseSchema(n, schemaBound);
2630 }
2631
2632 if (!dynCap.stated()) { refuseArgument(); return true; }
2633 return refuseCap(n, dynCap.value());
2634 }
2635
2636 /*!
2637 * @brief Wire type of the field currently being delivered.
2638 *
2639 * Valid inside a field callback / @c deserialize, before the field's
2640 * @ref read binds a destination. MESSAGE_SPEC §7.3: compare it against
2641 * the wire type the declared field maps to and, on a mismatch, return
2642 * without calling @ref read — the field is then skipped automatically,
2643 * exactly like an unknown id (a framing mismatch, not a malformed
2644 * message). Reads no bytes and does not consume the field.
2645 *
2646 * @return The delivered field's @ref Wire.
2647 */
2649 {
2650 // ctx_.target_opt holds the delivered wire opt on callback entry
2651 // (low 3 bits = wire type); a later read() overwrites it with the
2652 // schema opt, so this must be read before binding a destination.
2653 return static_cast<Wire>(ctx_.target_opt & 0x07);
2654 }
2655
2656 /*!
2657 * @brief Fixlen sub-type of the field currently being delivered.
2658 *
2659 * Only meaningful when @ref wire is @ref Wire::Fixlen or
2660 * @ref Wire::ArrayFixlen; §7.3 bounds the type check at wire type *plus*
2661 * this subtype, since @c fp32 / @c fp64 / @c string / @c blob share the
2662 * fixlen wire type. Valid inside a field callback / @c deserialize before
2663 * @ref read; reads no bytes and does not consume the field.
2664 *
2665 * @return The delivered field's @ref Fix.
2666 */
2668 {
2669 // The fixlen subtype is merged into bits 3..5 of target_opt before
2670 // the callback fires (istream.c: target_opt |= fixlen_type << 3).
2671 return static_cast<Fix>((ctx_.target_opt >> 3) & 0x07);
2672 }
2673
2674 /*!
2675 * @brief Whether the field currently being delivered has wire type @p w.
2676 *
2677 * The §7.3 tag test for a field whose type has no fixlen subtype (varint,
2678 * integer array, sequence) as ONE comparison. Valid, like @ref wire, only
2679 * before @ref read binds a destination. A @ref Wire::Fixlen /
2680 * @ref Wire::ArrayFixlen field is tested with the two-argument form: its
2681 * subtype is part of the test, and this form would read it as
2682 * @ref Fix::Fp32 (subtype 0).
2683 */
2684 [[nodiscard]] bool delivered(Wire w) const noexcept
2685 {
2686 return (ctx_.target_opt & 0x3F) == static_cast<uint8_t>(w);
2687 }
2688
2689 /*!
2690 * @brief Whether the field currently being delivered has wire type @p w
2691 * and fixlen subtype @p f.
2692 *
2693 * `wire() == w && fixType() == f` as ONE comparison: the type and the
2694 * subtype share one byte of the stream state, bits 0-2 and 3-5. Valid,
2695 * like @ref wire, only before @ref read binds a destination.
2696 */
2697 [[nodiscard]] bool delivered(Wire w, Fix f) const noexcept
2698 {
2699 return (ctx_.target_opt & 0x3F)
2700 == static_cast<uint8_t>(static_cast<uint8_t>(w) | (static_cast<uint8_t>(f) << 3));
2701 }
2702
2703 /*!
2704 * @brief @ref read for a scalar, reporting whether the field will be
2705 * decoded into @p value.
2706 *
2707 * Binds exactly as @ref read does and returns the §7.3 tag test the
2708 * stream applies to that bind once the callback returns: on @c false
2709 * the field is skipped and @p value is never written. The value
2710 * itself arrives after the callback returns, so the caller may act on
2711 * the result -- a tagged union selects the option here -- before it is
2712 * written. Integers, @c bool, @c float and @c double; must be the first
2713 * read of the field.
2714 *
2715 * @param value Destination to decode into.
2716 * @return @c true when the delivered field has the type @p T maps to.
2717 */
2718 template <typename T>
2719 [[nodiscard]] bool readMatch(T &value) noexcept
2720 {
2721 static_assert(std::is_arithmetic_v<T>,
2722 "readMatch binds a scalar: an integer, bool, float or double");
2723 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>)
2724 {
2725#if !SOFAB_CPP_HAVE_INT64
2726 static_assert(sizeof(T) <= 4,
2727 "64-bit integer fields require INT64 support, disabled "
2728 "via SOFAB_DISABLE_INT64_SUPPORT");
2729#endif
2730 return bindMatch_(
2731 reinterpret_cast<void*>(&value), sizeof(T),
2732 std::is_unsigned_v<T>
2735 }
2736 else if constexpr (std::is_same_v<T, bool>)
2737 {
2738 return bindMatch_(&value, sizeof(bool),
2741 }
2742 else if constexpr (std::is_same_v<T, float>)
2743 {
2744 return bindMatch_(&value, sizeof(float),
2747 }
2748 else
2749 {
2750 static_assert(std::is_same_v<T, double>,
2751 "readMatch binds a scalar: an integer, bool, float or double");
2752#if SOFAB_CPP_HAVE_FP64
2753 return bindMatch_(&value, sizeof(double),
2756#else
2757 static_assert(always_false_v<T>,
2758 "double (FP64) fields require FP64 support, disabled "
2759 "via SOFAB_DISABLE_FP64_SUPPORT");
2760 return false;
2761#endif
2762 }
2763 }
2764
2765 /*!
2766 * @brief Bind the current field to a typed destination, deducing the
2767 * wire type from @p T.
2768 *
2769 * Call from within a field callback / @c deserialize for the active
2770 * field. Supports integers, @c bool, @c float, @c double, @c std::string
2771 * (pre-sized to the field length), fixed contiguous ranges
2772 * (arrays/vectors/spans), and nested @ref IStreamMessage objects. The
2773 * destination must outlive decoding (filled by later @ref feed calls).
2774 *
2775 * @param value Destination to decode into.
2776 */
2777 template <typename T>
2778 void read(T &value) noexcept
2779 {
2780 if constexpr (!std::is_const_v<T>)
2781 {
2782 if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>)
2783 {
2784#if !SOFAB_CPP_HAVE_INT64
2785 static_assert(sizeof(T) <= 4,
2786 "64-bit integer fields require INT64 support, disabled "
2787 "via SOFAB_DISABLE_INT64_SUPPORT");
2788#endif
2789 if constexpr (std::is_unsigned_v<T>)
2790 {
2792 &ctx_, reinterpret_cast<void*>(&value), sizeof(T),
2794 }
2795 else
2796 {
2798 &ctx_, reinterpret_cast<void*>(&value), sizeof(T),
2800 }
2801 }
2802 else if constexpr (std::is_same_v<T, bool>)
2803 {
2804 sofab_istream_read_bool(&ctx_, &value);
2805 }
2806 else if constexpr (std::is_same_v<T, float>)
2807 {
2808 sofab_istream_read_fp32(&ctx_, &value);
2809 }
2810 else if constexpr (std::is_same_v<T, double>)
2811 {
2812#if SOFAB_CPP_HAVE_FP64
2813 sofab_istream_read_fp64(&ctx_, &value);
2814#else
2815 static_assert(always_false_v<T>,
2816 "double (FP64) fields require FP64 support, disabled "
2817 "via SOFAB_DISABLE_FP64_SUPPORT");
2818#endif
2819 }
2820#if SOFAB_CPP_HAVE_HOSTED
2821 else if constexpr (std::is_same_v<T, std::string>)
2822 {
2823 // std::string doesn't need a null terminator, so we use read_noterm
2824 sofab_istream_read_string_noterm(&ctx_, value.data(), value.size());
2825 }
2826#endif
2827 else if constexpr (is_fixed_string_v<T>)
2828 {
2829 // FixedString<N>: the heap-free counterpart of std::string.
2830 // The caller has already fixed the logical length (and the
2831 // terminating NUL) via set_len(_size), so value.size() is the
2832 // field length and value.data() the inline buffer. read_noterm
2833 // fills [0, size()) and never touches the pre-placed NUL, so
2834 // c_str()/string_view stay valid. Matched before the span
2835 // branch so a char buffer is never treated as an array.
2836 sofab_istream_read_string_noterm(&ctx_, value.data(), value.size());
2837 }
2838 else if constexpr (is_fixed_bytes_v<T>)
2839 {
2840 // FixedBytes<N>: the heap-free counterpart of a blob field.
2841 // The caller has already fixed the logical length via
2842 // set_len(_size), so value.size() is the field length clamped
2843 // to the capacity N. Binding that (rather than the raw wire
2844 // _size a bare read(data(), _size) would pass) lets the C
2845 // decoder enforce the schema bound: a wire length > N exceeds
2846 // the bound and is rejected as INVALID - never silently
2847 // truncated - per MESSAGE_SPEC §7.1. Matched before the span
2848 // branch so the byte buffer is never treated as an array.
2849 sofab_istream_read_blob(&ctx_, value.data(), value.size());
2850 }
2851 else if constexpr (InputMessage<T>)
2852 {
2853 // descend into a nested sequence: bind this message's own
2854 // decoder + field callback to the active stream context, so
2855 // its child fields dispatch to value.deserialize(...). Mirrors
2856 // the C object API's sequence handling (object.c).
2857 value.readNested_(&ctx_, this);
2858 }
2859 else if constexpr (
2860 requires {
2861 typename T::value_type;
2862 std::span{ std::declval<const T&>() };
2863 } &&
2864 !std::is_const_v<typename T::value_type>)
2865 {
2866#if SOFAB_CPP_HAVE_ARRAY
2867 using Elem = typename T::value_type;
2868 std::span<Elem> span{value};
2869
2870 if constexpr (std::is_integral_v<Elem> && !std::is_same_v<Elem, bool>)
2871 {
2872#if !SOFAB_CPP_HAVE_INT64
2873 static_assert(sizeof(Elem) <= 4,
2874 "64-bit integer arrays require INT64 support, "
2875 "disabled via SOFAB_DISABLE_INT64_SUPPORT");
2876#endif
2877 if constexpr (std::is_unsigned_v<Elem>)
2878 {
2880 &ctx_,
2881 span.data(),
2882 static_cast<int32_t>(span.size()),
2883 sizeof(Elem),
2885 }
2886 else
2887 {
2889 &ctx_,
2890 span.data(),
2891 static_cast<int32_t>(span.size()),
2892 sizeof(Elem),
2894 }
2895 }
2896 else if constexpr (std::is_same_v<Elem, bool>)
2897 {
2898 /* Excluded from the integral branch above on purpose: a
2899 * boolean rides the unsigned varint array form, but is
2900 * not an integer. Every non-zero element is `true` and
2901 * is normalized on store, and no element is bounded by
2902 * the width of its destination (CORELIB_PLAN §4.4) --
2903 * both of which the read below carries and the integer
2904 * path does not. */
2906 &ctx_,
2907 span.data(),
2908 static_cast<int32_t>(span.size()));
2909 }
2910 else if constexpr (std::is_same_v<Elem, float>)
2911 {
2913 &ctx_,
2914 span.data(),
2915 static_cast<int32_t>(span.size()));
2916 }
2917 else if constexpr (std::is_same_v<Elem, double>)
2918 {
2919#if SOFAB_CPP_HAVE_FP64
2921 &ctx_,
2922 span.data(),
2923 static_cast<int32_t>(span.size()));
2924#else
2925 static_assert(always_false_v<T>,
2926 "double (FP64) arrays require FP64 support, "
2927 "disabled via SOFAB_DISABLE_FP64_SUPPORT");
2928#endif
2929 }
2930 else
2931 {
2932 static_assert(always_false_v<T>,
2933 "Unsupported span element type in IStream::read()");
2934 }
2935#else
2936 static_assert(always_false_v<T>,
2937 "array/span fields require ARRAY support, disabled via "
2938 "SOFAB_DISABLE_ARRAY_SUPPORT");
2939#endif
2940 }
2941 else
2942 {
2943 static_assert(always_false_v<T>,
2944 "Unsupported type passed to IStream::read()");
2945 }
2946 }
2947 else
2948 {
2949 static_assert(always_false_v<T>,
2950 "Cannot read into const variable in IStream::read()");
2951 }
2952 }
2953
2954 /*!
2955 * @brief Decode a blob field into a caller-owned, address-stable buffer.
2956 *
2957 * The templated read() above routes std::string to a STRING-tagged read
2958 * and a std::vector<uint8_t> span to a VARINTARRAY-tagged read; neither
2959 * matches a BLOB field, so the C type check rejects them and the bytes are
2960 * dropped. This overload binds with the BLOB tag (via read_blob) so blob
2961 * fields decode correctly. The caller must size the destination to the
2962 * field length (provided as `size` in the field callback); the bytes are
2963 * filled by a subsequent feed() pass into this buffer, which must stay
2964 * alive and unmoved until decoding of the field completes.
2965 *
2966 * @param dst Destination buffer of at least @p maxlen bytes.
2967 * @param maxlen Field length to read (a zero length is a no-op).
2968 * @return Number of bytes bound to be read (@p maxlen, or 0 if @p maxlen is 0).
2969 */
2970 size_t read(void *dst, size_t maxlen) noexcept
2971 {
2972 // read_field() asserts varlen > 0; a zero-length blob binds no target
2973 // and is simply skipped (0 payload bytes), leaving dst untouched.
2974 if (maxlen == 0)
2975 {
2976 return 0;
2977 }
2978
2980 return maxlen;
2981 }
2982
2983 /*!
2984 * @brief Bind a string field, sizing the destination first.
2985 *
2986 * A string destination has to be given its logical length before the read
2987 * binds it, and that is a change to the destination — so unlike a scalar
2988 * read it cannot be issued unconditionally and left to the decoder to
2989 * unbind. This checks the delivered type first (MESSAGE_SPEC §7.3) and
2990 * touches @p value only if the field really is a string: a contradicting
2991 * field leaves the destination exactly as it was and is skipped like an
2992 * unknown id.
2993 *
2994 * Accepts both storage shapes: a @ref FixedString (inline, @c set_len)
2995 * and a @c std::string (@c resize), so the same call works in the no-heap
2996 * and the dynamic profile.
2997 *
2998 * @par The four ways a read refuses (§6.3)
2999 * All of them are decided on the length header, after the §7.3 type check
3000 * and before @p value is sized — and they are four different answers, not
3001 * one:
3002 * 1. @p maxlen is declared and the field is longer → @ref Error::InvalidMessage.
3003 * The schema says these bytes are invalid (MESSAGE_SPEC §7.1).
3004 * 2. the schema declares no bound and the field is longer than the
3005 * receiver cap → @ref Error::LimitExceeded. The bytes are well-formed;
3006 * this receiver declines to hold that much (§6.2.1). That is
3007 * @ref readStringCapped's answer, and only its: a cap must never be
3008 * applied to a field the schema already bounds.
3009 * 3. Both admit the field, but @p value is a @ref FixedString too small
3010 * for it → @ref Error::InvalidArgument (§6.6.3). Nothing is wrong with
3011 * the message or with the deployment; the storage this caller offered
3012 * is too short, and it is refused rather than filled part-way.
3013 * 4. No ceiling was stated at all — no @p maxlen, no cap, and a growable
3014 * @p value → @ref Error::InvalidArgument (§6.2.1, @ref refuseUnbounded).
3015 * The message and the deployment are again blameless; what is missing
3016 * is part of the call.
3017 * A `std::string` destination never reaches 3: it can hold whatever 1 and
3018 * 2 let through. A @ref FixedString never reaches 4: its capacity is a
3019 * ceiling of its own.
3020 *
3021 * @par This is the schema-bounded entry point
3022 * §6.2.1 gives the receiver caps to generated code and leaves this corelib
3023 * "the report and the category", so there is no limit on the stream to fall
3024 * back on — and, since the clause also forbids reading an omitted argument
3025 * as *unlimited*, there is no `dynCap = -1` here to omit. A field the schema
3026 * leaves unbounded goes through @ref readStringCapped instead, which takes
3027 * the cap and cannot be called without one. The two are never both in play:
3028 * §6.2.1 forbids a receiver cap on a field the schema already bounds.
3029 *
3030 * A read given neither ceiling — no @p maxlen, and a growable @p value that
3031 * publishes no capacity — is refused as @ref Error::InvalidArgument
3032 * (@ref refuseUnbounded), not decoded. A heap-free @p value needs no
3033 * @p maxlen: its capacity is a ceiling of its own.
3034 *
3035 * This is what generated code emits for the embedded profile, where every
3036 * `string` carries a `maxlen`:
3037 * ```cpp
3038 * is.readString(name, _size, 32);
3039 * ```
3040 *
3041 * @param value Destination string.
3042 * @param size Field length, as delivered to the field callback.
3043 * @param maxlen Schema `maxlen`, or -1 when the schema declares none — in
3044 * which case @p value must publish a capacity.
3045 */
3046 template <typename T>
3047 void readString(T &value, size_t size, long maxlen = -1) noexcept
3048 {
3049 if (wire() != Wire::Fixlen || fixType() != Fix::String)
3050 {
3051 noteSkip_();
3052 return;
3053 }
3054
3056 {
3057 return;
3058 }
3059
3060 bindString_(value, size);
3061 }
3062
3063 /*!
3064 * @brief @ref readString into a destination that comes into existence only
3065 * once the field matched: @p select is called behind the §7.3 test
3066 * and the two refusals, and returns the destination.
3067 *
3068 * For a tagged union's string option. Selecting the option -- ending the
3069 * held one and constructing this one's storage -- is a change a skipped
3070 * or refused field must not make, so it cannot happen before the call;
3071 * and spelling the test in front of the call makes it twice, since the
3072 * construction in between is a store the compiler cannot prove leaves
3073 * the stream's state alone. Here the test is made once:
3074 * ```cpp
3075 * is.readString([this]() -> auto & { return mutable_s(); }, _size, 8);
3076 * ```
3077 *
3078 * @param select Callable returning the destination string by reference.
3079 * @param size Field length, as delivered to the field callback.
3080 * @param maxlen Schema `maxlen`, or -1 when the schema declares none.
3081 */
3082 template <typename Select,
3083 std::enable_if_t<std::is_invocable_v<Select &>, int> = 0>
3084 void readString(Select &&select, size_t size, long maxlen = -1) noexcept
3085 {
3086 using T = std::remove_reference_t<std::invoke_result_t<Select &>>;
3087
3089 {
3090 noteSkip_();
3091 return;
3092 }
3093
3095 {
3096 return;
3097 }
3098
3099 bindString_(select(), size);
3100 }
3101
3102 /*!
3103 * @brief @ref readString for a **schema-unbounded** `string`, bounded by the
3104 * receiver cap the caller supplies (§6.2.1).
3105 *
3106 * The separate entry point is the point. @p dynCap is required and unsigned,
3107 * so "no cap" has no spelling: §6.2.1's "no unset state and no unlimited
3108 * mode" becomes a property of the signature rather than a rule every caller
3109 * has to remember. A breach is @ref Error::LimitExceeded — a **policy**
3110 * rejection of well-formed bytes, never @ref Error::InvalidMessage and never
3111 * a truncating read.
3112 *
3113 * The cap is applied at the length header, after the MESSAGE_SPEC §7.3 tag
3114 * test and before @p value is sized. Both halves matter: checking in front
3115 * of the call would cap a field this read is required to *skip*, which
3116 * §6.2.1 forbids in as many words, and checking after the resize would be
3117 * the allocation the cap exists to prevent.
3118 *
3119 * @p dynCap is used for this one comparison and not retained — the number is
3120 * the caller's, and this corelib neither defaults it nor remembers it.
3121 *
3122 * ```cpp
3123 * is.readStringCapped(name, _size, SOFAB_MAX_DYN_STRING_LEN);
3124 * ```
3125 *
3126 * @param value Destination string.
3127 * @param size Field length, as delivered to the field callback.
3128 * @param dynCap The §6.2.1 receiver cap. A maximum, not an exclusive bound.
3129 */
3130 template <typename T>
3131 void readStringCapped(T &value, size_t size, size_t dynCap) noexcept
3132 {
3133 if (wire() != Wire::Fixlen || fixType() != Fix::String)
3134 {
3135 noteSkip_();
3136 return;
3137 }
3138
3139 if (refuseCap(size, dynCap))
3140 {
3141 return;
3142 }
3143
3144 bindString_(value, size);
3145 }
3146
3147 /*!
3148 * @brief Bind a blob field, sizing the destination first.
3149 *
3150 * The blob counterpart of @ref readString, and for the same reason: the
3151 * destination must be sized before it is bound, so the delivered type is
3152 * checked before @p value is touched (MESSAGE_SPEC §7.3).
3153 *
3154 * The refusals of @ref readString apply unchanged, and so does the split
3155 * into two entry points: this one takes the schema `maxlen`,
3156 * @ref readBlobCapped takes `SOFAB_MAX_DYN_BLOB_LEN`. `blob` and `string`
3157 * are separate limits in §6.2.1 because a deployment may well accept a
3158 * megabyte of opaque bytes and no such quantity of text.
3159 *
3160 * @param value Destination byte buffer (@ref FixedBytes or
3161 * @c std::vector<uint8_t>).
3162 * @param size Field length, as delivered to the field callback.
3163 * @param maxlen Schema `maxlen`, or -1 when the schema declares none — in
3164 * which case @p value must publish a capacity.
3165 */
3166 template <typename T>
3167 void readBlob(T &value, size_t size, long maxlen = -1) noexcept
3168 {
3169 if (wire() != Wire::Fixlen || fixType() != Fix::Blob)
3170 {
3171 noteSkip_();
3172 return;
3173 }
3174
3176 {
3177 return;
3178 }
3179
3180 bindBlob_(value, size);
3181 }
3182
3183 /*!
3184 * @brief @ref readBlob into a destination that comes into existence only
3185 * once the field matched -- the blob counterpart of the selecting
3186 * @ref readString overload, for a tagged union's blob option.
3187 *
3188 * @param select Callable returning the destination buffer by reference.
3189 * @param size Field length, as delivered to the field callback.
3190 * @param maxlen Schema `maxlen`, or -1 when the schema declares none.
3191 */
3192 template <typename Select,
3193 std::enable_if_t<std::is_invocable_v<Select &>, int> = 0>
3194 void readBlob(Select &&select, size_t size, long maxlen = -1) noexcept
3195 {
3196 using T = std::remove_reference_t<std::invoke_result_t<Select &>>;
3197
3199 {
3200 noteSkip_();
3201 return;
3202 }
3203
3205 {
3206 return;
3207 }
3208
3209 bindBlob_(select(), size);
3210 }
3211
3212 /*!
3213 * @brief @ref readBlob for a **schema-unbounded** `blob`, bounded by the
3214 * receiver cap the caller supplies (§6.2.1).
3215 *
3216 * The blob counterpart of @ref readStringCapped, with the same required,
3217 * unsigned @p dynCap and the same ordering guarantees.
3218 *
3219 * @param value Destination byte buffer.
3220 * @param size Field length, as delivered to the field callback.
3221 * @param dynCap The §6.2.1 receiver cap. A maximum, not an exclusive bound.
3222 */
3223 template <typename T>
3224 void readBlobCapped(T &value, size_t size, size_t dynCap) noexcept
3225 {
3226 if (wire() != Wire::Fixlen || fixType() != Fix::Blob)
3227 {
3228 noteSkip_();
3229 return;
3230 }
3231
3232 if (refuseCap(size, dynCap))
3233 {
3234 return;
3235 }
3236
3237 bindBlob_(value, size);
3238 }
3239
3240 /*!
3241 * @brief Bind a native scalar array, preparing the destination first.
3242 *
3243 * Like @ref readString, this exists because the destination is touched
3244 * before it is bound — an inline @c std::array is reset so elements the
3245 * encoder trimmed off the tail decode as the element default rather than
3246 * as a schema default (MESSAGE_SPEC §3), and a @c std::vector is sized to
3247 * the wire count. Both must wait until the delivered field is known to be
3248 * an array of this element type (§7.3), and the count must be checked
3249 * against the schema bound before a resize, so an over-count message
3250 * cannot make the receiver allocate what the bound exists to prevent.
3251 *
3252 * The refusals of @ref readString apply unchanged, counting elements
3253 * instead of bytes, and so does the split into two entry points: this one
3254 * takes the schema `count`, @ref readArrayCapped takes
3255 * `SOFAB_MAX_DYN_ARRAY_COUNT`. Tier 3 matters more here than it does for a
3256 * string: a heap-free destination's @c resize *clamps*, so without the
3257 * check an over-capacity count would decode as a silently short array
3258 * rather than as a refusal.
3259 *
3260 * @param out Destination array or vector.
3261 * @param wireCount Element count delivered to the field callback.
3262 * @param cap Schema `count`, or -1 when the schema declares none —
3263 * in which case @p out must publish a capacity.
3264 */
3265 template <typename C>
3266 void readArray(C &out, size_t wireCount = 0, long cap = -1) noexcept
3267 {
3268 if (!arrayTagOk_<C>())
3269 {
3270 noteSkip_();
3271 return;
3272 }
3273
3274 const long room = arrayRoom_(out, wireCount);
3275
3276 if (refuseUnbounded(cap, room) || refuseSchema(wireCount, cap))
3277 {
3278 return;
3279 }
3280
3281 bindArray_(out, wireCount, room);
3282 }
3283
3284 /*!
3285 * @brief @ref readArray into a destination that comes into existence only
3286 * once the field matched: @p select is called behind the §7.3 test
3287 * and returns the destination -- the array counterpart of the
3288 * selecting @ref readString overload, for a tagged union's array
3289 * option.
3290 *
3291 * Where the destination type fixes its room (a heap-free container, or
3292 * one that resizes), @p select is also called only behind the count
3293 * refusals, as in the selecting @ref readString. A fixed-size view
3294 * publishes its room per object and is selected before them; a refusal
3295 * is terminal either way.
3296 *
3297 * @param select Callable returning the destination array by reference.
3298 * @param wireCount Element count delivered to the field callback.
3299 * @param cap Schema `count`, or -1 when the schema declares none.
3300 */
3301 template <typename Select,
3302 std::enable_if_t<std::is_invocable_v<Select &>, int> = 0>
3303 void readArray(Select &&select, size_t wireCount = 0, long cap = -1) noexcept
3304 {
3305 using C = std::remove_reference_t<std::invoke_result_t<Select &>>;
3306
3307 if (!arrayTagOk_<C>())
3308 {
3309 noteSkip_();
3310 return;
3311 }
3312
3313 if constexpr (fixed_capacity_v<C> >= 0 ||
3314 requires(C &c, size_t n) { c.resize(n); })
3315 {
3316 // The room follows from the type: refuse before selecting, as
3317 // the selecting readString/readBlob do.
3318 const long room = fixed_capacity_v<C>;
3319
3320 if (refuseUnbounded(cap, room) || refuseSchema(wireCount, cap))
3321 {
3322 return;
3323 }
3324
3326 }
3327 else
3328 {
3329 // A fixed-size view publishes its room per object, so it is
3330 // selected first: a refused array may already have switched the
3331 // option. Both refusals are terminal, so the destination's
3332 // value is unspecified either way.
3333 C &out = select();
3334 const long room = arrayRoom_(out, wireCount);
3335
3336 if (refuseUnbounded(cap, room) || refuseSchema(wireCount, cap))
3337 {
3338 return;
3339 }
3340
3341 bindArray_(out, wireCount, room);
3342 }
3343 }
3344
3345 /*!
3346 * @brief @ref readArray for a **schema-unbounded** array, bounded by the
3347 * receiver cap the caller supplies (§6.2.1).
3348 *
3349 * The array counterpart of @ref readStringCapped: @p dynCap is required and
3350 * unsigned, it is compared against the wire count at the count header —
3351 * behind the §7.3 tag test, before anything is sized from it — and a breach
3352 * is @ref Error::LimitExceeded.
3353 *
3354 * @param out Destination array or vector.
3355 * @param wireCount Element count delivered to the field callback.
3356 * @param dynCap The §6.2.1 receiver cap on the element count.
3357 */
3358 template <typename C>
3359 void readArrayCapped(C &out, size_t wireCount, size_t dynCap) noexcept
3360 {
3361 if (!arrayTagOk_<C>())
3362 {
3363 noteSkip_();
3364 return;
3365 }
3366
3367 if (refuseCap(wireCount, dynCap))
3368 {
3369 return;
3370 }
3371
3373 }
3374
3375 /*!
3376 * @brief Bind a wrapper-array field through a collector, clearing the
3377 * destination first.
3378 *
3379 * A wrapper array arrives as a sequence whose element index is the field
3380 * id (MESSAGE_SPEC §5.1); @p collector turns those elements into entries
3381 * of @p out. The destination is emptied first — a wrapper array replaces
3382 * rather than merges (§7.4) — and that, again, is a change that must not
3383 * happen for a field which turns out not to be a sequence at all.
3384 *
3385 * @param collector Collector for the element type (e.g. @ref FixedStringSeq).
3386 * @param out Destination container; must outlive decoding.
3387 */
3388 template <typename C, typename Out>
3389 void readSequence(C &collector, Out &out) noexcept
3390 {
3391 if (wire() != Wire::SequenceStart)
3392 {
3393 noteSkip_();
3394 return;
3395 }
3396
3397 out.clear();
3398 collector.out = &out;
3399 read(collector);
3400 }
3401
3402 /*!
3403 * @brief @ref readSequence into a destination that comes into existence
3404 * only once the field matched: @p select is called behind the §7.3
3405 * test and returns the destination -- for a tagged union's
3406 * wrapper-array option.
3407 *
3408 * @param collector Collector for the element type (e.g. @ref FixedStringSeq).
3409 * @param select Callable returning the destination container by
3410 * reference; it must outlive decoding.
3411 */
3412 template <typename C, typename Select,
3413 std::enable_if_t<std::is_invocable_v<Select &>, int> = 0>
3415 {
3417 {
3418 noteSkip_();
3419 return;
3420 }
3421
3422 auto &out = select();
3423 out.clear();
3424 collector.out = &out;
3425 read(collector);
3426 }
3427
3428 /*!
3429 * @brief Number of fields skipped because their wire type contradicted
3430 * the destination bound for them.
3431 *
3432 * Facade over @ref sofab_istream_skipped. Not an error count: a skip is
3433 * how a reader and a writer built from different revisions of a schema
3434 * keep talking (MESSAGE_SPEC §7.3). A non-zero value after a successful
3435 * decode means the two sides disagree about what an id means, which is
3436 * worth a log line or a health metric. Saturates at 255.
3437 *
3438 * @return Number of type-contradicting fields skipped.
3439 */
3440#if SOFAB_SKIP_COUNTER
3442 {
3443 return sofab_istream_skipped(&ctx_);
3444 }
3445#endif
3446
3447 /*!
3448 * @brief Decode a sequence of variable-length string elements into a vector.
3449 *
3450 * Each element is emplaced into `out` and the C read target is bound to
3451 * that persistent slot, so feed() fills it in place before the next
3452 * element's callback fires. A later emplace_back may reallocate `out`, but
3453 * it only moves already-filled elements (heap-stable, or SSO bytes copied
3454 * intact), never an unfilled bound target. This is the safe counterpart to
3455 * the transient read-into-local-then-move pattern, which dangles under the
3456 * deferred decoder.
3457 *
3458 * @param out Vector that receives one element per string in the sequence;
3459 * it must outlive decoding of the field.
3460 */
3461#if SOFAB_CPP_HAVE_HOSTED
3462 void read(std::vector<std::string> &out) noexcept
3463 {
3465 &ctx_, &arrayDecoder_, &strArrayElem_, &out);
3466 }
3467
3468 /*!
3469 * @brief Decode a sequence of variable-length blob elements into a vector.
3470 * @param out Vector that receives one byte-vector per blob in the sequence;
3471 * it must outlive decoding of the field.
3472 */
3473 void read(std::vector<std::vector<uint8_t>> &out) noexcept
3474 {
3476 &ctx_, &arrayDecoder_, &blobArrayElem_, &out);
3477 }
3478#endif /* SOFAB_CPP_HAVE_HOSTED */
3479
3480 private:
3481#if SOFAB_CPP_HAVE_HOSTED
3482 /*! @brief Per-element callback: emplace and bind one string element. */
3483 static void strArrayElem_(
3484 sofab_istream_t *ctx, sofab_id_t, size_t size, size_t, void *usrptr)
3485 {
3486 auto *out = static_cast<std::vector<std::string>*>(usrptr);
3487 out->emplace_back(size, '\0');
3488 // read_field() asserts varlen > 0; an empty element binds no target
3489 // and the (zero-length) payload is skipped, leaving "" in place.
3490 if (size > 0)
3491 {
3492 sofab_istream_read_string_noterm(ctx, out->back().data(), size);
3493 }
3494 }
3495
3496 /*! @brief Per-element callback: emplace and bind one blob element. */
3497 static void blobArrayElem_(
3498 sofab_istream_t *ctx, sofab_id_t, size_t size, size_t, void *usrptr)
3499 {
3500 auto *out = static_cast<std::vector<std::vector<uint8_t>>*>(usrptr);
3501 out->emplace_back(size);
3502 // read_field() asserts varlen > 0; an empty element binds no target
3503 // and the (zero-length) payload is skipped, leaving {} in place.
3504 if (size > 0)
3505 {
3506 sofab_istream_read_blob(ctx, out->back().data(), size);
3507 }
3508 }
3509#endif /* SOFAB_CPP_HAVE_HOSTED */
3510 };
3511
3512 /*!
3513 * @brief Input stream driven by a user-supplied per-field callback.
3514 *
3515 * The callback receives each decoded field's id, size and element count, and
3516 * binds a destination by calling one of the @c IStreamImpl::read() overloads
3517 * for the fields it is interested in; unhandled fields are skipped.
3518 */
3520 {
3521 public:
3522 /*! @brief Per-field callback signature: (field id, value size, element count).
3523 *
3524 * As with @ref OStreamImpl::flushCallback, a @c std::function hosted and a
3525 * plain function pointer freestanding. */
3526#if SOFAB_CPP_HAVE_HOSTED
3527 using fieldCallback = std::function<void(sofab::id _id, size_t _size, size_t _count)>;
3528#else
3529 using fieldCallback = void (*)(sofab::id _id, size_t _size, size_t _count);
3530#endif
3531
3532 private:
3533 fieldCallback callback_{};
3534
3535 /*! @brief C-ABI field-callback trampoline forwarding to the stored callback. */
3536 static void field_callback_(
3537 sofab_istream_t *ctx, sofab_id_t id, size_t size, size_t count, void *usrptr)
3538 {
3539 (void)ctx;
3540
3541 auto *self = static_cast<IStreamInline*>(usrptr);
3542 self->callback_(id, size, count);
3543 }
3544
3545 public:
3546 /*!
3547 * @brief Construct with the per-field callback.
3548 * @param callback Invoked for each decoded field to bind a destination.
3549 */
3551 : callback_{callback}
3552 {
3553 sofab_istream_init(&ctx_, field_callback_, this);
3554 }
3555 };
3556
3557 /*!
3558 * @brief Base class for decodable message objects.
3559 *
3560 * Derive from this and implement @ref deserialize to dispatch each field to
3561 * the matching @c IStreamImpl::read(). Instances are decoded standalone via
3562 * @ref IStreamObject, or as a nested field through @c IStreamImpl::read().
3563 */
3565 {
3566 private:
3567 sofab_istream_decoder_t decoder_;
3568
3569 friend class IStreamImpl;
3570 template <InputMessage MessageType>
3571 friend class IStreamObject;
3572 template <InputMessage MessageType>
3573 friend class IStreamInto;
3574
3575 struct Context
3576 {
3577 IStreamImpl *istream;
3578 IStreamMessage *message;
3579 };
3580
3581 Context context_{nullptr, nullptr};
3582
3583 static void field_callback_(
3584 sofab_istream_t *ctx, sofab_id_t id, size_t size, size_t count, void *usrptr)
3585 {
3586 (void)ctx;
3587
3588 auto context = static_cast<Context*>(usrptr);
3589 context->message->deserialize(*context->istream, id, size, count);
3590 }
3591
3592 // Wire this message up as a nested sequence decoded on the active stream:
3593 // bind its own decoder + field callback so each child field is dispatched
3594 // to this->deserialize(...). `ctx`/`istream` are passed in by IStreamImpl
3595 // so all stream-internal access stays inside IStreamImpl::read().
3596 void readNested_(sofab_istream_t *ctx, IStreamImpl *istream) noexcept
3597 {
3598 context_ = Context{istream, this};
3599 sofab_istream_read_sequence(ctx, &decoder_, field_callback_, &context_);
3600 }
3601
3602 public:
3603 /*!
3604 * @brief Dispatch one decoded field to the appropriate read.
3605 *
3606 * Called for each field of this message; implementations typically
3607 * switch on @p _id and call @c _istream.read(member).
3608 *
3609 * @param _istream Stream to bind the field's destination on.
3610 * @param _id Field identifier.
3611 * @param _size Field value size in bytes (e.g. string/blob length).
3612 * @param _count Number of array elements (for array fields).
3613 */
3614 virtual void deserialize(sofab::IStreamImpl &_istream, sofab::id _id, size_t _size, size_t _count) noexcept = 0;
3615 };
3616
3617 /*!
3618 * @brief A message that both encodes and decodes: exactly
3619 * @ref OStreamMessage + @ref IStreamMessage.
3620 *
3621 * Almost every message is both, so spelling out the pair at every declaration
3622 * is noise. This is an empty intermediate base — no storage, no vtable slot of
3623 * its own, identical layout to inheriting the two directly — so it is a naming
3624 * convenience and nothing else:
3625 *
3626 * ```cpp
3627 * struct Telemetry : sofab::Message {
3628 * sofab::OStreamImpl::Result serialize(sofab::OStreamImpl &os) const noexcept override;
3629 * void deserialize(sofab::IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override;
3630 * };
3631 * ```
3632 *
3633 * Both @ref sofab::InputMessage and @ref sofab::OutputMessage are satisfied
3634 * through it. Inherit a single side directly when a type really is one-way.
3635 */
3637 {
3638 };
3639
3640 /*!
3641 * @brief Self-contained decoder that owns a message instance.
3642 *
3643 * Wires a @ref IStreamMessage subclass to an input stream so fed bytes are
3644 * dispatched to its @c deserialize. Access the decoded message via @c -> or
3645 * @c *.
3646 *
3647 * @tparam MessageType An @ref InputMessage type.
3648 */
3649 template <InputMessage MessageType>
3651 {
3652 MessageType data_; //!< The owned message instance being decoded into.
3653
3654 public:
3655 /*! @brief Construct and bind the owned message to this stream. */
3657 {
3658 data_.context_ = IStreamMessage::Context{this, &data_};
3659 sofab_istream_init(&ctx_, MessageType::field_callback_, &data_.context_);
3660 }
3661
3662 /*! @brief Member-access to the owned message (e.g. @c obj->field). */
3663 MessageType& operator->() noexcept
3664 {
3665 return data_;
3666 }
3667
3668 /*! @brief Const member-access to the owned message. */
3669 const MessageType& operator->() const noexcept
3670 {
3671 return data_;
3672 }
3673
3674 /*! @brief Reference to the owned message. */
3675 MessageType& operator*() noexcept
3676 {
3677 return data_;
3678 }
3679
3680 /*! @brief Const reference to the owned message. */
3681 const MessageType& operator*() const noexcept
3682 {
3683 return data_;
3684 }
3685 };
3686
3687 /*!
3688 * @brief Decoder that decodes into a message instance the CALLER owns.
3689 *
3690 * @ref IStreamObject with the instance taken out: it binds the message handed
3691 * to the constructor instead of holding one, so fed bytes are dispatched to
3692 * that object's @c deserialize and nothing is staged and copied. The whole
3693 * difference is where the message lives -- same C-ABI field callback, same
3694 * dispatch, no @c std::function -- so it costs a pointer where
3695 * @ref IStreamObject costs a whole message, which on a heap-free target is
3696 * the difference between one and two copies of it on the stack.
3697 *
3698 * The bound object is written as the bytes arrive, so a rejected input
3699 * leaves the fields decoded before the error in it. Put it back where it
3700 * belongs first if that matters -- generated code calls its @c reset() --
3701 * and note that a field the bytes do not carry keeps whatever the object
3702 * already held (MESSAGE_SPEC §2 omits an all-default
3703 * field), which is the same reason.
3704 *
3705 * The message must outlive the stream, and must not be bound to a second
3706 * stream while this one is fed: binding is what the object's own callback
3707 * context points at.
3708 *
3709 * ```cpp
3710 * Telemetry msg; // kept across messages, reused
3711 * msg.reset();
3712 * sofab::IStreamInto<Telemetry> in{msg};
3713 * auto r = in.feed(bytes, len);
3714 * ```
3715 *
3716 * @tparam MessageType An @ref InputMessage type.
3717 */
3718 template <InputMessage MessageType>
3720 {
3721 MessageType *data_; //!< The caller's message instance being decoded into.
3722
3723 public:
3724 /*!
3725 * @brief Bind @p message to this stream.
3726 * @param message Destination; must outlive the stream.
3727 */
3728 explicit IStreamInto(MessageType &message) noexcept
3729 : data_{&message}
3730 {
3731 data_->context_ = IStreamMessage::Context{this, data_};
3732 sofab_istream_init(&ctx_, MessageType::field_callback_, &data_->context_);
3733 }
3734 };
3735
3736 /* ---------------------------------------------------------------------- */
3737 /* Wrapper-sequence collectors and encode helpers */
3738 /* */
3739 /* MESSAGE_SPEC §5 lowers an array of strings, blobs, structs or nested */
3740 /* arrays to a sequence whose child ids are the element indices. These */
3741 /* collect such a sequence into this profile's heap-free containers. They */
3742 /* mirror sofab::StringSeq / BlobSeq in corelib-cpp so both C++ outputs */
3743 /* read the same; the difference is the storage they fill — */
3744 /* InlineVector<FixedString<M>, N> here, std::vector<std::string> there. */
3745 /* */
3746 /* The MessageSeq/FixedMessageSeq counterpart for struct, union and row */
3747 /* elements is in seq.hpp, which this header includes. It used to be */
3748 /* missing: an earlier pair appended elements in ARRIVAL ORDER and grew */
3749 /* the container before deciding the child's wire type, so an interior id */
3750 /* gap shifted every later element down by one (§5.1) and a §7.3 */
3751 /* mismatched child left a phantom (generator#249), and it was removed */
3752 /* rather than shipped as a parity API that behaves unlike the one it */
3753 /* claims to mirror. The pair in seq.hpp places at the element id, like */
3754 /* the four below and like corelib-cpp's MessageSeq. */
3755 /* ---------------------------------------------------------------------- */
3756
3757 /**
3758 * @brief Collects a `string` wrapper sequence into inline storage.
3759 *
3760 * An element is *placed* at its index id rather than appended: a default
3761 * (empty) element is omitted on the wire (§2), so the vector is grown with
3762 * empty slots up to the id and the value stored there. Inline storage never
3763 * reallocates, so an element bound earlier stays address-stable while later
3764 * slots grow — which the deferred C decoder relies on.
3765 *
3766 * An index at or past the fixed capacity N is a schema-bound violation
3767 * (§5.1/§7) and is rejected with @ref IStreamImpl::invalidate, before the fill
3768 * loop. That also bounds an over-index amplification: InlineVector's
3769 * emplace_back is a no-op once full, so an unguarded loop would spin forever
3770 * on such an index (issue #126).
3771 *
3772 * @tparam Container Inline vector of @ref FixedString.
3773 */
3774 template <typename Container>
3776 {
3777 Container *out = nullptr;
3778
3779 void deserialize(IStreamImpl &is, sofab_id_t id, size_t size, size_t) noexcept override
3780 {
3781 if (is.wire() != Wire::Fixlen || is.fixType() != Fix::String) return; /* §7.3 */
3782 if (static_cast<size_t>(id) >= out->capacity())
3783 {
3784 is.invalidate();
3785 return;
3786 }
3787 while (out->size() <= static_cast<size_t>(id)) out->emplace_back();
3788 auto &s = (*out)[id];
3789 s.set_len(size);
3790 if (size) is.read(s);
3791 }
3792 };
3793
3794 /*!
3795 * The `blob` counterpart of @ref FixedStringSeq; same placement and bound
3796 * rules, filling @ref FixedBytes slots.
3797 */
3798 template <typename Container>
3800 {
3801 Container *out = nullptr;
3802
3803 void deserialize(IStreamImpl &is, sofab_id_t id, size_t size, size_t) noexcept override
3804 {
3805 if (is.wire() != Wire::Fixlen || is.fixType() != Fix::Blob) return; /* §7.3 */
3806 if (static_cast<size_t>(id) >= out->capacity())
3807 {
3808 is.invalidate();
3809 return;
3810 }
3811 while (out->size() <= static_cast<size_t>(id)) out->emplace_back();
3812 auto &b = (*out)[id];
3813 b.set_len(size);
3814 if (size) is.read(b.data(), b.size());
3815 }
3816 };
3817
3818 /*!
3819 * @brief Apply a collector's message-side bounds and report the verdict.
3820 *
3821 * The collectors below are the **static helper layer** (§6.6.1): they ship
3822 * here for reuse, the generated layer owns them, and no codec path calls
3823 * them — @ref IStreamImpl::readSequence hands control to the caller's
3824 * collector exactly as it hands control to any other handler. So a bound
3825 * applied here is generated code's bound, not the codec's, and §6.2.1's
3826 * "the codec never invents a limit of its own" is kept: every number below
3827 * arrives in a field the generated layer sets.
3828 *
3829 * A wrapper array is the one shape that has nowhere else to put it. It
3830 * announces no count and fires no callback per element, so the caller has no
3831 * point at which to check, and §6.2.1 puts the enforcement point on the
3832 * element **index**, before the container is extended.
3833 *
3834 * @param is The stream, for the verdict.
3835 * @param n The index + 1, or the element length.
3836 * @param schemaBound The schema's `count` / `maxlen`, or -1. Exceeding it is
3837 * @ref Error::InvalidMessage.
3838 * @param dynCap The §6.2.1 receiver cap. Consulted **only** where
3839 * @p schemaBound is -1. Exceeding it is
3840 * @ref Error::LimitExceeded; leaving it **unstated** there
3841 * is @ref Error::InvalidArgument, because §6.2.1 has no
3842 * unlimited mode for it to mean instead.
3843 * @return `true` when the element was refused.
3844 */
3845 [[nodiscard]] inline bool seqRefuse(
3846 IStreamImpl &is, size_t n, long schemaBound, DynCap dynCap) noexcept
3847 {
3848 // The collectors' spelling of IStreamImpl::refuseBound. One implementation
3849 // of the two message-side tiers, reached from both surfaces (§5.3.1).
3850 return is.refuseBound(n, schemaBound, dynCap);
3851 }
3852
3853#if SOFAB_CPP_HAVE_HOSTED
3854 /**
3855 * @brief Collects a `string` wrapper sequence into a `std::vector<std::string>`.
3856 *
3857 * Hosted only, as the growable storage mode it serves is heap-backed by
3858 * definition; @ref FixedStringSeq is the freestanding counterpart.
3859 *
3860 * The heap counterpart of @ref FixedStringSeq, for the `allow_dynamic`
3861 * storage mode: the schema's `count` and element `maxlen` still bind, they
3862 * just are not the container's capacity any more, so both are checked here.
3863 * An index at or past @ref cap is a schema-bound violation (§5.1/§7), as is
3864 * an element longer than @ref elemMax. Named to match `sofab::StringSeq` in
3865 * corelib-cpp so both C++ outputs read alike.
3866 *
3867 * Where the schema declares neither, @ref dynCap and @ref dynElemMax do — the
3868 * §6.2.1 receiver caps, set by generated code. This is the one collector that
3869 * has to apply them itself: a wrapper array announces no count and fires no
3870 * callback per element, so the caller has no point at which to check, and
3871 * §6.2.1 puts the enforcement point on the element **index**, before the
3872 * container is extended. Breaching one is @ref Error::LimitExceeded, never
3873 * `INVALID`: this is the growable profile's whole exposure, since the
3874 * container itself has no capacity to refuse with.
3875 */
3876 struct StringSeq : IStreamMessage
3877 {
3878 std::vector<std::string> *out = nullptr;
3879 long cap = -1; //!< Schema `count` N, or -1 when the schema declares none.
3880 long elemMax = -1; //!< Element `maxlen`, or -1 when the schema declares none.
3881 DynCap dynCap{}; //!< §6.2.1 receiver cap on the index; required where @ref cap is -1.
3882 DynCap dynElemMax{}; //!< §6.2.1 receiver cap on the element length; required where @ref elemMax is -1.
3883
3884 void deserialize(IStreamImpl &is, sofab_id_t id, size_t size, size_t) noexcept override
3885 {
3886 if (is.wire() != Wire::Fixlen || is.fixType() != Fix::String)
3887 {
3888 return; /* §7.3 */
3889 }
3890 /* The index, decided from the id alone and before the container grows
3891 * -- which is what keeps an announced index near 2^31 from becoming an
3892 * allocation. A wrapper array's length is highest present id + 1
3893 * (MESSAGE_SPEC §5.1), so that is what the bound is applied to. */
3894 if (seqRefuse(is, static_cast<size_t>(id) + 1, cap, dynCap))
3895 {
3896 return;
3897 }
3898 if (seqRefuse(is, size, elemMax, dynElemMax))
3899 {
3900 return;
3901 }
3902 while (out->size() <= static_cast<size_t>(id)) out->emplace_back();
3903 auto &s = (*out)[id];
3904 s.assign(size, '\0');
3905 if (size) is.read(s);
3906 }
3907 };
3908
3909 /*!
3910 * The `blob` counterpart of @ref StringSeq; same placement and bound rules,
3911 * filling `std::vector<std::uint8_t>` slots.
3912 */
3913 struct BlobSeq : IStreamMessage
3914 {
3915 std::vector<std::vector<uint8_t>> *out = nullptr;
3916 long cap = -1; //!< Schema `count` N, or -1 when the schema declares none.
3917 long elemMax = -1; //!< Element `maxlen`, or -1 when the schema declares none.
3918 DynCap dynCap{}; //!< §6.2.1 receiver cap on the index; required where @ref cap is -1.
3919 DynCap dynElemMax{}; //!< §6.2.1 receiver cap on the element length; required where @ref elemMax is -1.
3920
3921 void deserialize(IStreamImpl &is, sofab_id_t id, size_t size, size_t) noexcept override
3922 {
3923 if (is.wire() != Wire::Fixlen || is.fixType() != Fix::Blob)
3924 {
3925 return; /* §7.3 */
3926 }
3927 if (seqRefuse(is, static_cast<size_t>(id) + 1, cap, dynCap))
3928 {
3929 return;
3930 }
3931 if (seqRefuse(is, size, elemMax, dynElemMax))
3932 {
3933 return;
3934 }
3935 while (out->size() <= static_cast<size_t>(id)) out->emplace_back();
3936 auto &b = (*out)[id];
3937 b.resize(size);
3938 if (size) is.read(b.data(), b.size());
3939 }
3940 };
3941#endif /* SOFAB_CPP_HAVE_HOSTED */
3942
3943 /**
3944 * @brief Narrow a fixed-count array to its non-default prefix, for encode.
3945 *
3946 * @deprecated **Superseded and non-conformant.** MESSAGE_SPEC §3 now defines
3947 * `count: N` as a **capacity** and the wire count `M` as the array's
3948 * **length**, so nothing may be elided: `[1,2,3,0,0]` and `[1,2,3]` are
3949 * different values, and trimming the tail silently shortens the array. There
3950 * is no fill-back on decode either. This helper is retained only so generated
3951 * code emitted before the change still compiles; new code must not call it,
3952 * and it goes away with the generator that emits it. (Its C counterpart,
3953 * `_array_trim_count` in object.c, is already gone.)
3954 *
3955 * The superseded contract it implements: a `count: N` array's canonical
3956 * encoding carries `M` = one past the last element that differs from the
3957 * element default, and the decoder refills `[M, N)`.
3958 *
3959 * Elements compare by **byte image**, never `operator==`: `-0.0 == 0.0` holds
3960 * in C++, but `-0.0` is a distinct value that must survive the round-trip, and
3961 * a NaN payload likewise never matches the default.
3962 *
3963 * @param a Contiguous container of trivially-copyable elements.
3964 * @return A span over `[0, M)`.
3965 */
3966 template <typename C>
3967 std::span<const typename C::value_type> trimTail(const C &a) noexcept
3968 {
3969 using Elem = typename C::value_type;
3970 const Elem zero{};
3971 size_t n = a.size();
3972 while (n > 0 && std::memcmp(&a[n - 1], &zero, sizeof(Elem)) == 0) --n;
3973 return std::span<const Elem>(a.data(), n);
3974 }
3975};
3976
3977/** @} */ // end of defgroup
3978
3979/* The wrapper-array collectors for object and row elements live in their own
3980 * header (the static-helper layer), but they are part of the same API: including
3981 * sofab.hpp gives you all six. seq.hpp includes this file back, which the
3982 * include guards resolve either way round. */
3983#include "sofab/seq.hpp"
3984
3985/* The float-array bit-pattern equality the generated default test calls. */
3986#include "sofab/floats.hpp"
3987
3988#endif // SOFAB_HPP
A CORELIB_PLAN §6.2.1 receiver cap, exactly as the caller states it.
Definition sofab.hpp:2023
constexpr std::size_t value() const noexcept
The stated maximum. Meaningless unless stated.
Definition sofab.hpp:2043
constexpr DynCap(T)=delete
Deleted: a signed cap would let -1 re-enter as an unlimited mode.
constexpr bool stated() const noexcept
Whether the caller stated a number at all.
Definition sofab.hpp:2040
constexpr DynCap() noexcept=default
The unstated cap: missing, not unlimited.
Fixed-capacity, heap-free byte blob of up to N bytes.
Definition sofab.hpp:541
bool empty() const noexcept
True if the blob is empty.
Definition sofab.hpp:598
void set_len(std::size_t n) noexcept
Decode hook: set the logical length (clamped to N).
Definition sofab.hpp:613
std::size_t size_type
Size type (mirrors std::vector).
Definition sofab.hpp:549
std::size_t size() const noexcept
Number of bytes currently stored.
Definition sofab.hpp:596
void clear() noexcept
Reset to an empty blob.
Definition sofab.hpp:616
static constexpr std::size_t capacity() noexcept
Maximum number of bytes (the template parameter N).
Definition sofab.hpp:600
std::uint8_t value_type
Element type (mirrors std::vector).
Definition sofab.hpp:547
const std::uint8_t * end() const noexcept
Const iterator past the last byte.
Definition sofab.hpp:639
bool operator!=(const FixedBytes &o) const noexcept
Negated operator==.
Definition sofab.hpp:659
bool operator==(const FixedBytes &o) const noexcept
Content equality (same logical length and bytes).
Definition sofab.hpp:642
const std::uint8_t * begin() const noexcept
Const iterator to the first byte.
Definition sofab.hpp:637
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:570
const std::uint8_t & operator[](std::size_t i) const noexcept
Access the byte at i (no bounds checking).
Definition sofab.hpp:630
void push_back(std::uint8_t b) noexcept
Append one byte (no-op once at capacity N).
Definition sofab.hpp:619
static constexpr std::size_t max_size() noexcept
Alias of capacity.
Definition sofab.hpp:602
std::uint8_t * end() noexcept
Iterator past the last byte.
Definition sofab.hpp:635
FixedBytes() noexcept=default
Construct an empty blob.
const std::uint8_t * data() const noexcept
Const pointer to the byte buffer.
Definition sofab.hpp:593
std::uint8_t & operator[](std::size_t i) noexcept
Access the byte at i (no bounds checking).
Definition sofab.hpp:628
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:576
std::uint8_t * begin() noexcept
Iterator to the first byte.
Definition sofab.hpp:633
std::uint8_t * data() noexcept
Mutable pointer to the byte buffer (decode target).
Definition sofab.hpp:591
Fixed-capacity, heap-free string of up to N characters.
Definition sofab.hpp:310
char * end() noexcept
Iterator past the last character.
Definition sofab.hpp:446
bool operator!=(std::string_view rhs) const noexcept
Inequality against any string view-like operand.
Definition sofab.hpp:492
const char * end() const noexcept
Const iterator past the last character.
Definition sofab.hpp:450
FixedString & operator=(const char *s) noexcept
Assign from a NUL-terminated C string (clamped to N, see assign).
Definition sofab.hpp:356
static constexpr std::size_t max_size() noexcept
Alias of capacity.
Definition sofab.hpp:436
void clear() noexcept
Reset to an empty string.
Definition sofab.hpp:453
std::string_view view() const noexcept
Non-owning view over the current characters.
Definition sofab.hpp:460
const char * data() const noexcept
Const pointer to the character buffer.
Definition sofab.hpp:423
char & operator[](std::size_t i) noexcept
Access the character at i (no bounds checking).
Definition sofab.hpp:439
const char * c_str() const noexcept
NUL-terminated view of the contents.
Definition sofab.hpp:425
const char * begin() const noexcept
Const iterator to the first character.
Definition sofab.hpp:448
char * begin() noexcept
Iterator to the first character.
Definition sofab.hpp:444
FixedString & assign(std::string_view sv) noexcept
Replace the contents with sv, clamped to N bytes.
Definition sofab.hpp:391
FixedString & operator=(std::string_view sv) noexcept
Assign from a string view (clamped to N, see assign).
Definition sofab.hpp:363
const char & operator[](std::size_t i) const noexcept
Access the character at i (no bounds checking).
Definition sofab.hpp:441
FixedString(std::string_view sv) noexcept
Construct from a string view (clamped to N, see assign).
Definition sofab.hpp:336
bool empty() const noexcept
True if the string is empty.
Definition sofab.hpp:432
static constexpr std::size_t capacity() noexcept
Maximum number of characters (the template parameter N).
Definition sofab.hpp:434
char * data() noexcept
Mutable pointer to the character buffer (decode target).
Definition sofab.hpp:421
std::size_t length() const noexcept
Alias of size.
Definition sofab.hpp:430
std::size_t size() const noexcept
Number of characters currently stored.
Definition sofab.hpp:428
char value_type
Character type (mirrors std::string).
Definition sofab.hpp:316
bool operator==(std::string_view rhs) const noexcept
Equality against any string view-like operand.
Definition sofab.hpp:486
std::size_t size_type
Size type (mirrors std::string).
Definition sofab.hpp:318
void set_len(std::size_t n) noexcept
Decode hook: set the logical length and (re)place the trailing NUL.
Definition sofab.hpp:414
FixedString() noexcept=default
Construct an empty string.
Outcome of a feed call.
Definition sofab.hpp:2298
bool ok() const noexcept
True if the consumed bytes end exactly on a field boundary (a complete message so far)....
Definition sofab.hpp:2337
bool invalid() const noexcept
True if the bytes are malformed (Error::InvalidMessage). Deliberately false for limitExceeded(): a re...
Definition sofab.hpp:2355
bool operator==(Error e) const noexcept
Compare the held error code to e.
Definition sofab.hpp:2323
bool incomplete() const noexcept
True if the consumed bytes end mid-field or with an open sequence: a valid but partial decode (Error:...
Definition sofab.hpp:2346
bool operator!=(Error e) const noexcept
Negated operator==().
Definition sofab.hpp:2329
Error code() const noexcept
The Error result of the feed.
Definition sofab.hpp:2372
bool limitExceeded() const noexcept
True if a configured receiver limit was exceeded on a schema-unbounded field (Error::LimitExceeded,...
Definition sofab.hpp:2366
Base input stream: incrementally decodes fed bytes into bound targets.
Definition sofab.hpp:2057
void bindString_(T &value, size_t size) noexcept
Definition sofab.hpp:2178
void readSequence(C &collector, Select &&select) noexcept
readSequence into a destination that comes into existence only once the field matched: select is call...
Definition sofab.hpp:3414
void read(T &value) noexcept
Bind the current field to a typed destination, deducing the wire type from T.
Definition sofab.hpp:2778
void readBlob(T &value, size_t size, long maxlen=-1) noexcept
Bind a blob field, sizing the destination first.
Definition sofab.hpp:3167
void invalidate() noexcept
Reject the message in progress as malformed, from within a field callback (§6.3's first tier).
Definition sofab.hpp:2434
void readSequence(C &collector, Out &out) noexcept
Bind a wrapper-array field through a collector, clearing the destination first.
Definition sofab.hpp:3389
bool readMatch(T &value) noexcept
read for a scalar, reporting whether the field will be decoded into value.
Definition sofab.hpp:2719
IStreamImpl() noexcept=default
Wire wire() const noexcept
Wire type of the field currently being delivered.
Definition sofab.hpp:2648
void readStringCapped(T &value, size_t size, size_t dynCap) noexcept
readString for a schema-unbounded string, bounded by the receiver cap the caller supplies (§6....
Definition sofab.hpp:3131
IStreamImpl & operator=(const IStreamImpl &)=delete
Copy assignment is deleted (the context owns raw pointers).
sofab_istream_t ctx_
Underlying C input stream context.
Definition sofab.hpp:2059
void readArray(Select &&select, size_t wireCount=0, long cap=-1) noexcept
readArray into a destination that comes into existence only once the field matched: select is called ...
Definition sofab.hpp:3303
void readString(T &value, size_t size, long maxlen=-1) noexcept
Bind a string field, sizing the destination first.
Definition sofab.hpp:3047
Result feed(const uint8_t *buffer, size_t buflen) noexcept
Feed raw encoded bytes to the decoder.
Definition sofab.hpp:2410
bool refuseUnbounded(long schemaBound, long room) noexcept
Refuse a read that was given no ceiling of any kind.
Definition sofab.hpp:2595
void refuseArgument() noexcept
Reject the message because the destination this caller handed over cannot hold the value (§6....
Definition sofab.hpp:2470
void latchRefusal_(sofab_ret_t category) noexcept
Definition sofab.hpp:2099
Fix fixType() const noexcept
Fixlen sub-type of the field currently being delivered.
Definition sofab.hpp:2667
bool arrayTagOk_() noexcept
Definition sofab.hpp:2227
sofab_istream_decoder_t arrayDecoder_
Definition sofab.hpp:2073
bool refuseBound(size_t n, long schemaBound, DynCap dynCap) noexcept
The two message-side refusals of §6.3 in one call, in the order §6.2.1 fixes: the schema first,...
Definition sofab.hpp:2623
void readString(Select &&select, size_t size, long maxlen=-1) noexcept
readString into a destination that comes into existence only once the field matched: select is called...
Definition sofab.hpp:3084
static long arrayRoom_(C &out, size_t wireCount) noexcept
Definition sofab.hpp:2254
IStreamImpl(const IStreamImpl &)=delete
Copy construction is deleted (the context owns raw pointers).
bool delivered(Wire w, Fix f) const noexcept
Whether the field currently being delivered has wire type w and fixlen subtype f.
Definition sofab.hpp:2697
void readBlob(Select &&select, size_t size, long maxlen=-1) noexcept
readBlob into a destination that comes into existence only once the field matched – the blob counterp...
Definition sofab.hpp:3194
void bindArray_(C &out, size_t wireCount, long room) noexcept
Definition sofab.hpp:2271
void noteSkip_() noexcept
Definition sofab.hpp:2133
bool refuse(size_t n, long room) noexcept
Refuse an announced length or element count the caller's own destination cannot hold.
Definition sofab.hpp:2503
void bindBlob_(T &value, size_t size) noexcept
Definition sofab.hpp:2202
void readBlobCapped(T &value, size_t size, size_t dynCap) noexcept
readBlob for a schema-unbounded blob, bounded by the receiver cap the caller supplies (§6....
Definition sofab.hpp:3224
size_t read(void *dst, size_t maxlen) noexcept
Decode a blob field into a caller-owned, address-stable buffer.
Definition sofab.hpp:2970
void exceedLimit() noexcept
Reject the message because a configured receiver limit was exceeded (§6.3's second tier,...
Definition sofab.hpp:2453
void resetRefusal_() noexcept
Clear a latched refusal, for a subclass that re-initialises the stream itself.
Definition sofab.hpp:2120
bool delivered(Wire w) const noexcept
Whether the field currently being delivered has wire type w.
Definition sofab.hpp:2684
bool refuseCap(size_t n, size_t dynCap) noexcept
§6.3's second tier: the receiver cap on a schema-unbounded field (§6.2.1).
Definition sofab.hpp:2561
void readArrayCapped(C &out, size_t wireCount, size_t dynCap) noexcept
readArray for a schema-unbounded array, bounded by the receiver cap the caller supplies (§6....
Definition sofab.hpp:3359
bool refuseSchema(size_t n, long schemaBound) noexcept
§6.3's first tier: the bound the schema declares.
Definition sofab.hpp:2534
bool bindMatch_(void *var, size_t len, uint8_t opt) noexcept
Definition sofab.hpp:2156
IStreamImpl(IStreamImpl &&) noexcept=default
Move construction (transfers the underlying context).
void readArray(C &out, size_t wireCount=0, long cap=-1) noexcept
Bind a native scalar array, preparing the destination first.
Definition sofab.hpp:3266
Input stream driven by a user-supplied per-field callback.
Definition sofab.hpp:3520
void(*)(sofab::id _id, size_t _size, size_t _count) fieldCallback
Per-field callback signature: (field id, value size, element count).
Definition sofab.hpp:3529
IStreamInline(fieldCallback callback) noexcept
Construct with the per-field callback.
Definition sofab.hpp:3550
Decoder that decodes into a message instance the CALLER owns.
Definition sofab.hpp:3720
IStreamInto(MessageType &message) noexcept
Bind message to this stream.
Definition sofab.hpp:3728
Base class for decodable message objects.
Definition sofab.hpp:3565
friend class IStreamImpl
Definition sofab.hpp:3569
virtual void deserialize(sofab::IStreamImpl &_istream, sofab::id _id, size_t _size, size_t _count) noexcept=0
Dispatch one decoded field to the appropriate read.
Self-contained decoder that owns a message instance.
Definition sofab.hpp:3651
MessageType & operator*() noexcept
Reference to the owned message.
Definition sofab.hpp:3675
IStreamObject() noexcept
Construct and bind the owned message to this stream.
Definition sofab.hpp:3656
MessageType & operator->() noexcept
Member-access to the owned message (e.g. obj->field).
Definition sofab.hpp:3663
const MessageType & operator->() const noexcept
Const member-access to the owned message.
Definition sofab.hpp:3669
const MessageType & operator*() const noexcept
Const reference to the owned message.
Definition sofab.hpp:3681
Fixed-capacity, heap-free sequence of up to N elements of type T.
Definition sofab.hpp:703
void push_back(T &&v) noexcept
Append v by move; dropped once at capacity N (see above).
Definition sofab.hpp:828
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:731
static constexpr std::size_t capacity() noexcept
Maximum number of elements (the template parameter N).
Definition sofab.hpp:756
std::size_t size_type
Size type (mirrors std::vector).
Definition sofab.hpp:711
void push_back(const T &v) noexcept
Append a copy of v; once at capacity N, v is dropped.
Definition sofab.hpp:826
T & operator[](std::size_t i) noexcept
Access the element at i (no bounds checking).
Definition sofab.hpp:836
const T * begin() const noexcept
Const iterator to the first element.
Definition sofab.hpp:850
bool empty() const noexcept
True if the sequence is empty.
Definition sofab.hpp:754
T value_type
Element type (mirrors std::vector).
Definition sofab.hpp:709
T * begin() noexcept
Iterator to the first element.
Definition sofab.hpp:846
const T & back() const noexcept
Const reference to the last element.
Definition sofab.hpp:833
void reserve(std::size_t) noexcept
No-op (inline storage never reallocates); present for API parity.
Definition sofab.hpp:761
bool operator==(const InlineVector &o) const noexcept
Content equality (same logical length and elements).
Definition sofab.hpp:855
void resize(std::size_t n) noexcept
Set the logical length to n, value-initializing what changes.
Definition sofab.hpp:787
InlineVector() noexcept=default
Construct an empty sequence.
T & back() noexcept
Reference to the last element.
Definition sofab.hpp:831
static constexpr std::size_t max_size() noexcept
Alias of capacity.
Definition sofab.hpp:758
void clear() noexcept
Reset to an empty sequence (logical length only).
Definition sofab.hpp:763
const T * data() const noexcept
Const pointer to the underlying storage.
Definition sofab.hpp:843
const T & operator[](std::size_t i) const noexcept
Access the element at i (no bounds checking).
Definition sofab.hpp:838
bool operator!=(const InlineVector &o) const noexcept
Negated operator==.
Definition sofab.hpp:872
const T * end() const noexcept
Const iterator past the last element.
Definition sofab.hpp:852
T & emplace_back() noexcept
Append a default-constructed element and return a reference to it.
Definition sofab.hpp:811
T * end() noexcept
Iterator past the last element.
Definition sofab.hpp:848
T * data() noexcept
Mutable pointer to the underlying storage.
Definition sofab.hpp:841
std::size_t size() const noexcept
Number of elements currently stored.
Definition sofab.hpp:752
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:737
Outcome of an encode operation, supporting fluent chaining.
Definition sofab.hpp:952
Result sequenceEndKeep() noexcept
Chained frame-keeping sequence-end (no-op if a prior call failed).
Definition sofab.hpp:1046
Result writeIf(sofab_id_t id, const T &value, bool condition) noexcept
Chained conditional write (no-op if a prior call failed).
Definition sofab.hpp:1000
Result sequenceBeginLazy(sofab_id_t id) noexcept
Chained lazy sequence-begin (no-op if a prior call failed).
Definition sofab.hpp:1068
Result write(sofab_id_t id, const T &value) noexcept
Chained write of a field (no-op if a prior call failed).
Definition sofab.hpp:976
bool operator==(Error e) const noexcept
Compare the held error code to e.
Definition sofab.hpp:1111
Result sequenceEnd() noexcept
Chained sequence-end marker (no-op if a prior call failed).
Definition sofab.hpp:1088
Result writeLazy(sofab_id_t id, const T &value) noexcept
Chained nested-message field write that is omitted when the message is all-default (no-op if a prior ...
Definition sofab.hpp:1025
bool operator!=(Error e) const noexcept
Negated operator==().
Definition sofab.hpp:1117
Error code() const noexcept
The first Error encountered in the chain.
Definition sofab.hpp:1129
bool ok() const noexcept
True if the operation (and the chain so far) succeeded.
Definition sofab.hpp:1123
Base output stream: encodes fields into a caller-provided buffer.
Definition sofab.hpp:891
OStreamImpl() noexcept=default
Result sequenceBeginLazy(sofab_id_t id) noexcept
Open a nested sequence whose header is held back until it turns out to have content.
Definition sofab.hpp:1516
Error error() const noexcept
The first failure this stream saw, or Error::None.
Definition sofab.hpp:1583
Result sequenceEnd() noexcept
Close the current nested sequence, letting it vanish if it got no content (MESSAGE_SPEC §2).
Definition sofab.hpp:1526
sofab_ostream_t ctx_
Underlying C output stream context.
Definition sofab.hpp:908
void onFlushCallback(size_t len) noexcept
Invoke the user flush callback (if any) with len buffered bytes.
Definition sofab.hpp:918
Result rejectArgument() noexcept
Refuse the value being encoded: latch Error::InvalidArgument.
Definition sofab.hpp:1607
Result write(sofab_id_t id, const void *value, int32_t size) noexcept
Encode a raw binary blob field.
Definition sofab.hpp:1462
flushCallback flushCallback_
Optional user flush callback.
Definition sofab.hpp:913
const uint8_t * data() const noexcept
Pointer to the start of the active encode buffer.
Definition sofab.hpp:1173
OStreamImpl(OStreamImpl &&) noexcept=default
Move construction (transfers the underlying context).
size_t flush() noexcept
Flush buffered bytes through the flush callback (if any).
Definition sofab.hpp:1155
size_t bytesUsed() noexcept
Number of bytes written to the active buffer since the last flush.
Definition sofab.hpp:1164
uint8_t * buffer_
Pointer to the active encode buffer.
Definition sofab.hpp:909
OStreamImpl & operator=(const OStreamImpl &)=delete
Copy assignment is deleted (the context owns raw buffer pointers).
uint8_t failed_
Sticky: first failing write's sofab_ret_t (0 = none).
Definition sofab.hpp:914
Result sequenceEndKeep() noexcept
Close the current nested sequence, keeping its frame even without content.
Definition sofab.hpp:1544
Result writeLazy(sofab_id_t id, const T &value) noexcept
Encode a nested message field, omitting it when all-default.
Definition sofab.hpp:1437
bool ok() const noexcept
Whether every write on this stream has succeeded.
Definition sofab.hpp:1577
Result write(sofab_id_t id, const T &value) noexcept
Encode a single field, deducing the wire type from T.
Definition sofab.hpp:1195
Result writeIf(sofab_id_t id, const T &value, bool condition) noexcept
Encode a field only when condition is true.
Definition sofab.hpp:1475
OStreamImpl(const OStreamImpl &)=delete
Copy construction is deleted (the context owns raw buffer pointers).
static void static_flush_callback(sofab_ostream_t *ctx, const uint8_t *data, size_t len, void *usrptr) noexcept
C-ABI flush trampoline: forwards to onFlushCallback() via usrptr.
Definition sofab.hpp:927
void(*)(std::span< const uint8_t >) flushCallback
Callback invoked with the bytes to flush (buffer full or on flush()).
Definition sofab.hpp:904
Output stream backed by an inline, fixed-size buffer.
Definition sofab.hpp:1717
OStreamInline() noexcept
Construct with no flush callback.
Definition sofab.hpp:1724
OStreamInline(flushCallback callback) noexcept
Construct with a flush callback.
Definition sofab.hpp:1734
Base class for serializable message objects.
Definition sofab.hpp:1843
virtual OStreamImpl::Result serialize(OStreamImpl &_ostream) const noexcept=0
Serialize this message's fields into _ostream.
OStreamObject variant parameterized by offset only.
Definition sofab.hpp:1915
Self-contained encoder that owns a message and an inline buffer.
Definition sofab.hpp:1868
OStreamObject() noexcept=default
Construct with no flush callback.
OStreamImpl::Result serialize() noexcept
Serialize the owned message and flush.
Definition sofab.hpp:1895
MessageType & operator->() noexcept
Member-access to the owned message (e.g. obj->field = ...).
Definition sofab.hpp:1886
Output stream over a buffer the caller already owns.
Definition sofab.hpp:1758
OStreamView(uint8_t *buffer, size_t buflen, size_t offset=0) noexcept
Construct over caller storage.
Definition sofab.hpp:1766
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:1779
Detects a container that states its own fixed capacity: the condition behind fixed_capacity_v.
Definition sofab.hpp:1948
Detects the pre-0.11 spelling. Deprecated; see OutputMessage.
Definition sofab.hpp:1799
Detects the CORELIB_PLAN §6.1.1 spelling of the worst-case size.
Definition sofab.hpp:1793
Concept: a decodable message type usable with IStreamObject and the nested-message IStreamImpl::read(...
Definition sofab.hpp:1927
Concept: a serializable message type usable with OStreamObject.
Definition sofab.hpp:1832
SofaBuffers C++ - bit-pattern equality for float arrays.
sofab_ret_t sofab_ostream_write_sequence_end(sofab_ostream_t *ctx)
End encoding a nested sequence (end marker).
size_t sofab_ostream_flush(sofab_ostream_t *ctx)
Flush any pending bytes from the output stream.
static void sofab_istream_read_blob(sofab_istream_t *ctx, void *var, size_t varlen)
Reads a binary blob of fixed maximum size.
Definition istream.h:502
sofab_ret_t sofab_ostream_write_array_of_unsigned(sofab_ostream_t *ctx, sofab_id_t id, const void *data, int32_t element_count, int32_t element_size)
Write an array of unsigned integers.
void sofab_istream_invalidate(sofab_istream_t *ctx)
Reject the message in progress from within a field callback.
sofab_ret_t sofab_ostream_write_fixlen(sofab_ostream_t *ctx, sofab_id_t id, const void *data, int32_t datalen, sofab_fixlentype_t type)
Write a fixed-length field.
void sofab_istream_read_field(sofab_istream_t *ctx, void *var, size_t varlen, uint8_t opt)
Number of fields skipped because their wire type contradicted the destination a field callback bound.
sofab_ret_t sofab_ostream_write_sequence_begin_lazy(sofab_ostream_t *ctx, sofab_id_t id)
Begin a nested sequence whose header is held back until it has content.
void sofab_istream_read_sequence(sofab_istream_t *ctx, sofab_istream_decoder_t *decoder, sofab_istream_field_cb_t field_callback, void *usrptr)
Begins decoding a nested Sofab sequence.
static void sofab_istream_read_fp64(sofab_istream_t *ctx, double *var)
Reads a 64-bit floating-point value.
Definition istream.h:454
static sofab_ret_t sofab_ostream_write_array_of_fp32(sofab_ostream_t *ctx, sofab_id_t id, const float *data, int32_t element_count)
Write an array of 32-bit floating-point values.
Definition ostream.h:617
sofab_ret_t sofab_ostream_write_signed(sofab_ostream_t *ctx, sofab_id_t id, sofab_signed_t value)
Write a signed integer field.
#define SOFAB_ISTREAM_OPT_FIELDTYPE(type)
Definition istream.h:62
#define SOFAB_ISTREAM_OPT_FIXLENTYPE(type)
Definition istream.h:63
uint32_t sofab_id_t
Field identifier type.
Definition sofab.h:106
static sofab_ret_t sofab_ostream_write_fp64(sofab_ostream_t *ctx, sofab_id_t id, double value)
Write a 64-bit floating-point value.
Definition ostream.h:363
static void sofab_istream_read_array_of_bool(sofab_istream_t *ctx, bool *var, size_t element_count)
Reads an array of booleans.
Definition istream.h:623
sofab_ret_t sofab_ostream_write_array_of_signed(sofab_ostream_t *ctx, sofab_id_t id, const void *data, int32_t element_count, int32_t element_size)
Write an array of signed integers.
uint64_t sofab_unsigned_t
Scalar varint value types.
Definition sofab.h:118
static sofab_ret_t sofab_ostream_write_fp32(sofab_ostream_t *ctx, sofab_id_t id, float value)
Write a 32-bit floating-point value.
Definition ostream.h:347
static void sofab_istream_read_string_noterm(sofab_istream_t *ctx, char *var, size_t varlen)
Reads a string of fixed maximum size.
Definition istream.h:488
static void sofab_istream_read_fp32(sofab_istream_t *ctx, float *var)
Reads a 32-bit floating-point value.
Definition istream.h:440
#define SOFAB_ISTREAM_OPT_BOOLEAN
Definition istream.h:68
void sofab_ostream_buffer_set(sofab_ostream_t *ctx, uint8_t *buffer, size_t buflen, size_t offset)
Replace the active buffer used by the output stream.
size_t sofab_ostream_bytes_used(sofab_ostream_t *ctx)
Get the number of bytes used in the current buffer.
static void sofab_istream_read_bool(sofab_istream_t *ctx, bool *var)
Reads a boolean value.
Definition istream.h:426
sofab_ret_t sofab_ostream_write_sequence_end_keep(sofab_ostream_t *ctx)
End a nested sequence, keeping its frame even without content.
void sofab_ostream_init(sofab_ostream_t *ctx, uint8_t *buffer, size_t buflen, size_t offset, sofab_ostream_flush_cb_t flush, void *usrptr)
Initialize an Sofab output stream context.
static sofab_ret_t sofab_ostream_write_array_of_fp64(sofab_ostream_t *ctx, sofab_id_t id, const double *data, int32_t element_count)
Write an array of 64-bit floating-point values.
Definition ostream.h:635
sofab_ret_t sofab_ostream_write_unsigned(sofab_ostream_t *ctx, sofab_id_t id, sofab_unsigned_t value)
Write an unsigned integer field.
sofab_ret_t
Return status codes.
Definition sofab.h:39
void sofab_istream_init(sofab_istream_t *ctx, sofab_istream_field_cb_t field_callback, void *usrptr)
Initializes a Sofab input stream context.
int64_t sofab_signed_t
Signed value type.
Definition sofab.h:122
static sofab_ret_t sofab_ostream_write_boolean(sofab_ostream_t *ctx, sofab_id_t id, bool value)
Write a boolean value (1 byte).
Definition ostream.h:331
static void sofab_istream_read_array_of_fp32(sofab_istream_t *ctx, float *var, size_t element_count)
Reads an array of 32-bit floating-point values.
Definition istream.h:669
void sofab_istream_read_array(sofab_istream_t *ctx, void *var, size_t element_count, size_t element_size, uint8_t opt)
Reads an array of elements.
static void sofab_istream_read_array_of_fp64(sofab_istream_t *ctx, double *var, size_t element_count)
Reads an array of 64-bit floating-point values.
Definition istream.h:685
sofab_ret_t sofab_istream_feed(sofab_istream_t *ctx, const void *data, size_t datalen)
Feeds raw Sofab-encoded bytes into the input stream.
static sofab_ret_t sofab_ostream_write_blob(sofab_ostream_t *ctx, sofab_id_t id, const void *data, size_t size)
Write a binary blob field.
Definition ostream.h:400
@ SOFAB_FIXLENTYPE_FP32
Definition sofab.h:99
@ SOFAB_FIXLENTYPE_STRING
Definition sofab.h:101
@ SOFAB_FIXLENTYPE_FP64
Definition sofab.h:100
@ SOFAB_FIXLENTYPE_BLOB
Definition sofab.h:102
@ SOFAB_RET_INCOMPLETE
Consumed bytes end inside a field or with an open sequence: a valid but partial decode.
Definition sofab.h:43
@ SOFAB_RET_OK
OK.
Definition sofab.h:42
@ SOFAB_RET_E_INVALID_MSG
Sofab deserialization failed: the message is malformed, or it carries a wire construct this build was...
Definition sofab.h:57
@ SOFAB_RET_E_LIMIT_EXCEEDED
A configured receiver-side limit (CORELIB_PLAN §6.2.1) was exceeded on a schema-**unbounded** field.
Definition sofab.h:63
@ SOFAB_RET_E_ARGUMENT
The caller handed the library a value it cannot act on: an id above SOFAB_ID_MAX, a destination or de...
Definition sofab.h:49
@ SOFAB_RET_E_BUFFER_FULL
Sofab serialization failed due to buffer overflow.
Definition sofab.h:56
@ SOFAB_TYPE_FIXLEN
Definition sofab.h:88
@ SOFAB_TYPE_VARINTARRAY_SIGNED
Definition sofab.h:90
@ SOFAB_TYPE_VARINT_SIGNED
Definition sofab.h:87
@ SOFAB_TYPE_SEQUENCE_START
Definition sofab.h:92
@ SOFAB_TYPE_FIXLENARRAY
Definition sofab.h:91
@ SOFAB_TYPE_SEQUENCE_END
Definition sofab.h:93
@ SOFAB_TYPE_VARINT_UNSIGNED
Definition sofab.h:86
@ SOFAB_TYPE_VARINTARRAY_UNSIGNED
Definition sofab.h:89
#define SOFAB_CPP_HAVE_ENCODE_BOUNDS
1 if generated code refuses an over-bound value at encode, else 0.
Definition sofab.hpp:127
SofaBuffers C - Input stream decoder for Sofab messages.
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:269
constexpr int API_VERSION
SofaBuffers C++ API version (mirrors SOFAB_API_VERSION).
Definition sofab.hpp:134
Wire
Wire type of a decoded field (the 3-bit type tag of its header).
Definition sofab.hpp:224
@ 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 bool is_fixed_bytes_v
Convenience value for is_fixed_bytes.
Definition sofab.hpp:669
constexpr bool always_false_v
Always-false trait used to trigger a dependent static_assert in a discarded if constexpr branch (so i...
Definition sofab.hpp:143
constexpr long fixed_capacity_v
Compile-time capacity a heap-free container publishes, or -1.
Definition sofab.hpp:1991
constexpr long fixed_capacity_v< C >
Definition sofab.hpp:1994
bool bitsEqual(const T *a, std::size_t na, const T *b, std::size_t nb) noexcept
True iff both float arrays have the same length and the same bit pattern at every index.
Definition floats.hpp:58
constexpr size_t max_size_v
The worst-case encoded size of a generated message, whichever spelling it declares....
Definition sofab.hpp:1808
bool seqRefuse(IStreamImpl &is, size_t n, long schemaBound, DynCap dynCap) noexcept
Apply a collector's message-side bounds and report the verdict.
Definition sofab.hpp:3845
constexpr bool ENCODE_BOUNDS
Whether generated encode refuses an over-bound value (SOFAB_CPP_HAVE_ENCODE_BOUNDS; off with SOFAB_DI...
Definition sofab.hpp:138
sofab_id_t id
Field identifier type (alias of sofab_id_t).
Definition sofab.hpp:213
std::span< const typename C::value_type > trimTail(const C &a) noexcept
Narrow a fixed-count array to its non-default prefix, for encode.
Definition sofab.hpp:3967
typename wire_int< E >::type wire_int_t
Alias for wire_int.
Definition sofab.hpp:166
constexpr bool is_fixed_string_v
Convenience value for is_fixed_string.
Definition sofab.hpp:505
Error
Result/error code returned by the stream APIs (wraps sofab_ret_t).
Definition sofab.hpp:170
@ BufferFull
Output buffer overflowed during encoding.
@ LimitExceeded
A configured receiver limit (§6.2.1) was.
@ InvalidArgument
A field id out of range, a scalar width that is not 1/2/4/8 — or a destination too short for the valu...
@ Incomplete
Consumed bytes end inside a field or with an open sequence: a valid but partial decode.
@ None
Success (a complete message boundary).
@ InvalidMessage
Malformed message encountered while decoding.
Fix
Sub-type of a length-prefixed (Wire::Fixlen) payload.
Definition sofab.hpp:245
@ String
UTF-8 text.
@ Fp32
32-bit IEEE-754 float.
@ Fp64
64-bit IEEE-754 double.
@ Blob
Opaque byte string.
SofaBuffers C - Output stream encoder for Sofab messages.
SofaBuffers C++ - wrapper-array collectors for object and row elements.
Container * out
Definition sofab.hpp:3801
void deserialize(IStreamImpl &is, sofab_id_t id, size_t size, size_t) noexcept override
Dispatch one decoded field to the appropriate read.
Definition sofab.hpp:3803
Collects a string wrapper sequence into inline storage.
Definition sofab.hpp:3776
void deserialize(IStreamImpl &is, sofab_id_t id, size_t size, size_t) noexcept override
Dispatch one decoded field to the appropriate read.
Definition sofab.hpp:3779
A message that both encodes and decodes: exactly OStreamMessage + IStreamMessage.
Definition sofab.hpp:3637
Trait: true only for FixedBytes specializations.
Definition sofab.hpp:664
Trait: true only for FixedString specializations.
Definition sofab.hpp:500
std::underlying_type_t< E > type
Definition sofab.hpp:163
The integer type an element travels as on the wire: identity for an integer, the declared underlying ...
Definition sofab.hpp:160
Decoder context used for Sofab sequences.
Definition istream.h:123
Internal state of the Sofab input stream.
Definition istream.h:135
size_t target_len
Definition istream.h:156
uint8_t * target_ptr
Definition istream.h:148
uint8_t target_opt
Definition istream.h:160