protobuf API reference Changelog View on GitHub

API reference

Protocol Buffers in Zig: the wire format, and a typed layer over plain structs.

Reader and Writer are the primitives: a field at a time, no schema. The core loop allocates nothing. encode and decode sit above them and read a Zig struct as a message, with field numbers declared in a pub const protobuf table.

Based on the protobuf encoding specification: https://protobuf.dev/programming-guides/encoding/

pub fn decode( comptime T: type, gpa: Allocator, reader: *Io.Reader, options: Options, ) Error!Parsed(T)

src

Decode one message from a reader, copying strings and bytes into an arena.

pub fn decodeLeaky(comptime T: type, gpa: Allocator, reader: *Io.Reader, options: Options) Error!T

src

Decode one message from a reader into memory the caller owns.

pub fn decodeFromSlice( comptime T: type, gpa: Allocator, bytes: []const u8, options: Options, ) Error!Parsed(T)

src

Decode one message from a slice, borrowing strings and bytes from it.

pub fn decodeFromSliceLeaky( comptime T: type, gpa: Allocator, bytes: []const u8, options: Options, ) Error!T

src

The borrowing decode, into memory the caller owns.

pub fn decodeBorrowed(comptime T: type, bytes: []const u8, options: Options) Error!T

src

The allocation-free decode: borrow every string, take no allocator, and refuse a repeated field at compile time.

struct DecodeOptions

src
pub const DecodeOptions = @import("decode.zig").Options

Options for decode and its variants.

Fields

validate_utf8: bool = true

Reject bytes in a string field that are not valid UTF-8. Proto3 says a string is UTF-8, and a bytes field is never checked.

pub fn encode(comptime T: type, value: T, options: Options, writer: *Io.Writer) !void

src

Encode one message into a writer.

pub fn encodedSize(comptime T: type, value: T, options: Options) usize

src

The byte count that encode writes for this value.

struct EncodeOptions

src
pub const EncodeOptions = @import("encode.zig").Options

Options for encode.

Fields

write_defaults: bool = false

Write scalar fields that hold their type's zero value. Proto3 parsers read an absent field as its zero, so the default writes fewer bytes and means the same thing. A ?T field that is present is always written.

type fn Parsed

src
pub const Parsed = @import("decode.zig").Parsed

A decoded message and the arena that owns its allocations.

Fields

arena: ArenaAllocator
value: T

Functions

pub fn deinit(self: *Self) void

src

Free the arena.

This does not free the input passed to decodeFromSlice.

module proto

src

The comptime side of the typed layer: a Zig struct read as a message, and the table that says which field is which number.

Functions

pub fn field(number: u32) FieldDescriptor

src

A field whose Zig type says everything: int32 for an i32, uint32 for a u32, float for an f32, and a message or a repeated field straight from the shape. A []const u8 is not enough: say pb.string or pb.bytes.

pub fn string(number: u32) FieldDescriptor

src

A []const u8 checked as UTF-8 on decode.

pub fn bytes(number: u32) FieldDescriptor

src

A []const u8 that is raw bytes.

pub fn sint(number: u32) FieldDescriptor

src

An i32 or i64 written as a zigzag varint: sint32, sint64.

pub fn fixed(number: u32) FieldDescriptor

src

An i32, i64, u32, or u64 written at fixed width: fixed32, sfixed32, fixed64, sfixed64.

pub fn unpacked(number: u32) FieldDescriptor

src

A repeated numeric field written one element per tag, as proto2 does.

pub fn map(number: u32) FieldDescriptor

src

A map<K, V> field. On the wire a map is a repeated entry message with the key in field 1 and the value in field 2, and encode writes exactly that. JSON is where a map differs: the reference mapping writes it as one object, with each key as a member name, so the entry list needs to say it is a map.

more

The element type is a two-field struct at numbers 1 and 2:

const Entry = struct {
    pub const protobuf: Descriptor(@This()) = .{ .key = string(1), .value = field(2) };
    key: []const u8 = "",
    value: i64 = 0,
};
// map<string, int64> attrs = 25;
attrs: []const Entry = &.{},

A key is a string, an integer, or a bool. A value is any singular field.

pub fn oneof() FieldDescriptor

src

A oneof: one field of the message is set at a time, and each case has its own field number.

more

The Zig field is ?U, where U is a union(enum) that declares its own numbers in a pb.Variants(@This()) table:

const Result = union(enum) {
    pub const protobuf: pb.Variants(@This()) = .{
        .ok = pb.field(2),
        .err = pb.string(3),
    };

    ok: u32,
    err: []const u8,
};

const Reply = struct {
    pub const protobuf: pb.Descriptor(@This()) = .{ .result = pb.oneof() };
    result: ?Result = null,
};

A decode sets the case the wire carried and clears the one before it, so the last case on the wire wins. A case that is set is written even when its value is the type's zero.

pub fn hasUnknown(comptime T: type) bool

src

Whether T declares an Unknown field.

pub fn unknownFieldName(comptime T: type) ?[:0]const u8

src

The name of T's Unknown field, or null. More than one is a compile error: two collectors would split the skipped fields between them.

pub fn scalarWireType(comptime scalar: wire.Scalar) wire.WireType

src

The wire type a scalar arrives as.

pub fn scalarPacked(comptime scalar: wire.Scalar) wire.Encoding

src

The packed encoding of a numeric scalar, for the repeated reader.

pub fn elemWireType(elem: Elem) wire.WireType

src

The wire type an element arrives as.

pub fn info(comptime T: type) Info

src

Read T as a message. Everything here is comptime work, so a bad table is a compile error in the code that tried to encode or decode T.

pub fn init(comptime T: type) T

src

A message with every field at its declared default, or at its type's zero where it declares none. Decode starts here, so an absent field lands on the value the schema says it should.

pub fn mapFields(comptime E: type) struct { key: Field, value: Field }

src

The key and value of a map entry message: the fields at numbers 1 and 2. The checks are what the format allows, and they run when the table is read, so a wrong entry type fails at the message, not at the JSON call that reaches it.

pub fn variants(comptime U: type) Info

src

Every case of the oneof union U, in the order it declares them. The checks are the ones info applies to a message, minus the ones a case cannot have: a case is singular, has no presence of its own, and is never a nested oneof.

Types

enum Encoding

src

How a field's bytes are encoded. auto picks the obvious one for the Zig type: int32 for i32, uint32 for u32, float for f32. The others exist because the Zig type cannot say them, and a []const u8 has no obvious one at all.

Fields

auto auto

int32, int64, uint32, uint64, float, double.

string string

[]const u8, checked as UTF-8 on decode.

bytes bytes

[]const u8, raw.

sint sint

sint32, sint64: zigzag varint.

fixed fixed

sfixed32, sfixed64, fixed32, fixed64: little endian, fixed width.

oneof oneof

A oneof: the field is ?U, and each case of the union carries its own number. pb.oneof() selects it, and the number in the entry is unused.

struct FieldDescriptor

src

One field's wire metadata: its number, and the encoding when the Zig type cannot say it. Written as field(2), through a helper for the ambiguous cases, or as a literal when a rarer knob matters.

Fields

number: u32

Field number, from 1 to 2^29-1. A oneof field has no number of its own, so pb.oneof() leaves this at zero.

encoding: Encoding = .auto

How the bytes are encoded; .auto lets the Zig type decide.

@"packed": ?bool = null

Packed repeated encoding, the .proto option. null means packed for a numeric field and per element otherwise, which is what proto3 does. The name is quoted because packed is a Zig keyword.

map: bool = false

A repeated entry message that JSON writes as an object: pb.map(n).

type fn Variants

src
pub fn Variants(comptime U: type) type

The case table for the oneof union U: one FieldDescriptor per case, named exactly like the cases. Descriptor does the same job for a struct, and the same compiler checks apply.

struct Unknown

src

Fields a message did not recognize, kept so that a re-encode writes them back. An older reader then passes a newer message's fields through instead of deleting them.

more

Declare a field of this type; it is not part of Descriptor(T):

const Person = struct {
    pub const protobuf: Descriptor(@This()) = .{ .id = field(1) };
    id: u32 = 0,
    unknown: Unknown = .{},
};

Decode appends one Record per field it skipped, in arrival order. Encode writes them after the declared fields, so their position in the message can change across a round trip. Field order carries no meaning in the format.

The records hold wire values, not bytes, so a len record borrows its payload from the input exactly as a string field does. An unknown field still needs the record array, so a message with this field cannot use decodeBorrowed.

Fields

records: []const Record = &.{}

The fields that had no entry in the message's table.

Types

union Record

src
pub const Record = union(enum)

One unknown field: its number, and its value as it arrived.

Fields

varint: Varint
fixed64: Fixed64
fixed32: Fixed32
len: Len

Types

struct Varint

src

A field number and a raw varint.

Fields

number: u32
value: u64

struct Fixed64

src

A field number and eight little-endian bytes.

Fields

number: u32
value: u64

struct Fixed32

src

A field number and four little-endian bytes.

Fields

number: u32
value: u32

struct Len

src

A field number and a length-delimited payload.

Fields

number: u32
bytes: []const u8

type fn Descriptor

src
pub fn Descriptor(comptime T: type) type

The field-number table for message T: one FieldDescriptor per field of T, named exactly like the fields and with no defaults, so a literal must cover every field and may name no other. The compiler catches a missing entry, a misspelled one, and one of the wrong type.

union Elem

src
pub const Elem = union(enum)

A field's type, or the element type of a repeated field.

Fields

scalar: wire.Scalar

A varint or fixed-width numeric value.

@"enum": type

An enum(i32).

string string

A []const u8 checked as UTF-8.

bytes bytes

A []const u8 with no encoding check.

message: type

A nested message type.

oneof: type

A oneof: the union whose cases each carry a number.

struct Field

src

One field of a message, with everything the wire format needs.

Fields

name: [:0]const u8

The name in the Zig struct, which is this field's name in the table.

number: u32

Field number, from 1 to 2^29-1.

optional: bool

?T: the field can be absent, which is not the same as its default.

repeated: bool

A slice of elements, written as one tag per element or one packed tag.

is_packed: bool

A repeated numeric field written as one packed length-delimited field.

is_map: bool

A repeated entry message that JSON writes as an object: pb.map(n).

type: type

The Zig type of the struct field.

elem: Elem

What one element of the field is.

Functions

pub fn wireType(self: Field) wire.WireType

src

The wire type the encoder writes for this field.

type fn ElemType

src
pub fn ElemType(comptime elem: Elem) type

The Zig type of one element of elem. A singular field is a value of this type, a repeated field is a slice of it, and a ?T field wraps it.

struct Info

src

Every field of a message, in the order the struct declares them.

Fields

fields: []const Field

type fn Descriptor

src
pub const Descriptor = proto.Descriptor

The type of a message's protobuf table. Declare it as pub const protobuf: pb.Descriptor(@This()) = .{ ... }; so the compiler checks the literal against the struct.

struct FieldDescriptor

src
pub const FieldDescriptor = proto.FieldDescriptor

One entry in that table.

Fields

number: u32

Field number, from 1 to 2^29-1. A oneof field has no number of its own, so pb.oneof() leaves this at zero.

encoding: Encoding = .auto

How the bytes are encoded; .auto lets the Zig type decide.

@"packed": ?bool = null

Packed repeated encoding, the .proto option. null means packed for a numeric field and per element otherwise, which is what proto3 does. The name is quoted because packed is a Zig keyword.

map: bool = false

A repeated entry message that JSON writes as an object: pb.map(n).

module json

src

The proto3 JSON mapping of a message: one Descriptor, two encodings.

Constants

pub const base64_std: Base64 = …

src
value
.{
    .encoded_len = stdEncodedLen,
    .encode = stdEncode,
    .decoded_len = stdDecodedLen,
    .decode = stdDecode,
}

std's base64: scalar, and the only implementation in the standard library.

pub const Error = …

src
value
Scanner.AllocError || Allocator.Error || error{
    /// An object key that no field claims, with `ignore_unknown_fields` off.
    UnknownField,
    /// A number that the field's enum has no member for.
    UnknownEnumTag,
    /// A string in a `bytes` field that is not base64.
    InvalidBase64,
    /// A value the field cannot hold: a number out of range, a timestamp that
    /// is not a date, a duration with two signs.
    InvalidValue,
    /// A token in a place the schema does not allow it.
    UnexpectedToken,
    /// A streaming scanner that ran out of buffer. The complete-input scanner
    /// this package uses does not return it.
    BufferUnderrun,
}

Every error a JSON codec returns: the scanner's, the allocator's, and the mapping's own.

Functions

pub fn encode(comptime T: type, value: T, options: Options, writer: *Io.Writer) !void

src

Write value as proto3 JSON.

pub fn decode( comptime T: type, bytes: []const u8, options: Options, gpa: Allocator, ) Error!Parsed(T)

src

Read one JSON message, copying every string and array into an arena. Free the result with Parsed.deinit.

pub fn decodeLeaky(comptime T: type, bytes: []const u8, options: Options, gpa: Allocator) Error!T

src

Read one JSON message into allocations the caller owns. Free them, or pass an allocator that outlives the value.

Types

struct Options

src

Options for encode, decode, and decodeLeaky.

Fields

use_proto_names: bool = false

Write the Zig field names instead of their lowerCamelCase JSON names. The parser accepts either spelling whatever this is set to.

ignore_unknown_fields: bool = false

Accept an object key that no field claims instead of failing with error.UnknownField. The value behind it is skipped.

base64: Base64 = base64_std

The base64 codec for bytes fields. The default is std's, which is scalar: about 60 MB/s on an M-series core. A caller with large payloads passes a vectorized codec; Base64 has the four fields it needs.

struct Base64

src

The base64 codec a JSON pass uses for bytes. Four functions, no state: both std and stdx.base64 fit, and the one selected is the whole of the dependency question.

Fields

encoded_len: *const fn (source_len: usize) usize

The byte count encode writes for source_len input bytes.

encode: *const fn (dest: []u8, source: []const u8) []const u8

Encode source into dest, which holds at least encoded_len(source.len) bytes.

decoded_len: *const fn (source: []const u8) std.base64.Error!usize

The exact byte count decode produces, or why source is not base64.

decode: *const fn (dest: []u8, source: []const u8) std.base64.Error![]const u8

Decode source into dest, which holds at least decoded_len(source) bytes. The result is the bytes written.

type fn Parsed

src
pub const Parsed = decode_mod.Parsed

A decoded message and the arena behind it.

Fields

arena: ArenaAllocator
value: T

Functions

pub fn deinit(self: *Self) void

src

Free the arena.

This does not free the input passed to decodeFromSlice.

module wkt

src

The well-known types: timestamps, durations, wrappers, field masks, and the empty message.

Constants

pub const Error = …

src
value
error{
    /// A timestamp that no RFC 3339 string can express: before year 0001,
    /// after year 9999, or nanos outside 0 to 999 999 999.
    InvalidTimestamp,
    /// A duration beyond 315 576 000 000 seconds, or with a sign that the
    /// seconds and the nanos disagree on.
    InvalidDuration,
}

Errors in the string form of a Timestamp or a Duration.

pub const wrappers = …

src
value
.{
    DoubleValue, FloatValue, Int64Value,  UInt64Value, Int32Value,
    UInt32Value, BoolValue,  StringValue, BytesValue,
}

The nine wrapper types, in the order the protobuf documentation lists them.

Functions

pub fn form(comptime T: type) ?Form

src

The JSON form of T, or null when T is not a well-known type.

pub fn isBytesWrapper(comptime T: type) bool

src

Whether T is the wrapper that holds bytes, whose JSON form is base64 and not a string.

pub fn wrapped(comptime T: type) ?type

src

The value type of a wrapper, or null for any other type.

pub fn writeTimestamp(writer: *Io.Writer, ts: Timestamp) (Error || Io.Writer.Error)!void

src

Write ts as the RFC 3339 string that JSON and the text format use. The caller writes the quotes.

pub fn parseTimestamp(text: []const u8) Error!Timestamp

src

Read the RFC 3339 string that writeTimestamp writes, with a Z or a numeric offset. A string without an offset is not a timestamp.

pub fn writeDuration(writer: *Io.Writer, d: Duration) (Error || Io.Writer.Error)!void

src

Write d as the seconds-and-fraction string that JSON and the text format use: "3.5s". The caller writes the quotes.

pub fn parseDuration(text: []const u8) Error!Duration

src

Read the string that writeDuration writes.

Types

enum Form

src

The JSON form of a well-known type.

Fields

timestamp timestamp

An RFC 3339 string: "2024-04-05T12:00:00Z".

duration duration

Seconds and an optional fraction: "3.5s".

wrapper wrapper

The value the type wraps, with no object around it.

field_mask field_mask

Comma-separated camelCase paths.

empty empty

{}, with nothing in it.

struct Timestamp

src

An instant, google.protobuf.Timestamp.

Fields

seconds: i64 = 0

Seconds from 1970-01-01T00:00:00Z, negative before it.

nanos: i32 = 0

Non-negative, below 1e9.

Constants

pub const protobuf: proto.Descriptor(@This()) = …

src
value
.{
        .seconds = proto.field(1),
        .nanos = proto.field(2),
    }

struct Duration

src

A signed span of time, google.protobuf.Duration.

Fields

seconds: i64 = 0
nanos: i32 = 0

The same sign as seconds, and below 1e9 in magnitude.

Constants

pub const protobuf: proto.Descriptor(@This()) = …

src
value
.{
        .seconds = proto.field(1),
        .nanos = proto.field(2),
    }

struct FieldMask

src

A set of field paths, google.protobuf.FieldMask.

Fields

paths: []const []const u8 = &.{}

Constants

pub const protobuf: proto.Descriptor(@This()) = …

src
value
.{
        .paths = proto.string(1),
    }

struct Empty

src

google.protobuf.Empty: a message with no fields.

Constants

pub const protobuf: proto.Descriptor(@This()) = .{}

src

struct DoubleValue

src

A double with presence, google.protobuf.DoubleValue.

Fields

value: f64 = 0

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.field(1) }

src

struct FloatValue

src

A float with presence, google.protobuf.FloatValue.

Fields

value: f32 = 0

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.field(1) }

src

struct Int64Value

src

An int64 with presence, google.protobuf.Int64Value.

Fields

value: i64 = 0

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.field(1) }

src

struct UInt64Value

src

A uint64 with presence, google.protobuf.UInt64Value.

Fields

value: u64 = 0

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.field(1) }

src

struct Int32Value

src

An int32 with presence, google.protobuf.Int32Value.

Fields

value: i32 = 0

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.field(1) }

src

struct UInt32Value

src

A uint32 with presence, google.protobuf.UInt32Value.

Fields

value: u32 = 0

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.field(1) }

src

struct BoolValue

src

A bool with presence, google.protobuf.BoolValue.

Fields

value: bool = false

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.field(1) }

src

struct StringValue

src

A string with presence, google.protobuf.StringValue.

Fields

value: []const u8 = ""

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.string(1) }

src

struct BytesValue

src

bytes with presence, google.protobuf.BytesValue.

Fields

value: []const u8 = ""

Constants

pub const protobuf: proto.Descriptor(@This()) = .{ .value = proto.bytes(1) }

src

struct Unknown

src
pub const Unknown = proto.Unknown

Fields the decoder did not recognize, kept so a re-encode writes them back.

Fields

records: []const Record = &.{}

The fields that had no entry in the message's table.

Types

union Record

src
pub const Record = union(enum)

One unknown field: its number, and its value as it arrived.

Fields

varint: Varint
fixed64: Fixed64
fixed32: Fixed32
len: Len

Types

struct Varint

src

A field number and a raw varint.

Fields

number: u32
value: u64

struct Fixed64

src

A field number and eight little-endian bytes.

Fields

number: u32
value: u64

struct Fixed32

src

A field number and four little-endian bytes.

Fields

number: u32
value: u32

struct Len

src

A field number and a length-delimited payload.

Fields

number: u32
bytes: []const u8

pub fn field(number: u32) FieldDescriptor

src

A field whose Zig type says everything: pb.field(2).

pub fn string(number: u32) FieldDescriptor

src

A []const u8 checked as UTF-8.

pub fn bytes(number: u32) FieldDescriptor

src

A []const u8 that is raw bytes.

pub fn sint(number: u32) FieldDescriptor

src

A zigzag varint: sint32, sint64.

pub fn fixed(number: u32) FieldDescriptor

src

A fixed-width integer: fixed32, sfixed32, fixed64, sfixed64.

pub fn unpacked(number: u32) FieldDescriptor

src

A repeated numeric field written one element per tag.

pub fn map(number: u32) FieldDescriptor

src

A map<K, V>: a repeated entry message on the wire, one JSON object.

pub fn oneof() FieldDescriptor

src

A oneof: a ?U field whose union cases each carry their own number.

type fn Variants

src
pub const Variants = proto.Variants

The case table for a oneof union, the way Descriptor is the table for a message struct.

module Reader

src

Reads one field at a time from an Io.Reader.

Functions

pub fn init(reader: *Io.Reader) Reader

src

Read from reader, with no message bound.

pub fn next(self: *Reader) !?Field

src

Read the next field, or return null if at end of message.

Types

union Field

src
pub const Field = union(enum)

A protobuf field, tagged by wire type.

Fields

varint: Varint
fixed64: Fixed64
len: Len
fixed32: Fixed32

Constants

pub const Kind = meta.Tag(Field)

src

The tag of a Field arm.

Functions

pub fn wireType(self: Field) wire.WireType

src

The wire type this field arrived as.

pub fn fieldNumber(self: Field) u32

src

Get the field number regardless of wire type.

pub fn as(self: Field, comptime scalar: Scalar) Scalar.Type(scalar)

src

Get the payload as a specific scalar type.

pub fn expect(self: Field, comptime kind: Kind) Payload(kind)

src

Assert the wire type and return the payload.

Types

type fn Payload

src
pub fn Payload(comptime kind: Kind) type

The payload type of kind.

struct Varint

src

Varint field payload.

Fields

field_number: u32

The field number from the tag.

value: u64

The raw varint bits, before a scalar interpretation.

Functions

pub fn as(self: Varint, comptime scalar: Scalar) Scalar.Type(scalar)

src

Interpret as a specific scalar type.

struct Fixed64

src

Fixed64 field payload.

Fields

field_number: u32

The field number from the tag.

value: u64

The little-endian 64-bit payload.

Functions

pub fn as(self: Fixed64, comptime scalar: Scalar) Scalar.Type(scalar)

src

Interpret as a specific scalar type.

struct Fixed32

src

Fixed32 field payload.

Fields

field_number: u32

The field number from the tag.

value: u32

The little-endian 32-bit payload.

Functions

pub fn as(self: Fixed32, comptime scalar: Scalar) Scalar.Type(scalar)

src

Interpret as a specific scalar type.

struct Len

src

Length-delimited field payload.

Fields

field_number: u32

The field number from the tag.

length: usize

Payload length in bytes.

io: *Io.Reader

The stream the payload will be read from.

parent: ?*Reader = null

The enclosing message, when this field is nested.

Functions

pub fn string(self: Len, buf: []u8) ![]const u8

src

Read as UTF-8 string into the provided buffer. The returned slice points into buf.

pub fn stringAlloc(self: Len, gpa: Allocator) ![]u8

src

Read as UTF-8 string with allocation.

pub fn data(self: Len) ![]const u8

src

Borrow the payload from the reader's buffer, with no copy.

more

Requires the whole payload to be buffered already, which is true for a reader over a complete slice and false for a stream whose payload is larger than the buffer. Returns error.NotBuffered in that case. bytes copies the payload for any reader. The returned slice is valid until the next read from io.

pub fn bytes(self: Len, buf: []u8) ![]u8

src

Read raw bytes into the provided buffer. The returned slice points into buf.

pub fn bytesAlloc(self: Len, gpa: Allocator) ![]u8

src

Read raw bytes with allocation.

pub fn message(self: Len) !Reader

src

Read as embedded message (streaming, no copy). Returns a Reader that reads directly from the parent stream. Decrements parent's remaining since the bytes will be consumed by the nested reader.

pub fn skip(self: Len) !void

src

Skip this field without reading the data.

pub fn repeated( self: Len, comptime T: type, comptime encoding: Encoding, buf: []u8, ) !PackedIterator(T, encoding)

src

Read packed repeated field into buffer, returns iterator.

pub fn repeatedAlloc( self: Len, comptime T: type, comptime encoding: Encoding, gpa: Allocator, ) !PackedRepeated(T, encoding)

src

Read a packed repeated field with allocation.

The result holds the payload and an iterator. Its deinit method frees the payload.

Types

type fn PackedIterator

src
pub fn PackedIterator(comptime T: type, comptime encoding: Encoding) type

Iterator for packed repeated fields.

Fields

data: []const u8

The packed payload, borrowed from the caller's buffer.

pos: usize

The next byte to read.

Functions

pub fn next(self: *Self) !?T

src

Read the next element, or null at the end of the payload.

type fn PackedRepeated

src
pub fn PackedRepeated(comptime T: type, comptime encoding: Encoding) type

Result of repeatedAlloc - holds iterator and allocated data.

Fields

iter: PackedIterator(T, encoding)

The iterator over the allocated payload.

data: []u8

The payload buffer, freed by deinit.

Functions

pub fn deinit(self: *Self, gpa: Allocator) void

src

Free the payload buffer.

module delimited

src

Back-to-back messages on one stream: a varint length, then that many bytes.

Constants

pub const Error = wire.Error

src

Every error a frame can return.

Functions

pub fn encode(comptime T: type, value: T, options: Options, writer: *Io.Writer) !void

src

Write one message as a length and then its bytes.

pub fn encodedSize(comptime T: type, value: T, options: Options) usize

src

Bytes encode writes for this value, length prefix included.

pub fn writeBytes(writer: *Io.Writer, message: []const u8) !void

src

Write already-encoded message bytes as one frame.

Types

struct Options

src
pub const Options = encode_mod.Options

The options encode passes to the encoder.

Fields

write_defaults: bool = false

Write scalar fields that hold their type's zero value. Proto3 parsers read an absent field as its zero, so the default writes fewer bytes and means the same thing. A ?T field that is present is always written.

struct Reader

src

Reads one frame at a time from a stream.

Each next returns a reader bounded to one message. Reading a frame to its end, or calling next again, leaves the stream at the start of the next frame: a caller that stops early does not have to finish reading.

Fields

io: *Io.Reader
frame: Frame

The frame being read, or an empty one before the first next.

started: bool = false

Functions

pub fn init(io: *Io.Reader) Reader

src

Read frames from io.

pub fn next(self: *Reader) Error!?*Frame

src

The next frame, or null when the stream ends exactly at a frame boundary. A length with no payload behind it is error.Truncated.

Types

struct Frame

src

One frame: a Reader bounded to its length, so Reader.next returns null at the end of the message rather than reading into the next frame.

Fields

reader: FieldReader

Functions

pub fn fields(self: *Frame) *FieldReader

src

The fields of this frame. A Reader knows only its own bound, so reading through it keeps the frame's remaining length current.

pub fn remaining(self: *Frame) usize

src

Bytes left in this frame.

pub fn readAll(self: *Frame, buf: []u8) Error![]const u8

src

Read the rest of the frame into buf, which must hold all of it.

pub fn rest(self: *Frame) Error![]const u8

src

The rest of the frame, borrowed from the reader's buffer. Requires the whole frame to be buffered already: true for a reader over a complete slice, false for a stream and a frame larger than its buffer. Returns error.NotBuffered in that case.

pub fn drain(self: *Frame) Error!void

src

Skip what is left of the frame.

union Field

src
pub const Field = Reader.Field

One field from Reader.next.

Fields

varint: Varint
fixed64: Fixed64
len: Len
fixed32: Fixed32

Constants

pub const Kind = meta.Tag(Field)

src

The tag of a Field arm.

Functions

pub fn wireType(self: Field) wire.WireType

src

The wire type this field arrived as.

pub fn fieldNumber(self: Field) u32

src

Get the field number regardless of wire type.

pub fn as(self: Field, comptime scalar: Scalar) Scalar.Type(scalar)

src

Get the payload as a specific scalar type.

pub fn expect(self: Field, comptime kind: Kind) Payload(kind)

src

Assert the wire type and return the payload.

Types

type fn Payload

src
pub fn Payload(comptime kind: Kind) type

The payload type of kind.

struct Varint

src

Varint field payload.

Fields

field_number: u32

The field number from the tag.

value: u64

The raw varint bits, before a scalar interpretation.

Functions

pub fn as(self: Varint, comptime scalar: Scalar) Scalar.Type(scalar)

src

Interpret as a specific scalar type.

struct Fixed64

src

Fixed64 field payload.

Fields

field_number: u32

The field number from the tag.

value: u64

The little-endian 64-bit payload.

Functions

pub fn as(self: Fixed64, comptime scalar: Scalar) Scalar.Type(scalar)

src

Interpret as a specific scalar type.

struct Fixed32

src

Fixed32 field payload.

Fields

field_number: u32

The field number from the tag.

value: u32

The little-endian 32-bit payload.

Functions

pub fn as(self: Fixed32, comptime scalar: Scalar) Scalar.Type(scalar)

src

Interpret as a specific scalar type.

struct Len

src

Length-delimited field payload.

Fields

field_number: u32

The field number from the tag.

length: usize

Payload length in bytes.

io: *Io.Reader

The stream the payload will be read from.

parent: ?*Reader = null

The enclosing message, when this field is nested.

Functions

pub fn string(self: Len, buf: []u8) ![]const u8

src

Read as UTF-8 string into the provided buffer. The returned slice points into buf.

pub fn stringAlloc(self: Len, gpa: Allocator) ![]u8

src

Read as UTF-8 string with allocation.

pub fn data(self: Len) ![]const u8

src

Borrow the payload from the reader's buffer, with no copy.

more

Requires the whole payload to be buffered already, which is true for a reader over a complete slice and false for a stream whose payload is larger than the buffer. Returns error.NotBuffered in that case. bytes copies the payload for any reader. The returned slice is valid until the next read from io.

pub fn bytes(self: Len, buf: []u8) ![]u8

src

Read raw bytes into the provided buffer. The returned slice points into buf.

pub fn bytesAlloc(self: Len, gpa: Allocator) ![]u8

src

Read raw bytes with allocation.

pub fn message(self: Len) !Reader

src

Read as embedded message (streaming, no copy). Returns a Reader that reads directly from the parent stream. Decrements parent's remaining since the bytes will be consumed by the nested reader.

pub fn skip(self: Len) !void

src

Skip this field without reading the data.

pub fn repeated( self: Len, comptime T: type, comptime encoding: Encoding, buf: []u8, ) !PackedIterator(T, encoding)

src

Read packed repeated field into buffer, returns iterator.

pub fn repeatedAlloc( self: Len, comptime T: type, comptime encoding: Encoding, gpa: Allocator, ) !PackedRepeated(T, encoding)

src

Read a packed repeated field with allocation.

The result holds the payload and an iterator. Its deinit method frees the payload.

Types

type fn PackedIterator

src
pub fn PackedIterator(comptime T: type, comptime encoding: Encoding) type

Iterator for packed repeated fields.

Fields

data: []const u8

The packed payload, borrowed from the caller's buffer.

pos: usize

The next byte to read.

Functions

pub fn next(self: *Self) !?T

src

Read the next element, or null at the end of the payload.

type fn PackedRepeated

src
pub fn PackedRepeated(comptime T: type, comptime encoding: Encoding) type

Result of repeatedAlloc - holds iterator and allocated data.

Fields

iter: PackedIterator(T, encoding)

The iterator over the allocated payload.

data: []u8

The payload buffer, freed by deinit.

Functions

pub fn deinit(self: *Self, gpa: Allocator) void

src

Free the payload buffer.

module wire

src

The wire primitives: varints, zigzag, tags, and scalar types.

Constants

pub const Error = …

src
value
error{
    /// Varint encoding exceeds maximum allowed bytes
    VarintTooLong,
    /// Unexpected end of data
    Truncated,
    /// Invalid wire type in tag
    InvalidWireType,
    /// Field number must be >= 1
    InvalidFieldNumber,
    /// Field number too large (max 2^29-1)
    FieldNumberTooLarge,
    /// Wire type doesn't match expected type for operation
    WireTypeMismatch,
    /// Buffer too small for operation
    BufferTooSmall,
    /// Invalid UTF-8 in string field
    InvalidUtf8,
    /// The payload is not already in the reader's buffer, so it cannot be
    /// borrowed without reading it
    NotBuffered,
    /// Underlying I/O read failed
    ReadFailed,
}

Errors that can occur during protobuf operations.

pub const max_varint_len: usize = 10

src

Maximum bytes a varint can occupy (64-bit value).

Functions

pub inline fn readInt(comptime T: type, buffer: *const [@divExact(@typeInfo(T).int.bits, 8)]u8) T

src

Read a fixed-width integer from a little-endian buffer.

pub inline fn writeInt( comptime T: type, buffer: *[@divExact(@typeInfo(T).int.bits, 8)]u8, value: T, ) void

src

Write a fixed-width integer into a little-endian buffer.

pub fn encodeVarint(comptime T: type, value: T, buf: []u8) ![]const u8

src

Encode an integer as a varint into buf. Returns the written slice.

pub fn decodeVarint(comptime T: type, data: []const u8) !struct { T, usize }

src

Decode a varint from a byte slice into the specified integer type. Returns the decoded value and number of bytes consumed.

pub fn readVarintFromIo(io: *Io.Reader, comptime T: type) !struct { T, usize }

src

Read a varint from an Io.Reader. Returns the decoded value and number of bytes consumed.

pub fn zigzagEncode(comptime T: type, value: T) Unsigned(T)

src

Encode a signed integer using ZigZag encoding. Maps signed integers to unsigned so small absolute values have small encodings.

pub fn zigzagDecode(comptime T: type, value: T) Signed(T)

src

Decode a ZigZag-encoded unsigned integer back to signed.

pub fn varintLen(value: anytype) usize

src

Bytes the varint encoding of value occupies, from 1 to 10. Signed values are sign-extended to 64 bits first, the way the writer encodes them.

pub fn scalarLen(comptime scalar: Scalar, value: Scalar.Type(scalar)) usize

src

Bytes the scalar occupies alone, with no tag and no length prefix.

Types

enum WireType

src
pub const WireType = enum(u3)

Protobuf wire types.

Fields

varint varint = 0
fixed64 fixed64 = 1
len len = 2
fixed32 fixed32 = 5

Functions

pub fn format(self: WireType, writer: *Io.Writer) Io.Writer.Error!void

src

Format the wire type by name.

type fn Unsigned

src
pub fn Unsigned(comptime T: type) type

Returns the unsigned integer type with the same bit width as T.

type fn Signed

src
pub fn Signed(comptime T: type) type

Returns the signed integer type with the same bit width as T.

struct Tag

src

A field number and wire type, the two halves of a protobuf tag.

Fields

field_number: u32

The field number, from 1 to 2^29-1.

wire_type: WireType

The wire type that decides the payload encoding.

Functions

pub fn init(field_number: u32, wire_type: WireType) !Tag

src

Create a tag from field number and wire type. Returns error if field_number is invalid (must be 1 to 2^29-1).

pub fn parse(raw: u64) !Tag

src

Parse a tag from its raw encoded form.

pub fn encode(self: Tag) u32

src

Encode the tag to its raw form.

enum Scalar

src

Protobuf scalar types for type-safe field access.

Fields

i32 i32
i64 i64
u32 u32
u64 u64
sint32 sint32
sint64 sint64
bool bool
fixed64 fixed64
sfixed64 sfixed64
double double
fixed32 fixed32
sfixed32 sfixed32
float float

Types

type fn Type

src
pub fn Type(comptime self: Scalar) type

Get the Zig type corresponding to this scalar.

enum Encoding

src

Encoding type for packed repeated fields.

Fields

varint varint

Varint, for int32, int64, uint32, uint64, bool, and enums.

sint sint

Zigzag varint, for sint32 and sint64.

fixed fixed

Little-endian fixed width, for fixed32, sfixed32, float, and the 64-bit forms.

enum WireType

src
pub const WireType = wire.WireType

The four wire types this reader accepts.

Fields

varint varint = 0
fixed64 fixed64 = 1
len len = 2
fixed32 fixed32 = 5

Functions

pub fn format(self: WireType, writer: *Io.Writer) Io.Writer.Error!void

src

Format the wire type by name.

pub const Error = wire.Error

src

Errors from the wire primitives.

struct Tag

src
pub const Tag = wire.Tag

A field number and wire type.

Fields

field_number: u32

The field number, from 1 to 2^29-1.

wire_type: WireType

The wire type that decides the payload encoding.

Functions

pub fn init(field_number: u32, wire_type: WireType) !Tag

src

Create a tag from field number and wire type. Returns error if field_number is invalid (must be 1 to 2^29-1).

pub fn parse(raw: u64) !Tag

src

Parse a tag from its raw encoded form.

pub fn encode(self: Tag) u32

src

Encode the tag to its raw form.

module Writer

src

Builds a message one tag, scalar, or length-delimited value at a time.

Functions

pub fn init(writer: *Io.Writer) Writer

src

Write to writer.

pub fn writeVarint(self: *Writer, comptime T: type, value: T) !void

src

Write a raw varint. Useful when length is known upfront.

pub fn writeTag(self: *Writer, tag: Tag) !void

src

Write a tag (field number + wire type).

pub fn writeScalar(self: *Writer, comptime scalar: Scalar, value: Scalar.Type(scalar)) !void

src

Write a scalar value (no tag).

pub fn writeLen(self: *Writer, value: []const u8) !void

src

Write length-delimited bytes (no tag).