Files
2025-11-05 15:12:15 +08:00

17 KiB

BinProto Tutorial (English)

Table of Contents

  1. Introduction
  2. Installation and Setup
  3. Basic Concepts
  4. DSL Syntax Reference
  5. Quick Start Examples
  6. Advanced Usage
  7. Cross-Language Compilation
  8. FAQ and Troubleshooting
  9. Best Practices

Introduction

What is BinProto?

BinProto is a bit-level cross-language data exchange protocol compiler. It enables you to:

  • Define binary data structures using a custom DSL (Domain-Specific Language)
  • Automatically generate serialization/deserialization code for multiple languages
  • Support precise bit-level layout control without wasting any memory
  • Ensure cross-language data consistency

Core Features

Feature Description
Bit-Level Precision Support for 1-128 bit integer types, precise control over every bit
Multi-Language Support Auto-generate Rust, C/C++, Python code
Nested Structures Support nested structs, arrays, and dynamic arrays
Type System Signed integers (i1-i128), unsigned integers (u1-u128), character type
Cross-Platform Unified endianness handling, consistent across platforms

Use Cases

  • Network Protocols: Define packet headers and data formats
  • Binary File Formats: Image, audio, and custom file formats
  • Hardware Communication: Embedded device and host communication
  • Game Development: Network synchronization, save file formats
  • IoT: Efficient encoding for resource-constrained devices

Installation and Setup

Prerequisites

  • Operating System: Linux, macOS, or Windows
  • Rust: Version 1.70+ (if building from source)
  • Compiler: gcc/clang (for generated C/C++ code)
  • Python: 3.8+ (for generated Python code)

Build from Source

# Clone repository
git clone https://github.com/your-org/binproto.git
cd binproto

# Build project
cargo build --release

# Add to PATH (optional)
export PATH="$PATH:$(pwd)/target/release"

Verify Installation

binproto --version  # Show version info
binproto --help     # View help information

Basic Concepts

1. Type System

Primitive Types

BinProto supports the following primitive types:

Signed Integers: i1, i2, ..., i128

  • Two's complement representation
  • Range: -2^{n-1} to 2^{n-1}-1
  • Example: i8 ranges from -128 to 127

Unsigned Integers: u1, u2, ..., u128

  • Range: 0 to 2^n - 1
  • Example: u8 ranges from 0 to 255

Character Type: char

  • Occupies 8 bits (1 byte)
  • UTF-8 encoded single character

Type Examples

u4      // 4-bit unsigned integer, range 0-15
i8      // 8-bit signed integer, range -128-127
u16     // 16-bit unsigned integer
char    // Character type

2. Structs and Fields

A struct is a collection of fields, each with a specific type:

struct packet_header {
    version: u4           // 4-bit version number
    flags: u4             // 4-bit flags
    sequence_no: u16      // 16-bit sequence number
    timestamp: u32        // 32-bit timestamp
}

3. Arrays

BinProto supports two types of arrays:

Fixed-Size Arrays

u8[4]       // Array of 4 u8 elements
i32[10]     // Array of 10 i32 elements

Dynamic Arrays

Use another field in the same struct to specify array length:

struct message {
    length: u8              // Message length field
    payload: u8[length]    // Dynamic array, length specified by length field
}

4. Nested Structs

A struct can contain other structs as field types:

struct point {
    x: u8
    y: u8
}

struct rectangle {
    top_left: point        // Nested point struct
    width: u8
    height: u8
}

5. Memory Layout

BinProto uses bit-continuous layout:

  • Fields fill in order of declaration, bit by bit
  • No alignment padding inserted
  • Supports arbitrary bit widths

Example:

struct example {
    a: u3      // Bits 0-2
    b: u5      // Bits 3-7
    c: u8      // Bits 8-15
}
// Total size: 2 bytes (16 bits)

DSL Syntax Reference

File Structure

Basic .binproto file syntax:

// This is a comment, starts with //
struct struct_name {
    field_name: field_type
    field_name2: field_type2
}

Grammar Rules

1. Struct Definition

struct name {
    // field definitions
}

Rules:

  • Struct name must start with letter or underscore
  • Case-sensitive
  • Curly braces contain zero or more fields

2. Field Declaration

field_name: type
field_name: type[size]
field_name1, field_name2: type

Rules:

  • Field names cannot be duplicated
  • Type must be a defined primitive type or struct
  • Support declaring multiple same-type fields on one line (comma-separated)

Examples:

struct status {
    id: u8              // Single field
    flags: u8
    x, y: u8           // Multiple same-type fields
    count: u16
    data: u8[count]    // Dynamic array
    matrix: u16[3]     // Fixed array
}

3. Array Syntax

Fixed Size:

field: type[number]
data: u8[32]    // 32 u8 elements

Dynamic Size:

field: type[field_name]
payload: u8[payload_len]    // Length specified by payload_len field

Expressions:

items: u32[N*2]      // Support simple expressions
blocks: u8[count+1]

