#derive #send #networking #read #write #macro #marshall

bytebuff

该组件提供有用的 derive 宏,用于将数据序列化以通过网络发送

2 个版本

0.1.1 2020 年 10 月 15 日
0.1.0 2020 年 10 月 12 日

148#send

MIT 许可证

13KB
238 代码行

此组件纯粹用于将数据 marshalling 和 unmarshalling 以通过网络发送,主要处理的是 ByteBuff,它用于序列化和反序列化。还可以在结构体上派生 Marshal 特性。

示例

extern crate bytebuff;
use bytebuff::marshall_derive::Marshall;
use bytebuff::Marshall;
use bytebuff::ByteBuff;

#[derive(Marshall)]
struct Point {
    x: f32,
    y: f32,
}

#[derive(Marshall)]
struct Dummy {
    #[marshall(nested)]
    position: Point,
    name: String,
    #[marshall(ignore)]
    useless_stuff: i128,
}

fn main() {
    let mut buff = ByteBuff::new();

    let dummy = Dummy {
        useless_stuff: 10,
        position: Point { x: 10.0, y: 70.0 },
        name: String::from("Mlokogrgel"),
    };

    //dummy can write it self to ByteBuff
    dummy.marshall(&mut buff);

    //now imagine we sent buffer with dummy over the network
    let mut buff = ByteBuff::from_bytes(buff.data());

    //and dummy can also read its self from buffer
    let de_dummy = Dummy::unmarshall(&mut buff).unwrap();

    //ignored data don't ewen get written to buffer in first place and is replaced
    //by default, in any case you can always implement Default trait to your types
    assert_eq!(de_dummy.useless_stuff, Default::default());

    //you can nest how match you want as long as you annotate so
    assert_eq!(10.0, de_dummy.position.x);
    assert_eq!(70.0, de_dummy.position.y);

    // other then all numbers, strings, booleans and bite vectors are supported
    assert_eq!(String::from("Mlokogrgel"), de_dummy.name);
}

依赖项

~1.5MB
~36K SLoC