# fastalloc
[](https://crates.io/crates/fastalloc)
[](https://docs.rs/fastalloc)
[](README.md#license)
A high-performance memory pooling library for Rust with type-safe handles and zero-cost abstractions.
## Features
- 🚀 **Multiple pool types**: Fixed-size, growing, thread-local, and thread-safe pools
- 🔒 **Type-safe handles**: RAII-based handles that automatically return objects to the pool
- ⚙️ **Flexible configuration**: Builder pattern with extensive customization options
- 📊 **Optional statistics**: Track allocation patterns and pool usage
- 🔧 **Multiple allocation strategies**: Stack (LIFO), free-list, and bitmap allocators
- 🌐 **no_std support**: Works in embedded and bare-metal environments
## Quick Start
Add this to your `Cargo.toml`:
```toml
[dependencies]
fastalloc = "0.1.0"
```
Basic usage:
```rust
use fastalloc::FixedPool;
// Create a pool of 1000 integers
let pool = FixedPool::<i32>::new(1000).unwrap();
// Allocate from the pool
let mut handle = pool.allocate(42).unwrap();
// Use the value
assert_eq!(*handle, 42);
*handle = 100;
assert_eq!(*handle, 100);
// Automatically returned to pool when handle is dropped
drop(handle);
```
## Why Use Memory Pools?
Memory pools significantly improve performance in scenarios with frequent allocations:
- **Game Development**: Entities, particles, physics objects
- **Real-Time Systems**: Audio processing, robotics
- **High-Performance Servers**: Connection pooling, request handling
- **Data Processing**: Temporary objects in hot paths
- **Scientific Computing**: Matrices, particles, graph nodes
## Performance
Typical performance characteristics:
- Fixed pool allocation: **< 20ns** per object
- Deallocation: **< 10ns** per object
- Memory overhead: **< 5%** for pools over 1000 objects
- Thread-safe pool: **< 100ns** with moderate contention
## Examples
### Growing Pool with Configuration
```rust
use fastalloc::{GrowingPool, PoolConfig, GrowthStrategy};
let config = PoolConfig::builder()
.capacity(100)
.max_capacity(Some(1000))
.growth_strategy(GrowthStrategy::Exponential { factor: 2.0 })
.alignment(64) // Cache-line aligned
.build()
.unwrap();
let pool = GrowingPool::with_config(config).unwrap();
```
### Thread-Safe Pool
```rust
use fastalloc::ThreadSafePool;
use std::sync::Arc;
use std::thread;
let pool = Arc::new(ThreadSafePool::<i32>::new(1000).unwrap());
let mut handles = vec![];
for i in 0..4 {
let pool_clone = Arc::clone(&pool);
handles.push(thread::spawn(move || {
let handle = pool_clone.allocate(i * 100).unwrap();
*handle
}));
}
for handle in handles {
println!("Result: {}", handle.join().unwrap());
}
```
### Custom Initialization
```rust
use fastalloc::{PoolConfig, InitializationStrategy};
let config = PoolConfig::builder()
.capacity(100)
.reset_fn(
|| Vec::with_capacity(1024),
|v| v.clear(),
)
.build()
.unwrap();
```
### Statistics Tracking
```rust
#[cfg(feature = "stats")]
{
use fastalloc::FixedPool;
let pool = FixedPool::<i32>::new(100).unwrap();
// ... use pool ...
let stats = pool.statistics();
println!("Utilization: {:.1}%", stats.utilization_rate());
println!("Total allocations: {}", stats.total_allocations);
}
```
## Pool Types
### FixedPool
Pre-allocated fixed-size pool with O(1) operations and zero fragmentation.
```rust
let pool = FixedPool::<i32>::new(1000).unwrap();
```
### GrowingPool
Dynamic pool that grows based on demand according to a configurable strategy.
```rust
let pool = GrowingPool::with_config(config).unwrap();
```
### ThreadLocalPool
Per-thread pool that avoids synchronization overhead.
```rust
let pool = ThreadLocalPool::<i32>::new(100).unwrap();
```
### ThreadSafePool
Lock-based concurrent pool safe for multi-threaded access.
```rust
let pool = ThreadSafePool::<i32>::new(1000).unwrap();
```
## Features
Enable optional features in your `Cargo.toml`:
```toml
[dependencies]
fastalloc = { version = "0.1.0", features = ["stats", "serde", "parking_lot"] }
```
Available features:
- `std` (default): Enable standard library support
- `stats`: Pool statistics collection and reporting
- `serde`: Serialization support
- `parking_lot`: Faster mutex implementation
- `crossbeam`: Lock-free data structures
- `tracing`: Instrumentation support
- `lock-free`: Experimental lock-free pool (requires `crossbeam`)
## no_std Support
fastalloc works in `no_std` environments:
```toml
[dependencies]
fastalloc = { version = "0.1.0", default-features = false }
```
## Benchmarks
Run benchmarks with:
```bash
cargo bench
```
See `docs/benchmarks/` for detailed performance comparisons.
## Documentation
- [Getting Started Guide](docs/getting_started.md)
- [API Documentation](https://docs.rs/fastalloc)
- [Performance Tuning](docs/performance_guide.md)
- [Migration Guide](docs/migration_guide.md)
- [Architecture](docs/architecture.md)
## Examples
Run examples with:
```bash
cargo run --example basic_usage
cargo run --example game_entities
cargo run --example server_connections
cargo run --example particle_system
cargo run --example statistics --features stats
```
## Safety
fastalloc minimizes `unsafe` code and leverages Rust's ownership system to prevent:
- Use-after-free
- Double-free
- Data races
- Memory leaks
Debug builds include additional runtime checks.
## Contributing
Contributions are welcome! Please see [CONTRIBUTING.md](docs/contributing.md) for guidelines.
## License
Licensed under either of:
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
## Authors
- Eshan Roy <eshanized@proton.me>
## Organization
Tonmoy Infrastructure & Vision
## Repository
https://gitlab.com/tivisionoss/crates/fastalloc
## Changelog
See [CHANGELOG.md](CHANGELOG.md) for version history.