4. Comments

// Single-line comment, from // to end of line

struct example {
    // Struct comment
    field: u8   // Field comment
}

Type Conversion and Compatibility

  • Different-size integer types are incompatible
  • Signed and unsigned types are incompatible
  • Struct names must be unique within scope

Quick Start Examples

Example 1: Simple Struct

Step 1: Create DSL File

Create file simple.binproto:

struct sensor_reading {
    sensor_id: u8
    temperature: i16
    humidity: u8
    timestamp: u32
}

Step 2: Compile to Rust

binproto compile simple.binproto --lang rust --out ./generated

Step 3: View Generated Code

Generated Rust code (generated/simple.rs) includes:

#[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 bytes = 56 bits
    pub fn bytesize() -> usize { 7 }

    pub fn to_byte_array(&self) -> Vec<u8> { /* ... */ }
    pub fn from_byte_array(bytes: &[u8]) -> Result<Self> { /* ... */ }
}

Step 4: Use in Project

use binproto::SensorReading;

fn main() -> Result<()> {
    let reading = SensorReading {
        sensor_id: 1,
        temperature: 25,
        humidity: 60,
        timestamp: 1699200000,
    };

    // Encode to byte array
    let bytes = reading.to_byte_array()?;
    println!("Encoded: {:?}", bytes);

    // Decode from byte array
    let decoded = SensorReading::from_byte_array(&bytes)?;
    println!("Decoded: {:?}", decoded);

    Ok(())
}

Example 2: Nested Structures and Dynamic Arrays

DSL Definition

Create network_packet.binproto:

struct ipv4_header {
    version: u4
    ihl: u4
    dscp: u6
    ecn: u2
    total_length: u16
    identification: u16
    flags: u3
    fragment_offset: u13
    ttl: u8
    protocol: u8
    checksum: u16
    src_ip: u32
    dst_ip: u32
}

struct ethernet_frame {
    dest_mac: u8[6]
    src_mac: u8[6]
    eth_type: u16
    payload_len: u16
    payload: u8[payload_len]
}

Compile and Use

binproto compile network_packet.binproto --lang rust --out ./gen_net

In your code:

fn main() -> Result<()> {
    let mut 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(())
}

Advanced Usage

1. Complex Field Expressions

Dynamic Arrays with Calculations

struct variable_buffer {
    flags: u4
    data_blocks: u4
    block_size: u16
    data: u8[data_blocks * block_size]
}

2. Bit-Level Precision Control

Compact Bit Fields

struct packed_flags {
    enabled: u1          // 1 bit
    read_only: u1        // 1 bit
    compressed: u1       // 1 bit
    encrypted: u1        // 1 bit
    version: u4          // 4 bits
    // Total 8 bits = 1 byte
}

Unaligned Data

struct misaligned_data {
    magic: u7            // 7-bit magic number
    type_id: u3          // 3-bit type
    padding: u6          // 6-bit padding
    checksum: u10        // 10-bit checksum
    payload: u32         // 32-bit payload
    // Total 58 bits
}

3. Large Structure Combinations

struct gps_reading {
    latitude: i32        // 32 bits
    longitude: i32       // 32 bits
    altitude: i16        // 16 bits
    accuracy: u8         // 8 bits
    timestamp: u32       // 32 bits
}

struct gps_batch {
    batch_id: u32
    count: u16
    readings: gps_reading[count]
}

4. File Interaction

// Write to file
reading.to_file("data.bin")?;

// Read from file
let loaded = SensorReading::from_file("data.bin")?;

Cross-Language Compilation

Rust Generation

binproto compile schema.binproto --lang rust --out ./rust_gen

Features:

  • Generates Rust idiomatic struct
  • Supports Result<T> error handling
  • Optional serde serialization feature

Usage:

let data = MyStruct { /* ... */ };
data.to_byte_array()?;
data.to_file("output.bin")?;

C++ Generation

binproto compile schema.binproto --lang cpp --out ./cpp_gen

Features:

  • Generates #pragma pack(1) structs
  • Includes encode/decode functions
  • Uses std::vector<uint8_t>

Usage:

MyStruct data;
data.field = value;
std::vector<uint8_t> bytes = data.encode();

MyStruct restored = MyStruct::decode(bytes);

Python Generation

binproto compile schema.binproto --lang python --out ./python_gen

Features:

  • Generates @dataclass classes
  • Uses bitarray or pure Python implementation
  • Full type annotations

Usage:

from generated.schema import MyStruct

data = MyStruct(field1=10, field2=20)
bytes_data = data.to_bytes()
restored = MyStruct.from_bytes(bytes_data)

Multi-Language Simultaneous Compilation

binproto compile schema.binproto \
    --lang rust,cpp,python \
    --out ./generated

This generates:

  • generated/rust/ - Rust code
  • generated/cpp/ - C/C++ code
  • generated/python/ - Python code

Output AST (Intermediate Representation)

binproto compile schema.binproto --emit ast --out ./ast.json

