2025-11-06 14:14:36 +08:00
2025-11-06 14:08:13 +08:00
2025-11-05 15:00:05 +08:00
2025-11-05 15:00:10 +08:00
2025-10-09 19:40:39 +08:00
2025-10-15 00:27:25 +08:00
2025-10-15 00:27:25 +08:00
2025-11-06 14:14:36 +08:00
2025-11-06 14:14:36 +08:00

BinProto - Bit-Level Cross-Language Data Serialization Compiler

English | 中文

Dev Doc | Tec Doc | Tutorial

📖 Introduction

BinProto is an innovative binary protocol compiler supporting bit-level precision cross-language data exchange. With a custom DSL (Domain-Specific Language), you can:

  • 🎯 Define Precise Binary Structures - Support for 1-128 bit integer types with bit-level precision
  • 🚀 Auto-Generate Multi-Language Code - One schema generates Rust, C/C++, and Python code
  • 🔄 Cross-Language Consistency - Seamless data interaction across different languages
  • 📦 Zero-Waste Memory - Bit-level precision eliminates alignment padding for maximum efficiency
  • 🛡️ Type Safety - Compile-time checking with runtime validation

Core Features

Feature Description
Bit-Level Precision 1-128 bit signed/unsigned integers with complete control
Multi-Language Support Rust, C/C++, Python with 3 mainstream languages supported
Complex Types Nested structs, fixed/dynamic arrays, character types
Automatic Serialization Auto-generated encode/decode functions with array and file I/O
Cross-Platform Compatibility Unified endianness handling ensures consistent data across platforms
High Performance Bit-packing optimized for resource-constrained environments

🚀 Quick Start

Prerequisites

  • Rust 1.70+ (for building the compiler)
  • GCC/Clang (for compiling generated C/C++ code)
  • Python 3.8+ (for generated Python code, optional)

Installation

Option 1: Build from Source

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

# Build release version
cargo build --release

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

Option 2: Install via Cargo (if published)

cargo install binproto

Verify Installation

binproto --version
binproto --help

5-Minute Quick Example

1️⃣ Create Schema File (hello.binproto)

struct hello_packet {
    u8 magic
    u4 version
    u4 flags
    u16 sequence
    u32 timestamp
}

2️⃣ Compile to Rust

binproto compile hello.binproto --lang rust --out ./gen

3️⃣ Use in Rust Project

// Include generated code
include!("gen/hello_packet.rs");

fn main() -> Result<()> {
    // Create data structure
    let packet = HelloPacket {
        magic: 0xFF,
        version: 1,
        flags: 0x0F,
        sequence: 42,
        timestamp: 1699200000,
    };

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

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

    // Save to file
    packet.to_file("packet.bin")?;

    // Load from file
    let loaded = HelloPacket::from_file("packet.bin")?;
    println!("Loaded: {:?}", loaded);

    Ok(())
}

📚 Documentation

📖 Tutorials

  • English Tutorial - Comprehensive English learning guide
    • Basic concepts explained
    • DSL syntax tutorial
    • Advanced usage
    • Best practices
    • FAQ

📋 Technical Documentation

  • Technical Requirements - Project technical architecture and design

    • Overall architecture
    • Dependency strategy
    • Functional requirements
    • Non-functional requirements
  • Application Development Guide - Development workflow and API conventions

    • Overview
    • API conventions
    • Development process

🎯 Use Cases

Network Protocols

Define network packets and protocol headers with multi-version support:

struct tcp_header {
    u16 src_port
    u16 dst_port
    u32 seq_num
    u32 ack_num
    u4 data_offset
    u3 reserved
    u9 flags
    u16 window
}

Binary File Formats

Precisely define image, audio, and other file formats:

struct png_chunk {
    u32 length
    u8[4] chunk_type
    u8[length] data
    u32 crc
}

Hardware Communication

Communicate with embedded devices with optimized bandwidth:

struct sensor_data {
    u8 sensor_id
    i16 temperature
    u8 humidity
    u4 battery
    u4 status
}

Game Development

Network synchronization, save file formats, performance optimization:

struct player_state {
    u16 player_id
    u8 health
    u8 mana
    i16 x
    i16 y
    i16 z
}

💻 Command Line Tools

Basic Usage

binproto compile <schema.binproto> [OPTIONS]

Options

--lang <LANG>              Output language (rust, cpp, python)
                          Can specify multiple: rust,cpp,python
--out <DIR>               Output directory (default: ./generated)
--emit <FORMAT>           Output format: ast (emit JSON AST)
--config <FILE>           Use configuration file

Common Commands

# Generate single language
binproto compile schema.binproto --lang rust --out ./gen_rust

# Generate multiple languages
binproto compile schema.binproto --lang rust,cpp,python --out ./gen

# Output AST for debugging
binproto compile schema.binproto --emit ast --out ./schema_ast.json

# Use verbose mode for compilation info
binproto compile schema.binproto --lang rust -v

🏗️ Project Structure

