Class OStream
- Namespace
- sofab
- Assembly
- SofaBuffers.dll
Streaming SofaBuffers encoder writing into a caller-provided byte buffer.
public sealed class OStream
- Inheritance
-
OStream
- Inherited Members
Examples
byte[] buf = new byte[64];
var os = new OStream(buf);
os.WriteUnsigned(1, 42);
os.WriteSigned(2, -7);
os.WriteString(3, "hi");
int used = os.BytesUsed;
Remarks
The encoder never allocates the output buffer itself: it writes into the array you hand it. When that array fills, the accumulated bytes are passed to an optional FlushSink and writing resumes at the start of the buffer, so a message larger than the buffer (or larger than RAM) can be streamed out. With no sink, a full buffer raises BufferFull.
An initial offset reserves space at the front of the buffer for a
lower-layer protocol header, avoiding a copy. A sink that takes the buffer it
is handed installs a replacement with BufferSet(byte[], int) and gets that
reservation again — the offset belongs to the installation, not to the buffer
(CORELIB_PLAN §5.1).
Hot-path convention. The single-byte varint case — every small field
header and small scalar, which the format is designed to make the common one
(CORELIB_PLAN §1) — is written out at each call site rather than shared
behind a helper, and each writer checks buffer capacity once for a whole
field instead of once per byte. Measured under Callgrind
(bench/run_callgrind.sh) the JIT does not inline a helper that itself
contains a call, even when marked AggressiveInlining, which cost about
twenty instructions per varint written; longer varints go to
WriteVarintAtMulti, which assembles the whole encoding in a register.
This class is not thread-safe; encode one message from one thread.
Constructors
OStream(byte[])
Create an encoder over buffer with no flush sink.
Writing past the end of the buffer raises BufferFull.
public OStream(byte[] buffer)
Parameters
bufferbyte[]caller-owned output buffer (any length, incl. 0)
OStream(byte[], int)
Like OStream(byte[]) but begin writing at offset
bytes into the buffer, reserving room for a lower-layer header.
public OStream(byte[] buffer, int offset)
Parameters
OStream(byte[], int, FlushSink?)
Create an encoder with a flush sink. When the buffer
fills, the accumulated bytes are passed to sink and
writing resumes at the start of the buffer.
public OStream(byte[] buffer, int offset, FlushSink? sink)
Parameters
bufferbyte[]caller-owned output buffer
offsetintinitial write position (
0..buffer.Length)sinkFlushSinkflush sink, or
nullfor none
Remarks
With a sink the buffer is a streaming buffer and must satisfy
buffer.Length - offset >= MinOutputBuffer;
it is rejected here, where it is handed over, rather than partway through
a message. Without a sink no flush can occur and no minimum applies
(CORELIB_PLAN §5.1).
Properties
BytesUsed
Number of bytes written to the active buffer since the last flush.
public int BytesUsed { get; }
Property Value
Methods
BufferSet(byte[], int)
Replace the active buffer (typically from within a flush sink), resuming
writes at offset in the new buffer.
public void BufferSet(byte[] buffer, int offset)
Parameters
Remarks
The start offset belongs to the installation, not to the buffer
(CORELIB_PLAN §5.1): the cursor starts at offset and
the offset is consumed there, so a later flush the sink returns from
without installing anything resumes at 0. Handing the same buffer
back is an installation like any other, which is how a sink re-arms its
framing-header reservation for every flushed packet.
An encoder that has a sink installed is streaming, so the replacement is
held to MinOutputBuffer exactly as the constructor's
buffer was — buffer.Length - offset must reach it, and a buffer
that does not is rejected here rather than partway through the message.
On a sinkless encoder no minimum applies (CORELIB_PLAN §5.1).
Flush()
Flush any pending bytes to the sink (if one is set) and report how many bytes were pending. With no sink the buffer is left intact.
public int Flush()
Returns
- int
number of bytes that were pending
Reset(byte[], int)
Start a new message on this encoder: install buffer at
offset exactly as BufferSet(byte[], int) does, and drop
every open sequence and held-back sequence header of the previous message —
including one abandoned mid-message by an exception.
public void Reset(byte[] buffer, int offset)
Parameters
Remarks
This is what lets a caller encoding many messages keep one encoder
instead of constructing one per message. Construction is where the encoder
lays down its fixed-size state (the MAX_DEPTH-entry pending run,
1020 bytes, CORELIB_PLAN §6.6), so a per-message new OStream pays that
allocation and its zero-fill on every message; a reset pays nothing and
allocates nothing. The flush sink, if any, stays attached. The state it
leaves is indistinguishable from a freshly constructed encoder's: nothing
in the pending run is read before it is written again.
WriteArrayFp32(int, float[])
Write an array of 32-bit floats.
public void WriteArrayFp32(int id, float[] data)
Parameters
WriteArrayFp64(int, double[])
Write an array of 64-bit floats.
public void WriteArrayFp64(int id, double[] data)
Parameters
WriteArraySigned(int, short[])
Write an array of signed 16-bit integers.
public void WriteArraySigned(int id, short[] data)
Parameters
WriteArraySigned(int, int[])
Write an array of signed 32-bit integers.
public void WriteArraySigned(int id, int[] data)
Parameters
WriteArraySigned(int, long[])
Write an array of signed 64-bit integers.
public void WriteArraySigned(int id, long[] data)
Parameters
WriteArraySigned(int, sbyte[])
Write an array of signed 8-bit integers.
public void WriteArraySigned(int id, sbyte[] data)
Parameters
WriteArrayUnsigned(int, byte[])
Write an array of unsigned 8-bit integers.
public void WriteArrayUnsigned(int id, byte[] data)
Parameters
WriteArrayUnsigned(int, ushort[])
Write an array of unsigned 16-bit integers.
public void WriteArrayUnsigned(int id, ushort[] data)
Parameters
WriteArrayUnsigned(int, uint[])
Write an array of unsigned 32-bit integers.
public void WriteArrayUnsigned(int id, uint[] data)
Parameters
WriteArrayUnsigned(int, ulong[])
Write an array of unsigned 64-bit integers.
public void WriteArrayUnsigned(int id, ulong[] data)
Parameters
WriteBlob(int, byte[])
Write a binary blob field.
public void WriteBlob(int id, byte[] data)
Parameters
WriteBlob(int, byte[], int, int)
Write a slice of a byte array as a binary blob field.
public void WriteBlob(int id, byte[] data, int from, int length)
Parameters
WriteBoolean(int, bool)
Write a boolean as an unsigned 0 / 1.
public void WriteBoolean(int id, bool value)
Parameters
WriteFixlen(int, byte[], int, int, FixlenType)
Write a fixed-length field: the id header, a (len << 3) | subtype
length header, then length raw bytes from
data (already in wire / little-endian order for floats).
public void WriteFixlen(int id, byte[] data, int from, int length, FixlenType subtype)
Parameters
idintfield id
databyte[]payload bytes (may be
nullonly iflengthis 0)fromintstart offset within
datalengthintnumber of payload bytes
subtypeFixlenTypefixed-length sub-type
Exceptions
- SofabException
Argument when
subtypeis not one of the four defined tags (0x4–0x7 are reserved) or when it is Fp32 / Fp64 andlengthis not exactly 4 / 8. Both make a malformedfixlen_word(CORELIB_PLAN §4.6), so the encoder rejects them rather than emit bytes its own decoder reports asINVALID.Also Argument when
subtypeis String and the byte range is not valid UTF-8. This is the byte-container entry point for astringfield — the one writer that takes the payload as raw bytes rather than as a C#string— so it is where MESSAGE_SPEC §8's producer-side "MUST NOT emit invalid UTF-8" is enforced (CORELIB_PLAN §6.4.1). Without it this library's encoder could emit astringfield its own Decode(byte[], int, int) rejects. The refusal is atomic: it happens before any byte, and before any held-back sequence header, reaches the buffer.
WriteFp32(int, float)
Write a 32-bit float field.
public void WriteFp32(int id, float value)
Parameters
WriteFp64(int, double)
Write a 64-bit float field.
public void WriteFp64(int id, double value)
Parameters
WriteSequenceBeginLazy(int)
Open a nested sequence whose header is held back until the sequence turns out to have content. Fields written until the matching WriteSequenceEnd() / WriteSequenceEndKeep() belong to the sequence and form a fresh id scope.
public void WriteSequenceBeginLazy(int id)
Parameters
idintfield id of the sequence
Remarks
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.
Held-back ids are encoder state, not buffer content, so a flush can never split a pending run: an output buffer far smaller than the message produces exactly the one-shot bytes.
The hold-back reaches the full MAX_DEPTH (255): the pending run is
sized for that at construction, so this encoder emits the canonical §2 bytes
at every nesting depth the format allows and no write path
allocates (CORELIB_PLAN §6.0.1, §6.6). A bounded run — framing eagerly and
non-canonically past the bound — is a constrained-profile allowance this port
does not take.
This is the only way to open a sequence. How it closes decides whether a contentless one survives: WriteSequenceEnd() drops it, WriteSequenceEndKeep() forces the frame out.
Exceptions
- SofabException
with Argument if opening this sequence would nest deeper than
MAX_DEPTH(255) levels, or ifidis out of range
WriteSequenceEnd()
Close the most recently opened nested sequence, letting it vanish if it received no content.
public void WriteSequenceEnd()
Remarks
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 WriteSequenceEndKeep() instead.
WriteSequenceEndKeep()
Close the most recently opened nested sequence, keeping its frame even when it received no content.
public void WriteSequenceEndKeep()
Remarks
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
still 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 (MESSAGE_SPEC §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 WriteSequenceEnd() would do costs one non-canonical empty frame that a decoder normalizes away, while the reverse silently changes an array's length.
WriteSigned(int, long)
Write a signed-integer field (ZigZag + varint).
public void WriteSigned(int id, long value)
Parameters
WriteString(int, string)
Write a string field (raw UTF-8 bytes, no NUL on the wire).
public void WriteString(int id, string text)
Parameters
Exceptions
- SofabException
with Argument if
textcannot be encoded as valid UTF-8 (i.e. it contains an unpaired surrogate). Per MESSAGE_SPEC §8 the value is refused, never silently rewritten toU+FFFD. EmbeddedU+0000is valid UTF-8 and is written verbatim.
WriteString(int, string, int)
Write a string field whose UTF-8 encoding must not be longer than
maxlen bytes (raw UTF-8 bytes, no NUL on the wire).
public void WriteString(int id, string text, int maxlen)
Parameters
idintfield id
textstringstring value (must be encodable as valid UTF-8)
maxlenintthe most UTF-8 bytes the value may encode to (>= 0)
Remarks
The bounded form of WriteString(int, string) for a field whose
schema declares a maxlen. Generated code passes that literal; this
library holds no limit of its own (CORELIB_PLAN §6.2.1). The UTF-8 length of a
C# string is only known inside the transcoder, so the comparison lives
here, in the same measuring pass that sizes the fixlen_word: no second
pass over the text and no allocation. A UTF-8 encoding is never shorter than
the UTF-16 code-unit count, so a text.Length already above the bound is
refused without measuring at all. The one-argument overload forwards
MaxValue, which no UTF-8 length an int can report
exceeds: the comparison is vacuous there, not a default limit.
Exceptions
- SofabException
with Argument if
textcannot be encoded as valid UTF-8, if its UTF-8 encoding is longer thanmaxlenbytes, or ifmaxlenis negative. Every refusal is atomic: it happens before any byte, and before any held-back sequence header, reaches the buffer.
WriteUnsigned(int, ulong)
Write an unsigned-integer field.
public void WriteUnsigned(int id, ulong value)