SofaBuffers C/C++ 0.12.0
API Documentation
Loading...
Searching...
No Matches
seq.hpp
Go to the documentation of this file.
1/*!
2 * @file seq.hpp
3 * @brief SofaBuffers C++ - wrapper-array collectors for object and row elements.
4 *
5 * This is the **static-helper layer** of the C++ API: code whose shape is the
6 * same for every schema, so it is written once here instead of being emitted
7 * into every generated header. Nothing here knows a schema. A `count`, a
8 * capacity or an element width arrives as a template argument or a member, i.e.
9 * as an ordinary runtime value — exactly the way @ref sofab::StringSeq already
10 * takes its `cap` and `elemMax`.
11 *
12 * What lives here is the collector for the element kinds the four
13 * string/blob collectors in `sofab.hpp` do not cover: a struct/union element,
14 * a row of native scalars (a matrix), and a row the stream cannot read on its
15 * own — one that is itself a wrapper sequence, or an enum/boolean row that binds
16 * through a view — whose read the caller hands in (@ref sofab::FixedRowSeq /
17 * @ref sofab::RowSeq). Their placement rule is the shared one — MESSAGE_SPEC
18 * §5.1 makes an element's child id its array index — and it is the rule an
19 * appending collector gets wrong, so it is spelled out once, on
20 * @ref sofab::FixedMessageSeq, and referred to from the others.
21 *
22 * Include `sofab/sofab.hpp`; it pulls this in. Including this header alone
23 * works too and means the same thing.
24 *
25 * SPDX-License-Identifier: MIT
26 */
27
28#ifndef SOFAB_SEQ_HPP
29#define SOFAB_SEQ_HPP
30
31/**
32 * @defgroup cpp_api C++ API
33 * @{
34 */
35
36/* includes *******************************************************************/
37#include "sofab/sofab.hpp"
38
39#include <cstddef>
40#include <type_traits>
41
42/* types **********************************************************************/
43namespace sofab
44{
45 /*!
46 * @brief Wire type an element of type @p Elem arrives with, or -1 for none.
47 *
48 * MESSAGE_SPEC §7.3 bounds an element by the wire type its @b declared type
49 * implies, and the collectors below must apply that check before they touch
50 * the destination — one step earlier than @ref IStreamImpl::read or
51 * @ref IStreamImpl::readArray would settle it for themselves. The two must
52 * not be able to disagree, so the choice made here mirrors readArray's
53 * exactly: a struct/union element is a nested sequence, and a native-scalar
54 * row is the array wire type its element kind selects.
55 *
56 * -1 means the element type implies no single wire type; the check is then
57 * left to the read, which still refuses to bind a contradicting field.
58 *
59 * @tparam Elem Element type (an @ref IStreamMessage, or a row container).
60 */
61 template <typename Elem>
62 inline constexpr int seq_elem_wire_v =
63 [] () constexpr -> int
64 {
65 if constexpr (std::is_base_of_v<IStreamMessage, Elem>)
66 {
67 return static_cast<int>(Wire::SequenceStart);
68 }
69 else if constexpr (requires { typename Elem::value_type; })
70 {
71 using RowElem = typename Elem::value_type;
72 if constexpr (std::is_same_v<RowElem, float> || std::is_same_v<RowElem, double>)
73 {
74 return static_cast<int>(Wire::ArrayFixlen);
75 }
76 else if constexpr (std::is_integral_v<RowElem>)
77 {
78 return static_cast<int>(
79 std::is_signed_v<RowElem> ? Wire::ArraySigned : Wire::ArrayUnsigned);
80 }
81 else
82 {
83 return -1;
84 }
85 }
86 else
87 {
88 return -1;
89 }
90 }();
91
92 /*!
93 * @brief Fixlen sub-type an element of type @p Elem arrives with, or -1.
94 *
95 * The companion to @ref seq_elem_wire_v for the one wire type that is not
96 * self-describing: @c fp32 and @c fp64 rows share @ref Wire::ArrayFixlen, so
97 * §7.3 only separates them at the sub-type. -1 wherever the wire type already
98 * settles the element kind.
99 *
100 * @tparam Elem Element type (an @ref IStreamMessage, or a row container).
101 */
102 template <typename Elem>
103 inline constexpr int seq_elem_fix_v =
104 [] () constexpr -> int
105 {
106 if constexpr (!std::is_base_of_v<IStreamMessage, Elem>
107 && requires { typename Elem::value_type; })
108 {
109 using RowElem = typename Elem::value_type;
110 if constexpr (std::is_same_v<RowElem, float>)
111 {
112 return static_cast<int>(Fix::Fp32);
113 }
114 else if constexpr (std::is_same_v<RowElem, double>)
115 {
116 return static_cast<int>(Fix::Fp64);
117 }
118 else
119 {
120 return -1;
121 }
122 }
123 else
124 {
125 return -1;
126 }
127 }();
128
129 /*!
130 * @brief Collects a struct/union or nested-array wrapper sequence into
131 * inline storage.
132 *
133 * The object counterpart of @ref FixedStringSeq: same placement rule, same
134 * bound, filling elements that are messages (a struct or union) or rows of
135 * native scalars (a matrix) rather than @ref FixedString slots. Bind it the
136 * way its four siblings are bound, through
137 * @ref IStreamImpl::readSequence.
138 *
139 * **An element is placed at its index id, never appended.** MESSAGE_SPEC
140 * §5.1 makes the element's child id the array index, and the ids may have
141 * gaps: an @b interior element equal to the element default is left off the
142 * wire by a conformant encoder (§2), so the container is grown with default
143 * elements up to the id and the value stored there. Appending instead would
144 * silently @b shorten the array by every gap — elements at id 0 and id 2 are
145 * the 3-element array `[a, default, c]`, not `[a, c]` — and would turn a
146 * reopened element id into a second element instead of continuing the first
147 * (§7.4). The array's last element is always on the wire, so the decoded
148 * length (highest present id + 1) is exact; the schema `count` is a
149 * @b capacity and never adds an element the wire did not carry.
150 *
151 * An index at or past the fixed capacity N is a schema-bound violation
152 * (§5.1/§7) and is rejected with @ref IStreamImpl::invalidate, @b before the
153 * fill loop. That also bounds an over-index amplification: @ref InlineVector
154 * reuses its last slot once full, so an unguarded fill loop would spin
155 * forever on such an index (issue #126), and no announced index can make the
156 * receiver reserve anything.
157 *
158 * An element whose wire type contradicts the declared one is skipped exactly
159 * like an unknown id (§7.3), which means it must leave the container
160 * untouched — so that decision, too, comes before the fill.
161 *
162 * Inline storage never reallocates, so an element bound earlier stays
163 * address-stable while later slots grow, which the deferred C decoder relies
164 * on.
165 *
166 * @tparam Container Inline vector of messages, or of rows.
167 */
168 template <typename Container>
170 {
171 /*! @brief Element type: an @ref IStreamMessage, or a row container. */
172 using Elem = typename Container::value_type;
173
174 /*! @brief Declared element wire type, or -1 (@ref seq_elem_wire_v). */
175 static constexpr int elemWire = seq_elem_wire_v<Elem>;
176 /*! @brief Declared element fixlen sub-type, or -1 (@ref seq_elem_fix_v). */
177 static constexpr int elemFix = seq_elem_fix_v<Elem>;
178
179 static_assert(fixed_capacity_v<Container> >= 0,
180 "FixedMessageSeq needs a heap-free container: its capacity IS the "
181 "schema bound this collector applies. Use sofab::MessageSeq, with an "
182 "explicit cap, for a growable one.");
183
184 Container *out = nullptr; //!< Destination, bound by @ref IStreamImpl::readSequence.
185
186 void deserialize(IStreamImpl &is, sofab_id_t id, size_t, size_t count) noexcept override
187 {
188 /* §7.3 first: an element whose wire type contradicts the declared one
189 * is not this array's element at all. It is skipped like an unknown
190 * id, which means the destination must be left exactly as it was --
191 * so this comes before the fill below, and an id that is not an index
192 * cannot breach the index bound either. */
193 if constexpr (elemWire >= 0)
194 {
195 if (static_cast<int>(is.wire()) != elemWire) return;
196 }
197 if constexpr (elemFix >= 0)
198 {
199 if (static_cast<int>(is.fixType()) != elemFix) return;
200 }
201 if (static_cast<size_t>(id) >= static_cast<size_t>(fixed_capacity_v<Container>))
202 {
203 is.invalidate();
204 return;
205 }
206 while (out->size() <= static_cast<size_t>(id)) (void)out->emplace_back();
207 Elem &elem = (*out)[static_cast<size_t>(id)];
208 if constexpr (std::is_base_of_v<IStreamMessage, Elem>)
209 {
210 is.read(elem); /* the element's own sub-sequence */
211 }
212 else
213 {
214 /* A native-scalar row goes through readArray rather than a bare
215 * resize() + read(): readArray owns the row's tag check, sizes the
216 * row from the wire count and refuses a count the row cannot hold
217 * instead of truncating into it (§7.1). A heap-free row's capacity
218 * IS the schema `count` it was generated for, so it is passed as
219 * the bound: a count past it is INVALID (§7.1), where leaving the
220 * bound out would report the same row as a too-short destination
221 * (InvalidArgument, §6.6.3). */
222 is.readArray(elem, count, fixed_capacity_v<Elem>);
223 }
224 }
225 };
226
227 /*!
228 * @brief Collects a struct/union or nested-array wrapper sequence into a
229 * growable container.
230 *
231 * The heap counterpart of @ref FixedMessageSeq, for the `allow_dynamic`
232 * storage mode, and the object counterpart of @ref StringSeq: the schema's
233 * `count` still binds, it just is not the container's capacity any more, so
234 * it is carried in @ref cap. Placement, gap fill and the §7.3 skip are
235 * @ref FixedMessageSeq's, unchanged and documented there; only the bound
236 * moves. Named to match `sofab::MessageSeq` in corelib-cpp so both C++
237 * outputs read alike — the generator emits one call site for the two.
238 *
239 * A growable row is bounded by the wire count alone: unlike an inline row it
240 * publishes no capacity, and the schema `count` of the inner array is not
241 * something the outer collector is told.
242 *
243 * Growing the container may reallocate it, which the deferred decoder would
244 * not survive if it moved a destination already bound. It cannot: an element
245 * is placed only when its own child field opens, i.e. once the element before
246 * it has closed and every target inside it has been filled. That is the same
247 * reasoning @c read(std::vector<std::string>&) relies on; @ref
248 * FixedMessageSeq does not need it at all, since inline storage never moves.
249 *
250 * @tparam Container Growable container of messages, or of rows.
251 */
252 template <typename Container>
254 {
255 /*! @brief Element type: an @ref IStreamMessage, or a row container. */
256 using Elem = typename Container::value_type;
257
258 /*! @brief Declared element wire type, or -1 (@ref seq_elem_wire_v). */
259 static constexpr int elemWire = seq_elem_wire_v<Elem>;
260 /*! @brief Declared element fixlen sub-type, or -1 (@ref seq_elem_fix_v). */
261 static constexpr int elemFix = seq_elem_fix_v<Elem>;
262
263 Container *out = nullptr; //!< Destination, bound by @ref IStreamImpl::readSequence.
264 long cap = -1; //!< Schema `count` N, or -1 when the schema declares none.
265 DynCap dynCap{}; //!< §6.2.1 receiver cap on the index; required where @ref cap is -1.
266 long elemCount = -1; //!< A ROW element's own schema `count`, or -1. Ignored for message elements.
267 DynCap dynElemCount{}; //!< §6.2.1 receiver cap on a row's element count; required where @ref elemCount is -1.
268
269 void deserialize(IStreamImpl &is, sofab_id_t id, size_t, size_t count) noexcept override
270 {
271 if constexpr (elemWire >= 0)
272 {
273 if (static_cast<int>(is.wire()) != elemWire) return; /* §7.3 */
274 }
275 if constexpr (elemFix >= 0)
276 {
277 if (static_cast<int>(is.fixType()) != elemFix) return; /* §7.3 */
278 }
279 /* §5.1/§7, decided from the id alone and before the container grows --
280 * which is what keeps an announced index near 2^31 from becoming an
281 * allocation. A wrapper array's length is highest present id + 1
282 * (MESSAGE_SPEC §5.1), so that is what the bound is applied to. Where
283 * the schema declares no `count`, dynCap does (§6.2.1) -- there is no
284 * capacity here to refuse with, exactly as in @ref StringSeq. */
285 if (seqRefuse(is, static_cast<size_t>(id) + 1, cap, dynCap))
286 {
287 return;
288 }
289 while (out->size() <= static_cast<size_t>(id)) (void)out->emplace_back();
290 Elem &elem = (*out)[static_cast<size_t>(id)];
291 if constexpr (std::is_base_of_v<IStreamMessage, Elem>)
292 {
293 is.read(elem);
294 }
295 else
296 {
297 /* A growable row publishes no capacity of its own, so the ceiling
298 * has to be stated here -- @ref elemCount for the row's schema
299 * `count`, @ref dynElemCount for the §6.2.1 receiver cap where the
300 * schema declares none. An inline row needs neither: its capacity
301 * IS a ceiling the sender cannot move.
302 *
303 * Neither stated, on a growable row, is not "unlimited": the read
304 * refuses it as Error::InvalidArgument rather than sizing the row
305 * from a count the SENDER chose. */
306 if (elemCount >= 0)
307 {
308 is.readArray(elem, count, elemCount);
309 }
310 else if (dynElemCount.stated())
311 {
312 is.readArrayCapped(elem, count, dynElemCount.value());
313 }
314 else
315 {
316 is.readArray(elem, count);
317 }
318 }
319 }
320 };
321
322 /*!
323 * @brief Collects a wrapper sequence of rows the stream cannot read on its
324 * own, into inline storage.
325 *
326 * @ref FixedMessageSeq reads a struct/union element or a row of native
327 * scalars itself. A row that is itself a wrapper sequence
328 * (`array<array<string>>`, `array<array<struct>>`, deeper) is neither, and an
329 * `enum` or `boolean` row has to bind through a view of its elements. For
330 * those the row read is the caller's: @p Reader. It is the only part of a row
331 * collector that differs between schemas; the rest is
332 * @ref FixedMessageSeq's rule, unchanged and in the same order — the §7.3
333 * skip first, then the index bound against the inline capacity, then the
334 * placement at the index id (see @ref FixedMessageSeq for why each comes
335 * where it does).
336 *
337 * @tparam Container Inline vector of rows.
338 * @tparam Reader The row read, one level down. A default-constructible
339 * type with
340 * - `static constexpr Wire wire()`, the wire type a row of
341 * this schema arrives with — @ref Wire::SequenceStart for
342 * a row that is a wrapper sequence, the array wire type of
343 * the backing integer for an enum or boolean row; and
344 * - `void operator()(IStreamImpl &, Elem &, size_t count)`,
345 * binding the row that was placed; @p count is the
346 * element count the stream announced for it, as
347 * @ref IStreamImpl::readArray takes it.
348 *
349 * `wire()` is a function rather than a constant because a
350 * local class — which is where generated code declares the
351 * reader, next to the field it reads — may not have static
352 * data members.
353 */
354 template <typename Container, typename Reader>
356 {
357 /*! @brief Row type: the container's element. */
358 using Elem = typename Container::value_type;
359
360 /*! @brief Declared row wire type (§7.3), from @p Reader. */
361 static constexpr int elemWire = static_cast<int>(Reader::wire());
362
363 static_assert(fixed_capacity_v<Container> >= 0,
364 "FixedRowSeq needs a heap-free container: its capacity IS the "
365 "schema bound this collector applies. Use sofab::RowSeq, with an "
366 "explicit cap, for a growable one.");
367
368 Container *out = nullptr; //!< Destination, bound by @ref IStreamImpl::readSequence.
369 [[no_unique_address]] Reader readRow{}; //!< The row read.
370
371 void deserialize(IStreamImpl &is, sofab_id_t id, size_t, size_t count) noexcept override
372 {
373 if (static_cast<int>(is.wire()) != elemWire) return; /* §7.3 */
374 if (static_cast<size_t>(id) >= static_cast<size_t>(fixed_capacity_v<Container>))
375 {
376 is.invalidate(); /* §5.1/§7 */
377 return;
378 }
379 while (out->size() <= static_cast<size_t>(id)) (void)out->emplace_back();
380 readRow(is, (*out)[static_cast<size_t>(id)], count);
381 }
382 };
383
384 /*!
385 * @brief The index bounds of a @ref RowSeq whose schema `count` is not a
386 * template argument: the schema `count` and the §6.2.1 receiver cap,
387 * as runtime members, exactly as @ref MessageSeq carries them.
388 */
389 template <long Count>
391 {
392 // A count given as a template argument needs no storage.
393 };
394
395 /*! @copydoc RowSeqBounds */
396 template <>
397 struct RowSeqBounds<-1>
398 {
399 long cap = -1; //!< Schema `count` N, or -1 when the schema declares none.
400 DynCap dynCap{}; //!< §6.2.1 receiver cap on the index; required where @ref cap is -1.
401 };
402
403 /*!
404 * @brief Collects a wrapper sequence of rows the stream cannot read on its
405 * own, into a growable container.
406 *
407 * The heap counterpart of @ref FixedRowSeq, as @ref MessageSeq is of
408 * @ref FixedMessageSeq. Named to match `sofab::RowSeq` in corelib-cpp. The
409 * schema `count` arrives one of two ways:
410 *
411 * - as the template argument @p Count — the bound is then a constant, the
412 * collector stores no bound at all and a row at or past it is
413 * @ref Error::InvalidMessage. This is the generated layer's form: the
414 * footprint profile requires a `count` on every array level, so a receiver
415 * cap could never apply, and neither its storage nor its branch is paid for;
416 * - or, with @p Count left at -1, as the runtime member `cap`, with the
417 * §6.2.1 receiver cap `dynCap` beside it for a schema-unbounded array —
418 * applied by @ref seqRefuse exactly as @ref MessageSeq applies them.
419 *
420 * A row is placed only once its own field opens, i.e. once every target in
421 * the row before it has been filled, so growing the container cannot move a
422 * destination the deferred decoder still has bound (see @ref MessageSeq).
423 *
424 * @tparam Container Growable container of rows.
425 * @tparam Reader The row read, as for @ref FixedRowSeq.
426 * @tparam Count Schema `count` N, or -1 to take the bounds as members.
427 */
428 template <typename Container, typename Reader, long Count = -1>
430 {
431 static_assert(Count >= -1, "Count is a schema count, or -1 for runtime bounds");
432
433 /*! @brief Row type: the container's element. */
434 using Elem = typename Container::value_type;
435
436 /*! @brief Declared row wire type (§7.3), from @p Reader. */
437 static constexpr int elemWire = static_cast<int>(Reader::wire());
438
439 Container *out = nullptr; //!< Destination, bound by @ref IStreamImpl::readSequence.
440 [[no_unique_address]] Reader readRow{}; //!< The row read.
441
442 void deserialize(IStreamImpl &is, sofab_id_t id, size_t, size_t count) noexcept override
443 {
444 if (static_cast<int>(is.wire()) != elemWire) return; /* §7.3 */
445 if constexpr (Count >= 0)
446 {
447 if (static_cast<size_t>(id) >= static_cast<size_t>(Count))
448 {
449 is.invalidate(); /* §5.1/§7 */
450 return;
451 }
452 }
453 else if (seqRefuse(is, static_cast<size_t>(id) + 1, this->cap, this->dynCap))
454 {
455 return;
456 }
457 while (out->size() <= static_cast<size_t>(id)) (void)out->emplace_back();
458 readRow(is, (*out)[static_cast<size_t>(id)], count);
459 }
460 };
461};
462
463/** @} */ // end of defgroup
464
465#endif // SOFAB_SEQ_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 bool stated() const noexcept
Whether the caller stated a number at all.
Definition sofab.hpp:2040
Base input stream: incrementally decodes fed bytes into bound targets.
Definition sofab.hpp:2057
Base class for decodable message objects.
Definition sofab.hpp:3565
uint32_t sofab_id_t
Field identifier type.
Definition sofab.h:106
constexpr int seq_elem_wire_v
Wire type an element of type Elem arrives with, or -1 for none.
Definition seq.hpp:62
@ ArrayUnsigned
Count-prefixed array of unsigned varints.
@ ArraySigned
Count-prefixed array of zig-zag varints.
@ ArrayFixlen
Count-prefixed array of fixed-size elements.
@ SequenceStart
Opens a nested sub-message.
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
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 int seq_elem_fix_v
Fixlen sub-type an element of type Elem arrives with, or -1.
Definition seq.hpp:103
sofab_id_t id
Field identifier type (alias of sofab_id_t).
Definition sofab.hpp:213
@ Fp32
32-bit IEEE-754 float.
@ Fp64
64-bit IEEE-754 double.
SofaBuffers C++ - Input and output stream decoder for Sofab messages.
Collects a struct/union or nested-array wrapper sequence into inline storage.
Definition seq.hpp:170
static constexpr int elemWire
Declared element wire type, or -1 (seq_elem_wire_v).
Definition seq.hpp:175
void deserialize(IStreamImpl &is, sofab_id_t id, size_t, size_t count) noexcept override
Dispatch one decoded field to the appropriate read.
Definition seq.hpp:186
static constexpr int elemFix
Declared element fixlen sub-type, or -1 (seq_elem_fix_v).
Definition seq.hpp:177
typename Container::value_type Elem
Element type: an IStreamMessage, or a row container.
Definition seq.hpp:172
Container * out
Destination, bound by IStreamImpl::readSequence.
Definition seq.hpp:184
Collects a wrapper sequence of rows the stream cannot read on its own, into inline storage.
Definition seq.hpp:356
Reader readRow
The row read.
Definition seq.hpp:369
void deserialize(IStreamImpl &is, sofab_id_t id, size_t, size_t count) noexcept override
Dispatch one decoded field to the appropriate read.
Definition seq.hpp:371
static constexpr int elemWire
Declared row wire type (§7.3), from Reader.
Definition seq.hpp:361
typename Container::value_type Elem
Row type: the container's element.
Definition seq.hpp:358
Container * out
Destination, bound by IStreamImpl::readSequence.
Definition seq.hpp:368
Collects a struct/union or nested-array wrapper sequence into a growable container.
Definition seq.hpp:254
void deserialize(IStreamImpl &is, sofab_id_t id, size_t, size_t count) noexcept override
Dispatch one decoded field to the appropriate read.
Definition seq.hpp:269
Container * out
Destination, bound by IStreamImpl::readSequence.
Definition seq.hpp:263
DynCap dynElemCount
§6.2.1 receiver cap on a row's element count; required where elemCount is -1.
Definition seq.hpp:267
static constexpr int elemFix
Declared element fixlen sub-type, or -1 (seq_elem_fix_v).
Definition seq.hpp:261
static constexpr int elemWire
Declared element wire type, or -1 (seq_elem_wire_v).
Definition seq.hpp:259
long elemCount
A ROW element's own schema count, or -1. Ignored for message elements.
Definition seq.hpp:266
long cap
Schema count N, or -1 when the schema declares none.
Definition seq.hpp:264
DynCap dynCap
§6.2.1 receiver cap on the index; required where cap is -1.
Definition seq.hpp:265
typename Container::value_type Elem
Element type: an IStreamMessage, or a row container.
Definition seq.hpp:256
The index bounds of a RowSeq whose schema count is not a template argument: the schema count and the ...
Definition seq.hpp:391
Collects a wrapper sequence of rows the stream cannot read on its own, into a growable container.
Definition seq.hpp:430
typename Container::value_type Elem
Row type: the container's element.
Definition seq.hpp:434
static constexpr int elemWire
Declared row wire type (§7.3), from Reader.
Definition seq.hpp:437
void deserialize(IStreamImpl &is, sofab_id_t id, size_t, size_t count) noexcept override
Dispatch one decoded field to the appropriate read.
Definition seq.hpp:442
Reader readRow
The row read.
Definition seq.hpp:440
Container * out
Destination, bound by IStreamImpl::readSequence.
Definition seq.hpp:439