65 lines
2.0 KiB
Markdown
65 lines
2.0 KiB
Markdown
# roto
|
|
|
|
Rust protos without the pointers.
|
|
|
|
The codegen is different; we don't create data structures.
|
|
We mark what where each field is, and only read it when asked.
|
|
The binary blob is never decompressed by the library; it is your
|
|
job to figure out how to store the data if you need to access it
|
|
more than once.
|
|
|
|
And building protos? You use a builder. We don't make some fancy
|
|
structure and give you a marshal function, nah. You give us a blob
|
|
to write data into, and we write what you tell us, no questions asked.
|
|
|
|
### Sample usage
|
|
|
|
```rust
|
|
/*
|
|
message Hello {
|
|
string hello_world = 1;
|
|
message InnerWorld {
|
|
string thought = 1;
|
|
}
|
|
InnerWorld inner_world = 2;
|
|
}
|
|
*/
|
|
|
|
fn parse_proto(data: &[u8]) -> Result<String> {
|
|
// Scans the data, marks where each flag is as an offset
|
|
// into the proto.
|
|
let accessor = HelloProto::new(data)?;
|
|
// Load the hello world string; returns bytes, not
|
|
// a Rust string.
|
|
let hello_world = accessor.hello_world()?;
|
|
// Inspect a nested message; accessing inner_world scans it
|
|
// for flag locations and returns a similiar access struct
|
|
let inner_world = accessor.inner_world()?.thought()?;
|
|
|
|
format!("{} is about {}", hello_world, inner_world)
|
|
}
|
|
```
|
|
|
|
### Sample builder usage
|
|
|
|
```rust
|
|
let mut buf = [0u8; 1024];
|
|
let mut builder = HelloProto::Builder::new(&mut buf)
|
|
.hello_world("some world")
|
|
.inner_world() // Returns an HelloProto::InnerWorld::Builder
|
|
.thought("some thought")
|
|
.done(); // returns the HelloProto::Builder
|
|
let bytes_written = builder.finish()?; // returns the number of bytes written to buffer
|
|
```
|
|
|
|
### High level design
|
|
|
|
The runtime library offers an iterator over the fields in a message, using the protobuf wire format provide
|
|
objects of flag and type. Codegen creates a 'wrapper' that iterates over the message, and records the
|
|
byte offset of each element. Helper methods in the wrapper give the user access to the name fields,
|
|
casted to the appropriate data type.
|
|
|
|
### Literature
|
|
|
|
https://protobuf.dev/programming-guides/encoding/
|