Skip to content

Repository files navigation

SofaBuffers

SofaBuffers

Structured Objects For Anyone
... so optimized, feels amazing.

Would you like to know more?

SofaBuffers Zig library

CI Coverage Docs

GitHub repository

A maximum-throughput, streaming Zig implementation of the SofaBuffers (Sofab) serialization format. The decoder advances a Protocol-Buffers-style cursor over contiguous memory with zero copies, field dispatch is comptime duck typing (monomorphized, no vtable), and the codec itself — OStream and IStream/decode — is allocation-free: caller-owned buffers on both sides, a fixed carry buffer inside the streaming decoder, no allocator held or taken. (The sofab.arrays helpers that generated decode code uses for dynamically sized arrays are the one exception: they take the caller's allocator as an argument.) It is wire-compatible, byte-for-byte, with every other corelib-* port.

Requirements

Zig 0.16.0 or newer. No OS assumptions in the library itself; the benchmark tools use the Linux process-CPU clock.

Add the package to your project and wire up the sofab module:

zig fetch --save git+https://github.com/sofa-buffers/corelib-zig#v0.12.0

Pin the release with the #-ref: without one, zig fetch resolves whatever the default branch points at just then. --save writes the resolved hash into your build.zig.zon either way.

// build.zig
const corelib = b.dependency("sofa_buffers_corelib", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("sofab", corelib.module("sofab"));
const sofab = @import("sofab");

The package name is sofa_buffers_corelib; the importable namespace is sofab.

Dependencies

None — only the Zig standard library, and std.json is used solely by the test suite. Nothing is pulled into downstream builds.

Why this design

Goal How
Streaming out OStream writes into a caller buffer and calls a flush callback when it fills, so a message can exceed the buffer; bufferSet swaps the buffer mid-stream.
Streaming in IStream.feed takes arbitrarily small chunks and suspends/resumes at any byte boundary; string/blob payloads are delivered incrementally.
Zero unnecessary copies decode parses straight from the input buffer, handing string/blob fields to the visitor as callback-scoped slices; feed copies only the few bytes of the one small item that straddles a chunk boundary — once that item is complete the rest of the chunk is parsed in place, at full contiguous speed.
No allocation The codec is allocator-free — not just the hot path. Encoder state is a struct over your buffer (plus the inline sequence hold-back run, see below); the decoder's only memory is a fixed 64-byte carry buffer. Only the sofab.arrays helpers for dynamically sized arrays take an allocator, and only as a parameter.
Raw speed Unchecked pointer-advancing varint encode and decode once bounds are guaranteed, bulk @memcpy/native little-endian float loads, comptime-monomorphized visitor dispatch, inline field writers (a generated serialize() pays no call per field), @branchHint(.cold) on the drain path and on the chunk-boundary stitch, ReleaseFast shipping profile.
Type safety Wire types and value widths live in the type system; array element widths are comptime-checked, so an invalid element type is a compile error.
Cross-language compatibility The shared assets/test_vectors.json is replayed — the same bytes every other port produces — plus a big-endian (s390x) CI leg.

Usage

The codec has four use cases — serialize a message that fits in one buffer, serialize one too large for the buffer (streamed out in chunks), deserialize a whole message, and deserialize one arriving in chunks — plus the generated-code path that wraps them.

Serialize

OStream.init wraps a caller-owned buffer big enough for the whole message. Each write* returns an error union, never allocates, and bytesUsed() reports the byte count:

const sofab = @import("sofab");

var buf: [64]u8 = undefined;
var os = sofab.OStream.init(&buf);
try os.writeUnsigned(1, 42);
try os.writeSigned(2, -7);
try os.writeString(3, "hi");
const message = buf[0..os.bytesUsed()];

Nested scopes are opened with writeSequenceBeginLazy(id), which holds the header back until the sequence turns out to have content, so an all-default sequence is omitted without ever buffering the sub-message. Which closer you use is a property of the position, decided at generation time:

try os.writeSequenceBeginLazy(4);
try os.writeUnsigned(1, 99);
try os.writeSequenceEnd(); // struct/union field, or an array field:
                           // a sequence that got no content vanishes entirely
position closer
struct / union field writeSequenceEnd
array field (the wrapper) writeSequenceEnd
wrapper-array element (struct/union/nested row) writeSequenceEndKeep
array field known to differ from a non-empty declared default writeSequenceEndKeep

writeSequenceEndKeep behaves like a write: it emits the held-back headers and the end marker, so a contentless sequence still reaches the wire as begin + end. It is the safe default where a call site is ambiguous.

The hold-back reaches MAX_DEPTH (255), the format's own nesting ceiling: this encoder never falls back to eager framing, so a contentless sequence is omitted at every depth. The run is reserved inline in the OStream value (see Memory handling), and held-back ids are encoder state rather than buffer content, so a pending run cannot straddle a flush.

Serialize stream

Attach a flush callback with OStream.initFlush. When the scratch buffer fills, its bytes drain to the callback and writing resumes at the start; flush() pushes the tail — so the message can far exceed the buffer:

const Sink = struct {
    list: std.ArrayList(u8) = .empty,
    gpa: std.mem.Allocator,

    fn push(ctx: ?*anyopaque, chunk: []const u8) void {
        const self: *@This() = @ptrCast(@alignCast(ctx.?));
        self.list.appendSlice(self.gpa, chunk) catch @panic("oom");
    }
};

var out: Sink = .{ .gpa = gpa }; // or a socket / file writer
var scratch: [16]u8 = undefined;
var os = sofab.OStream.initFlush(&scratch, 0, &out, Sink.push);
for (0..1000) |i| try os.writeUnsigned(@intCast(i), i);
_ = os.flush(); // push the tail

The scratch buffer may be as small as sofab.MIN_OUTPUT_BUFFER (1 byte) — this encoder splits every atomic unit across a flush, so any non-empty buffer streams a message of any size and the bytes are identical to the one-shot path. That minimum binds a buffer installed with a sink, and only such a buffer; see Memory handling for what happens to one below it.

Deserialize

Decoding is push-based: pass a pointer to any struct implementing the callbacks you care about, and the decoder calls one method per field. Missing methods are comptime no-ops, so unhandled fields are skipped automatically. decode runs the zero-copy fast path over a complete message:

const My = struct {
    a: u64 = 0,
    b: i64 = 0,
    s: [16]u8 = undefined,
    s_len: usize = 0,

    pub fn unsigned(self: *@This(), id: sofab.Id, v: u64) void {
        if (id == 1) self.a = v;
    }
    pub fn signed(self: *@This(), id: sofab.Id, v: i64) void {
        if (id == 2) self.b = v;
    }
    pub fn string(self: *@This(), id: sofab.Id, total: usize, offset: usize, chunk: []const u8) void {
        _ = total;
        if (id == 3) {
            @memcpy(self.s[offset..][0..chunk.len], chunk);
            self.s_len = offset + chunk.len;
        }
    }
    // blob, fp32, fp64, arrayBegin, sequenceBegin, sequenceEnd … as needed
};

var sink: My = .{};
_ = try sofab.decode(message, &sink); // .complete at a clean message boundary
// sink.a == 42, sink.b == -7, sink.s[0..sink.s_len] == "hi"

Nested scopes: declaring sequenceBegin is what opts you in. Every sequence opens a fresh id namespace — a child's id 1 is unrelated to the enclosing scope's id 1. A visitor that declares no sequenceBegin has the decoder consume and discard the entire sub-sequence, children and the matching sequenceEnd alike, and sees the message's top-level fields only; declare it (as generated code always does) and you get every nested field, with the scope bookkeeping yours to do. Either way the skipped bytes are still fully parsed: MAX_DEPTH, every malformed-input verdict and the resync onto the field after the scope are unaffected, and the outcome does not depend on where the chunk boundaries fall.

Deserialize stream

IStream.feed takes chunks of any size, suspends/resumes at any byte boundary, and drives the same visitor. feed returns the message-boundary Status after each chunk: .complete at a clean field boundary and .incomplete when the bytes ended inside a field or with a sequence still open. That call is the whole answer — there is no finish()/finalize() and no separate status accessor beside it; to re-ask without new bytes, feed an empty chunk. The caller owns end-of-input and decides, from its own framing, whether a trailing .incomplete is a truncation failure; malformed bytes are rejected as error.InvalidMessage by feed itself.

var sink: My = .{};
var is = sofab.IStream.init();
var status = sofab.Status.complete; // fed nothing: at a field boundary
while (transport.nextChunk()) |chunk| { // 7 bytes at a time, or 1, or 64k
    status = try is.feed(chunk, &sink); // error.InvalidMessage on malformed input
}
switch (status) {
    .complete => {},
    .incomplete => {}, // stream ended mid-message: your framing decides
    .invalid => {},    // unreachable after a `try` — see below
}

A rejection is terminal. The decoder latches error.InvalidMessage rather than resynchronizing after the malformed construct: every further feed — a whole valid message, a truncated prefix and an empty end-of-input probe alike — returns error.InvalidMessage again. is.reset() clears the latch — the only way out — and readies the decoder for the next message. A receiver-side error.LimitExceeded raised out of a visitor callback latches the same way — CORELIB_PLAN §6.3 calls it a terminal policy rejection — but keeps its own identity: every further feed returns error.LimitExceeded again, never InvalidMessage, which is where §6.3 keeps its five codes apart.

One fact, one place to read it. feed publishes the outcome on its two channels — the Status it returns, the error it raises — and this library offers no second surface that answers the same question: §6.3 allows a refusal to be surfaced either as a fourth outcome or as "a terminal failure carrying the LimitExceeded code on the error channel", and this port takes the error channel. Status.invalid is kept as the name of MESSAGE_SPEC §7's third outcome for callers that must map the caught error.InvalidMessage back onto it; feed itself never returns it.

The error set also carries error.LimitExceeded, for a receiver-configured decode limit on an unbounded field (max_dyn_array_count, max_dyn_string_len, max_dyn_blob_len). This library holds no limit and defines no default value: the caps come from the sofabgen config, and each is a number the caller supplies for one call. Every comparison runs here, at the header that announces the size and before anything is sized from it. The array cap rides into sofab.arrays as Bound.receiver, compared at the count or element index by whichever of overIndex, placeElem, reserveElem, reserveRow and allocCounted the field's shape calls; the string and blob caps go to sofab.PayloadAcc.beginCapped, at the payload's announced length, and to takeCapped again ahead of the copy or the stitch that would otherwise commit it. The announced length is the point that matters, because a message may end at the header: 02 a2 06 declares a hundred-byte string and stops, so nothing ever reaches a payload callback and a cap living only there would never fire. Both header hooks are declared fallible for that reason — raise error.LimitExceeded out of fixlenBegin or arrayBegin and the decoder latches it, so the refusal is terminal rather than an .incomplete a further feed would continue past. No cap is raised twice: whichever side checks, the other does not. error.LimitExceeded is distinct from error.InvalidMessage — a receiver limit is policy, not wire malformation — and the format ceilings ARRAY_MAX and FIXLEN_MAX are not receiver caps: exceeding one is error.InvalidMessage (see generator#102).

UTF-8 validation (SOFAB_STRICT_UTF8)

A string payload is UTF-8; blob is opaque bytes and is never validated. Strict UTF-8 validation is gated by the compile-time build option strict_utf8 (SOFAB_STRICT_UTF8, CORELIB_PLAN §6.4), on by default:

zig build test                       # strict on (default)
zig build test -Dstrict_utf8=false   # non-strict build (validation compiled out)

Zig is a byte-container target (a string is []const u8), so the corelib exposes the primitive sofab.utf8Valid(bytes: []const u8) bool. Generated decode code calls it unconditionally on every materialized string; the gate lives inside the primitive, so flipping the flag never regenerates code. On the encode side the check lives in OStream.writeFixlen(id, data, .string), so both it and OStream.writeString refuse a non-UTF-8 value with error.InvalidArgument under strict (blob and the float subtypes are never validated). sofab.STRICT_UTF8 reflects the compiled state. When the option is off, utf8Valid folds to true (no validator compiled in) and both writers emit bytes verbatim — never silent/lossy. Skipped fields are never validated. The validator rejects overlong forms including C0 80, surrogates, and code points above U+10FFFF, and accepts embedded U+0000.

Code generator

Usually you never touch the raw API: the generator turns a schema into typed structs whose surface is the closed name set of CORELIB_PLAN §6.1.1 — the one-shot encode() / decode() pair users reach for, and the streaming serialize() / deserialize pair that talks to this corelib (deserialize being, in Zig, the generated visitor the decoder calls). The one-shot helpers are thin wrappers over the streaming path.

sofabgen --lang zig over a two-field schema

messages:
  point:
    summary: A 2D point.
    payload:
      x: { id: 1, type: i32 }
      y: { id: 2, type: i32 }

emits this — doc comments shortened, and the array/string/nested-sequence machinery this schema does not use left out:

// Code generated by sofabgen; DO NOT EDIT.
const std = @import("std");
const sofab = @import("sofab");

/// The corelib baseline plus IncompleteMessage: for a one-shot decode over a
/// whole buffer, a trailing .incomplete means the message was truncated.
pub const DecodeError = sofab.Error || error{IncompleteMessage};

/// A 2D point.
pub const Point = struct {
    x: i32 = 0,
    y: i32 = 0,

    /// Worst-case encoded size of this message, derived from the schema.
    pub const MAX_SIZE: usize = 12;

    /// Streaming out: write this value's fields into any OStream.
    pub fn serialize(self: *const Point, os: *sofab.OStream) sofab.Error!void {
        if (self.x != 0) try os.writeSigned(1, self.x);
        if (self.y != 0) try os.writeSigned(2, self.y);
    }

    /// One-shot: `serialize` into a scratch buffer drained by a growing sink.
    pub fn encode(self: *const Point, alloc: std.mem.Allocator) (sofab.Error || std.mem.Allocator.Error)![]u8 {
        var sink: _EncodeSink = .{ .alloc = alloc };
        var scratch: [512]u8 = undefined;
        var os = sofab.OStream.initFlush(&scratch, 0, &sink, _EncodeSink.push);
        try self.serialize(&os);
        _ = os.flush();
        if (sink.failed) return error.OutOfMemory;
        return sink.list.toOwnedSlice(alloc);
    }

    /// One-shot: the generated visitor driven over one whole buffer. Zero-copy —
    /// string/blob fields would borrow from `data`; truncated input fails with
    /// error.IncompleteMessage, malformed input with error.InvalidMessage.
    pub fn decode(alloc: std.mem.Allocator, data: []const u8) DecodeError!Point {
        var m: Point = .{};
        var v: _dec_Point = .{ .m = &m, .alloc = alloc };
        const st = try sofab.decode(data, &v);
        if (v.inv) return error.InvalidMessage;
        if (st == .incomplete) return error.IncompleteMessage;
        return m;
    }

    /// Incremental decoder: hold one and feed the message as bytes arrive.
    /// Unlike decode(), this path COPIES every string and blob into `alloc`.
    pub const Decoder = struct {
        is: sofab.IStream = sofab.IStream.init(),
        v: _dec_Point,
        last: sofab.Status = .complete, // what the last feed answered

        /// Feed the next chunk, of any size. `.complete` means the bytes ended
        /// on a field boundary, `.incomplete` mid-field — neither answers
        /// whether the MESSAGE is done.
        pub fn feed(self: *Decoder, chunk: []const u8) DecodeError!sofab.Status {
            const st = try self.is.feed(chunk, &self.v);
            if (self.v.inv) return error.InvalidMessage;
            self.last = st;
            return st;
        }

        /// Declare end-of-input: a stream that ended mid-field fails here.
        /// The corelib publishes the outcome once, through `feed`, so this
        /// layer keeps what `feed` last answered rather than asking again.
        pub fn finish(self: *const Decoder) DecodeError!void {
            if (self.last == .incomplete) return error.IncompleteMessage;
        }
    };

    /// Streaming in: an incremental decoder filling `out`.
    pub fn decoder(out: *Point, alloc: std.mem.Allocator) Decoder {
        return .{ .v = .{ .m = out, .alloc = alloc, .own = true } };
    }
};

/// The `deserialize` half of §6.1.1: the per-field hook the corelib's decoder
/// calls.
const _dec_Point = struct {
    m: *Point,
    alloc: std.mem.Allocator,
    own: bool = false, // copy payloads instead of borrowing (streaming path)
    inv: bool = false, // a value outside its schema bound -> INVALID

    pub fn signed(self: *_dec_Point, id: sofab.Id, value: sofab.Signed) void {
        switch (id) {
            1 => {
                if (value < -2147483648 or value > 2147483647) {
                    self.inv = true;
                    return;
                }
                self.m.x = @intCast(value);
            },
            2 => {
                if (value < -2147483648 or value > 2147483647) {
                    self.inv = true;
                    return;
                }
                self.m.y = @intCast(value);
            },
            else => {},
        }
    }
};

/// Flush sink behind encode(): drains the OStream scratch into a byte list.
const _EncodeSink = struct {
    alloc: std.mem.Allocator,
    list: std.ArrayList(u8) = .empty,
    failed: bool = false,
    fn push(ctx: ?*anyopaque, data: []const u8) void {
        const self: *_EncodeSink = @ptrCast(@alignCast(ctx.?));
        self.list.appendSlice(self.alloc, data) catch {
            self.failed = true;
        };
    }
};

Both paths, on that generated type — the convenience pair first, then the streaming pair the corelib actually talks to:

// The generated layer allocates; the corelib still does not. An arena
// frees the whole message at once.
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = arena.allocator();

// --- one-shot: encode()/decode(), thin wrappers over the streaming pair ---
const wire = try (Point{ .x = 3, .y = 4 }).encode(alloc);
const got = try Point.decode(alloc, wire); // got.x == 3, got.y == 4

// --- streaming out: an output buffer smaller than the message + a sink ---
const Sink = struct {
    buf: [Point.MAX_SIZE]u8 = undefined,
    len: usize = 0,
    fn push(ctx: ?*anyopaque, chunk: []const u8) void {
        const self: *@This() = @ptrCast(@alignCast(ctx.?));
        @memcpy(self.buf[self.len..][0..chunk.len], chunk);
        self.len += chunk.len;
    }
};
var sink: Sink = .{};
var scratch: [4]u8 = undefined; // well under MAX_SIZE: the sink drains it
var os = sofab.OStream.initFlush(&scratch, 0, &sink, Sink.push);
try (Point{ .x = 3, .y = 4 }).serialize(&os);
_ = os.flush(); // sink.buf[0..sink.len] is the same message

// --- streaming in: feed the message in chunks of any size ---------------
var out: Point = .{};
var dec = Point.decoder(&out, alloc);
var st = try dec.feed(wire[0..1]); // .incomplete — ended mid-field
st = try dec.feed(wire[1..]); // .complete — ended on a field boundary
try dec.finish(); // end-of-input: a trailing .incomplete fails here

feed reports only whether the bytes handed in ended on a field boundary, so finish() is where the generated layer turns a trailing .incomplete into error.IncompleteMessage. Both blocks are compiled and run by the test suite (tests/readme_generated_example.zig), and tests/readme_tests.zig fails the build if this section drifts from them.

Support layer for generated code

The parts of generated code that do not change shape from one schema to the next live here rather than in every generated module (ARCHITECTURE §8): the capacity is a type parameter, and the count, the allocator and the payload length are arguments.

symbol what it holds
sofab.FixedArray(T, N) a count: N array field: N elements of inline capacity plus the length actually carried
sofab.CollectingSink the flush sink behind a one-shot encode(), collecting the drained bytes into the caller's allocator
sofab.PayloadAcc one string/blob payload however it arrived — borrowed whole, copied whole, or stitched out of pieces — via take and the receiver-capped beginCapped / takeCapped
sofab.floats bitsEqual(T, a, b), the encode-side default test for f32/f64 arrays: equal length and equal IEEE-754 bit patterns, so -0.0 differs from 0.0 and a NaN equals another NaN only bit for bit
sofab.arrays the decode-side array helpers — placeElem, reserveElem, reserveRow, allocCounted, overIndex, plus the element stores putChecked / putGrowing and the pointer helper at

FixedArray keeps its storage to itself, so a length can never be left disagreeing with the elements beside it. A schema count is a capacity and the wire count is the length, so .{} is the empty array and .init(&.{ 10, 20 }) is a two-element value in a four-element field. An element past N sets the caller's inv flag — a wire count above the schema count is INVALID, never clamped.

sofab.arrays takes the field's bound, and there is one entry point per operation. Three signatures cover every wrapper array — placeElem puts a string or blob element at its wire id, reserveElem reserves the slot a struct, union or nested-array element is routed into, and reserveRow reserves a matrix row and sizes it at its announced count — with allocCounted beside them for the count-prefixed native array.

Each takes a comptime sofab.arrays.Bound saying which rule governs the field, and therefore what breaching it is called: .{ .schema = n } for a declared count: n, where a breach contradicts the agreed schema and is error.InvalidMessage; .{ .receiver = n } for a receiver cap on a field the schema leaves unbounded, where the bytes are well formed and a breach is error.LimitExceeded. The two are never both in play and there is no third state, so the rule has exactly one implementation and generated code carries no copy of it — Bound.Err() even narrows the error set to the one verdict that bound can raise. The comparison runs at the count word or the element index, before the destination is sized, and an allocation failure keeps its own channel (an empty slice, or false) so it stays distinguishable from a refusal. Because the bound is comptime, the call lowers to the same comparison against the same constant an inline if (id >= n) would.

overIndex is published beside them for the one site with no container operation to ride: a generated fixlenBegin bounds a string or blob element's index at the length word, where a message ending right there must still be INVALID rather than incomplete. That element's own maxlen is decided in the same place and is deliberately not a Bound: there is no sizing call here for it to ride.

PayloadAcc has the same two entry points. take materializes one payload whichever way it arrived: handed straight back when it came whole and the caller's buffer may be borrowed (the contiguous decode path), copied when it came whole but the caller must not borrow (the streaming path, where a payload completing inside the decoder's reused carry buffer would be overwritten by the next stitched item), stitched when it came in pieces. It is the entry point for a field the schema bounds with maxlen, whose violation is INVALID and the caller's to decide. beginCapped and takeCapped are for a field the schema leaves unbounded: both compare max_dyn_string_len / max_dyn_blob_len against the announced length, before a byte is borrowed, copied or appended, so an over-cap payload costs nothing at all. Comparing afterwards would report the same refusal having already committed the memory it exists to deny. beginCapped is the one a generated fixlenBegin calls, at the length word itself — the only place that still answers when the message ends there and no payload chunk is ever delivered; takeCapped stays the second line of defence for the payload that does arrive.

CollectingSink is a sink the caller constructs with its own allocator and installs like any other flush target; the corelib still allocates nothing. It is for the unbounded-schema shape, where MAX_SIZE is a configured ceiling rather than a size the message cannot reach. A schema whose bound is real needs no sink at all: allocate that many bytes, install them with OStream.init, encode in one pass.

var sink: sofab.CollectingSink = .{ .alloc = alloc };
defer sink.deinit();
var scratch: [512]u8 = undefined;
var os = sofab.OStream.initFlush(&scratch, 0, &sink, sofab.CollectingSink.push);
try os.writeUnsigned(1, 42);
_ = os.flush();
// error.OutOfMemory if any drain was lost: a prefix is never returned as a
// whole message.
const message = try sink.toOwnedSlice();
defer alloc.free(message);

The generator still emits its own copy of each of these; switching it over is tracked by generator#345. Nothing here is needed to use the library by hand.

Memory handling

You own every buffer. The codec is allocation-free and holds no heap memory — OStream, IStream and decode neither take nor keep an allocator.

  • Encode (OStream): you own the output []u8; the library never allocates or grows it. With no flush sink, overflow is error.BufferFull; with a flush callback the buffer drains and is reused (bufferSet swaps in a fresh one), and initOffset reserves leading framing space. Each write copies its bytes into the buffer, so caller source strings/slices may be reused immediately. A sink is never handed memory other than the output buffer: this port grants no string/blob pass-through. sofab.MIN_OUTPUT_BUFFER is 1: the smallest buffer accepted for streaming, i.e. one installed together with a flush sink, which must offer at least that many usable bytes (buffer.len - offset). A buffer installed without a sink is subject to no minimum — no flush can occur, so it either holds the message or reports error.BufferFull, and a two-byte message encodes into a two-byte buffer. Every installation is judged where the buffer is handed over — initOffset, initFlush, bufferSet — never partway through a message: an offset past the end of the buffer, or less than MIN_OUTPUT_BUFFER behind a sink, is refused there and leaves the stream inert, writing nothing and reporting error.InvalidArgument from every write. The *Checked variant of each of those three reports the same refusal as an error status up front, for a buffer or offset computed at runtime. What the flush callback does before it returns decides where the encoder goes on writing. Returning without installing a buffer means the sink copied the bytes: the active buffer stays active, with the cursor back at 0. A sink that takes the buffer must bufferSet a replacement before returning. The start offset belongs to the installation, not to the buffer, so the encoder resumes at that call's offset — os.bufferSet(fresh, 4) re-arms four bytes of header room in the next flushed unit, and re-installing the same buffer is how a sink gets that room in every unit rather than only in the first. A later bare return resumes at 0 again. A replacement refused inside a callback leaves the stream inert, and the write that triggered the flush reports error.InvalidArgument instead of storing into it. The struct itself is 1080 bytes on a 64-bit target: it reserves the full MAX_DEPTH lazy sequence hold-back run inline (see Serialize).
  • Decode (decode / IStream + visitor): you own the input bytes and they must outlive the decode/feed call. Scalars and floats arrive by value; a string/blob payload arrives through the callback, as a slice you copy where you want it. Nothing the decoder delivers outlives the callback it was delivered in. A delivered slice is valid only until that callback returns — on the one-shot decode path exactly as on the streaming feed path, since the two differ only in how the bytes got here. Copy it out to keep it. No value is readable after the call that delivered it: there is no payload position, no getter, and no “valid until the next feed” slice. Where a slice borrows from is not part of the contract and must not be relied on: it usually points into the buffer or chunk you just fed, and the few bytes of an item that straddled a chunk boundary come out of IStream's fixed carry buffer, which the next straddling item overwrites. No wire value decides an allocation here — no count and no length sizes anything the codec holds, on either path, and there is no library-owned accumulator for a chunk-straddling field.
Buffer Owner / lifetime
Output buffer Caller-owned []u8; library never allocates or grows it (no sink → error.BufferFull). With a sink it must offer at least MIN_OUTPUT_BUFFER = 1 usable byte, checked at every installation; without one, no minimum applies.
Input buffer (decode) Caller-owned; must outlive the call. Delivered string/blob slices are valid only for the duration of the callback — callback-scoped, never retainable.
Input chunk (feed) Caller-owned; must outlive the call. Delivered string/blob slices are valid only for the duration of the callback; a carry-completed payload borrows from IStream, not from your chunk.

Decoded values are pushed to a visitor, so nothing requires them to be address-stable. The only memory the decoder owns is IStream's fixed 64-byte carry buffer — the few bytes of an item that straddled a chunk boundary; it is sized once, in the struct, and no message can make it larger.

Beside the codec the package ships a static helper layer — sofab.arrays and sofab.support — which the codec itself never calls. Those helpers take an allocator as a parameter and allocate on the generated layer's behalf, which owns the storage each decoded field lands in. Their buffers are not the codec's.

Build & test

zig build --release=fast         # static library in the shipping config (ReleaseFast)
zig build test                   # unit + conformance tests (incl. shared vectors)
zig build test --release=fast    # the same suite in the shipping config
./coverage.sh                    # line coverage via kcov (HTML + percentage; fails below 90%)

CI runs zig fmt --check, the full suite in Debug and ReleaseFast, the same suite on a big-endian s390x host under QEMU and on a 32-bit x86 target in both modes, and the kcov coverage job. Conformance tests live in tests/ (shared-vector replay including the sequence_growth block, chunked encode/decode, chunk-lifetime scrubs, roundtrip, malformed-input, tolerance, cross-chunk UTF-8, array-growth geometry and skip scenarios — every vector carrying skip_ids, decoded whole and one byte at a time, both through a receiver that filters those ids out and through receivers that leave their callback undeclared so the decoder skips the field itself); unit tests live next to the code in src/. The vector suite prints how many vectors and how many checks each scenario ran.

Feature flags

There are no toggles for wire types. The one build option is the strict UTF-8 validation policy:

Build option Default Effect
-Dstrict_utf8=<bool> (SOFAB_STRICT_UTF8) true (on) Strict UTF-8 validation of string fields — see UTF-8 validation. Off compiles the validator out (zero cost) and stores/writes bytes verbatim. A validation policy only, never a wire-format switch.

Benchmarks

Three tools mirror the other ports' perf, bench and run_callgrind.sh tooling — same workloads and output format per BENCH_SPEC.md, so results are comparable across languages:

zig build perf                   # cycles/op + CPU ns/op + throughput per op
zig build bench                  # practical MB/s (encode + decode)
zig build bench -Dcpu=native     # last few percent
bash bench/run_callgrind.sh      # instructions/op (Callgrind Ir/op)

perf reports the CPU-independent per-op cost (hardware cycle counter); bench reports throughput in MB/s on the current machine, both measured over a ~1 s process-CPU-time loop.

bench/run_callgrind.sh reports instructions retired per op (Ir/op) under Callgrind — deterministic, independent of clock speed and scheduler, and available on every target, unlike perf's cycle counter. It needs valgrind installed (the devcontainer image ships it) and builds its own tool (zig build callgrind); collection is toggled on that tool's run_<workload> symbol, so each printed number is one operation's cost with no rep-count subtraction. It is reporting tooling, not part of the test suite or CI.

All three tools drive one list of workloads — the table in bench/workloads.zig — so the MB/s rows, the per-op report and the Ir/op rows measure the same code on the same data. tests/bench_spec_tests.zig holds that table against BENCH_SPEC's rows and runs every entry, including the two encoded sizes the spec states outright (blob 1MB = 1,000,005 bytes, composite = 956).

How to read the rows

Measured figures are not reproduced here — they belong to the cross-language benchmark arena, which runs every port on one host under one methodology. This section says how to obtain them, not what they came out as.

Three of those rows have to be read against their configuration:

  • The blob 1MB rows are read against each other. Five bytes of that message are metadata and a million are payload, so their MB/s is the host's memory bandwidth, and the 4 KiB streaming buffer stays in L1 where a contiguous megabyte does not. The two encode rows differ only in the sink: one contiguous write into a caller buffer, against the same megabyte through a 4096-byte buffer and ~245 flushes, and the gap between them is what the flush path costs. BENCH_SPEC's optional blob 1MB passthrough row is absent — this port grants no pass-through.
  • decode: blob 1MB never touches the payload. The visitor is handed a slice borrowed from the input buffer, so its Ir/op is the framing of 245 chunks alone.
  • decode: composite skip-all is barely cheaper than decode: composite. Skipping suppresses delivery, not parsing: every header, length word and count is still walked.

Releases

Packages

Contributors

Languages