Crate pbf_core

Source
Expand description

The pbf Rust crate provides functionalities to read and write Protocol Buffers (protobuf) messages. This crate is a 0 dependency package that uses no_std and is intended to be used in embedded systems and WASM applications. The crate is designed to be small and efficient, with the cost of some features and flexibility. It is up to the user to create the necessary data structures and implement the ProtoRead and ProtoWrite traits in order to use it effectively.

§Usage

use pbf_core::{ProtoRead, ProtoWrite, Protobuf, Field, Type};

#[derive(Default)]
struct TestMessage {
    a: i32,
    b: String,
}
impl TestMessage {
    fn new(a: i32, b: &str) -> Self {
        TestMessage { a, b: b.to_owned() }
    }
}
impl ProtoWrite for TestMessage {
    fn write(&self, pb: &mut Protobuf) {
        pb.write_varint_field(1, self.a);
        pb.write_string_field(2, &self.b);
    }
}
impl ProtoRead for TestMessage {
    fn read(&mut self, tag: u64, pb: &mut Protobuf) {
        println!("tag: {}", tag);
        match tag {
            1 => self.a = pb.read_varint(),
            2 => self.b = pb.read_string(),
            _ => panic!("Invalid tag"),
        }
    }
}

let mut pb = Protobuf::new();
let msg = TestMessage::new(1, "hello");
pb.write_fields(&msg);

let bytes = pb.take();
let mut pb = Protobuf::from_input(bytes);

let mut msg = TestMessage::default();
pb.read_fields(&mut msg, None);
assert_eq!(msg.a, 1);
assert_eq!(msg.b, "hello");

Re-exports§

pub use bit_cast::*;

Modules§

bit_cast
All encoding and decoding is done via u64. So all types must implement this trait to be able to be encoded and decoded.

Structs§

Field
The Field struct contains a tag and a type. The tag is used to track the data type in the message for decoding. The type is used to determine how to encode and decode the field.
Protobuf
The Protobuf struct is used to read and write protobuf messages.

Enums§

Type
The Type enum represents the different types that a field can have in a protobuf message. The Type enum is used to determine how to encode and decode the field.

Traits§

ProtoRead
The ProtoRead trait is used to read a protobuf message. This crate forces the user to implement this trait in order to read a protobuf message.
ProtoWrite
The ProtoWrite trait is used to write a protobuf message. This crate forces the user to implement this trait in order to write a protobuf message.

Functions§

zagzig
convert an unsigned integer to a signed integer using zigzag decoding.
zigzag
convert a signed integer to an unsigned integer using zigzag encoding.