SofaBuffers C++ 0.12.0
Pure-C++20 SofaBuffers — API Documentation
Loading...
Searching...
No Matches
sofab::OStreamImpl Class Reference

Base of the output streams: encodes values into a caller-provided buffer. More...

#include <sofab.hpp>

Inheritance diagram for sofab::OStreamImpl:
[legend]
Collaboration diagram for sofab::OStreamImpl:
[legend]

Classes

class  PendingRun
 The held-back sequence run: ids of the innermost open sequences whose header has not been written yet (sequenceBeginLazy). More...
 
class  Result
 Chainable result of a write operation. More...
 

Public Types

using flushCallback = std::function< void(std::span< const uint8_t >)>
 Callback invoked with a span of finished bytes whenever the buffer flushes.
 

Public Member Functions

 OStreamImpl (const OStreamImpl &)=delete
 
OStreamImpl & operator= (const OStreamImpl &)=delete
 
 OStreamImpl (OStreamImpl &&) noexcept=default
 
OStreamImpl & operator= (OStreamImpl &&) noexcept=default
 
virtual ~OStreamImpl () noexcept
 Flushes any buffered bytes through the callback before destruction.
 
size_t flush () noexcept
 Hand any buffered bytes to the flush callback and rewind the cursor.
 
size_t bytesUsed () const noexcept
 
const uint8_t * data () const noexcept
 
bool ok () const noexcept
 Whether every write on this stream has succeeded.
 
Error error () const noexcept
 The code behind ok, latched first-failure-wins.
 
Result rejectArgument () noexcept
 Refuse the value being encoded: latch Error::InvalidArgument.
 
template<typename T >
Result write (sofab::id fieldId, const T &value) noexcept
 Write a field, dispatching on the value's type.
 
template<typename T >
requires std::is_base_of_v<OStreamMessage, T>
Result writeLazy (sofab::id fieldId, const T &value) noexcept
 Write a nested message field, omitting it when it is all-default.
 
Result write (sofab::id fieldId, const void *value, int32_t size) noexcept
 Write a raw byte blob field.
 
template<typename T >
Result writeIf (sofab::id fieldId, const T &value, bool condition) noexcept
 Write a field only when condition holds.
 
Result sequenceBeginLazy (sofab::id fieldId) noexcept
 Open a nested sub-message whose header is held back until the sub-message turns out to have content.
 
Result sequenceEnd () noexcept
 Close the most recently opened sub-message, letting it vanish if it received no content.
 
Result sequenceEndKeep () noexcept
 Close the most recently opened sub-message, keeping its frame even when it received no content.
 

Protected Member Functions

 OStreamImpl () noexcept=default
 Construct an unattached stream; a derived class must call initBuffer.
 
Error latch (Error e) noexcept
 Record a failure in the sticky verdict and hand it straight back.
 
void initBuffer (uint8_t *buffer, size_t buflen, size_t offset) noexcept
 Point the stream at a buffer and position the write cursor.
 
Error pushByte (uint8_t b) noexcept
 Append a single byte, flushing first if the buffer is full.
 
Error pushBytes (const uint8_t *data, size_t len) noexcept
 Append a run of bytes.
 
Error putVarint (uint64_t v) noexcept
 Encode a value as a varint and append it to the buffer.
 
Error putSequenceEnd () noexcept
 Write the sequence-end marker (§4.9) — id 0, wire type 7.
 
Error commitPending () noexcept
 Write out the held-back sequence headers, outermost first.
 
Error beforeContent () noexcept
 Commit any held-back sequence run before writing content.
 
Error writeScalar (sofab::id fieldId, Wire type, uint64_t value) noexcept
 Write a scalar field: header varint plus one value varint, in a single bulk write.
 
Error writeFixlen (sofab::id fieldId, Fix ft, const uint8_t *data, size_t len) noexcept
 Write a length-prefixed field (string, blob or other fixlen payload).
 
