Rust 中的简单协议定义
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:
ParcelsCheckout the examples folder for usage.
Add this to your Cargo.toml:
[dependencies]
protocol = { version = "3.4", features = ["derive"] }And then define a type with the #[derive(protocol::Protocol)] attribute:
#[derive(protocol::Protocol)]
struct Hello {
pub a: String,
pub b: u32,
}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::Protocol)] to do this. Note that in order for a type to implement Parcel, it must also implement Clone, Debug, and PartialEq.
#[derive(Parcel, Clone, Debug, PartialEq)]
pub struct Health(f32);
#[derive(Parcel, Clone, Debug, PartialEq)]
pub struct SetPlayerPosition {
pub position: (f32, f32),
pub health: Health,
pub values: Vec,
}Any user-defined type can have the Parcel trait automatically derived.
…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 = "")] attribute.
Supported discriminant types:
string (default)integer#[derive(protocol::Protocol, Clone, Debug, PartialEq)]
#[protocol(discriminant = "string")]
pub enum PlayerState {
Stationary,
Flying { velocity: (f32,f32,f32) },
// Discriminators can be explicitly specified.
#[protocol(discriminator("ArbitraryOverTheWireName"))]
Jumping { height: f32 },
}You can rename the variant for their serialisation.
#[derive(protocol::Protocol, Clone, Debug, PartialEq)]
#[protocol(discriminant = "string")]
pub enum Foo {
Bar,
#[protocol(name = "Biz")] // the Bing variant will be send/received as 'Biz'.
Bing,
Baz,
}暂无开放 Issues,或尚未同步最近议题。