pub struct Pool<A> { /* private fields */ }
Expand description
A pool of preallocated memory sized to match type A
.
In order to use it to allocate objects, pass it to
PoolRef::new()
or PoolRef::default()
.
§Example
let mut pool: Pool<usize> = Pool::new(1024);
let pool_ref = PoolRef::new(&mut pool, 31337);
assert_eq!(31337, *pool_ref);
Implementations§
Source§impl<A> Pool<A>
impl<A> Pool<A>
Sourcepub fn new(max_size: usize) -> Self
pub fn new(max_size: usize) -> Self
Construct a new pool with a given max size and return a handle to it.
Values constructed via the pool will be returned to the pool when
dropped, up to max_size
. When the pool is full, values will be dropped
in the regular way.
If max_size
is 0
, meaning the pool can never hold any dropped
values, this method will give you back a null handle without allocating
a pool. You can still use this to construct PoolRef
values, they’ll
just allocate in the old fashioned way without using a pool. It is
therefore advisable to use a zero size pool as a null value instead of
Option<Pool>
, which eliminates the need for unwrapping the Option
value.
Sourcepub fn get_max_size(&self) -> usize
pub fn get_max_size(&self) -> usize
Get the maximum size of the pool.
Sourcepub fn get_pool_size(&self) -> usize
pub fn get_pool_size(&self) -> usize
Get the current size of the pool.
Sourcepub fn fill(&self)
pub fn fill(&self)
Fill the pool with empty allocations.
This operation will pre-allocate self.get_max_size() - self.get_pool_size()
memory chunks, without initialisation, and put
them in the pool.
§Examples
let pool: Pool<usize> = Pool::new(1024);
assert_eq!(0, pool.get_pool_size());
pool.fill();
assert_eq!(1024, pool.get_pool_size());
Sourcepub fn filled(self) -> Self
pub fn filled(self) -> Self
Fill the pool and return it.
This is a convenience function that calls fill()
on
the pool, so that you can construct a pool with a one liner:
let pool: Pool<u64> = Pool::new(1024).filled();
assert!(pool.is_full());
This is functionally equivalent to, but terser than:
let mut pool: Pool<u64> = Pool::new(1024);
pool.fill();
assert!(pool.is_full());
Sourcepub fn cast<B>(&self) -> Pool<B>
pub fn cast<B>(&self) -> Pool<B>
Convert a pool handle for type A
into a handle for type B
.
The types A
and B
must have the same size and alignment, as
per std::mem::size_of
and
std::mem::align_of
, or this method will panic.
This lets you use the same pool to construct values of different types, as long as they are of the same size and alignment, so they can reuse each others’ memory allocations.
§Examples
let u64_pool: Pool<u64> = Pool::new(1024);
let u64_number = PoolRef::new(&u64_pool, 1337);
let i64_pool: Pool<i64> = u64_pool.cast();
let i64_number = PoolRef::new(&i64_pool, -1337);