template<std::floating_point F>
Error writeFloatScalar (sofab::id fieldId, F value) noexcept
 Write a single float or double as a little-endian fixlen field.
 
template<typename E >
requires (std::integral<E> || std::is_enum_v<E>)
Error writeIntArray (sofab::id fieldId, std::span< const E > elems) noexcept
 Write an array of integers as a count-prefixed run of varints.
 
template<std::floating_point F>
Error writeFloatArray (sofab::id fieldId, std::span< const F > elems) noexcept
 Write an array of floats or doubles as a count-prefixed fixlen array.
 

Static Protected Member Functions

static size_t encodeVarint (uint8_t *out, uint64_t v) noexcept
 Encode an unsigned value as a base-128 varint.
 
static size_t encodeVarintPadded (uint8_t *out, uint64_t v) noexcept
 Encode a varint into a destination with a full varint window.
 
static constexpr uint64_t headerWord (sofab::id fieldId, Wire w) noexcept
 Compose a field header word: the id in the high bits, the wire type in the low three (§4.1).
 
static constexpr uint64_t fixlenWord (uint64_t len, Fix ft) noexcept
 Compose a fixlen word: the payload length (or element size) in the high bits, the subtype in the low three (§4.6, §4.8).
 

Protected Attributes

uint8_t * buffer_ = nullptr
 Start of the active buffer.
 
uint8_t * cursor_ = nullptr
 Current write position.
 
uint8_t * end_ = nullptr
 One past the end of the buffer.
 
size_t offset_ = 0
 Start offset of the current installation (§5.1).
 
flushCallback flushCallback_
 Invoked when the buffer fills; may be empty.
 
size_t seqDepth_ = 0
 Number of currently-open nested sequences (§4.9 MAX_DEPTH).
 
PendingRun pending_
 
Error failure_ = Error::None
 Sticky first failure of this stream (see ok, error).
 
bool installed_ = false
 Set by initBuffer, cleared right before a flush callback runs.
 

Detailed Description

Base of the output streams: encodes values into a caller-provided buffer.

Holds the write cursor and the encoding logic but owns no storage itself; the buffer is supplied by a derived class (OStream, OStreamInline). When the buffer fills, the optional flush callback is invoked with the bytes accumulated so far and the cursor rewinds, so a message may exceed the buffer (and even RAM). Without a callback, overflow returns Error::BufferFull.

Write calls return a chainable Result that latches the first error.

Definition at line 1348 of file sofab.hpp.

Member Typedef Documentation

◆ flushCallback

using sofab::OStreamImpl::flushCallback = std::function<void(std::span<const uint8_t>)>

Callback invoked with a span of finished bytes whenever the buffer flushes.

Definition at line 1357 of file sofab.hpp.

Constructor & Destructor Documentation

◆ OStreamImpl() [1/3]

sofab::OStreamImpl::OStreamImpl ( )
protecteddefaultnoexcept

Construct an unattached stream; a derived class must call initBuffer.

◆ OStreamImpl() [2/3]

sofab::OStreamImpl::OStreamImpl ( const OStreamImpl &  )
delete

◆ OStreamImpl() [3/3]

sofab::OStreamImpl::OStreamImpl ( OStreamImpl &&  )
defaultnoexcept

◆ ~OStreamImpl()

virtual sofab::OStreamImpl::~OStreamImpl ( )
inlinevirtualnoexcept

Flushes any buffered bytes through the callback before destruction.

Definition at line 2125 of file sofab.hpp.

Member Function Documentation

◆ beforeContent()

Error sofab::OStreamImpl::beforeContent ( )
inlineprotectednoexcept

Commit any held-back sequence run before writing content.

This is the choke point — there is no other. The five writers below (writeScalar, writeFixlen, writeFloatScalar, writeIntArray, writeFloatArray) compose their header inline for speed, so every field written by this library goes through one of them and through this call, and through nothing else: dropping it from any one of the five loses that field's frame, and each of the five has a check in lazySequenceFraming() that fails when it does. A sequenceBeginLazy run is framed exactly when the first child field appears (MESSAGE_SPEC §2).

