8个版本 (4个重大更新)

0.5.0 2024年7月25日
0.4.2 2024年7月23日
0.4.0 2024年5月18日
0.3.2 2024年5月3日
0.1.0 2024年3月25日

#229 in #bit

Download history 167/week @ 2024-04-29 139/week @ 2024-05-06 398/week @ 2024-05-13 274/week @ 2024-05-20 341/week @ 2024-05-27 288/week @ 2024-06-03 372/week @ 2024-06-10 308/week @ 2024-06-17 48/week @ 2024-06-24 263/week @ 2024-07-22 15/week @ 2024-07-29

每月下载量278次
bin-proto 中使用

MIT 许可协议

35KB
878

bin-proto

crates tests docs.rs license

在Rust中实现简单且快速的结构化位级二进制编解码。

protocol的一个改进和现代化分支。与deku相比,它更高效(但功能略少)。

此crate添加了一个可以在类型上实现的trait(以及一个自定义derive以简化使用),允许结构化数据在任何二进制流中发送和接收。如果您需要位流,建议使用bitstream_io,因为它们的BitReadBitWrite traits在内部使用。

示例

将以下内容添加到您的 Cargo.toml

[dependencies]
bin-proto = "0.4"

然后定义一个具有#[derive(bin_proto::Protocol)] 属性的类型。

use bin_proto::{Protocol, ProtocolNoCtx};

#[derive(Debug, Protocol, PartialEq)]
#[protocol(discriminant_type = "u8")]
#[protocol(bits = 4)]
enum E {
    V1 = 1,
    #[protocol(discriminant = "4")]
    V4,
}

#[derive(Debug, Protocol, PartialEq)]
struct S {
    #[protocol(bits = 1)]
    bitflag: bool,
    #[protocol(bits = 3)]
    bitfield: u8,
    enum_: E,
    #[protocol(write_value = "self.arr.len() as u8")]
    arr_len: u8,
    #[protocol(length = "arr_len as usize")]
    arr: Vec<u8>,
    #[protocol(flexible_array_member)]
    read_to_end: Vec<u8>,
}

assert_eq!(
    S::from_bytes(&[
        0b1000_0000 // bitflag: true (1)
       | 0b101_0000 // bitfield: 5 (101)
           | 0b0001, // enum_: V1 (0001)
        0x02, // arr_len: 2
        0x21, 0x37, // arr: [0x21, 0x37]
        0x01, 0x02, 0x03, // read_to_end: [0x01, 0x02, 0x03]
    ], bin_proto::ByteOrder::BigEndian).unwrap(),
    S {
        bitflag: true,
        bitfield: 5,
        enum_: E::V1,
        arr_len: 2,
        arr: vec![0x21, 0x37],
        read_to_end: vec![0x01, 0x02, 0x03],
    }
);

您可以为您的类型实现Protocol,并使用上下文进行解析

use bin_proto::Protocol;

pub struct Ctx;

pub struct NeedsCtx;

impl Protocol<Ctx> for NeedsCtx {
    fn read(
        _read: &mut dyn bin_proto::BitRead,
        _byte_order: bin_proto::ByteOrder,
        _ctx: &mut Ctx,
    ) -> Result<Self, bin_proto::Error> {
        // Use ctx here
        Ok(Self)
    }

    fn write(
        &self,
        _write: &mut dyn bin_proto::BitWrite,
        _byte_order: bin_proto::ByteOrder,
        _ctx: &mut Ctx,
    ) -> Result<(), bin_proto::Error> {
        // Use ctx here
        Ok(())
    }
}

#[derive(Protocol)]
#[protocol(ctx = "Ctx")]
pub struct WithCtx(NeedsCtx);

WithCtx(NeedsCtx)
    .bytes_ctx(bin_proto::ByteOrder::LittleEndian, &mut Ctx)
    .unwrap();

性能/替代方案

此crate的主要替代方案是deku,以及用于字节级协议的binrw

bin-proto 在所有测试场景中都显著快于 deku。下表中的单位是 ns/iter,来源于 github CI。您可以在 bench 目录下找到基准测试。

读取 枚举 写入 枚举 读取 Vec 写入 Vec 读取 IPv4 头部 写入 IPv4 头部
bin-proto 21 93 738 821 151 141
deku 67 227 3,041 9,705 2,468 821

路线图

以下功能计划实现

  • 位/字节对齐
  • no_std 支持(仅在 bitstream_io 支持 no_std 后)

依赖项

~1.5MB
~35K SLoC