forked from DawnMagnet/binproto
16 KiB
16 KiB
BinProto 详细教程 (中文)
目录
介绍
什么是 BinProto?
BinProto 是一个位粒度(bit-level)的跨语言数据交换协议编译器。它能够:
- 通过自定义 DSL(领域特定语言)描述二进制数据结构
- 为多种编程语言(Rust、C/C++、Python)自动生成序列化/反序列化代码
- 支持精确的位级别布局控制,不浪费任何内存
- 确保跨语言数据一致性
核心特性
| 特性 | 说明 |
|---|---|
| 位级精度 | 支持 1-128 位的整数类型,可精确控制每个比特 |
| 多语言支持 | 自动生成 Rust、C/C++、Python 代码 |
| 嵌套结构 | 支持结构体嵌套、数组、动态数组 |
| 类型系统 | 有符号整数 (i1-i128)、无符号整数 (u1-u128)、字符类型 |
| 跨平台 | 统一字节序处理,确保不同平台兼容 |
应用场景
- 网络协议:定义报文头、数据包结构
- 二进制文件格式:如图像、音频格式定义
- 硬件通信:嵌入式设备与上位机数据交换
- 游戏开发:网络同步、存档文件格式
- 物联网:资源受限设备的高效编码
安装与环境配置
前置要求
- 操作系统:Linux、macOS 或 Windows
- Rust:版本 1.70+(如果从源码编译)
- 编译器:gcc/clang(用于生成的 C/C++ 代码)
- Python:3.8+(用于生成的 Python 代码)
从源码编译
# 克隆仓库
1. 尝试编写自己的 `.binproto` schema
cd binproto
# 编译项目
cargo build --release
# 添加到 PATH(可选)
export PATH="$PATH:$(pwd)/target/release"
验证安装
binproto --version # 显示版本信息
binproto --help # 查看帮助信息
基础概念
1. 类型系统
原始类型
BinProto 支持以下原始类型:
有符号整数:i1, i2, ..., i128
- 使用二进制补码表示
- 范围:
-2^{n-1}到2^{n-1}-1 - 例:
i8范围为 -128 到 127
无符号整数:u1, u2, ..., u128
- 范围:
0到2^n - 1 - 例:
u8范围为 0 到 255
字符类型:char
- 占用 8 位(1 字节)
- UTF-8 编码的单个字符
类型示例
u4 // 4 位无符号整数,范围 0-15
i8 // 8 位有符号整数,范围 -128-127
u16 // 16 位无符号整数
char // 字符类型
2. 结构体与字段(类型前置语法)
结构体是多个字段的集合。BinProto 采用类型前置语法:
- 单字段:
类型 字段名 - 多字段同类型:
类型 名1, 名2 - 数组:
类型[表达式] 字段名或类型 名1, 名2[表达式]
struct packet_header {
u4 version // 4 位版本号
u4 flags // 4 位标志位
u16 sequence_no // 16 位序列号
u32 timestamp // 32 位时间戳
}
3. 数组
BinProto 支持两种数组:
固定大小数组
u8[4] bytes // 4 个 u8 元素的数组
i32[10] values // 10 个 i32 元素的数组
动态数组
使用同一结构体中的另一字段来指定数组长度:
struct message {
u8 length // 长度字段
u8[length] payload // 动态数组,长度由 length 指定
}
也支持将数组后缀写在类型与名字之间:
item[count] items
4. 嵌套结构体
一个结构体可以包含其他结构体作为字段类型:
struct point {
u8 x
u8 y
}
struct rectangle {
point top_left // 嵌套 point 结构体
u8 width
u8 height
}
5. 内存布局
BinProto 采用位连续布局(bit-packing),即:
- 字段按声明顺序逐位填充
- 不插入对齐填充
- 支持任意位宽
示例:
struct example {
u3 a // 比特 0-2
u5 b // 比特 3-7
u8 c // 比特 8-15
}
// 总大小:2 字节(16 位)
DSL 语法详解
文件结构
.binproto 文件的基本语法:
// 这是注释,使用 // 开头
struct struct_name {
type field
type field1, field2
type[size] field
}
语法规则(类型前置)
1. 结构体定义
struct name {
// 字段定义
}
规则:
- 结构体名必须以字母或下划线开头
- 大小写敏感
- 花括号中包含零个或多个字段
2. 字段声明
type name
type name1, name2
type[size] name
type name1, name2[size]
规则:
- 字段名不能重复
- 类型必须是已定义的原始类型或结构体
- 允许用逗号在同一行声明多个同类型字段
- 数组后缀既可跟在类型后,也可跟在字段名后(语义相同,建议统一风格)
示例:
struct status {
u8 id // 单个字段
u8 flags
u8 x, y // 多个同类型字段
u16 count
u8[count] data // 动态数组
u16[3] matrix // 固定数组
}
3. 数组表达式
固定大小:
u8[32] data // 32 个 u8 元素
动态大小:
u8[payload_len] payload // 长度由 payload_len 字段指定
支持简单表达式:
u32[N*2] items
u8[count+1] blocks
4. 注释
// 单行注释,从 // 开始到行尾
struct example {
// 结构体注释
u8 field // 字段注释
}
类型兼容性
- 不同大小的整数类型不兼容
- 有符号与无符号类型不兼容
- 结构体名在作用域内必须唯一
快速开始示例
示例 1:简单结构体
步骤 1:创建 DSL 文件 simple.binproto
struct sensor_reading {
u8 sensor_id
i16 temperature
u8 humidity
u32 timestamp
}
步骤 2:编译为 Rust
binproto compile simple.binproto --lang rust --out ./generated
步骤 3:查看生成的代码(节选)
#[derive(Debug, Clone)]
pub struct SensorReading {
pub sensor_id: u8,
pub temperature: i16,
pub humidity: u8,
pub timestamp: u32,
}
impl SensorReading {
pub fn bitsize() -> usize { 56 } // 7 字节 = 56 比特
pub fn bytesize() -> usize { 7 }
pub fn to_byte_array(&self) -> Vec<u8> { /* ... */ }
pub fn from_byte_array(bytes: &[u8]) -> Result<Self, _> { /* ... */ }
}
步骤 4:在项目中使用
use binproto::SensorReading;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let reading = SensorReading {
sensor_id: 1,
temperature: 25,
humidity: 60,
timestamp: 1699200000,
};
// 编码为字节数组
let bytes = reading.to_byte_array();
println!("Encoded: {:?}", bytes);
// 从字节数组解码
let decoded = SensorReading::from_byte_array(&bytes)?;
println!("Decoded: {:?}", decoded);
Ok(())
}
示例 2:嵌套结构与动态数组
DSL 定义(network_packet.binproto):
struct ipv4_header {
u4 version
u4 ihl
u6 dscp
u2 ecn
u16 total_length
u16 identification
u3 flags
u13 fragment_offset
u8 ttl
u8 protocol
u16 checksum
u32 src_ip
u32 dst_ip
}
struct ethernet_frame {
u8[6] dest_mac
u8[6] src_mac
u16 eth_type
u16 payload_len
u8[payload_len] payload
}
编译与使用:
binproto compile network_packet.binproto --lang rust --out ./gen_net
fn main() -> Result<(), Box<dyn std::error::Error>> {
let frame = EthernetFrame {
dest_mac: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
src_mac: [0x00, 0x11, 0x22, 0x33, 0x44, 0x55],
eth_type: 0x0800,
payload_len: 4,
payload: vec![0xDE, 0xAD, 0xBE, 0xEF],
};
let bytes = frame.to_byte_array();
let restored = EthernetFrame::from_byte_array(&bytes)?;
println!("Frame size: {} bytes", bytes.len());
Ok(())
}
进阶用法
1. 复杂的字段表达式
动态数组与计算:
struct variable_buffer {
u4 flags
u4 data_blocks
u16 block_size
u8[data_blocks * block_size] data
}
2. 位级精度控制
紧凑位字段:
struct packed_flags {
u1 enabled // 1 比特
u1 read_only // 1 比特
u1 compressed // 1 比特
u1 encrypted // 1 比特
u4 version // 4 比特
// 总计 8 比特 = 1 字节
}
不对齐数据:
struct misaligned_data {
u7 magic // 7 比特魔数
u3 type_id // 3 比特类型
u6 padding // 6 比特填充
u10 checksum // 10 比特校验和
u32 payload // 32 比特有效负载
// 总计 58 比特
}
3. 大型结构体组合
struct gps_reading {
i32 latitude // 32 比特
i32 longitude // 32 比特
i16 altitude // 16 比特
u8 accuracy // 8 比特
u32 timestamp // 32 比特
}
struct gps_batch {
u32 batch_id
u16 count
gps_reading[count] readings
}
4. 与文件交互
// 写入文件
reading.to_file("data.bin")?;
// 从文件读取
let loaded = SensorReading::from_file("data.bin")?;
跨语言编译
Rust 生成
binproto compile schema.binproto --lang rust --out ./rust_gen
特点:
- 生成符合 Rust idiom 的
struct - 支持
Result<T>错误处理 - 可选的 serde 序列化特性
使用:
let data = MyStruct { /* ... */ };
let bytes = data.to_byte_array();
data.to_file("output.bin")?;
C++ 生成
binproto compile schema.binproto --lang cpp --out ./cpp_gen
特点:
- 生成
#pragma pack(1)结构体 - 包含编码/解码函数
- 使用
std::vector<uint8_t>
使用:
MyStruct data;
data.field = value;
std::vector<uint8_t> bytes = data.encode();
MyStruct restored = MyStruct::decode(bytes);
Python 生成
binproto compile schema.binproto --lang python --out ./python_gen
特点:
- 生成
@dataclass类 - 使用 bitarray 或纯 Python 实现
- 完全类型注解
使用:
from generated.schema import MyStruct
data = MyStruct(field1=10, field2=20)
bytes_data = data.to_bytes()
restored = MyStruct.from_bytes(bytes_data)
多语言同时编译
binproto compile schema.binproto \
--lang rust,cpp,python \
--out ./generated
输出:
- generated/rust/ - Rust 代码
- generated/cpp/ - C/C++ 代码
- generated/python/ - Python 代码
输出 AST(中间表示)
binproto compile schema.binproto --emit ast --out ./ast.json
常见问题与解决方案
Q1:字段为什么不按字节对齐?
BinProto 支持位级精度,字段无需按字节对齐。例如:
struct misaligned {
u3 a // 3 位
u5 b // 5 位
u8 c // 8 位
}
// 总大小:16 位 = 2 字节
Q2:如何处理可变长度数据?
使用动态数组,并声明长度字段:
struct message {
u8 msg_len
char[msg_len] message
}
Q3:不同平台间字节序如何处理?
BinProto 默认使用小端序(Little-Endian),跨语言生成代码保持一致。
Q4:能否在一个结构体中使用另一个结构体?
可以,这就是嵌套结构体:
struct inner { u16 value }
struct outer {
inner header
u32 data
}
Q5:生成的 Rust 代码支持 serde 吗?
支持,可选开启后自动派生 Serialize/Deserialize。
Q6:如何验证生成代码的正确性?
cargo test --test rust_generator
cargo test --test cpp_generator
cargo test --test python_generator
Q7:DSL 有大小限制吗?
没有硬性限制。建议对大型 schema 拆分模块以提升可读性。
最佳实践
1. 命名约定
// ✓ 好的命名
struct packet_header {
u32 source_addr
u32 dest_addr
u16 payload_len
}
// ✗ 不好的命名
struct ph {
u32 sa
u32 da
u16 pl
}
2. 文档化
// GPS 定位数据结构
// 每个读数包含纬度、经度和时间戳
struct gps_reading {
// 十进制度数 * 1000000,范围 [-180M, 180M]
i32 latitude
// 十进制度数 * 1000000,范围 [-90M, 90M]
i32 longitude
// Unix 时间戳(秒)
u32 timestamp
}
3. 版本管理
struct message {
u4 version // 协议版本,便于兼容性管理
u4 message_type
}
4. 错误处理
match MyStruct::from_byte_array(&bytes) {
Ok(data) => println!("Decoded: {:?}", data),
Err(e) => eprintln!("Decode failed: {}", e),
}
5. 性能优化
// ✓ 优化的
struct flags {
u1 enabled
u2 priority
u5 reserved
}
// ✗ 浪费空间
struct flags {
u8 enabled
u8 priority
u8 reserved
}
6. 跨语言测试
#[test]
fn test_roundtrip() {
let original = MyStruct { /* ... */ };
let bytes = original.to_byte_array();
let decoded = MyStruct::from_byte_array(&bytes).unwrap();
assert_eq!(original, decoded);
}
7. 模块化 DSL
schemas/
├── core.binproto # 基础类型
├── network.binproto # 网络相关
└── application.binproto # 应用层
完整工作流示例
项目结构:
my_project/
├── Cargo.toml
├── schemas/
│ └── protocol.binproto
├── src/
│ ├── main.rs
│ └── generated/
│ └── protocol.rs
└── tests/
└── integration_test.rs
步骤 1:定义 Schema(类型前置)
struct command {
u8 cmd_id
u4 param_count
u2 priority
u2 reserved
u16 timeout
}
struct response {
u8 status
u16 data_len
u8[data_len] data
}
步骤 2:编译 Schema
cargo run --bin binproto -- \
compile schemas/protocol.binproto \
--lang rust \
--out src/generated
步骤 3:在项目中使用
mod generated;
use generated::{Command, Response};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cmd = Command {
cmd_id: 42,
param_count: 3,
priority: 2,
reserved: 0,
timeout: 5000,
};
let bytes = cmd.to_byte_array();
println!("Sent {} bytes", bytes.len());
let response = Response {
status: 0,
data_len: 4,
data: vec![1, 2, 3, 4],
};
response.to_file("response.bin")?;
Ok(())
}
步骤 4:测试
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_command_roundtrip() {
let original = Command {
cmd_id: 42,
param_count: 3,
priority: 2,
reserved: 0,
timeout: 5000,
};
let bytes = original.to_byte_array();
let decoded = Command::from_byte_array(&bytes).unwrap();
assert_eq!(original.cmd_id, decoded.cmd_id);
assert_eq!(original.timeout, decoded.timeout);
}
}
总结
本教程涵盖了 BinProto 的核心功能和用法:
- 基础知识:类型系统、结构体、数组
- DSL 语法:类型前置、字段声明、嵌套、动态数组
- 快速开始:简单和复杂示例
- 进阶技巧:位级控制、跨语言编译
- 最佳实践:命名、文档、测试
下一步:
- 尝试编写自己的
.binprotoschema(类型前置) - 为多个语言编译
- 在项目中集成生成的代码
- 运行跨语言测试验证一致性
最后更新:2025 年 11 月 维护者:BinProto 开发团队