Definition at line 1734 of file sofab.hpp.

◆ bytesUsed()

size_t sofab::OStreamImpl::bytesUsed ( ) const
inlinenoexcept
Returns
Number of bytes written into the buffer since the last flush.

Definition at line 2162 of file sofab.hpp.

◆ commitPending()

Error sofab::OStreamImpl::commitPending ( )
inlineprotectednoexcept

Write out the held-back sequence headers, outermost first.

Runs at most once per non-default sequence, never per field.

The run is dropped even when a header write fails partway, and that is deliberate: the only way to fail here is Error::BufferFull, which is unreachable while a flush callback is set and otherwise latches the sticky failure_ with the cursor parked at the buffer end — so every later push fails too and ok is already false. Keeping the leftover ids could therefore only ever emit them into an output that is already condemned. bufferFullCondemnsTheRun() in test/test_roundtrip.cpp pins that: a truncated encode stays a byte-exact prefix of the full one and reports ok() == false.

Definition at line 1708 of file sofab.hpp.

◆ data()

const uint8_t * sofab::OStreamImpl::data ( ) const
inlinenoexcept
Returns
Pointer to the start of the buffer; the first bytesUsed bytes are valid.

Definition at line 2164 of file sofab.hpp.

◆ encodeVarint()

static size_t sofab::OStreamImpl::encodeVarint ( uint8_t *  out,
uint64_t  v 
)
inlinestaticprotectednoexcept

Encode an unsigned value as a base-128 varint.

Parameters
outDestination buffer; must hold at least 10 bytes.
vValue to encode.
Returns
Number of bytes written to out (1–10).

Definition at line 1541 of file sofab.hpp.

◆ encodeVarintPadded()

static size_t sofab::OStreamImpl::encodeVarintPadded ( uint8_t *  out,
uint64_t  v 
)
inlinestaticprotectednoexcept

Encode a varint into a destination with a full varint window.

The caller must guarantee detail::VARINT_MAX_BYTES writable bytes at out. That buys a branch-free body: the length comes from the value's bit width in one instruction instead of being discovered a byte at a time, and all ten bytes are then written unconditionally, with only the last one of the encoded run untagged. Bytes past the returned length are scratch — the cursor never advances over them, so they are always overwritten by the next value or left outside the message.

The single-byte case is peeled off first: it is by far the most common value in real data, and paying ten stores for it would lose more on small-element arrays than the wide case gains.

Parameters
outDestination, with at least detail::VARINT_MAX_BYTES bytes.
vValue to encode.
Returns
Number of meaningful bytes written (1–10).

Definition at line 1575 of file sofab.hpp.

◆ error()

Error sofab::OStreamImpl::error ( ) const
inlinenoexcept

The code behind ok, latched first-failure-wins.

Returns
Error::BufferFull once a write has overflowed with no sink (or a hold-back run could not grow), Error::InvalidArgument when a buffer installation was rejected (§5.1 — an out-of-range offset, or fewer than MIN_OUTPUT_BUFFER usable bytes behind a sink) or a field was refused as unencodable (§6.2's ID_MAX, ARRAY_MAX, FIXLEN_MAX and MAX_DEPTH, §6.4's UTF-8 rule), else Error::None.

Definition at line 2199 of file sofab.hpp.

◆ fixlenWord()

static constexpr uint64_t sofab::OStreamImpl::fixlenWord ( uint64_t  len,
Fix  ft 
)
inlinestaticconstexprprotectednoexcept

Compose a fixlen word: the payload length (or element size) in the high bits, the subtype in the low three (§4.6, §4.8).

Parameters
lenPayload length in bytes, or the element size for an array.
ftFixlen subtype.
Returns
The fixlen word, ready for encodeVarint.

Definition at line 1760 of file sofab.hpp.

◆ flush()

size_t sofab::OStreamImpl::flush ( )
inlinenoexcept

