Class OStream

java.lang.Object
org.sofabuffers.sofab.OStream

public final class OStream extends Object
Streaming SofaBuffers encoder writing into a caller-provided byte buffer.

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

    Constructors
    Constructor
    Description
    OStream(byte[] buffer)
    Create an encoder over buffer with no flush sink.
    OStream(byte[] buffer, int offset)
    Like OStream(byte[]) but begin writing at offset bytes into the buffer, reserving room for a lower-layer header.
    OStream(byte[] buffer, int offset, FlushSink sink)
    Create an encoder with a flush sink.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    bufferSet(byte[] buffer, int offset)
    Replace the active buffer (typically from within a flush sink), resuming writes at offset in the new buffer.
    int
    Number 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.
    int
    Flush any pending bytes to the sink (if one is set) and report how many bytes were pending.
    static OStream
    overScratch(int size)
    An encoder over a per-thread scratch buffer of at least size bytes — the mechanism behind a one-shot encode() that returns a fresh array without re-allocating (and re-zeroing) a worst-case buffer per call.
    void
    reset(byte[] buffer)
    Return this stream to its just-constructed state, writing into buffer from its start, so a caller encoding many messages in a row (a server loop, the generated encode helper) can hold one instance instead of letting each encode allocate and immediately discard one.
    void
    writeArrayFp32(int id, float[] data)
    Write an array of 32-bit floats.
    void
    writeArrayFp64(int id, double[] data)
    Write an array of 64-bit floats.
    void
    writeArraySigned(int id, byte[] data)
    Write an array of signed 8-bit integers.
    void
    writeArraySigned(int id, int[] data)
    Write an array of signed 32-bit integers.
    void
    writeArraySigned(int id, long[] data)
    Write an array of signed 64-bit integers.
    void
    writeArraySigned(int id, short[] data)
    Write an array of signed 16-bit integers.
    void
    writeArrayUnsigned(int id, byte[] data)
    Write an array of unsigned 8-bit integers (each element zero-extended).
    void
    writeArrayUnsigned(int id, int[] data)
    Write an array of unsigned 32-bit integers (each element zero-extended).
    void
    writeArrayUnsigned(int id, long[] data)
    Write an array of unsigned 64-bit integers (each long treated as an unsigned value).
    void
    writeArrayUnsigned(int id, short[] data)
    Write an array of unsigned 16-bit integers (each element zero-extended).
    void
    writeBlob(int id, byte[] data)
    Write a binary blob field.
    void
    writeBlob(int id, byte[] data, int from, int length)
    Write a slice of a byte array as a binary blob field.
    void
    writeBoolean(int id, boolean value)
    Write a boolean as an unsigned 0 / 1.
    void
    writeFixlen(int id, byte[] data, int from, int length, FixlenType subtype)
    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).
    void
    writeFp32(int id, float value)
    Write a 32-bit float field.
    void
    writeFp64(int id, double value)
    Write a 64-bit float field.
    void
    Open a nested sequence with the given field id, whose header is held back until the sequence turns out to have content.
    void
    Close the most recently opened nested sequence, letting it vanish if it received no content.
    void
    Close the most recently opened nested sequence, keeping its frame even when it received no content.
    void
    writeSigned(int id, long value)
    Write a signed-integer field (ZigZag + varint).
    void
    writeString(int id, String text)
    Write a string field (raw UTF-8 bytes, no NUL on the wire).
    void
    writeString(int id, String text, int maxlen)
    Write a string field whose UTF-8 byte length must not exceed maxlen.
    void
    writeUnsigned(int id, long value)
    Write an unsigned-integer field.

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • OStream

      public OStream(byte[] buffer)
      Create an encoder over buffer with no flush sink. Writing past the end of the buffer raises SofabError.BUFFER_FULL.
      Parameters:
      buffer - caller-owned output buffer
    • OStream

      public OStream(byte[] buffer, int offset)
      Like OStream(byte[]) but begin writing at offset bytes into the buffer, reserving room for a lower-layer header.
      Parameters:
      buffer - caller-owned output buffer
      offset - initial write position (0..buffer.length)
    • OStream

      public OStream(byte[] buffer, int offset, FlushSink sink)
      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.

      With a sink the buffer must leave at least Sofab.MIN_OUTPUT_BUFFER usable bytes — buffer.length - offset — and is rejected here if it does not (CORELIB_PLAN §5.1).

      Parameters:
      buffer - caller-owned output buffer
      offset - initial write position (0..buffer.length)
      sink - flush sink, or null for none
      Throws:
      IllegalArgumentException - if the buffer is null, the offset is out of range, or a sink is given and the buffer leaves less than Sofab.MIN_OUTPUT_BUFFER usable bytes
  • Method Details

    • bytesUsed

      public int bytesUsed()
      Number of bytes written to the active buffer since the last flush.
      Returns:
      the byte count
    • overScratch

      public static OStream overScratch(int size)
      An encoder over a per-thread scratch buffer of at least size bytes — the mechanism behind a one-shot encode() that returns a fresh array without re-allocating (and re-zeroing) a worst-case buffer per call.

      size is 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 own MAX_SIZE and 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 own MAX_SIZE rather 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 OStream object every time, re-armed at offset 0. Take the bytes out with copyOfBytesUsed() before the next call, and do not call it re-entrantly — an encode() reached from inside another message's serialize on 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 with OStream(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 raises SofabError.BUFFER_FULL — the streaming path is the caller's own buffer plus a sink.

      Parameters:
      size - smallest buffer that will do, normally the generated MAX_SIZE — 0 for 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 - if size is 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 a FlushSink, where earlier bytes have already left the buffer.

      Returns:
      the bytes written so far, copied out
    • flush

      public int flush() throws IOException
      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 at offset in the new buffer.

      Called from within a FlushSink this 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_BUFFER usable 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 buffer
      offset - initial write position (0..buffer.length)
      Throws:
      IllegalArgumentException - if the buffer is null, the offset is out of range, or this stream carries a sink and the buffer leaves less than Sofab.MIN_OUTPUT_BUFFER usable bytes
    • reset

      public void reset(byte[] buffer)
      Return this stream to its just-constructed state, writing into buffer from its start, so a caller encoding many messages in a row (a server loop, the generated encode helper) can hold one instance instead of letting each encode allocate and immediately discard one.

      The FlushSink is 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 stale sequence start to it — three bytes instead of two for one open sequence, and 498 instead of four at Sofab.MAX_DEPTH.

      The pending array keeps its allocation — it is sized once at construction and never re-made — and it is never read while nPending is zero, which is cleared here. Everything else this class declares is restored, and ResetCoversEveryFieldTest holds that to every field added later.

      Parameters:
      buffer - caller-owned output buffer
    • writeUnsigned

      public void writeUnsigned(int id, long value) throws IOException
      Write an unsigned-integer field. The long is 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

      public void writeSigned(int id, long value) throws IOException
      Write a signed-integer field (ZigZag + varint).
      Parameters:
      id - field id
      value - signed value
      Throws:
      IOException - on buffer overflow or sink failure
    • writeBoolean

      public void writeBoolean(int id, boolean value) throws IOException
      Write a boolean as an unsigned 0 / 1.
      Parameters:
      id - field id
      value - 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) | subtype length header, then length raw bytes from data (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): with FixlenType.STRING the payload range is validated and a malformed one is refused with SofabError.ARGUMENT before any byte is emitted, so this API cannot produce a message that the family's own decoders reject. Every other sub-type — including FixlenType.BLOB, the type for opaque bytes — passes through unvalidated at the cost of one enum comparison.

      Parameters:
      id - field id
      data - payload bytes (may be null only if length is 0)
      from - start offset within data
      length - number of payload bytes
      subtype - fixed-length sub-type
      Throws:
      SofabException - with SofabError.ARGUMENT if length is negative, or if subtype is FixlenType.STRING and the payload range is not well-formed UTF-8
      IOException - on buffer overflow or sink failure
    • writeFp32

      public void writeFp32(int id, float value) throws IOException
      Write a 32-bit float field.
      Parameters:
      id - field id
      value - value
      Throws:
      IOException - on buffer overflow or sink failure
    • writeFp64

      public void writeFp64(int id, double value) throws IOException
      Write a 64-bit float field.
      Parameters:
      id - field id
      value - value
      Throws:
      IOException - on buffer overflow or sink failure
    • writeString

      public void writeString(int id, String text) throws IOException
      Write a string field (raw UTF-8 bytes, no NUL on the wire).

      Encoding is always strict UTF-8 (MESSAGE_SPEC §8): a String is 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 with SofabError.ARGUMENT before 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 id
      text - string value
      Throws:
      SofabException - with SofabError.ARGUMENT if text contains an unpaired surrogate (invalid UTF-8)
      IOException - on buffer overflow or sink failure
    • writeString

      public void writeString(int id, String text, int maxlen) throws IOException
      Write a string field whose UTF-8 byte length must not exceed maxlen.

      The bound is the caller's -- generated code passes the schema's maxlen for the field (or the element of a string array); this library holds no bound of its own. A string longer than maxlen UTF-8 bytes is refused with SofabError.ARGUMENT before 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 than maxlen is refused before that pass, since every char contributes at least one byte.

      Parameters:
      id - field id
      text - string value
      maxlen - the most UTF-8 bytes text may encode to
      Throws:
      SofabException - with SofabError.ARGUMENT if text encodes to more than maxlen bytes or contains an unpaired surrogate (invalid UTF-8)
      IOException - on buffer overflow or sink failure
    • writeBlob

      public void writeBlob(int id, byte[] data) throws IOException
      Write a binary blob field.
      Parameters:
      id - field id
      data - blob bytes
      Throws:
      IOException - on buffer overflow or sink failure
    • writeBlob

      public void writeBlob(int id, byte[] data, int from, int length) throws IOException
      Write a slice of a byte array as a binary blob field.
      Parameters:
      id - field id
      data - backing array
      from - start offset
      length - number of bytes
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArrayUnsigned

      public void writeArrayUnsigned(int id, byte[] data) throws IOException
      Write an array of unsigned 8-bit integers (each element zero-extended).
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArrayUnsigned

      public void writeArrayUnsigned(int id, short[] data) throws IOException
      Write an array of unsigned 16-bit integers (each element zero-extended).
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArrayUnsigned

      public void writeArrayUnsigned(int id, int[] data) throws IOException
      Write an array of unsigned 32-bit integers (each element zero-extended).
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArrayUnsigned

      public void writeArrayUnsigned(int id, long[] data) throws IOException
      Write an array of unsigned 64-bit integers (each long treated as an unsigned value).
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArraySigned

      public void writeArraySigned(int id, byte[] data) throws IOException
      Write an array of signed 8-bit integers.
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArraySigned

      public void writeArraySigned(int id, short[] data) throws IOException
      Write an array of signed 16-bit integers.
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArraySigned

      public void writeArraySigned(int id, int[] data) throws IOException
      Write an array of signed 32-bit integers.
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArraySigned

      public void writeArraySigned(int id, long[] data) throws IOException
      Write an array of signed 64-bit integers.
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArrayFp32

      public void writeArrayFp32(int id, float[] data) throws IOException
      Write an array of 32-bit floats.
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeArrayFp64

      public void writeArrayFp64(int id, double[] data) throws IOException
      Write an array of 64-bit floats.
      Parameters:
      id - field id
      data - elements
      Throws:
      IOException - on buffer overflow or sink failure
    • writeSequenceBeginLazy

      public void writeSequenceBeginLazy(int id) throws IOException
      Open a nested sequence with the given field id, 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 failure
      SofabException - with SofabError.ARGUMENT if opening this sequence would exceed Sofab.MAX_DEPTH nesting levels, or if id is out of range
    • writeSequenceEnd

      public void writeSequenceEnd() throws IOException
      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/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.

      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_DEPTH check on begin cannot be fooled by an underflow.

      Throws:
      IOException - on buffer overflow or sink failure
    • writeSequenceEndKeep

      public void writeSequenceEndKeep() throws IOException
      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