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
每月下载量278次
在 bin-proto 中使用
35KB
878 行
bin-proto
在Rust中实现简单且快速的结构化位级二进制编解码。
是protocol的一个改进和现代化分支。与deku相比,它更高效(但功能略少)。
此crate添加了一个可以在类型上实现的trait(以及一个自定义derive以简化使用),允许结构化数据在任何二进制流中发送和接收。如果您需要位流,建议使用bitstream_io,因为它们的BitRead
和BitWrite
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