Hand any buffered bytes to the flush callback and rewind the cursor.

With no flush callback installed this is a no-op and the buffered message stays exactly where it is, reachable through data / bytesUsed. There is nowhere to drain to, so §5.1's "drain any remaining buffered bytes" has nothing to do, and the cursor only returns to offset 0 after a handover the callback returned from — which never happened. Rewinding here would discard the encode and drop the installation's reserved head, so the next write would overwrite both.

Returns
Number of bytes that were buffered before the flush.

Definition at line 2141 of file sofab.hpp.

◆ headerWord()

static constexpr uint64_t sofab::OStreamImpl::headerWord ( sofab::id  fieldId,
Wire  w 
)
inlinestaticconstexprprotectednoexcept

Compose a field header word: the id in the high bits, the wire type in the low three (§4.1).

Parameters
fieldIdField identifier.
wWire type of the field that follows.
Returns
The header word, ready for encodeVarint.

Definition at line 1747 of file sofab.hpp.

◆ initBuffer()

void sofab::OStreamImpl::initBuffer ( uint8_t *  buffer,
size_t  buflen,
size_t  offset 
)
inlineprotectednoexcept

Point the stream at a buffer and position the write cursor.

This is the one place a buffer is handed over, so it is where §5.1's preconditions are checked and where a bad buffer is rejected — never partway through a message. On rejection the stream is left inert (cursor at the end, nothing writable) with failure_ latched, so no subsequent write can touch storage that cannot hold it.

Parameters
bufferStorage to encode into.
buflenCapacity of buffer in bytes.
offsetNumber of leading bytes to leave untouched before the cursor.

Definition at line 1514 of file sofab.hpp.

◆ latch()

Error sofab::OStreamImpl::latch ( Error  e)
inlineprotectednoexcept

Record a failure in the sticky verdict and hand it straight back.

The one place failure_ is written, so every refusal the write path can return also reaches ok / error. That matters because the per-call Result is routinely discarded — a generated serialize() issues its writes one at a time and checks nothing — and without this an encode that dropped a field would come back indistinguishable from a complete one (§5.1: an encoder MUST NOT return partial output as if it were complete).

First failure wins: a stream stays condemned for the reason it was condemned for, so a later overflow cannot paper over the refusal that actually cost the message a field.

Parameters
eThe failure to report; must not be Error::None.
Returns
e, unchanged, whatever the verdict already held.

Definition at line 1495 of file sofab.hpp.

◆ ok()

bool sofab::OStreamImpl::ok ( ) const
inlinenoexcept

Whether every write on this stream has succeeded.

Sticky and independent of how the writes were issued — chained, or one at a time with each Result discarded, which is what a generated serialize() does — so it is the verdict to check after encoding: §5.1 forbids handing on partial output as if it were complete, and this is what tells the two apart.

It turns false whenever a field the caller asked for did not reach the output: an overflow with no flush callback set (OStreamView with a buffer smaller than the message), a rejected buffer installation, a field id past ID_MAX, a sub-message past MAX_DEPTH, a string that is not valid UTF-8 under §6.4, an array of more than ARRAY_MAX elements or a payload past FIXLEN_MAX, a negative raw-blob length, and — rarely — a sequenceBeginLazy that cannot allocate room to hold a header back.

Returns
true while every write this stream was given has been honoured.

Definition at line 2186 of file sofab.hpp.

◆ operator=() [1/2]

OStreamImpl & sofab::OStreamImpl::operator= ( const OStreamImpl &  )
delete

◆ operator=() [2/2]

OStreamImpl & sofab::OStreamImpl::operator= ( OStreamImpl &&  )
defaultnoexcept

◆ pushByte()

Error sofab::OStreamImpl::pushByte ( uint8_t  b)
inlineprotectednoexcept

Append a single byte, flushing first if the buffer is full.

Parameters
bByte to write.
Returns
Error::None on success, or Error::BufferFull if the buffer is full and no flush callback is set.

