protocol
Easy protocol definitions in Rust.
This crate adds a custom derive that can be added to types, allowing structured data to be sent and received from any IO stream.
Networking is built-in, with special support for TCP and UDP.
The protocol you define can be used outside of networking too - see the Parcel::from_raw_bytes
and Parcel::raw_bytes
methods.
This crate also provides:
- TCP and UDP modules for easy sending and receiving of
Parcel
s - A generic middleware library for automatic transformation of sent/received data
- Middleware has already been written to support compression
- Custom middleware can be implemented via a trait with two methods
Checkout the examples folder for usage.
Usage
Add this to your Cargo.toml
:
[]
= { = "3.4", = ["derive"] }
And then define a type with the #[derive(Protocol)]
attribute:
Under the hood
The most interesting part here is the protocol::Parcel
trait. Any type that implements this trait can then be serialized to and from a byte stream. All primitive types, standard collections, tuples, and arrays implement this trait.
This crate becomes particularly useful when you define your own Parcel
types. You can use #[derive(Protocol)]
to do this. Note that in order for a type to implement Parcel
, it must also implement Clone
, Debug
, and PartialEq
.
;
Custom derive
Any user-defined type can have the Parcel
trait automatically derived.
Example
extern crate protocol_derive;
extern crate protocol;
;
Enums
Discriminators
Enum values can be transmitted either by their 1-based variant index, or by transmitting the string name of each variant.
NOTE: The default behaviour is to use the variant name as a string (string
).
This behaviour can be changed by the #[protocol(discriminant = "<type>")]
attribute.
Supported discriminant types:
string
(default)- This transmits the enum variant name as the over-the-wire discriminant
- This uses more bytes per message, but it very flexible
integer
- This transmits the 1-based variant number as the over-the-wire discriminant
- If enum variants have explicit discriminators, the
- Enum variants cannot be reordered in the source without breaking the protocol
Misc
You can rename the variant for their serialisation.