Macros for convenient serialization of Rust data structures into/from Protocol Buffers.
Introduction
This is a fork of exonum-derive with some changes to allow easier integration with other projects, and some new features.
Usage
First, add the dependency in Cargo.toml:
protobuf-convert = "0.1.0"
Then, define a ProtobufConvert trait:
And to use it, import the trait and the macro:
For example, given the following protobuf:
message Ping {
fixed64 nonce = 1;
}
rust-protobuf will generate the following struct:
We may want to convert that struct into a more idiomatic one, and derive more traits. This is the necessary code:
// Import trait
use crateProtobufConvert;
// Import macro
use ProtobufConvert;
// Import module autogenerated by protocol buffers
use crateschema;
Note that the ProtobufConvert trait must be implemented for all the fields,
see an example implementation for u64:
Now, converting between Ping and schema::Ping can be done effortlessly.
Enum support
A more complex example, featuring enums:
message Ping {
fixed64 nonce = 1;
}
message Pong {
fixed64 nonce = 1;
}
message Message {
oneof kind {
Ping Ping = 1;
Pong Pong = 2;
}
}
And it just works!
Skipping fields
This macro also supports skipping fields in structs so they are ignored when serializing, i.e they will not be mapped to any field in the schema:
Note that you can only skip fields whose type implements the Default trait.