Definition at line 1604 of file sofab.hpp.

◆ pushBytes()

Error sofab::OStreamImpl::pushBytes ( const uint8_t *  data,
size_t  len 
)
inlineprotectednoexcept

Append a run of bytes.

Uses a single memcpy when the payload fits the remaining buffer (the common case); otherwise falls back to a byte-by-byte copy that flushes across buffer boundaries.

Parameters
dataSource bytes.
lenNumber of bytes to append.
Returns
Error::None on success, or Error::BufferFull if the buffer fills with no flush callback set.

Definition at line 1647 of file sofab.hpp.

◆ putSequenceEnd()

Error sofab::OStreamImpl::putSequenceEnd ( )
inlineprotectednoexcept

Write the sequence-end marker (§4.9) — id 0, wire type 7.

The only header not composed inline by one of the five writers, and deliberately not a general putHeader(id, type): a general one would look like the place to commit a held-back run, and it is not. It is reached from sequenceEnd and sequenceEndKeep only, neither of which may commit here — sequenceEnd only gets here when the run is already empty, and sequenceEndKeep has committed it itself one line earlier. The commit choke point is beforeContent, called by the five inline writers; see the note there.

Returns
Error::BufferFull on overflow, otherwise Error::None.

Definition at line 1688 of file sofab.hpp.

◆ putVarint()

Error sofab::OStreamImpl::putVarint ( uint64_t  v)
inlineprotectednoexcept

Encode a value as a varint and append it to the buffer.

Parameters
vValue to write.
Returns
Error::None on success, or Error::BufferFull on overflow.

Definition at line 1668 of file sofab.hpp.

◆ rejectArgument()

Result sofab::OStreamImpl::rejectArgument ( )
inlinenoexcept

Refuse the value being encoded: latch Error::InvalidArgument.

The hook a generated serialize() calls when a field's value is past a bound only the schema knows – a string or blob longer than its maxlen, an array with more elements than its count. The corelib holds no schema bound; it records the refusal, so that ok and error report it exactly like its own §6.2 / §6.4 refusals and no byte of the message is returned as a success (§5.1). Writes nothing itself. The encode-side counterpart of IStreamImpl::invalidate.

