Bitfold
A modern, high-performance reliable UDP networking library for Rust, inspired by ENet.
Bitfold provides flexible delivery guarantees, automatic fragmentation, congestion control, and multi-channel communication—ideal for games, real-time applications, and high-performance network services.
Table of Contents
- Why Bitfold?
- Features
- Quick Start
- Delivery Guarantees
- Multi-Channel Communication
- Configuration Options
- Network Utilities
- Examples
- Event Loop Integration
- Architecture
- Best Practices
- Performance
- Testing
- Contributing
- License
Why Bitfold?
UDP performance with TCP-like reliability when you need it.
Traditional networking presents a trade-off: TCP offers reliability but with high latency and head-of-line blocking, while UDP offers low latency but no guarantees. Bitfold gives you the best of both worlds:
- Flexible Delivery - Choose reliability per packet, not per connection
- Low Latency - No head-of-line blocking across channels
- Zero Allocation - Arc-based buffer sharing for zero-copy operations
- Production Ready - Battle-tested congestion control and PMTU discovery
- Pure Rust - Memory safe, no unsafe dependencies
Features
Core Features
- Multiple delivery modes - Reliable, unreliable, ordered, sequenced, and unsequenced
- Multi-channel support - Up to 255 independent channels per connection
- Automatic fragmentation - Handles packets up to 32KB transparently
- PMTU discovery - Adaptive MTU detection to maximize throughput (enabled by default)
- Congestion control - RTT-based adaptive throttling with configurable parameters
- Bandwidth limiting - Per-peer incoming/outgoing bandwidth throttling
Advanced Features
- Compression - Optional LZ4 or Zlib compression with configurable threshold
- Data integrity - Optional CRC32 checksums for error detection
- Zero-copy design - Efficient buffer management with Arc-based sharing
- Command batching - Multiple operations packed into single UDP packets
- Flow control - Dynamic sliding window based on network conditions
- Packet pooling - Reusable buffer pools to minimize allocations
Network Utilities
Built-in utilities for common networking tasks:
- DNS resolution - Hostname to IP address resolution
- Reverse DNS - IP address to hostname lookup
- IP parsing - Parse and format IPv4/IPv6 addresses
Quick Start
Add Bitfold to your Cargo.toml:
[]
= "0.1"
Basic Server Example
use ;
use Instant;
Basic Client Example
use ;
use Instant;
Delivery Guarantees
Bitfold offers five delivery modes, each optimized for different use cases:
1. Unreliable (Fire-and-Forget)
Best for: High-frequency position updates, non-critical state
let packet = unreliable;
- Latency: Lowest (single transmission)
- Guarantee: None (may be lost, duplicated, or reordered)
- Use case: Player positions, entity transforms, temporary visual effects
2. Reliable Unordered
Best for: Important events that can arrive in any order
let packet = reliable_unordered;
- Latency: Low (retransmitted until acknowledged)
- Guarantee: Delivery guaranteed, no ordering
- Use case: Item pickups, damage events, notifications
3. Reliable Ordered
Best for: Critical sequential data (TCP-like)
let packet = reliable_ordered;
- Latency: Higher (waits for missing packets)
- Guarantee: Delivery and order guaranteed
- Use case: Chat messages, cutscene triggers, quest updates
4. Reliable Sequenced
Best for: State updates where only the latest matters
let packet = reliable_sequenced;
- Latency: Low (drops outdated packets)
- Guarantee: Only latest packet delivered
- Use case: Animation states, UI updates, inventory snapshots
5. Unsequenced (Duplicate Prevention)
Best for: One-time events that can be reordered
let packet = unsequenced;
- Latency: Lowest (single transmission)
- Guarantee: No duplicates, but may be reordered or lost
- Use case: Spawning particles, sound effects, temporary markers
Multi-Channel Communication
Channels allow you to separate different traffic types with independent ordering guarantees. This prevents head-of-line blocking across different data streams.
use ;
// Configure 4 independent channels
let mut config = default;
config.channel_count = 4;
let mut host = bind_with_config?;
// Each channel has independent ordering
host.send?;
host.send?;
host.send?;
host.send?;
Channel Use Cases
| Channel | Type | Delivery | Use Case |
|---|---|---|---|
| 0 | Critical | Reliable Ordered | Player commands, RPC calls |
| 1 | State | Unreliable | Entity positions, physics state |
| 2 | Messages | Reliable Ordered | Chat, notifications |
| 3 | Effects | Reliable Sequenced | Animations, UI updates |
Configuration Options
Bitfold is highly configurable to suit your application's needs:
use ;
use Duration;
let mut config = default;
// Connection Settings
config.idle_connection_timeout = from_secs;
config.heartbeat_interval = Some;
// Multi-Channel Configuration
config.channel_count = 8; // Up to 255 channels
// Fragmentation & MTU
config.max_packet_size = 32 * 1024; // Maximum packet size (32 KB)
config.use_pmtu_discovery = true; // Enable PMTU discovery (default)
config.pmtu_min = 576; // Minimum MTU (IPv4 safe)
config.pmtu_max = 1400; // Maximum MTU
config.pmtu_interval_ms = 5000; // Probe interval
// Flow Control
config.initial_window_size = 64; // Initial window in packets
config.min_window_size = 16; // Minimum window
config.max_window_size = 256; // Maximum window
// Bandwidth Limiting (0 = unlimited)
config.outgoing_bandwidth_limit = 0; // Bytes per second
config.incoming_bandwidth_limit = 0; // Bytes per second
// Compression (optional)
config.compression = Lz4; // None, Lz4, or Zlib
config.compression_threshold = 128; // Compress if > 128 bytes
// Data Integrity (optional)
config.use_checksums = true; // Enable CRC32 checksums
// Congestion Control
config.rtt_smoothing_factor = 0.125; // RTT estimation smoothing
let host = bind_with_config?;
Configuration Presets
// Low-latency gaming (minimal reliability)
let mut config = default;
config.use_pmtu_discovery = true;
config.compression = None;
config.use_checksums = false;
// Reliable messaging (maximum reliability)
let mut config = default;
config.use_checksums = true;
config.compression = Lz4;
config.initial_window_size = 128;
// Bandwidth-constrained (mobile/embedded)
let mut config = default;
config.outgoing_bandwidth_limit = 100_000; // 100 KB/s
config.compression = Lz4;
config.pmtu_max = 1200;
Network Utilities
Bitfold includes built-in utilities for common networking operations:
use utilities;
// DNS Resolution
let addr = resolve_host?;
println!;
// Reverse DNS Lookup
use ;
let ip = V4;
let hostname = reverse_lookup?;
println!;
// IP Parsing
let addr = parse_ip?;
println!;
// IP Formatting
use SocketAddr;
let addr: SocketAddr = "127.0.0.1:8080".parse?;
let ip_str = format_ip;
println!; // "127.0.0.1"
Examples
The repository includes working examples for common scenarios:
Run the Server
Run the Client
The examples demonstrate:
- Connection establishment
- Multiple delivery modes
- Multi-channel communication
- Event handling
- Error recovery
Event Loop Integration
Bitfold supports two polling modes to fit different application architectures:
Manual Polling (Recommended for Game Loops)
use ;
use Host;
let mut host = bind_any?;
let frame_duration = from_millis; // 60 FPS
loop
Automatic Polling (Background Thread)
use thread;
use Host;
let mut host = bind_any?;
let event_rx = host.get_event_receiver;
// Start background polling thread (polls every 1ms)
spawn;
// Main thread processes events
for event in event_rx.iter
Integration with async/await
use ;
use Host;
async
Architecture
Bitfold uses a modular workspace architecture with clear separation of concerns:
bitfold/
├── core - Configuration, types, utilities, memory pooling
├── protocol - Pure protocol logic (no I/O)
│ ├── Packet encoding/decoding
│ ├── Acknowledgment handling
│ ├── Congestion control
│ ├── Compression (LZ4, Zlib)
│ └── CRC32 checksums
├── peer - Per-peer state machine
│ ├── Command queuing & batching
│ ├── Flow control (sliding window)
│ ├── Fragment reassembly
│ ├── PMTU discovery
│ └── Statistics tracking
└── host - Socket I/O and session management
├── UDP socket handling
├── Multi-peer coordination
├── Event emission
└── Polling modes
Design Principles
- Layered Architecture - Clear separation between I/O, protocol, and application logic
- Zero I/O Protocol Layer - Protocol logic is pure and easily testable
- Per-Peer Isolation - No shared mutable state between peers
- Arc-Based Sharing - Zero-copy buffer management
- Workspace Modularity - Users can depend on specific packages
Package Structure
bitfold (facade)
↓
bitfold-host (I/O layer)
↓
bitfold-peer (state machine)
↓
bitfold-protocol (pure protocol logic)
↓
bitfold-core (foundation)
For detailed architecture documentation, see WORKSPACE.md.
Best Practices
1. Choose the Right Delivery Mode
// High-frequency updates → Unreliable
host.send?;
// Important events → Reliable Unordered
host.send?;
// Sequential messages → Reliable Ordered
host.send?;
// Latest state only → Reliable Sequenced
host.send?;
2. Use Channels for Traffic Separation
const CHANNEL_COMMANDS: u8 = 0;
const CHANNEL_STATE: u8 = 1;
const CHANNEL_CHAT: u8 = 2;
// Prevents chat messages from blocking game state
host.send?;
3. Enable PMTU Discovery
// Default is already enabled, but you can configure it
config.use_pmtu_discovery = true; // Automatically finds optimal MTU
config.pmtu_min = 576; // IPv4 minimum
config.pmtu_max = 1400; // Safe for most networks
4. Poll Regularly
// Call at least once per frame (16ms for 60 FPS)
host.manual_poll;
// More frequent polling = lower latency
// 1ms polling is recommended for real-time applications
5. Clean Up Stale Fragments
// Call periodically in long-running applications (once per second)
let now = now;
for in host.peers_mut
6. Monitor Statistics
for in host.peers
7. Handle Bandwidth-Constrained Connections
config.compression = Lz4;
config.compression_threshold = 128;
config.outgoing_bandwidth_limit = 100_000; // 100 KB/s
8. Use Checksums for Critical Data
config.use_checksums = true; // Detect data corruption
Performance
Bitfold is designed for high performance:
- Zero-copy operations - Arc-based buffer sharing eliminates unnecessary copies
- Packet pooling - Reusable buffers minimize allocations
- Command batching - Multiple operations per UDP packet reduce overhead
- Efficient encoding - Compact binary protocol with optional compression
- Lock-free channels - Crossbeam channels for inter-thread communication
- Adaptive flow control - Dynamic window sizing based on network conditions
Benchmarks
Typical performance on a modern system (i7-9700K, 1Gbps LAN):
- Throughput: 500+ MB/s with large packets
- Latency: <1ms local network, <50ms WAN
- Packets/sec: 100,000+ small packets
- CPU usage: <5% at moderate load
Memory Usage
- Per-peer overhead: ~8-16 KB (depending on configuration)
- Buffer pools: Configurable, typically 1-4 MB
- Packet overhead: 5-20 bytes depending on delivery mode
Testing
Run the test suite:
# Run all tests
# Run tests for a specific package
# Run with verbose output
# Run doc tests
Code Quality
# Format code
# Lint code
# Check without building
# Generate documentation
Contributing
We code with AI. All implementation is done through AI-assisted development to maintain consistency and quality.
We Welcome
- Bug reports with reproduction steps
- Performance proposals with benchmarks
- Feature requests with use cases and rationale
- PRs for config files (
clippy.toml,.rustfmt.toml, CI/CD, documentation)
We Don't Accept
- PRs that modify source code - all implementation is done via our AI workflow
How to Contribute
- File an issue with detailed information
- We implement using AI-assisted development
- You get credited in the changelog and commit messages
Reporting Bugs
Please include:
- Rust version (
rustc --version) - Bitfold version
- Operating system
- Minimal reproduction code
- Expected vs actual behavior
License
This project is licensed under the MIT License. See the LICENSE file for details.
Acknowledgments
Bitfold is inspired by ENet, a proven reliable UDP library used in thousands of games and applications. We've modernized the concepts for Rust's ownership model and added features requested by the community.