Inspect the generated AST structure for debugging or custom tooling.


FAQ and Troubleshooting

Q1: Why is my field size not aligned to byte boundary?

A: BinProto supports bit-level precision, fields don't need to align to byte boundaries. For example:

struct misaligned {
    a: u3     // 3 bits
    b: u5     // 5 bits
    c: u8     // 8 bits
}
// Total size: 16 bits = 2 bytes

Q2: How do I handle variable-length data?

A: Use dynamic arrays, specifying another field as the length marker:

struct message {
    msg_len: u8
    message: char[msg_len]
}

The compiler will automatically add length validation.

Q3: How is endianness handled across platforms?

A: BinProto uses little-endian by default. All generated code follows unified endianness, ensuring cross-platform consistency.

Q4: Can I use one struct inside another struct?

A: Absolutely! This is nested structs:

struct inner {
    value: u16
}

struct outer {
    header: inner
    data: u32
}

Q5: Does generated code support serde?

A: Rust generation supports optional serde features. When enabled, generated structs automatically derive Serialize and Deserialize.

Q6: How do I verify correctness of compiled code?

A: Run the cross-language test suite:

cargo test --test rust_generator
cargo test --test cpp_generator
cargo test --test python_generator

These tests include round-trip verification to ensure data consistency after encode-decode.

Q7: Are there file size limits for DSL?

A: No hard limits, but keep schema files readable. For large-scale definitions, consider splitting into multiple modules.


Best Practices

1. Naming Conventions

Use clear, self-descriptive names:

// ✓ Good naming
struct packet_header {
    source_addr: u32
    dest_addr: u32
    payload_len: u16
}

// ✗ Poor naming
struct ph {
    sa: u32
    da: u32
    pl: u16
}

2. Documentation

Add comments for complex structures:

// GPS location data structure
// Each reading contains latitude, longitude, and timestamp
struct gps_reading {
    // Decimal degrees * 1000000, range [-180M, 180M]
    latitude: i32
    // Decimal degrees * 1000000, range [-90M, 90M]
    longitude: i32
    // Unix timestamp (seconds)
    timestamp: u32
}

3. Version Management

Add version fields for potentially evolving protocols:

struct message {
    version: u4         // Protocol version for compatibility
    message_type: u4
    // Other fields
}

4. Error Handling

Always check decode results:

match MyStruct::from_byte_array(&bytes) {
    Ok(data) => println!("Decoded: {:?}", data),
    Err(e) => eprintln!("Decode failed: {}", e),
}

5. Performance Optimization

Use minimum necessary bit width:

// ✓ Optimized
struct flags {
    enabled: u1
    priority: u2
    reserved: u5
}

// ✗ Wasteful
struct flags {
    enabled: u8
    priority: u8
    reserved: u8
}

6. Cross-Language Testing

Write cross-language tests for each new schema:

#[test]
fn test_roundtrip() {
    let original = MyStruct { /* ... */ };
    let bytes = original.to_byte_array().unwrap();
    let decoded = MyStruct::from_byte_array(&bytes).unwrap();
    assert_eq!(original, decoded);
}

7. Modular DSL

For large projects, group schemas:

schemas/
  ├── core.binproto       // Base types
  ├── network.binproto    // Network-related
  └── application.binproto // Application layer

Complete Workflow Example

Project Structure

my_project/
├── Cargo.toml
├── schemas/
│   └── protocol.binproto
├── src/
│   ├── main.rs
│   └── generated/
│       └── protocol.rs
└── tests/
    └── integration_test.rs

Step 1: Define Schema

schemas/protocol.binproto:

struct command {
    cmd_id: u8
    param_count: u4
    priority: u2
    reserved: u2
    timeout: u16
}

struct response {
    status: u8
    data_len: u16
    data: u8[data_len]
}

Step 2: Compile Schema

cargo run --bin binproto -- \
    compile schemas/protocol.binproto \
    --lang rust \
    --out src/generated

Step 3: Use in Project

src/main.rs:

mod generated;
use generated::{Command, Response};

fn main() -> Result<()> {
    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(())
}

Step 4: Test

#[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().unwrap();
        let decoded = Command::from_byte_array(&bytes).unwrap();

        assert_eq!(original.cmd_id, decoded.cmd_id);
        assert_eq!(original.timeout, decoded.timeout);
    }
}

Summary

This tutorial covers BinProto's core functionality and usage:

✅ Fundamentals: Type system, structs, arrays ✅ DSL Syntax: Field declaration, nesting, dynamic arrays ✅ Quick Start: Simple and complex examples ✅ Advanced: Bit-level control, cross-language compilation ✅ Best Practices: Naming, documentation, testing

Next Steps:

  1. Write your own .binproto schema
  2. Compile for multiple languages
  3. Integrate generated code into your project
  4. Run cross-language tests to verify consistency

For more information, see Technical Requirements and Application Development Guide.


Last Updated: November 2025 Maintainers: BinProto Development Team