Cold and out of line: the refusal is the rare path, and keeping it out of a generated serialize() keeps that function small enough for GCC to go on inlining the writes into it (measured: the bench schema's encode is 11546 Ir/op with this, 12423 with the hook inlined at its 18 call sites, 11904 before any guard existed).

Returns
A Result carrying Error::InvalidArgument.

Definition at line 2220 of file sofab.hpp.

◆ sequenceBeginLazy()

Result sofab::OStreamImpl::sequenceBeginLazy ( sofab::id  fieldId)
inlinenoexcept

Open a nested sub-message whose header is held back until the sub-message turns out to have content.

MESSAGE_SPEC §2 omits a sequence-typed field whose value equals its declared default, and "not one child was written" is exactly that condition — evaluated per child field, recursively, for free. A sequence closed with nothing in it therefore emits nothing instead of a two-byte empty frame, and an all-default message becomes the empty byte string.

The predicate never touches a byte image of the object, so struct padding cannot influence it and a non-zero nested default is handled by the caller's ordinary per-field test.

This is the only way to open a sub-message. How it closes decides whether a contentless one survives: sequenceEnd drops it, sequenceEndKeep forces the frame out.

The hold-back has no depth window: the pending run is sized at construction to the full MAX_DEPTH, so the output is canonical at every legal depth and no nesting depth allocates (CORELIB_PLAN §6.0.1, "How deep the hold-back reaches" — only a constrained profile may bound the run below MAX_DEPTH and frame eagerly past the bound, and this port takes no such allowance).

Parameters
fieldIdField identifier of the sub-message.
Returns
A Result carrying Error::None on success, Error::InvalidArgument past MAX_DEPTH or ID_MAX.

Definition at line 2410 of file sofab.hpp.

◆ sequenceEnd()

Result sofab::OStreamImpl::sequenceEnd ( )
inlinenoexcept

Close the most recently opened sub-message, letting it vanish if it received no content.

Use it wherever absence encodes the same value as an empty frame: a struct/union field, and an array field whose declared default is the empty collection (MESSAGE_SPEC §2). Where the frame must be visible, close with sequenceEndKeep instead.

Returns
A Result carrying Error::None on success, or the error encountered.

Definition at line 2439 of file sofab.hpp.

◆ sequenceEndKeep()

Result sofab::OStreamImpl::sequenceEndKeep ( )
inlinenoexcept

Close the most recently opened sub-message, keeping its frame even when it received no content.

Behaves like a write: it first emits any held-back headers — this frame's and every enclosing one's — and then the end marker, so an empty sequence reaches the wire as begin + end.

Required wherever the frame carries information beyond its contents:

  • a wrapper-array element (struct/union/nested row): element presence is what carries a dynamic array's length — highest present id
    • 1 (§5.1) — so dropping an all-default element would change the decoded length, not just the bytes;
  • an array field already known to differ from a non-empty declared default: absence would reconstruct that default, so the empty frame is the only encoding of "explicitly empty" (§2, §3).

The two failure directions are not symmetric, which is why this is the safe choice when in doubt: using it where sequenceEnd would do costs one non-canonical empty frame that a decoder normalizes away, while the reverse silently changes an array's length.

Returns
A Result carrying Error::None on success, or the error encountered.

Definition at line 2475 of file sofab.hpp.

◆ write() [1/2]

template<typename T >
Result sofab::OStreamImpl::write ( sofab::id  fieldId,
const T &  value 
)
inlinenoexcept

Write a field, dispatching on the value's type.

Handles integers (signed values are zig-zag encoded), bool, float, double, anything convertible to std::string_view, contiguous ranges of integers, enumerations, booleans or floats (encoded as arrays), and nested sofab::OStreamMessage objects (encoded as a sub-message). An enumeration element travels as its declared underlying type, so a container of scoped enums needs no converted copy; a boolean element travels as the unsigned 0/1 of §4.4. Unsupported types fail to compile.

Template Parameters
TDeduced value type.
Parameters
fieldIdField identifier; must not exceed ID_MAX.
valueValue to encode.
Returns
A Result carrying Error::None on success, or the first error encountered.

Definition at line 2244 of file sofab.hpp.

◆ write() [2/2]

Result sofab::OStreamImpl::write ( sofab::id  fieldId,
const void *  value,
int32_t  size 
)
inlinenoexcept

Write a raw byte blob field.

size is signed for symmetry with the generated accessors, but §6.2 bounds a fixlen payload to 0 .. 2,147,483,647: a negative length is outside the format and is refused with Error::InvalidArgument (§6.3), emitting nothing, exactly as an unencodable string is. The guard has to sit here, before the conversion — static_cast<size_t> would turn -1 into SIZE_MAX and the encoder would copy from value until the buffer filled, reading past the caller's object.

Like every other refusal it also reaches ok / error: the field the caller asked for is not on the wire, and §5.1 does not let a stream missing a field report success (latch).

Parameters
fieldIdField identifier; must not exceed ID_MAX.
valuePointer to the bytes to copy.
sizeNumber of bytes to copy; must not be negative.
Returns
A Result carrying Error::None on success, or the error encountered.

Definition at line 2359 of file sofab.hpp.

◆ writeFixlen()

Error sofab::OStreamImpl::writeFixlen ( sofab::id  fieldId,
Fix  ft,
const uint8_t *  data,
size_t  len 
)
inlineprotectednoexcept

Write a length-prefixed field (string, blob or other fixlen payload).

Parameters
fieldIdField identifier; must not exceed ID_MAX.
ftPayload sub-type (Fix::String, Fix::Blob, ...).
dataPayload bytes.
lenPayload length in bytes; must not exceed FIXLEN_MAX.
Returns
Error::InvalidArgument if fieldId or len is too large, Error::BufferFull on overflow, otherwise Error::None.

Definition at line 1804 of file sofab.hpp.

◆ writeFloatArray()

template<std::floating_point F>
Error sofab::OStreamImpl::writeFloatArray ( sofab::id  fieldId,
std::span< const F >  elems 
)
inlineprotectednoexcept

Write an array of floats or doubles as a count-prefixed fixlen array.

On little-endian hosts the payload is copied in one block since the wire layout matches native memory; on big-endian hosts each element is byte-swapped.

Template Parameters
FFloating-point element type (float or double).
Parameters
fieldIdField identifier; must not exceed ID_MAX.
elemsElements to encode, in order; at most ARRAY_MAX of them.
Returns
Error::InvalidArgument if fieldId is too large or elems holds more than ARRAY_MAX elements, Error::BufferFull on overflow, otherwise Error::None.

Definition at line 1977 of file sofab.hpp.

◆ writeFloatScalar()

template<std::floating_point F>
Error sofab::OStreamImpl::writeFloatScalar ( sofab::id  fieldId,
F  value 
)
inlineprotectednoexcept

Write a single float or double as a little-endian fixlen field.

Template Parameters
FFloating-point type (float or double).
Parameters
fieldIdField identifier; must not exceed ID_MAX.
valueValue to encode.
Returns
Error::InvalidArgument if fieldId is too large, Error::BufferFull on overflow, otherwise Error::None.

Definition at line 1845 of file sofab.hpp.

◆ writeIf()

template<typename T >
Result sofab::OStreamImpl::writeIf ( sofab::id  fieldId,
const T &  value,
bool  condition 
)
inlinenoexcept

Write a field only when condition holds.

Template Parameters
TValue type accepted by write.
Parameters
fieldIdField identifier.
valueValue to encode when condition is true.
conditionWrite the field only if this is true.
Returns
The result of the write, or a success Result if skipped.

Definition at line 2375 of file sofab.hpp.

◆ writeIntArray()

template<typename E >
requires (std::integral<E> || std::is_enum_v<E>)
Error sofab::OStreamImpl::writeIntArray ( sofab::id  fieldId,
std::span< const E >  elems 
)
inlineprotectednoexcept

Write an array of integers as a count-prefixed run of varints.

The wire type is chosen from the signedness of the type the elements travel as (detail::WireInt); signed elements are zig-zag encoded.

Template Parameters
EIntegral or enumeration element type. An enumeration encodes at its declared underlying width, converted per element; a bool encodes as the unsigned 0/1 of §4.4.
Parameters
fieldIdField identifier; must not exceed ID_MAX.
elemsElements to encode, in order; at most ARRAY_MAX of them.
Returns
Error::InvalidArgument if fieldId is too large or elems holds more than ARRAY_MAX elements, Error::BufferFull on overflow, otherwise Error::None.

Definition at line 1885 of file sofab.hpp.

◆ writeLazy()

template<typename T >
requires std::is_base_of_v<OStreamMessage, T>
Result sofab::OStreamImpl::writeLazy ( sofab::id  fieldId,
const T &  value 
)
inlinenoexcept

Write a nested message field, omitting it when it is all-default.

Same as write for an OStreamMessage, except it closes with sequenceEnd rather than sequenceEndKeep: the nested serialize omits every child that equals its default, so "not one child was written" is exactly "the object equals its declared default" — evaluated per child field, recursively — and the field is then dropped instead of emitted as an empty frame (MESSAGE_SPEC §2).

Use it for a struct/union field. Keep plain write for an array element: element presence carries a dynamic array's length (§5.1), so an all-default element stays framed.

Template Parameters
TA type deriving from OStreamMessage.
Parameters
fieldIdField identifier; must not exceed ID_MAX.
valueNested message to encode.
Returns
A Result carrying Error::None on success, or the error encountered.

Definition at line 2331 of file sofab.hpp.

◆ writeScalar()

Error sofab::OStreamImpl::writeScalar ( sofab::id  fieldId,
Wire  type,
uint64_t  value 
)
inlineprotectednoexcept

Write a scalar field: header varint plus one value varint, in a single bulk write.

Parameters
fieldIdField identifier; must not exceed ID_MAX.
typeWire type (Wire::Unsigned or Wire::Signed).
valueAlready-encoded scalar value (zig-zagged for signed fields).
Returns
Error::InvalidArgument if fieldId is too large, Error::BufferFull on overflow, otherwise Error::None.

Definition at line 1773 of file sofab.hpp.

Member Data Documentation

◆ buffer_

uint8_t* sofab::OStreamImpl::buffer_ = nullptr
protected

Start of the active buffer.

Definition at line 1360 of file sofab.hpp.

◆ cursor_

uint8_t* sofab::OStreamImpl::cursor_ = nullptr
protected

Current write position.

Definition at line 1361 of file sofab.hpp.

◆ end_

uint8_t* sofab::OStreamImpl::end_ = nullptr
protected

One past the end of the buffer.

Definition at line 1362 of file sofab.hpp.

◆ failure_

Error sofab::OStreamImpl::failure_ = Error::None
protected

Sticky first failure of this stream (see ok, error).

Error::None while the encode is healthy, and one of §6.3's codes from the moment a write could not be honoured: Error::BufferFull on an overflow with no sink (and on a hold-back run that could not grow), Error::InvalidArgument when a buffer installation was rejected (§5.1 — an out-of-range offset, or less than MIN_OUTPUT_BUFFER usable bytes behind a sink) or when a field the caller asked for was refused (a field id past ID_MAX, a sub-message past MAX_DEPTH, a string that is not valid UTF-8 under §6.4, an array of more than ARRAY_MAX elements, a payload past FIXLEN_MAX, a negative raw-blob length past §6.2's fixlen bound). Only the first is kept: once condemned, the stream stays condemned for the reason it was condemned for.

