Class OStream
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 SofabError.BUFFER_FULL.
An initial offset reserves space at the front of the buffer for a
lower-layer protocol header, avoiding a copy.
A buffer installed with a sink must leave at least
Sofab.MIN_OUTPUT_BUFFER usable bytes and is rejected where it is handed
over if it does not; a buffer installed without one is subject to no minimum
(CORELIB_PLAN §5.1).
Writes take a fast path that advances a cursor over the buffer with no per-byte bounds check whenever the remaining room is known to be sufficient (a varint is at most ten bytes; a float four or eight); a buffer-spanning slow path that flushes mid-value is used only when the buffer is too small to hold the value outright. Raw string / blob payloads are copied in bulk up to each buffer boundary. The wire output is identical regardless of buffer size.
A field is written with as few stores as its shape allows: a multi-byte
varint is assembled in a register and written with one eight-byte store, a
one-byte header and one-byte value go out together as one two-byte store, and a
whole fp32 field — header, fixlen_word and payload — fits one
eight-byte store. A store may therefore reach past the field it wrote, leaving
up to seven scratch bytes in the buffer immediately after the current
write position. They are never part of the message and never escape: they sit
strictly between bytesUsed() and the end of the buffer, are overwritten
by the next write, and only [0, bytesUsed()) is ever handed to a
FlushSink. Bytes before the starting offset — the region
reserved for a lower-layer header — are
never touched. A buffer with fewer than ten bytes free falls back to the
byte-at-a-time path, so small buffers see no scratch writes at all.
Sequences are framed lazily: writeSequenceBeginLazy(int)
holds the header back until the sequence turns out to have content. A
sequence-typed field that receives none is therefore dropped entirely
rather than emitted as an empty frame (MESSAGE_SPEC §2) — "always framed" is no
longer true for a field. It is still true for a wrapper-array element,
whose presence carries the array's length (§5.1); that position closes with
writeSequenceEndKeep(), which forces the frame out. Held-back ids are
encoder state, not buffer content, so this never interacts with flushing, and
the run grows to the full Sofab.MAX_DEPTH so the output is canonical at
every legal depth.
This class is not thread-safe; encode one message from one thread.
Example
byte[] buf = new byte[64];
OStream os = new OStream(buf);
os.writeUnsigned(1, 42);
os.writeSigned(2, -7);
os.writeString(3, "hi");
int used = os.bytesUsed();
-
Constructor Summary
ConstructorsConstructorDescriptionOStream(byte[] buffer) Create an encoder overbufferwith no flush sink.OStream(byte[] buffer, int offset) LikeOStream(byte[])but begin writing atoffsetbytes into the buffer, reserving room for a lower-layer header.Create an encoder with a flushsink. -
Method Summary
Modifier and TypeMethodDescriptionvoidbufferSet(byte[] buffer, int offset) Replace the active buffer (typically from within a flush sink), resuming writes atoffsetin the new buffer.intNumber of bytes written to the active buffer since the last flush.byte[]An exact-size copy of[0, bytesUsed())— the bytes standing in the active buffer.intflush()Flush any pending bytes to the sink (if one is set) and report how many bytes were pending.static OStreamoverScratch(int size) An encoder over a per-thread scratch buffer of at leastsizebytes — the mechanism behind a one-shotencode()that returns a fresh array without re-allocating (and re-zeroing) a worst-case buffer per call.voidreset(byte[] buffer) Return this stream to its just-constructed state, writing intobufferfrom its start, so a caller encoding many messages in a row (a server loop, the generatedencodehelper) can hold one instance instead of letting each encode allocate and immediately discard one.voidwriteArrayFp32(int id, float[] data) Write an array of 32-bit floats.voidwriteArrayFp64(int id, double[] data) Write an array of 64-bit floats.voidwriteArraySigned(int id, byte[] data) Write an array of signed 8-bit integers.voidwriteArraySigned(int id, int[] data) Write an array of signed 32-bit integers.voidwriteArraySigned(int id, long[] data) Write an array of signed 64-bit integers.voidwriteArraySigned(int id, short[] data) Write an array of signed 16-bit integers.voidwriteArrayUnsigned(int id, byte[] data) Write an array of unsigned 8-bit integers (each element zero-extended).voidwriteArrayUnsigned(int id, int[] data) Write an array of unsigned 32-bit integers (each element zero-extended).voidwriteArrayUnsigned(int id, long[] data) Write an array of unsigned 64-bit integers (eachlongtreated as an unsigned value).voidwriteArrayUnsigned(int id, short[] data) Write an array of unsigned 16-bit integers (each element zero-extended).voidwriteBlob(int id, byte[] data) Write a binary blob field.voidwriteBlob(int id, byte[] data, int from, int length) Write a slice of a byte array as a binary blob field.voidwriteBoolean(int id, boolean value) Write a boolean as an unsigned0/1.voidwriteFixlen(int id, byte[] data, int from, int length, FixlenType subtype) Write a fixed-length field: the id header, a(len << 3) | subtypelength header, thenlengthraw bytes fromdata(already in wire / little-endian order for floats).voidwriteFp32(int id, float value) Write a 32-bit float field.voidwriteFp64(int id, double value) Write a 64-bit float field.voidwriteSequenceBeginLazy(int id) Open a nested sequence with the given fieldid, whose header is held back until the sequence turns out to have content.voidClose the most recently opened nested sequence, letting it vanish if it received no content.voidClose the most recently opened nested sequence, keeping its frame even when it received no content.voidwriteSigned(int id, long value) Write a signed-integer field (ZigZag + varint).voidwriteString(int id, String text) Write a string field (raw UTF-8 bytes, no NUL on the wire).voidwriteString(int id, String text, int maxlen) Write a string field whose UTF-8 byte length must not exceedmaxlen.voidwriteUnsigned(int id, long value) Write an unsigned-integer field.
-
Constructor Details
-
OStream
public OStream(byte[] buffer) Create an encoder overbufferwith no flush sink. Writing past the end of the buffer raisesSofabError.BUFFER_FULL.- Parameters:
buffer- caller-owned output buffer
-
OStream
public OStream(byte[] buffer, int offset) LikeOStream(byte[])but begin writing atoffsetbytes into the buffer, reserving room for a lower-layer header.- Parameters:
buffer- caller-owned output bufferoffset- initial write position (0..buffer.length)
-
OStream
Create an encoder with a flushsink. When the buffer fills, the accumulated bytes are passed tosinkand writing resumes at the start of the buffer.With a sink the buffer must leave at least
Sofab.MIN_OUTPUT_BUFFERusable bytes —buffer.length - offset— and is rejected here if it does not (CORELIB_PLAN §5.1).- Parameters:
buffer- caller-owned output bufferoffset- initial write position (0..buffer.length)sink- flush sink, ornullfor none- Throws:
IllegalArgumentException- if the buffer isnull, the offset is out of range, or a sink is given and the buffer leaves less thanSofab.MIN_OUTPUT_BUFFERusable bytes
-
-
Method Details
-
bytesUsed
public int bytesUsed()Number of bytes written to the active buffer since the last flush.- Returns:
- the byte count
-
overScratch
An encoder over a per-thread scratch buffer of at leastsizebytes — the mechanism behind a one-shotencode()that returns a fresh array without re-allocating (and re-zeroing) a worst-case buffer per call.sizeis the caller's: CORELIB_PLAN §5.1 leaves the output buffer's size to the layer that knows the message, so generated code passes its ownMAX_SIZEand this library never invents one. What lives here is only the reuse — a thread-confined array, kept between calls and grown, never shrunk, to the largest size that thread has asked for. Encoding several message types on one thread therefore shares one buffer, and the returned stream may be over a longer array than requested; bound the message by its ownMAX_SIZErather than by the buffer's length.The buffer and the encoder over it are reused, not owned: everything written into the buffer is valid only until the same thread calls this again, and this method hands that thread the same
OStreamobject every time, re-armed at offset 0. Take the bytes out withcopyOfBytesUsed()before the next call, and do not call it re-entrantly — anencode()reached from inside another message'sserializeon the same thread overwrites the outer one's bytes, and now its cursor with them. A caller that needs to hold either hands in its own buffer withOStream(byte[])instead.The stream has no
FlushSink: a scratch buffer sized to hold the whole message has nowhere to flush to, and a message that outgrows it raisesSofabError.BUFFER_FULL— the streaming path is the caller's own buffer plus a sink.- Parameters:
size- smallest buffer that will do, normally the generatedMAX_SIZE—0for a message with no fields, whose encoding is the empty byte string- Returns:
- an encoder positioned at the start of this thread's scratch buffer
- Throws:
IllegalArgumentException- ifsizeis negative
-
copyOfBytesUsed
public byte[] copyOfBytesUsed()An exact-size copy of[0, bytesUsed())— the bytes standing in the active buffer.This is how a one-shot encode ends: write the whole message into a buffer that holds it, then hand the caller an array of exactly the message's length. It pairs with
overScratch(int), whose buffer must not escape, and it is the only way to get bytes out of one. It says nothing about a stream with aFlushSink, where earlier bytes have already left the buffer.- Returns:
- the bytes written so far, copied out
-
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.This is a buffer handover like the automatic one: a sink that takes the buffer may install a replacement with
bufferSet(byte[], int), and writing then resumes at that installation's offset rather than at 0.- Returns:
- number of bytes that were pending
- Throws:
IOException- if the sink fails
-
bufferSet
public void bufferSet(byte[] buffer, int offset) Replace the active buffer (typically from within a flush sink), resuming writes atoffsetin the new buffer.Called from within a
FlushSinkthis is how a sink that takes the buffer it was handed hands the encoder a replacement (CORELIB_PLAN §5.1); a sink that returns without calling it copied, and writing resumes at 0 in the buffer that is still active. The start offset belongs to the installation, not to the buffer: passing the same array again is a new installation like any other, which is how a sink re-arms header room in every flushed unit. The offset is consumed by the flush it was installed in, so the next flush the sink returns from bare resumes at 0 again.On a stream that carries a sink the replacement must leave at least
Sofab.MIN_OUTPUT_BUFFERusable bytes —buffer.length - offset— and is rejected here if it does not, which is why a sink cannot hand back storage the encoder could not write a single byte into (CORELIB_PLAN §5.1). On a sink-less stream no minimum applies.- Parameters:
buffer- new caller-owned output bufferoffset- initial write position (0..buffer.length)- Throws:
IllegalArgumentException- if the buffer isnull, the offset is out of range, or this stream carries a sink and the buffer leaves less thanSofab.MIN_OUTPUT_BUFFERusable bytes
-
reset
public void reset(byte[] buffer) Return this stream to its just-constructed state, writing intobufferfrom its start, so a caller encoding many messages in a row (a server loop, the generatedencodehelper) can hold one instance instead of letting each encode allocate and immediately discard one.The
FlushSinkis not part of what is reset: it is fixed at construction, so this resets a sink-carrying stream to a sink-carrying one and a sink-less stream to a sink-less one. Reuse therefore stays within one output discipline — an instance built for streaming cannot be recycled into a one-shot encode, or the other way round.Unlike
bufferSet(byte[], int)this also clears the sequence nesting depth and the held-back sequence run. That is the whole point for reuse: an encode that threw part-way leaves the depth counter non-zero and can leave sequence headers pending, and carrying either into the next message on the same thread would corrupt its nesting validation or prepend a stalesequence startto it — three bytes instead of two for one open sequence, and 498 instead of four atSofab.MAX_DEPTH.The
pendingarray keeps its allocation — it is sized once at construction and never re-made — and it is never read whilenPendingis zero, which is cleared here. Everything else this class declares is restored, andResetCoversEveryFieldTestholds that to every field added later.- Parameters:
buffer- caller-owned output buffer
-
writeUnsigned
Write an unsigned-integer field. Thelongis treated as an unsigned 64-bit value.- Parameters:
id- field id (0..ID_MAX)value- unsigned value- Throws:
IOException- on buffer overflow (no sink) or sink failure
-
writeSigned
Write a signed-integer field (ZigZag + varint).- Parameters:
id- field idvalue- signed value- Throws:
IOException- on buffer overflow or sink failure
-
writeBoolean
Write a boolean as an unsigned0/1.- Parameters:
id- field idvalue- boolean value- Throws:
IOException- on buffer overflow or sink failure
-
writeFixlen
public void writeFixlen(int id, byte[] data, int from, int length, FixlenType subtype) throws IOException Write a fixed-length field: the id header, a(len << 3) | subtypelength header, thenlengthraw bytes fromdata(already in wire / little-endian order for floats).This is the byte-container string entry point, so it carries the same strict-UTF-8 encode obligation as
writeString(int, String)(CORELIB_PLAN §6.4, MESSAGE_SPEC §8): withFixlenType.STRINGthe payload range is validated and a malformed one is refused withSofabError.ARGUMENTbefore any byte is emitted, so this API cannot produce a message that the family's own decoders reject. Every other sub-type — includingFixlenType.BLOB, the type for opaque bytes — passes through unvalidated at the cost of one enum comparison.- Parameters:
id- field iddata- payload bytes (may benullonly iflengthis 0)from- start offset withindatalength- number of payload bytessubtype- fixed-length sub-type- Throws:
SofabException- withSofabError.ARGUMENTiflengthis negative, or ifsubtypeisFixlenType.STRINGand the payload range is not well-formed UTF-8IOException- on buffer overflow or sink failure
-
writeFp32
Write a 32-bit float field.- Parameters:
id- field idvalue- value- Throws:
IOException- on buffer overflow or sink failure
-
writeFp64
Write a 64-bit float field.- Parameters:
id- field idvalue- value- Throws:
IOException- on buffer overflow or sink failure
-
writeString
Write a string field (raw UTF-8 bytes, no NUL on the wire).Encoding is always strict UTF-8 (MESSAGE_SPEC §8): a
Stringis a Unicode string type, so the only value it can hold that is not representable as well-formed UTF-8 is an unpaired UTF-16 surrogate. Such a string is rejected withSofabError.ARGUMENTbefore any bytes are written, rather than being silently lossily replaced. There is no strict mode to toggle — for a Unicode string type the check is unconditional.- Parameters:
id- field idtext- string value- Throws:
SofabException- withSofabError.ARGUMENTiftextcontains an unpaired surrogate (invalid UTF-8)IOException- on buffer overflow or sink failure
-
writeString
Write a string field whose UTF-8 byte length must not exceedmaxlen.The bound is the caller's -- generated code passes the schema's
maxlenfor the field (or the element of a string array); this library holds no bound of its own. A string longer thanmaxlenUTF-8 bytes is refused withSofabError.ARGUMENTbefore any byte of the field is written, exactly like an unpaired surrogate. The byte length is only known after the measuring pass this method runs anyway, so the comparison costs no second pass and no allocation; a string with more UTF-16 chars thanmaxlenis refused before that pass, since every char contributes at least one byte.- Parameters:
id- field idtext- string valuemaxlen- the most UTF-8 bytestextmay encode to- Throws:
SofabException- withSofabError.ARGUMENTiftextencodes to more thanmaxlenbytes or contains an unpaired surrogate (invalid UTF-8)IOException- on buffer overflow or sink failure
-
writeBlob
Write a binary blob field.- Parameters:
id- field iddata- blob bytes- Throws:
IOException- on buffer overflow or sink failure
-
writeBlob
Write a slice of a byte array as a binary blob field.- Parameters:
id- field iddata- backing arrayfrom- start offsetlength- number of bytes- Throws:
IOException- on buffer overflow or sink failure
-
writeArrayUnsigned
Write an array of unsigned 8-bit integers (each element zero-extended).- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArrayUnsigned
Write an array of unsigned 16-bit integers (each element zero-extended).- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArrayUnsigned
Write an array of unsigned 32-bit integers (each element zero-extended).- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArrayUnsigned
Write an array of unsigned 64-bit integers (eachlongtreated as an unsigned value).- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArraySigned
Write an array of signed 8-bit integers.- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArraySigned
Write an array of signed 16-bit integers.- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArraySigned
Write an array of signed 32-bit integers.- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArraySigned
Write an array of signed 64-bit integers.- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArrayFp32
Write an array of 32-bit floats.- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeArrayFp64
Write an array of 64-bit floats.- Parameters:
id- field iddata- elements- Throws:
IOException- on buffer overflow or sink failure
-
writeSequenceBeginLazy
Open a nested sequence with the given fieldid, whose header is held back until the sequence turns out to have content. Fields written until the matching close belong to the sequence and form a fresh id scope.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, because the message layer already omits every child equal to its default. 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 is never 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
Sofab.MAX_DEPTH: the pending run grows on demand, so this encoder is canonical at every legal nesting depth. Bounding the run and framing eagerly beyond the bound is an allowance for heap-free profiles only (CORELIB_PLAN §6), and the JVM is not one.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.- Parameters:
id- field id of the sequence- Throws:
IOException- on buffer overflow or sink failureSofabException- withSofabError.ARGUMENTif opening this sequence would exceedSofab.MAX_DEPTHnesting levels, or ifidis out of range
-
writeSequenceEnd
Close the most recently opened nested sequence, letting it vanish if it received no content.Use it wherever absence encodes the same value as an empty frame: a
struct/unionfield, and an array field whose declareddefaultis the empty collection (MESSAGE_SPEC §2). Where the frame must be visible, close withwriteSequenceEndKeep()instead.An end with no matching begin is not rejected here: the encoder writes what it is told and the resulting bytes are then malformed, which is the decoder's verdict to make. Every other port behaves this way; the depth counter simply stops at zero so the
MAX_DEPTHcheck on begin cannot be fooled by an underflow.- Throws:
IOException- on buffer overflow or sink failure
-
writeSequenceEndKeep
Close the most recently opened nested sequence, 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 (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.- Throws:
IOException- on buffer overflow or sink failure
- a wrapper-array element (
-