Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,8 @@ to skip. Handing the number in makes both conditions a property of the structure
A wrapper array — an array of `string`, `blob`, `struct` or nested rows — carries
no count header: its length is *highest present id + 1*, so the element **index**
is what the cap binds, and it is checked before the container is extended. The
`StringSeq` / `BlobSeq` / `MessageSeq` collectors take it as their `dynCap`.
`StringSeq` / `BlobSeq` / `MessageSeq` / `RowSeq` collectors take it as their
`dynCap`.

**A nested row has a second axis, and it states its own pair.** In
`array<array<u32>>` the outer array's length is the row **index**, bounded by
Expand All @@ -384,6 +385,30 @@ c.out = &numrows; c.cap = 2; c.rowCap = 3;
sofab::read(is, c);
```

**A row the stream cannot read on its own goes through `RowSeq`.** `MessageSeq`
reads a row of native scalars itself. A row that is itself a wrapper sequence
(`array<array<string>>`, `array<array<struct>>`, deeper) is not a span of
scalars, and an `enum` or `boolean` row has to bind through a view of its
elements. For those, `RowSeq` takes the row read from the caller as a *reader*
and does the rest: the §7.3 skip, the index bound in §6.3's three categories,
the placement at `dest[id]` and the §7.4 reset. The reader states the row's wire
type through a static `wire()` and reads the placed row in `operator()`:

```cpp
// array<array<string>>: outer count 2, row count 3, element maxlen 8
struct Row {
static constexpr sofab::detail::Wire wire() noexcept { return sofab::detail::Wire::SequenceStart; }
void operator()(sofab::IStreamImpl &is, std::vector<std::string> &row) const noexcept {
sofab::StringSeq c{row, 3, 8, -1, -1}; sofab::read(is, c);
}
};
sofab::RowSeq c{grid, /*count*/ 2, /*dynCap*/ -1, Row{}};
sofab::read(is, c);
```

Like `StringSeq`, `RowSeq` takes the schema `count` and the receiver cap as
constructor arguments, so neither can be left out.

#### Strict UTF-8 validation (`SOFAB_STRICT_UTF8`, default ON)

A `string` carries UTF-8 text; `blob` is the type for opaque bytes. With
Expand Down Expand Up @@ -566,8 +591,8 @@ the bytes arrive, whole or one byte at a time.
top-level field may span and is a **required** constructor argument. The three
per-field caps — `max_dyn_string_len`, `max_dyn_blob_len`,
`max_dyn_array_count` — are **arguments**, not settings: the `…Capped` reads
take one, and the `StringSeq` / `BlobSeq` / `MessageSeq` collectors take one as
`dynCap` for the element index of a wrapper array — and, on `MessageSeq`, as
take one, and the `StringSeq` / `BlobSeq` / `MessageSeq` / `RowSeq` collectors
take one as `dynCap` for the element index of a wrapper array — and, on `MessageSeq`, as
`rowDynCap` for the element count of a native nested row. Nothing defaults: the
numbers belong to generated code, which knows the schema and the target, and an
omitted one is a compile error or an `Error::InvalidArgument`, never "no cap"
Expand Down
110 changes: 110 additions & 0 deletions include/sofab/sofab.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6998,6 +6998,116 @@ namespace sofab
}
};

/**
* @brief Collects a wrapper sequence whose elements are **rows the stream
* cannot read on its own** — a row that is itself a wrapper sequence
* (`array<array<string>>`, `array<array<struct>>`, deeper), or a row
* that must bind through a view of its elements (an `enum` or
* `boolean` row).
*
* @ref MessageSeq hands each element to @ref IStreamImpl::read, which reads
* a message or a span of native scalars and nothing else. A row of strings
* is neither, so its read has to be stated by the caller: that is
* @p Reader, and it is the only part of a row collector that differs
* between schemas. Everything else is the wrapper-array rule every collector
* here applies, in the same order:
*
* 1. **§7.3 first.** An element whose wire type contradicts the row's is
* not an element of this array at all. It is skipped like an unknown id,
* before the index bound — so it cannot breach it — and before the
* placement, so the destination is left exactly as it was. The row's wire
* type is published as @ref elemWire, so the stream runs the same test
* one step earlier, at the element header, and applies the bound only to
* an element that survives it.
* 2. **§5.1 index bound**, in §6.3's three categories
* (@ref detail::seqIndexAdmitted): the schema `count` (`cap`,
* `InvalidMessage`), else the receiver cap (`dynCap`, `LimitExceeded`),
* and the destination's own capacity (@ref elemDestCap).
* 3. **Placement.** The element id IS the index: the container is grown with
* default rows up to it and the row is read in place at `dest[id]`.
* 4. **§7.4.** A repeated field id replaces the array whole, via
* @ref prepare.
*
* @tparam C Destination container of rows — `std::vector<Row>` or
* `InlineVector<Row, N>`; deduced from the constructor.
* @tparam Reader The row read, one level down. A default-constructible type
* with
* - `static constexpr detail::Wire wire()`, the wire type a
* row of this schema arrives with — @c SequenceStart for a
* row that is a wrapper sequence, the array wire type of the
* backing integer for an enum or boolean row; and
* - `void operator()(IStreamImpl &, typename C::value_type &)`,
* reading the row that was placed.
*
* `wire()` is a function rather than a constant because a
* local class — which is where generated code declares the
* reader, next to the field it reads — may not have static
* data members.
*
* @par Example
* @code
* // array<array<string>>: outer count 2, row count 3, element maxlen 8
* struct Row {
* static constexpr sofab::detail::Wire wire() noexcept { return sofab::detail::Wire::SequenceStart; }
* void operator()(sofab::IStreamImpl &is, std::vector<std::string> &row) const noexcept {
* sofab::StringSeq c{row, 3, 8, -1, -1}; sofab::read(is, c);
* }
* };
* sofab::RowSeq c{grid, 2, -1, Row{}}; sofab::read(is, c);
* @endcode
*/
template <typename C, typename Reader>
struct RowSeq : IStreamMessage
{
/** Destination container. */
using Container = C;
/** Row type: the container's element. */
using Elem = typename C::value_type;

C &out;
/** Schema `count` N, or -1; an id at or past N is INVALID (§5.1/§7.1). */
long cap;
/** @copydoc StringSeq::dynCap */
long dynCap;
/** The row read (@p Reader). */
[[no_unique_address]] Reader readRow;

/** @copydoc StringSeq::elemDestCap */
static constexpr long elemDestCap = detail::destCapacity<C>();

/** @brief The row's wire type, published to the stream (§7.3), as
* @ref StringSeq::elemWire is. */
static constexpr int elemWire = static_cast<int>(Reader::wire());

/**
* @param o Destination; rows are placed at their index id.
* @param capacity Schema `count` N, or -1 for an unbounded array.
* @param indexCap The caller's `max_dyn_array_count` (@ref dynCap), or -1
* when none was supplied. Mandatory, as on @ref StringSeq:
* a schema-unbounded growable array with neither is
* refused with @ref Error::InvalidArgument, never read as
* unlimited (§6.2.1).
* @param reader The row read.
*/
explicit RowSeq(C &o, long capacity, long indexCap, Reader reader = {}) noexcept
: out(o), cap(capacity), dynCap(indexCap), readRow(reader) {}

/** §7.4 replace-whole, and absent ⇒ never called: @copydoc StringSeq::prepare */
void prepare() noexcept { out.clear(); }

void deserialize(IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override
{
/* Decide, place, read in place -- see MessageSeq::deserialize. The
* §7.3 test is repeated here although the stream has already run it
* for a bounded array: `deserialize` is public, and an unbounded array
* publishes no bound for the stream to key on. */
if (static_cast<int>(is.wire()) != elemWire) return; /* §7.3 */
if (!detail::seqIndexAdmitted(is, id, cap, dynCap, elemDestCap)) return;
while (out.size() <= static_cast<size_t>(id)) (void)out.emplace_back();
readRow(is, out[static_cast<size_t>(id)]);
}
};

/* No encode-side trailing-default trim helper lives here, deliberately.
*
* A `trimTail` used to, narrowing a container to its non-default prefix
Expand Down
196 changes: 196 additions & 0 deletions test/test_roundtrip.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8627,6 +8627,201 @@ static void decoderReuseAcrossTypes()
checkStreamReuse<Utf8SkipMsg>("Utf8SkipMsg");
}

/* --- RowSeq: a row the stream cannot read on its own -----------------------
*
* A row that is itself a wrapper sequence (array<array<string>>) is neither a
* message nor a span of scalars, so MessageSeq cannot read it; RowSeq takes the
* row read from the caller and owns everything else -- the §7.3 skip, the index
* bound in §6.3's categories, the placement and the §7.4 reset. None of that is
* wire-visible from the encoder's side, so it is pinned here.
*
* Wire notes: a tag byte is (id << 3) | wire, a string element is `02 0a 41`
* (id 0, fixlen word len 1 / subtype string, "A"), and a row is a sequence of
* those closed by `07`. --- */

/* The row read for array<array<string>>, row `count: 3`, element `maxlen: 8`. */
struct StrRowReader
{
static constexpr sofab::detail::Wire wire() noexcept { return sofab::detail::Wire::SequenceStart; }
void operator()(sofab::IStreamImpl &is, std::vector<std::string> &row) const noexcept
{
sofab::StringSeq c{row, 3, 8, -1, -1};
sofab::read(is, c);
}
};

/* The same row in heap-free storage. */
struct FixedStrRowReader
{
static constexpr sofab::detail::Wire wire() noexcept { return sofab::detail::Wire::SequenceStart; }
void operator()(sofab::IStreamImpl &is, sofab::InlineVector<sofab::FixedString<8>, 3> &row) const noexcept
{
sofab::StringSeq c{row, 3, 8, -1, -1};
sofab::read(is, c);
}
};

/* A row that arrives as a native array but has to be read by the caller -- the
* shape of an enum or boolean row, which binds through a view of its elements. */
struct ByteRowReader
{
static constexpr sofab::detail::Wire wire() noexcept { return sofab::detail::Wire::ArrayUnsigned; }
void operator()(sofab::IStreamImpl &is, std::vector<uint8_t> &row) const noexcept
{
(void)sofab::readArray(is, row, 3);
}
};

struct RowSeqMsg : sofab::IStreamMessage
{
std::vector<std::vector<std::string>> grid; /* id 1 -- count 3 */
std::vector<std::vector<std::string>> open; /* id 2 -- unbounded, cap 4 */
sofab::InlineVector<sofab::InlineVector<sofab::FixedString<8>, 3>, 2> fixed; /* id 3 -- count 2 */
std::vector<std::vector<std::string>> nobound; /* id 4 -- unbounded, no cap */
std::vector<std::vector<uint8_t>> bytes; /* id 5 -- count 2 */
void deserialize(sofab::IStreamImpl &is, sofab::id id, size_t, size_t) noexcept override
{
switch (id)
{
case 1: { sofab::RowSeq c{grid, 3, -1, StrRowReader{}}; sofab::read(is, c); break; }
case 2: { sofab::RowSeq c{open, -1, 4, StrRowReader{}}; sofab::read(is, c); break; }
case 3: { sofab::RowSeq c{fixed, 2, -1, FixedStrRowReader{}}; sofab::read(is, c); break; }
case 4: { sofab::RowSeq c{nobound, -1, -1, StrRowReader{}}; sofab::read(is, c); break; }
case 5: { sofab::RowSeq c{bytes, 2, -1, ByteRowReader{}}; sofab::read(is, c); break; }
}
}
};

static_assert(std::is_same_v<decltype(sofab::RowSeq{std::declval<std::vector<std::vector<std::string>> &>(), 1L, 1L,
StrRowReader{}})::Container,
std::vector<std::vector<std::string>>>,
"RowSeq deduces its container from the destination");
static_assert(sofab::RowSeq<std::vector<std::vector<std::string>>, StrRowReader>::elemWire
== static_cast<int>(sofab::detail::Wire::SequenceStart),
"RowSeq publishes the reader's row wire type to the stream");
static_assert(sofab::RowSeq<sofab::InlineVector<sofab::InlineVector<sofab::FixedString<8>, 3>, 2>,
FixedStrRowReader>::elemDestCap == 2,
"RowSeq publishes a heap-free destination's capacity");
static_assert(sizeof(sofab::RowSeq<std::vector<std::vector<std::string>>, StrRowReader>)
== sizeof(sofab::IStreamMessage) + sizeof(void *) + 2 * sizeof(long),
"a stateless reader costs the collector nothing");

static void rowSeqCollector()
{
auto feed = [](const char *hex) {
sofab::IStreamObject<RowSeqMsg> in{kMaxSpan};
auto w = fromHex(hex);
auto r = in.feed(w.data(), w.size());
return std::pair<sofab::IStreamImpl::Result, RowSeqMsg>{r, *in};
};

/* §5.1: rows at id 0 and id 2 are the THREE-row array [["A"], [], ["B"]]. */
const char *gap = "0e 06 020a41 07 16 020a42 07 07";
{
auto [r, m] = feed(gap);
CHECK(r.complete(), "RowSeq: the id-gap wire decodes COMPLETE");
CHECK(m.grid.size() == 3, "RowSeq: the id gap is filled, length 3");
if (m.grid.size() == 3)
CHECK(m.grid[0] == std::vector<std::string>{"A"} && m.grid[1].empty()
&& m.grid[2] == std::vector<std::string>{"B"},
"RowSeq: every row lands at its id: [[A], [], [B]]");
}
{
/* The same wire, one byte per feed: a row re-entered after a chunk
* boundary is the SAME occurrence, so nothing already placed is reset. */
sofab::IStreamObject<RowSeqMsg> in{kMaxSpan};
auto w = fromHex(gap);
bool complete = false;
for (size_t i = 0; i < w.size(); ++i) complete = in.feed(&w[i], 1).complete();
CHECK(complete, "RowSeq: byte-by-byte feed decodes COMPLETE");
CHECK((*in).grid.size() == 3 && (*in).grid[0] == std::vector<std::string>{"A"}
&& (*in).grid[2] == std::vector<std::string>{"B"},
"RowSeq: byte-by-byte feed places the same rows");
}

/* §7.3 before §5.1: an over-index element that IS a row is INVALID, one that
* contradicts the row's wire type is not an element at all and is skipped. */
{
auto [r, m] = feed("0e 1e 07 07");
(void)m;
CHECK(r.invalid(), "RowSeq: a well-typed row at id == count is INVALID");
}
{
auto [r, m] = feed("0e 18 01 07");
CHECK(r.complete() && m.grid.empty(), "RowSeq: a mis-typed element past the count is skipped");
CHECK(r.skipped() == 1, "RowSeq: and the skip is counted once");
}
{
auto [r, m] = feed("0e 00 01 07");
CHECK(r.complete() && m.grid.empty(), "RowSeq: a mis-typed in-range element is skipped and places nothing");
}
{
/* a valid row followed by a mis-typed over-index one: length 1, not 4 */
auto [r, m] = feed("0e 06 020a41 07 18 01 07");
CHECK(r.complete() && m.grid.size() == 1, "RowSeq: a skipped element does not extend the array");
}

/* §7.4: a repeated field id replaces the array whole... */
{
auto [r, m] = feed("0e 06 020a41 07 07 0e 0e 020a42 07 07");
CHECK(r.complete(), "RowSeq: a repeated field decodes COMPLETE");
CHECK(m.grid.size() == 2 && m.grid[0].empty() && m.grid[1] == std::vector<std::string>{"B"},
"RowSeq: the later occurrence replaces the array whole");
}
/* ...but an occurrence skipped under §7.3 is not an occurrence. */
{
auto [r, m] = feed("0e 06 020a41 07 07 08 01");
CHECK(r.complete() && m.grid.size() == 1 && m.grid[0] == std::vector<std::string>{"A"},
"RowSeq: a mis-typed repeat leaves the earlier value intact");
}

/* §6.3's other two tiers: the receiver cap, and no bound at all. */
{
auto [r, m] = feed("16 1e 07 07");
const bool placed = r.complete() && m.open.size() == 4;
CHECK(placed, "RowSeq: an index under the receiver cap is placed");
}
{
auto [r, m] = feed("16 26 07 07");
(void)m;
CHECK(r.code() == sofab::Error::LimitExceeded, "RowSeq: an index at the receiver cap is LimitExceeded");
}
{
auto [r, m] = feed("26 06 07 07");
(void)m;
CHECK(r.code() == sofab::Error::InvalidArgument,
"RowSeq: a growable array with neither count nor cap is refused, not read as unlimited");
}

/* heap-free storage: the schema count is the bound, and nothing allocates */
{
sofab::IStreamObject<RowSeqMsg> in{kMaxSpan};
auto w = fromHex("1e 0e 020a41 07 07");
const unsigned long afterCtor = g_allocCount;
auto r = in.feed(w.data(), w.size());
CHECK(r.complete() && (*in).fixed.size() == 2 && (*in).fixed[1].size() == 1,
"RowSeq<InlineVector>: the row lands at id 1");
CHECK(g_allocCount == afterCtor, "RowSeq<InlineVector>: collecting into heap-free storage allocates nothing");
}
{
auto [r, m] = feed("1e 16 07 07");
(void)m;
CHECK(r.invalid(), "RowSeq<InlineVector>: a row at id == count is INVALID");
}

/* a row whose wire type is a native array, read by the caller */
{
auto [r, m] = feed("2e 0b 02 0101 07");
CHECK((r.complete() && m.bytes.size() == 2 && m.bytes[0].empty()
&& m.bytes[1] == std::vector<uint8_t>({1, 1})),
"RowSeq: an array-wire row is placed and read by its reader");
}
{
auto [r, m] = feed("2e 0e 07 07");
CHECK(r.complete() && m.bytes.empty(), "RowSeq: a sequence where an array row is declared is skipped");
}
}

int main()
{
encodeVectors();
Expand Down Expand Up @@ -8667,6 +8862,7 @@ int main()
messageSeqStorageProfiles();
nestedNativeRowBounds();
overIndexSkipOrdering();
rowSeqCollector();
skippedSubtreeSuspendsBound();
truncatedNestedFieldIsNotDeclined();
heapFreeStorage();
Expand Down
Loading