binproto/
├── Cargo.toml                 # Rust project configuration
├── Cargo.lock
├── README.md                  # English README (this file)
├── README_zh.md              # Chinese README
│
├── src/
│   ├── main.rs               # CLI entry point
│   ├── lib.rs                # Library exports
│   ├── compiler/
│   │   ├── mod.rs            # Compiler module
│   │   ├── ast.rs            # Abstract syntax tree definitions
│   │   ├── lexer.rs          # Lexical analysis
│   │   ├── parser.rs         # Syntax analysis
│   │   ├── semantics.rs      # Semantic checking
│   │   └── binproto.pest     # PEG grammar rules
│   │
│   └── generator/
│       ├── mod.rs            # Code generator common module
│       ├── rust/
│       │   └── mod.rs        # Rust code generation
│       ├── cpp/
│       │   └── mod.rs        # C/C++ code generation
│       └── python/
│           └── mod.rs        # Python code generation
│
├── docs/
│   ├── tutorial_en.md         # English tutorial (detailed)
│   ├── tutorial_zh.md         # Chinese tutorial (detailed)
│   ├── technical_requirements.md  # Technical requirements document
│   └── application_development.md # Application development guide
│
├── tests/
│   ├── parser_and_generator.rs    # Parser and generator tests
│   ├── rust_generator.rs          # Rust generator tests
│   ├── cpp_generator.rs           # C++ generator tests
│   ├── python_generator.rs        # Python generator tests
│   ├── run_schema_tests.rs        # Schema integration tests
│   └── schemas/                   # Test schema files
│       ├── simple_struct.binproto
│       ├── nested_structs_and_constant_array.binproto
│       ├── array_of_structs_constant.binproto
│       ├── nested_array_of_structs_and_dynamic_array.binproto
│       ├── primitives_edge_cases.binproto
│       ├── comment_test.binproto
│       └── new_syntax_features.binproto
│
└── target/
    └── debug/release/        # Build output

🔧 Development Guide

Build from Source

# Build debug version
cargo build

# Build release version (optimized)
cargo build --release

# Run unit tests
cargo test

# Run specific tests
cargo test test_parser
cargo test --test rust_generator

# View test coverage (requires tarpaulin)
cargo tarpaulin --out Html

Project Architecture

Compilation Pipeline:

Source File (.binproto)
    ↓
Lexical Analysis (Lexer)
    ↓
Syntax Analysis (Parser) → AST
    ↓
Semantic Checking (Semantics)
    ↓
Code Generation (Generator)
    ├→ Rust Generator → .rs
    ├→ C++ Generator → .h / .cpp
    └→ Python Generator → .py

Key Modules:

  1. Compiler (src/compiler/)

    • lexer.rs: Lexical analysis, converts source to tokens
    • parser.rs: Syntax analysis, converts tokens to AST
    • semantics.rs: Semantic checking, validates types and references
    • ast.rs: AST node definitions
  2. Generator (src/generator/)

    • Common generation framework
    • One submodule per language
    • Generates source code for target language
  3. Tests (tests/)

    • Unit tests verify compiler functionality
    • Integration tests verify code generation
    • Cross-language round-trip tests

Contribution Guide

We welcome pull requests! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Code Standards:

  • Follow Rust official style guidelines
  • Run cargo fmt to format code
  • Run cargo clippy to check code quality
  • Write tests for new features

📖 DSL Syntax Overview

Basic Syntax

// Comments
struct struct_name {
    type field_name
    type2 field_name2
}

Supported Types

Primitive Types:

  • Signed integers: i1, i2, ..., i128
  • Unsigned integers: u1, u2, ..., u128
  • Character: char (8-bit UTF-8)

Complex Types:

  • Struct: struct_name
  • Fixed array: type[N]
  • Dynamic array: type[field_name]

Examples

struct point {
    u8 x
    u8 y
}

struct shape {
    u8 point_count
    point[point_count] points
    u24 color
}

For more details, see English Tutorial.


🧪 Testing

Run Test Suite

# Run all tests
cargo test

# Run specific tests
cargo test parser
cargo test generator

# Run tests with output
cargo test -- --nocapture

# Run integration tests
cargo test --test '*'

Test Coverage

  • ✅ Lexical Analysis: Basic token recognition, comment handling
  • ✅ Syntax Analysis: Structs, fields, arrays, nesting
  • ✅ Semantic Checking: Type checking, reference validation, array length
  • ✅ Code Generation: Rust, C++, Python
  • ✅ Integration Tests: End-to-end compilation pipeline
  • ✅ Cross-Language Tests: Round-trip consistency verification

📊 Performance

BinProto is optimized for the following scenarios:

Scenario Performance
Compilation Speed Typical schema (~100 lines) < 100ms
Encoding Speed ~1M structs/sec (Rust)
Decoding Speed ~1M structs/sec (Rust)
Memory Efficiency Bit-level packing, no alignment padding

🔐 Security

  • ✅ Compile-Time Checking - DSL validation prevents invalid schemas
  • ✅ Runtime Checking - Array bounds, type validation
  • ✅ Type Safety - Rust strong type system
  • ✅ Error Handling - Detailed error reports with location information

📝 License

This project is licensed under the MIT License. See LICENSE file for details.


🤝 Contributing

Contributions are welcome! Whether you:

  • 🐛 Report bugs
  • 💡 Suggest new features
  • 📖 Improve documentation
  • 🔧 Submit code fixes

Please participate through:

  1. Issues - Submit bug reports or feature requests
  2. Discussions - Discuss designs and ideas
  3. Pull Requests - Contribute code

📞 Contact


🗺️ Roadmap

Completed ✅

  • Basic DSL syntax
  • Rust code generation
  • C/C++ code generation
  • Python code generation
  • Nested struct support
  • Dynamic array support
  • Basic test suite

In Progress 🚧

  • Performance optimization
  • More language support (Go, Java, TypeScript)
  • Incremental compilation caching
  • Visual Studio Code extension
  • Online editor & Playground

Planned 📋

  • Streaming parser
  • Automatic CRC/checksum generation
  • Schema versioning
  • Backward compatibility checking
  • Distributed schema registry
  • Performance benchmarking tools


⭐ Acknowledgments

Thank you to all contributors and users for your support!


🎓 Educational Resources


Let BinProto help you build efficient, cross-language compatible binary protocols! 🚀


Last Updated: November 2025 Maintained by: BinProto Development Team

S
Description
No description provided
Readme
139 KiB
Languages
Rust 92.8%
C++ 3.8%
Python 3.4%