pub struct Pool<T> { /* private fields */ }Expand description
Growable object pool with LIFO reuse.
Objects are created on demand via the factory function when the pool
is empty. Use try_acquire() for the fast path that only returns
pooled objects, or acquire() which may create new objects.
§Example
use nexus_pool::local::Pool;
let pool = Pool::new(
|| Vec::<u8>::with_capacity(1024),
|v| v.clear(),
);
let mut buf = pool.acquire(); // Creates new object
buf.extend_from_slice(b"hello");
drop(buf); // Returns to pool, clear() is called
let buf2 = pool.acquire(); // Reuses existing (now empty) objectImplementations§
Source§impl<T> Pool<T>
impl<T> Pool<T>
Sourcepub fn new<F, R>(factory: F, reset: R) -> Self
pub fn new<F, R>(factory: F, reset: R) -> Self
Creates an empty pool with the given factory and reset functions.
§Arguments
factory- Creates new objects when pool is emptyreset- Called when object returns to pool (e.g.,Vec::clear)
Sourcepub fn with_capacity<F, R>(capacity: usize, factory: F, reset: R) -> Self
pub fn with_capacity<F, R>(capacity: usize, factory: F, reset: R) -> Self
Creates a pool pre-populated with capacity objects.
Sourcepub fn acquire(&self) -> Pooled<T>
pub fn acquire(&self) -> Pooled<T>
Acquires an object from the pool, creating one if necessary.
This always succeeds but may allocate if the pool is empty.
Sourcepub fn try_acquire(&self) -> Option<Pooled<T>>
pub fn try_acquire(&self) -> Option<Pooled<T>>
Attempts to acquire an object from the pool without creating.
Returns None if the pool is empty. This is the fast path.
Sourcepub fn take(&self) -> T
pub fn take(&self) -> T
Takes an object from the pool without an RAII guard, creating one via the factory if the pool is empty.
The caller is responsible for returning the object via put().
§Example
use nexus_pool::local::Pool;
let pool = Pool::new(
|| Vec::<u8>::with_capacity(1024),
|v| v.clear(),
);
let mut buf = pool.take();
buf.extend_from_slice(b"hello");
pool.put(buf); // manual return, reset is calledSourcepub fn try_take(&self) -> Option<T>
pub fn try_take(&self) -> Option<T>
Takes an object from the pool if one is available, without creating.
Returns None if the pool is empty. The caller is responsible for
returning the object via put().