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()) }
}
}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,repeatedand packed fields,oneof,map<K, V>,optional, and all scalar types.import,option,reserved,extendandserviceblocks 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.
bytesare 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 aValueError. - 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:
ProtoWriterhas a method per scalar type (int32,sint64,fixed32,float64,string,bytes, …), plusmessagefor nesting andpackedVarintsandpackedDoubles.ProtoReader.next()moves from field to field (field,wireType); the matching reader takes the value, orskip()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) -> ProtoWriterfn int64(field: int, v: long) -> ProtoWriterfn uint32(field: int, v: long) -> ProtoWriterfn uint64(field: int, v: long) -> ProtoWriterfn sint32(field: int, v: long) -> ProtoWriterfn sint64(field: int, v: long) -> ProtoWriterfn boolean(field: int, v: bool) -> ProtoWriterfn enumValue(field: int, v: int) -> ProtoWriterfn fixed32(field: int, v: long) -> ProtoWriterfn sfixed32(field: int, v: long) -> ProtoWriterfn fixed64(field: int, v: long) -> ProtoWriterfn sfixed64(field: int, v: long) -> ProtoWriterfn float32(field: int, v: double) -> ProtoWriterfn float64(field: int, v: double) -> ProtoWriterfn string(field: int, v: string) -> ProtoWriterfn bytes(field: int, v: Bytes) -> ProtoWriterfn 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() -> intfn 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() -> longfn int32() -> longfn sint() -> longfn boolean() -> boolfn fixed32() -> longfn sfixed32() -> longfn fixed64() -> longfn float32() -> doublefn float64() -> doublefn bytes() -> Bytesfn string() -> stringfn 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: stringjsonName: stringnumber: inttype: string— A scalar type ("int32", "string", ...) or a message or enum's full name.repeated: bool = falsepacked: bool = trueisMap: bool = falsemapKey: 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: stringfields: 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: stringbyNumber: 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) -> boolfn encode(type: string, value: JsonValue) -> Bytes— A message as protobuf bytes, from JSON (typeits 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()