AutoZig

Safe Rust to Zig FFI with Generics, Async & Stream Support
AutoZig enables safe, ergonomic interop between Rust and Zig code, inspired by autocxx for C++.
Quick Start • Features • Phase 4: Advanced Features • Documentation • Examples • Contributing
🎯 Core Goals
🛡️ Safety First
Zero unsafe in user code - All FFI complexity is handled by the framework
⚡ Performance
Compile-time code generation - Zig code is compiled during cargo build
🔒 Type Safety
Automatic type conversion - Safe bindings between Rust and Zig types
🚀 Developer Experience
Write Zig inline - Embed Zig code directly in your Rust files
🚀 Quick Start
1. Add dependencies
# Cargo.toml
[]
= "0.1"
[]
= "0.1"
2. Create build.rs
// build.rs
3. Write your code
// src/main.rs
use autozig;
autozig!
✨ Key Features
🎉 Phase 5: WebAssembly Support (NEW!)
Latest Release - AutoZig now supports WebAssembly with Zig + Rust static linking for extreme performance in browsers!
🌐 WASM Static Linking
Compile Zig and Rust into a single WASM file with zero-copy memory sharing:
use *;
use autozig;
autozig!
Features:
- ✅ Static Linking: Zig + Rust → Single
.wasmfile - ✅ Zero-Copy: Shared linear memory, no data copying
- ✅ SIMD Optimization: Zig
@Vector+ WASM SIMD128 instructions - ✅ High Performance: 3-5x faster than pure JavaScript, 3x faster than Rust native
- ✅ Small Binary: Optimized with
-O ReleaseFast+wasm-opt
Real-World Performance (Image Filter Benchmark - 2.1 MB image):
| Implementation | Processing Time | Throughput | Relative Performance |
|---|---|---|---|
| ⚡ AutoZig (Zig SIMD) | 0.80 ms | 2631.84 MB/s | Baseline (1.00x) |
| 🦀 Rust Native | 2.50 ms | 842.19 MB/s | 3.13x slower |
| 🟨 JavaScript | 3.80 ms | 554.07 MB/s | 4.75x slower |
Why AutoZig is faster:
- 🔥 SIMD128 Instructions: Zig's
@Vector(16, u8)compiles tov128.load/sub/store - 🚀 Zero Abstractions: Direct memory manipulation with no runtime overhead
- ⚡ Compiler Optimization: Zig + LLVM's aggressive optimizations
- 🎯 Saturating Arithmetic: Hardware-accelerated
+|and-|operations
Build for WASM:
📖 Learn More: examples/wasm_filter | docs/PHASE_5_WASM_DESIGN.md
🎉 Phase 4: Advanced Features
Latest Release - AutoZig Phase 1-4 fully complete! New Stream support, zero-copy optimization, SIMD detection and more advanced features!
🌊 Stream Support
异步数据流支持,基于 futures::Stream trait:
use create_stream;
use StreamExt;
let = ;
pin_mut!;
while let Some = stream.next.await
Features:
- ✅
futures::Streamtrait implementation - ✅ Async data stream processing
- ✅ Error handling and state management
- ✅ Seamless integration with Zig generators
🚀 Zero-Copy Buffer
Zero-copy buffer passing for efficient Zig → Rust data transfer with no overhead:
use ZeroCopyBuffer;
// Zig generates data, Rust receives with zero-copy
let buffer = from_zig_vec;
let data = buffer.into_vec; // Zero-copy conversion
Performance:
- ✅ 1.93x speedup (compared to copying)
- ✅ Zero additional memory allocation
- ✅ Completely safe API
🔥 SIMD Detection
Compile-time SIMD feature detection and automatic optimization:
// build.rs
let simd_config = detect_and_report;
println!;
Supported Features:
- ✅ x86_64: SSE2, SSE4.2, AVX, AVX2, AVX-512
- ✅ ARM: NEON
- ✅ Zig automatic vectorization optimization
📖 Learn More: examples/stream_basic | examples/zero_copy | examples/simd_detect
🎉 Phase 3: Generics & Async
AutoZig supports generic monomorphization and async FFI!
🔷 Generic Monomorphization
Write generic Rust functions and let AutoZig generate type-specific Zig implementations:
use autozig;
autozig!
Features:
- ✅ C++-style template instantiation for Rust generics
- ✅ Automatic name mangling (
process<T>→process_i32,process_f64) - ✅ Type substitution engine (handles
&[T],&mut [T], nested types) - ✅ Zero runtime overhead
⚡ Async FFI with spawn_blocking
Write async Rust APIs backed by synchronous Zig implementations:
use include_zig;
include_zig!;
async
Zig side (stays synchronous!):
// src/compute.zig
export fn heavy_computation(data: i32) i32 {
// Write normal synchronous Zig code
// No async/await needed!
return data * 2;
}
Features:
- ✅ Rust: Async wrappers using
tokio::spawn_blocking - ✅ Zig: Synchronous implementations (no async/await complexity)
- ✅ Thread pool offload prevents blocking async runtime
- ✅ Automatic parameter capture and conversion
📖 Learn More: examples/generics | examples/async
🧪 Zig Test Integration
🎉 Run Zig unit tests as part of your Rust test suite!
AutoZig integrates Zig unit tests into the Rust test framework!
// build.rs
// zig/math.zig
export fn factorial(n: u32) u64 {
// ... implementation
}
test "factorial basic cases" {
try std.testing.expectEqual(@as(u64, 120), factorial(5));
}
// tests/zig_tests.rs
Run tests:
📖 Learn More: docs/ZIG_TEST_INTEGRATION.md
🔗 C Library Integration
🌐 Seamless integration with existing C libraries through Zig wrappers
AutoZig supports calling C functions through Zig wrappers for Rust → Zig → C three-way interoperability:
// build.rs - Add C source files
use Builder;
// wrapper.zig - Zig wraps C functions
extern "c" fn c_add(a: i32, b: i32) i32;
export fn add(a: i32, b: i32) i32 {
return c_add(a, b);
}
// main.rs - Rust calls through autozig
use zig;
zig!
Benefits:
- ✅ Leverage existing C libraries without rewriting
- ✅ Add Zig enhancements on top of C functions
- ✅ Type-safe FFI across all three languages
- ✅ Single build system manages everything
📖 Complete Example: examples/zig-c
📦 External File Support
📁 Import external
.zigfiles into your Rust project
Use the include_zig! macro to reference external .zig files:
use include_zig;
include_zig!;
🎯 Smart Lowering
🔄 Automatic conversion between Rust high-level types and Zig FFI-compatible types
| Rust Type | Zig Signature | Auto Conversion |
|---|---|---|
&str |
[*]const u8, usize |
✅ |
&[T] |
[*]const T, usize |
✅ |
&mut [T] |
[*]T, usize |
✅ |
String |
[*]const u8, usize |
✅ |
🧩 Trait Support
Implement Rust traits with Zig backends
Zero-Sized Types (ZST)
autozig!
let calc = default;
assert_eq!;
Opaque Pointers (Stateful)
autozig!
📖 Learn More: docs/TRAIT_SUPPORT_DESIGN.md
📦 Examples & Verification
📚 15 Working Examples
All examples are fully tested and ready to run:
- structs - Structure bindings
- enums - Enum types and Result/Option
- complex - Complex nested types
- smart_lowering - Automatic type conversion
- external - External Zig files with
include_zig! - trait_calculator - Trait implementation (ZST)
- trait_hasher - Trait implementation (Opaque Pointer)
- security_tests - Memory safety tests
- generics - Generic monomorphization (Phase 3)
- async - Async FFI with spawn_blocking (Phase 3)
- zig-c - C + Zig + Rust three-way interop
- stream_basic - Stream support (Phase 4)
- simd_detect - SIMD detection (Phase 4)
- zero_copy - Zero-copy optimization (Phase 4)
- wasm_filter - WebAssembly image filter with SIMD optimization (Phase 5) 🌐
🌐 Multi-Language Interop: C + Zig + Rust
🎉 NEW! AutoZig now supports full C + Zig + Rust three-way interoperability!
The zig-c example demonstrates a complete calling chain: Rust → Zig → C
use zig;
zig!
Key Features:
- ✅ C Integration: Use existing C libraries through Zig wrappers
- ✅ Smart Lowering:
&[i32]and&strautomatically converted toptr + len - ✅ Type Safety: Full type checking across all three languages
- ✅ Zero Overhead: Direct FFI calls with no runtime cost
- ✅ Build System: Single
build.rswithwith_c_sources()API
Architecture:
Rust (safe API)
↓ FFI call
Zig (wrapper + enhancements)
↓ extern "c"
C (low-level implementation)
📖 Learn More: examples/zig-c/README.md
🔍 Batch Verification
Run all examples at once:
Output:
======================================
Verification Results Summary
======================================
Total: 15 examples (14 standard + 1 WASM)
Success: 15
Failed: 0
Skipped: 0
[✓] All examples verified successfully! 🎉
📖 Learn More: examples/README.md
📐 Architecture
AutoZig follows a three-stage pipeline for seamless Rust-Zig interop:
┌─────────────┐
│ Rust Code │
│ with │
│ autozig! │
└──────┬──────┘
│
▼
┌─────────────────────────────────────────┐
│ Stage 1: Parsing (Compile Time) │
│ ───────────────────────────────── │
│ • Scan .rs files for autozig! macros │
│ • Extract Zig code │
│ • Parse Rust signatures │
│ • Detect generics & async │
└──────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ Stage 2: Build (build.rs) │
│ ────────────────────────────── │
│ • Compile Zig → static library (.a) │
│ • Generate monomorphized versions │
│ • Link with Rust binary │
└──────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ Stage 3: Macro Expansion │
│ ──────────────────────────── │
│ • Generate safe Rust wrappers │
│ • Handle &str → (ptr, len) conversion │
│ • Generate async spawn_blocking │
│ • Include FFI bindings │
└──────┬──────────────────────────────────┘
│
▼
┌─────────────┐
│ Safe Rust │
│ API │
└─────────────┘
📦 Project Structure
autozig/
├── src/lib.rs # Main library
├── parser/ # Macro input parser
│ └── src/lib.rs # Parse generics & async
├── macro/ # Procedural macro
│ └── src/lib.rs # Code generation (Phase 3)
├── engine/ # Core build engine
│ ├── scanner.rs # Source code scanner
│ ├── zig_compiler.rs # Zig compiler wrapper
│ └── type_mapper.rs # Type conversion logic
├── gen/build/ # Build script helpers
├── examples/ # 14 working examples
│ ├── verify_all.sh # Batch verification script
│ └── README.md # Examples documentation
└── docs/ # Technical documentation
🔧 Requirements
|
| Component | Version | Notes |
|---|---|---|
| Rust | 1.77+ | Workspace features required |
| Zig | 0.11+ or 0.12+ | Must be in PATH |
| Tokio | 1.0+ | Required for async examples |
🎓 Comparison with autocxx
| Feature | autocxx (C++) | autozig (Zig) |
|---|---|---|
| Target Language | C++ | Zig |
| Binding Generator | bindgen + cxx | bindgen |
| Safe Wrappers | ✅ | ✅ |
| Inline Code | ❌ | ✅ |
| Generics Support | ✅ | ✅ |
| Async Support | ❌ | ✅ |
| Stream Support | ❌ | ✅ |
| Zero-Copy | ❌ | ✅ |
| SIMD Optimization | ❌ | ✅ |
| Build Complexity | High | Medium |
| Type Safety | Strong | Strong |
📚 Type Mapping
| Zig Type | Rust Type | Notes |
|---|---|---|
i8, i16, i32, i64 |
i8, i16, i32, i64 |
✅ Direct mapping |
u8, u16, u32, u64 |
u8, u16, u32, u64 |
✅ Direct mapping |
f32, f64 |
f32, f64 |
✅ Direct mapping |
bool |
u8 |
⚠️ Zig bool is u8 in C ABI |
[*]const u8 |
*const u8 |
🔧 Raw pointer |
[*]const u8 + len |
&[u8] |
🛡️ With safe wrapper |
🤝 Contributing
Contributions are welcome! This is an experimental project exploring Rust-Zig interop.
Ways to contribute:
- 🐛 Report bugs and issues
- 💡 Suggest new features
- 📖 Improve documentation
- 🔧 Submit pull requests
- 🎯 Add new examples
📄 License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
🙏 Acknowledgments
- 💡 Inspired by autocxx
- 🔨 Built on bindgen
- ⚡ Leverages the excellent Zig language
- 🚀 Async architecture inspired by Tokio best practices
⚠️ Status
✅ Phase 1-5 Complete! - AutoZig 全功能完成,支持 WebAssembly!
Current Status:
- ✅ Phase 1: Basic FFI bindings (100%)
- ✅ Phase 2: Smart Lowering & Traits (100%)
- ✅ Phase 3: Generics & Async (100%)
- ✅ Phase 4: Stream, Zero-Copy & SIMD (100%)
- ✅ Phase 5: WebAssembly Support (100%) 🌐
Statistics:
- 📦 15 working examples
- ✅ 39/39 tests passing (100%)
- 📝 22+ documentation files
- 🌐 Full WASM support with static linking
- 🚀 Production ready
📖 Further Reading
Core Documentation
- 📝 Design Notes - Architecture overview
- 🎯 Quick Start - Get started in 5 minutes
- 📚 Implementation Summary - Technical deep dive
Phase-Specific Documentation
- 🔷 Phase 3: Generics Design
- ⚡ Phase 3: Async Design
- ✅ Phase 3: Complete Status
- 🌊 Phase 4: Stream Design
- 🚀 Phase 4: Implementation Status
- 🎯 Phase 4.2: Advanced Features
Feature Documentation
- 🧪 Zig Test Integration
- 🗺️ Trait Support Design
- 🛡️ Security Best Practices
- 🔒 Zero Unsafe Achievement
- 📋 Feature Summary - Complete feature checklist
Examples
- 📂 Examples Directory - 14 working examples
- 📖 Examples README - Detailed guide
- 🔍 Batch Verification - Test all examples
Made with ❤️ for the Rust and Zig communities