A fast, single-threaded arena allocator with automatic reference counting in Rust.
RefArena provides a memory-efficient way to allocate objects in an arena while managing their lifetimes through reference counting. Unlike traditional arenas, RefArena allows individual objects to be deallocated when no longer referenced, preventing memory leaks in long-running applications.
- Single-threaded: Designed for single-threaded use cases where performance is critical.
- Reference counting: Automatic deallocation when the last reference is dropped.
- Growable: Dynamic capacity expansion.
- Memory efficient: Uses bitsets for internal tracking.
- Safe API: Lifetime-bound references prevent use-after-free.
Add to your Cargo.toml:
[dependencies]
refarena = "0.1"use refarena::Arena;
let arena = Arena::with_capacity(10);
// Allocate values
let ref1 = arena.alloc(String::from("Hello")).unwrap();
let ref2 = arena.alloc(String::from("World")).unwrap();
// Access values
println!("{} {}", ref1, ref2); // Prints: Hello World
// Clone references
let ref3 = ref1.clone();
// Values are deallocated when last reference is dropped
drop(ref1);
drop(ref2);
// ref3 still holds the value
drop(ref3); // Now deallocatedlet mut arena = Arena::with_capacity(5);
// ... allocate up to 5 items ...
arena.grow(10); // Expand capacity
// ... allocate more items ...new() -> Arena<T>: Create an arena with zero capacity.with_capacity(capacity: usize) -> Arena<T>: Create with initial capacity.alloc(value: T) -> Option<Ref<'_, T>>: Allocate a value, returns None if full.grow(new_cap: usize): Increase capacity.
- Implements
Deref<Target=T>for value access. - Implements
Clonefor shared ownership. - Automatically deallocates when count reaches zero.
Arena<T>is notSync- use only in single thread.Ref<'arena, T>is bound by the arena's lifetime.- No unsafe public APIs - all unsafety is internal and verified.
- Allocation: O(1) amortized
- Deallocation: O(1) when reference count reaches zero
- Memory overhead: ~1 bit per allocated slot for tracking