Files
binproto/docs/application_development.md
2025-10-09 19:40:39 +08:00

3.2 KiB
Raw Permalink Blame History

BinProto 应用开发文档

目标概述

BinProto 是一个基于位粒度的跨语言数据交换协议,通过自定义 DSL 描述结构体布局,并为 Rust、C/C++ 与 Python 生成等价的结构定义及编解码逻辑。开发者可以利用 BinProto 将结构化数据与原始比特流、字节流、二进制文件以及十六进制/二进制编码互相转换。

快速开始

  1. 定义 DSL 文件:使用 .binproto 扩展名,通过 BinProto DSL 描述结构体及其字段、数组、嵌套结构。
  2. 编译 DSL:运行 binproto 编译器,产出针对目标语言的结构体声明、序列化/反序列化实现,以及运行时支持代码。
  3. 集成生成代码:在目标项目中引用编译器输出,利用生成的 API 完成数据与比特流的转换。

DSL 概念

  • 原生类型:支持 i1-i128、u1-u128 以及 char (1 字节)。
  • 结构体定义:struct name { field: type [= default], ... }。
  • 数组:field: type[n],n 可以为常量整型或常量表达式。
  • 嵌套:字段类型可引用其他自定义结构体。
  • 属性方法:生成的类型提供 .bitsize() / .bytesize(),返回布局大小。

API 约定

每个生成的结构体包含以下方法:

  • fn to_bit_array(&self) -> Vec<bool>
  • fn to_byte_array(&self) -> Vec<u8>
  • fn from_bit_array(bits: &[bool]) -> Result<Self>
  • fn from_byte_array(bytes: &[u8]) -> Result<Self>
  • fn to_file(path: impl AsRef<Path>) -> Result<()>
  • fn from_file(path: impl AsRef<Path>) -> Result<Self>

语言绑定遵循各语言惯例。例如:

  • Rust:生成 struct 及实现 TryFrom/From 等 trait。
  • C/C++:生成符合 #pragma pack(push, 1) 约定的结构体与辅助函数。
  • Python:生成 dataclass 与 bitarray 编解码辅助模块。

开发流程

  1. 在 dsl/ 目录编写 .binproto 文件。
  2. 执行 cargo run -- compile <input.binproto> --lang rust --out gen/rust。
  3. 集成生成代码并编写单元测试。
  4. 通过 cargo test 与 Python/C++ 构建脚本验证跨语言兼容性。

示例

struct header {
    version: u4
    flags: u4
}

struct packet {
    header: header
    payload_len: u16
    payload: u8[payload_len]
}
  • Rust 生成:Packet 结构体,拥有自动长度校验与读写方法。
  • C++ 生成:struct Packet 与 PacketCodec,提供序列化接口。
  • Python 生成:@dataclass class Packet 搭配 to_bits/ from_bits 方法。

测试与验证

  • Rust:cargo test,覆盖 DSL 解析、语义检查、生成代码与运行时库。
  • C++:使用 ctest 驱动的交叉验证脚本,验证字节序与对齐。
  • Python:pytest 运行跨语言 round-trip 测试。

常见问题

  • 对齐:DSL 默认采用位连续布局,不插入填充。跨语言实现需禁用对齐填充。
  • 可变数组:使用 field: type[len_field],编译器生成运行时校验。
  • 默认值:支持常量表达式,用于初始化。

未来扩展

  • 流式解析器
  • CRC/校验字段自动生成
  • Schema 版本管理与兼容性检查

如需贡献或扩展,请参阅技术要求文档与架构设计。