Everything that turns this non-None goes through latch, so that the set of failures the verdict covers is the set of failures the write path can report — §5.1's "an encoder that could not write what it was asked to write reports it".

Definition at line 1460 of file sofab.hpp.

◆ flushCallback_

flushCallback sofab::OStreamImpl::flushCallback_
protected

Invoked when the buffer fills; may be empty.

Definition at line 1377 of file sofab.hpp.

◆ installed_

bool sofab::OStreamImpl::installed_ = false
protected

Set by initBuffer, cleared right before a flush callback runs.

This is how the stream tells the two halves of §5.1's returning-callback contract apart: a sink that returns without installing a buffer copied, and the encoder resumes in the same buffer at offset 0; a sink that took the buffer installed a replacement, and that installation's own start offset is the cursor. Without it a taking sink's offset would be overwritten the moment the callback returned, so per-packet header room could not be re-armed.

Definition at line 1472 of file sofab.hpp.

◆ offset_

size_t sofab::OStreamImpl::offset_ = 0
protected

Start offset of the current installation (§5.1).

Where this installation's writable region begins, so cursor_ - (buffer_

  • offset_) is the number of message bytes buffered — as opposed to bytesUsed, which counts from the buffer start because the reserved head is part of the packet a sink is handed. flush uses the former: a freshly installed buffer holding nothing but its own reservation has nothing to drain, and must not be pushed at the sink as an empty packet.

The offset is consumed by the first flush that returns without an installation, which is why it drops to zero there alongside the cursor.

Definition at line 1376 of file sofab.hpp.

◆ pending_

PendingRun sofab::OStreamImpl::pending_
protected

Definition at line 1437 of file sofab.hpp.

◆ seqDepth_

size_t sofab::OStreamImpl::seqDepth_ = 0
protected

Number of currently-open nested sequences (§4.9 MAX_DEPTH).

Definition at line 1378 of file sofab.hpp.


The documentation for this class was generated from the following file: