Grav v1.14.0

protobuf

import "std/data" (included in import "std") · namespace std.data

Protocol Buffers: messages encoded and decoded from a .proto schema as JSON values, with no code generation, and the wire format read and written field by field.

grav
import "std"

fn main() {
    let schema = ProtoSchema.parse("""
        syntax = "proto3";
        package shop;
        message Order {
          string id = 1;
          enum Status { PENDING = 0; PAID = 1; SHIPPED = 2; }
          Status status = 2;
          message Line { string sku = 1; int32 qty = 2; double price = 3; }
          repeated Line lines = 3;
          map<string, string> tags = 4;
        }
        """)
    let order = Json.parse("{\"id\": \"INV-42\", \"status\": \"PAID\", \"lines\": [{\"sku\": \"TEA\", \"qty\": 2, \"price\": 2.5}], \"tags\": {\"channel\": \"web\"}}")
    let bytes = schema.encode("Order", order)
    print("${bytes.size()} bytes (JSON: ${order.toJson().length})")
    print(bytes.toHex())
    print(schema.decode("shop.Order", bytes).toJson())

    let w = new ProtoWriter().string(1, "Ada").int32(2, 150).packedVarints(3, [1, 2, 3])
    let r = new ProtoReader(w.toBytes())
    while (r.next()) {
        if (r.field == 1) { print(r.string()) }
        else if (r.field == 2) { print(r.varint()) }
        else { print(r.packedVarints()) }
    }
}
Output
44 bytes (JSON: 100)
0a06494e562d343210011a100a035445411002190000000000000440220e0a076368616e6e656c1203776562
{"id":"INV-42","status":"PAID","lines":[{"sku":"TEA","qty":2,"price":2.5}],"tags":{"channel":"web"}}
Ada
150
[1, 2, 3]
  • Schemas: ProtoSchema.parse(source) reads proto2 and proto3 files: packages, nested messages and enums, repeated and packed fields, oneof, map<K, V>, optional, and all scalar types. import, option, reserved, extend and service blocks are read and ignored. add(source) adds another file's types to the same schema. Type names resolve from the inner scope outward, as protoc does. Messages are found by full name (shop.Order) or by the end of it (Order).
  • JSON mapping: field names stay as declared, and camelCase is accepted on input. Enums are their names. bytes are Base64. 64-bit integers are numbers. Maps are objects. A proto3 field holding its default is left out on encoding, and absent fields are not filled in on decoding. Unknown fields in the input bytes are skipped; unknown JSON keys are a ValueError.
  • Output is byte-for-byte what Google's protobuf libraries produce. Fields are written in number order and repeated scalars packed in proto3. Tests compare it with the python-protobuf runtime.
  • The wire format: ProtoWriter has a method per scalar type (int32, sint64, fixed32, float64, string, bytes, …), plus message for nesting and packedVarints and packedDoubles. ProtoReader.next() moves from field to field (field, wireType); the matching reader takes the value, or skip() passes it. message() reads a nested message in place, without copying it.
  • gRPC framing will build on this.

API

class ProtoWriter

Builds a message in the protobuf wire format, field by field.

Constructors

  • new ProtoWriter()

Methods

  • fn int32(field: int, v: long) -> ProtoWriter
  • fn int64(field: int, v: long) -> ProtoWriter
  • fn uint32(field: int, v: long) -> ProtoWriter
  • fn uint64(field: int, v: long) -> ProtoWriter
  • fn sint32(field: int, v: long) -> ProtoWriter
  • fn sint64(field: int, v: long) -> ProtoWriter
  • fn boolean(field: int, v: bool) -> ProtoWriter
  • fn enumValue(field: int, v: int) -> ProtoWriter
  • fn fixed32(field: int, v: long) -> ProtoWriter
  • fn sfixed32(field: int, v: long) -> ProtoWriter
  • fn fixed64(field: int, v: long) -> ProtoWriter
  • fn sfixed64(field: int, v: long) -> ProtoWriter
  • fn float32(field: int, v: double) -> ProtoWriter
  • fn float64(field: int, v: double) -> ProtoWriter
  • fn string(field: int, v: string) -> ProtoWriter
  • fn bytes(field: int, v: Bytes) -> ProtoWriter
  • fn message(field: int, m: ProtoWriter) -> ProtoWriter — A nested message (written by its own ProtoWriter).
  • fn packedVarints(field: int, values: Array<long>, zigzag: bool = false) -> ProtoWriter — A packed repeated field of varints (int32, int64, uint, bool, enum); zigzag for sint.
  • fn packedDoubles(field: int, values: Array<double>) -> ProtoWriter — A packed repeated field of doubles.
  • fn toBytes() -> Bytes — The message so far.
  • fn size() -> int
  • fn tag(field: int, wire: int) — A field's key: (field << 3) | wire type.
  • fn varint(v: long) — A raw varint.

class ProtoReader

Reads a message in the wire format: next() moves to each field in turn, then one of the readers takes its value (or skip() passes it).

Constructors

  • new ProtoReader(data: Bytes, start: int = 0, end: int = -1)

Fields

  • field: int = 0 — The current field's number and wire type (0 varint, 1 64-bit, 2 length-delimited, 5 32-bit).
  • wireType: int = 0

Methods

  • fn next() -> bool — Moves to the next field; false at the end.
  • fn varint() -> long
  • fn int32() -> long
  • fn sint() -> long
  • fn boolean() -> bool
  • fn fixed32() -> long
  • fn sfixed32() -> long
  • fn fixed64() -> long
  • fn float32() -> double
  • fn float64() -> double
  • fn bytes() -> Bytes
  • fn string() -> string
  • fn message() -> ProtoReader — A nested message, read by a reader of its own (no copy).
  • fn packedVarints(zigzag: bool = false) -> Array<long> — A packed repeated field of varints (zigzag-decoded for sint).
  • fn skip() — Passes over the current field's value.
  • fn remaining() -> int — Bytes left to read.
  • fn rawVarint() -> long

class ProtoField

A field of a message type.

Constructors

  • new ProtoField(name: string, number: int, type: string)

Fields

  • name: string
  • jsonName: string
  • number: int
  • type: string — A scalar type ("int32", "string", ...) or a message or enum's full name.
  • repeated: bool = false
  • packed: bool = true
  • isMap: bool = false
  • mapKey: string = ""
  • mapValue: string = ""
  • explicit: bool = false — In a oneof, or marked optional: written even when it holds the default.

class ProtoMessageType

Constructors

  • new ProtoMessageType(name: string, proto3: bool)

Fields

  • name: string
  • fields: Array<ProtoField> = new Array<ProtoField>()
  • byNumber: HashMap<int, ProtoField> = new HashMap<int, ProtoField>()
  • byName: HashMap<string, ProtoField> = new HashMap<string, ProtoField>()
  • proto3: bool

Methods

  • fn add(f: ProtoField) — Keeps fields in number order: messages are written that way, as protoc's code does.

class ProtoEnumType

Constructors

  • new ProtoEnumType(name: string)

Fields

  • name: string
  • byNumber: HashMap<long, string> = new HashMap<long, string>()
  • byName: HashMap<string, long> = new HashMap<string, long>()

class ProtoSchema

The messages and enums of one or more .proto files.

Constructors

  • new ProtoSchema()

Static members

  • static fn parse(source: string) -> ProtoSchema — A schema from .proto source; ValueError (with the line) when it does not parse.
  • static fn isScalar(t: string) -> bool

Methods

  • fn add(source: string) -> ProtoSchema — Adds another file's types (for imports: add the imported file first or after).
  • fn messageNames() -> Array<string> — The full names of the message types ("pkg.Person", "pkg.Person.Address").
  • fn hasMessage(name: string) -> bool
  • fn encode(type: string, value: JsonValue) -> Bytes — A message as protobuf bytes, from JSON (type its full or short name).
  • fn decode(type: string, data: Bytes) -> JsonValue — Protobuf bytes as JSON.
  • fn defineMessage(m: ProtoMessageType)
  • fn defineEnum(e: ProtoEnumType)
  • fn want(f: ProtoField, scope: string)

class ProtoParser

Reads .proto source into a ProtoSchema.

Constructors

  • new ProtoParser(source: string, schema: ProtoSchema)

Methods

  • fn file()

Edit this page on GitHub