Struct Pool
pub struct Pool<T> { /* private fields */ }Expand description
A lazily allocated pool with a fixed slot limit and stable live handles.
Values are never moved between slots by removal or retention. The backing vector can move when it grows, so handles provide identity, not pinned addresses.
Implementations§
§impl<T> Pool<T>
impl<T> Pool<T>
pub fn new(capacity: usize) -> Pool<T>
pub fn new(capacity: usize) -> Pool<T>
Create an empty pool without allocating storage. A zero limit is valid.
pub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
The configured slot limit, including slots retired by generation exhaustion.
This limit never changes and is not the currently allocated storage size.
Use Self::available to plan how many insertions can succeed.
use ferravex_engine::pool::Pool;
let mut pool = Pool::new(2);
let handle = pool.insert("temporary").unwrap();
pool.remove(handle);
assert_eq!(pool.capacity(), 2);pub fn available(&self) -> usize
pub fn available(&self) -> usize
Number of insertions the pool can accept without intervening removals.
Counts reusable and not-yet-created slots in constant time. Retired slots
are excluded, so this can be less than capacity() - len(). Availability
describes the slot limit; it does not promise allocation-free insertion.
use ferravex_engine::pool::Pool;
let mut pool = Pool::new(2);
let handle = pool.insert(10).unwrap();
assert_eq!(pool.available(), 1);
pool.remove(handle);
assert_eq!(pool.available(), 2);pub fn is_full(&self) -> bool
pub fn is_full(&self) -> bool
Whether no further insertion can succeed without removing a live value.
A zero-capacity pool, or one whose slots are all retired, is both empty and full. Removing a value at its final generation does not free a slot.
use ferravex_engine::pool::Pool;
let mut pool = Pool::new(1);
pool.insert(10).unwrap();
assert!(pool.is_full());
assert_eq!(pool.insert(20), Err(20));
assert!(Pool::<u8>::new(0).is_full());pub fn insert(&mut self, value: T) -> Result<Handle, T>
pub fn insert(&mut self, value: T) -> Result<Handle, T>
Insert a value, reusing the most recently freed slot when possible.
Returns the value unchanged if no usable slot remains.
pub fn get(&self, h: Handle) -> Option<&T>
pub fn get_mut(&mut self, h: Handle) -> Option<&mut T>
pub fn get2_mut(
&mut self,
first: Handle,
second: Handle,
) -> Result<(&mut T, &mut T), PoolAccessError>
pub fn get2_mut( &mut self, first: Handle, second: Handle, ) -> Result<(&mut T, &mut T), PoolAccessError>
Borrow two live values mutably in the requested order without allocation.
Both handles must belong to this pool and select distinct live slots.
Validation and error precedence match Self::get_many_mut. No values
are removed or moved, and their handles remain valid. This also works
when the pool is full.
This fixed-tick recipe transfers energy and resolves a one-dimensional equal-mass collision between two live actors. Feedback can follow the successful response; a rejected selection applies neither change.
use ferravex_engine::pool::{Pool, PoolAccessError};
#[derive(Debug)]
struct Actor { energy: u32, velocity: i32 }
let mut actors = Pool::new(2);
let left = actors.insert(Actor { energy: 12, velocity: 3 }).unwrap();
let right = actors.insert(Actor { energy: 2, velocity: -1 }).unwrap();
let (donor, receiver) = actors.get2_mut(left, right)?;
let transfer = donor.energy.min(4);
donor.energy -= transfer;
receiver.energy += transfer;
std::mem::swap(&mut donor.velocity, &mut receiver.velocity);
assert_eq!(actors.get(left).unwrap().energy, 8);
assert_eq!(actors.get(right).unwrap().energy, 6);
assert_eq!(actors.get(left).unwrap().velocity, -1);
assert_eq!(actors.get(right).unwrap().velocity, 3);
assert!(actors.is_full());pub fn get_many_mut<const N: usize>(
&mut self,
handles: [Handle; N],
) -> Result<[&mut T; N], PoolAccessError>
pub fn get_many_mut<const N: usize>( &mut self, handles: [Handle; N], ) -> Result<[&mut T; N], PoolAccessError>
Borrow a fixed selection of live values mutably in caller order.
All handles must belong to this pool. Before returning any references,
checks every handle for a live matching generation in caller order,
then rejects duplicate slots. PoolAccessError describes which error
wins when a selection has multiple problems. An empty selection succeeds,
including on a zero-capacity pool. Failure leaves all values, generations,
and storage unchanged. Mutations through successful references are ordinary
Rust mutations; they are not rolled back if subsequent caller code panics.
Uses safe disjoint slice access with O(N²) validation work and O(N) stack
storage, independent of pool capacity. Neither pool storage nor a returned
collection allocates; values stay in their slots and handles stay valid.
Prefer small selections; use Self::iter_mut to visit the whole pool.
use ferravex_engine::pool::{Pool, PoolAccessError};
let mut pool = Pool::new(3);
let a = pool.insert(10).unwrap();
let b = pool.insert(20).unwrap();
let c = pool.insert(30).unwrap();
let [last, first, middle] = pool.get_many_mut([c, a, b])?;
*last += 3;
*first += 1;
*middle += 2;
assert_eq!(pool.get(a), Some(&11));
assert_eq!(pool.get(b), Some(&22));
assert_eq!(pool.get(c), Some(&33));pub fn remove(&mut self, h: Handle) -> Option<T>
pub fn iter(&self) -> impl Iterator<Item = (Handle, &T)>
pub fn iter(&self) -> impl Iterator<Item = (Handle, &T)>
Visit live handles and values in ascending slot order without allocating.
Slot order can differ from insertion order after reuse.
pub fn iter_mut(&mut self) -> impl Iterator<Item = (Handle, &mut T)>
pub fn iter_mut(&mut self) -> impl Iterator<Item = (Handle, &mut T)>
Mutably visit live values in the same ascending slot order as Self::iter.
No pool storage is allocated. Updating a value preserves its handle.
use ferravex_engine::pool::Pool;
let mut pool = Pool::new(2);
let handle = pool.insert(3).unwrap();
for (current, value) in pool.iter_mut() {
assert_eq!(current, handle);
*value += 2;
}
assert_eq!(pool.get(handle), Some(&5));pub fn retain<F>(&mut self, keep: F)
pub fn retain<F>(&mut self, keep: F)
Update live values and retain only those for which keep returns true.
Visits each live slot once, in Self::iter order. Kept values preserve
their handles; removed values are dropped and their handles invalidated
just as with Self::remove. Retired and vacant slots are skipped.
No temporary collection is created; the reusable-index vector can grow
as in remove, and retains its allocation for subsequent reuse.
If the predicate panics, earlier mutations and removals remain applied. The current value remains live (including any mutation before the panic), and later slots are untouched. If a removed value’s destructor panics, its slot has already been removed and made reusable or retired.
use ferravex_engine::pool::Pool;
let mut lifetimes = Pool::new(2);
let expired = lifetimes.insert(1_u32).unwrap();
let active = lifetimes.insert(3_u32).unwrap();
lifetimes.retain(|_, ticks| {
*ticks = ticks.saturating_sub(1);
*ticks > 0
});
assert_eq!(lifetimes.get(expired), None);
assert_eq!(lifetimes.get(active), Some(&2));
let reused = lifetimes.insert(5).unwrap();
assert_ne!(expired, reused);pub fn clear(&mut self)
pub fn clear(&mut self)
Drop all live values while retaining slot generations and backing storage.
Old handles remain invalid after reinsertion. Exhausted slots stay retired;
clearing does not restore their availability. This is equivalent to
retain(|_, _| false), including its allocation and destructor-panic behavior.
use ferravex_engine::pool::Pool;
let mut pool = Pool::new(1);
let old = pool.insert("before restart").unwrap();
pool.clear();
assert!(pool.is_empty());
assert_eq!(pool.available(), 1);
let new = pool.insert("after restart").unwrap();
assert_ne!(old, new);
assert_eq!(pool.get(old), None);