pub struct OpaquePool { /* private fields */ }Expand description
A thread-safe pool of reference-counted objects with uniform memory layout.
Stores objects of any Send type that match a Layout defined at pool creation
time. All values in the pool remain pinned for their entire lifetime.
The pool automatically expands its capacity when needed.
§Lifetime management
When inserting an object into the pool, a handle to the object is returned.
The object is removed from the pool when the last remaining handle to the object
is dropped (Arc-like behavior).
Clones of the pool are functionally equivalent views over the same memory capacity.
§Thread safety
The pool is thread-safe (Send and Sync) and requires that any inserted items are Send.
§Example: unique object ownership
use std::fmt::Display;
use infinity_pool::OpaquePool;
let mut pool = OpaquePool::with_layout_of::<String>();
// Insert an object into the pool, returning a unique handle to it.
let mut handle = pool.insert("Hello, world!".to_string());
// A unique handle grants the same access as a `&mut` reference to the object.
handle.push_str(" Welcome to Infinity Pool!");
println!("Updated value: {}", &*handle);
// The object is removed when the handle is dropped.§Example: shared object ownership
use std::fmt::Display;
use infinity_pool::OpaquePool;
let mut pool = OpaquePool::with_layout_of::<String>();
// Insert an object into the pool, returning a unique handle to it.
let handle = pool.insert("Hello, world!".to_string());
// The unique handle can be converted into a shared handle,
// allowing multiple clones of the handle to be created.
let shared_handle = handle.into_shared();
let shared_handle_clone = shared_handle.clone();
// Shared handles grant the same access as `&` shared references to the object.
println!("Shared access to value: {}", &*shared_handle);
// The object is removed when the last shared handle is dropped.§Clones of the pool are functionally equivalent
use infinity_pool::OpaquePool;
let mut pool1 = OpaquePool::with_layout_of::<i32>();
let pool2 = pool1.clone();
assert_eq!(pool1.len(), pool2.len());
_ = pool1.insert(42_i32);
assert_eq!(pool1.len(), pool2.len());Implementations§
Source§impl OpaquePool
impl OpaquePool
Sourcepub fn with_layout(object_layout: Layout) -> Self
pub fn with_layout(object_layout: Layout) -> Self
Creates a new instance of the pool with the specified layout.
Shorthand for a builder that keeps all other options at their default values.
§Panics
Panics if the layout is zero-sized.
Sourcepub fn with_layout_of<T: Sized + Send>() -> Self
pub fn with_layout_of<T: Sized + Send>() -> Self
Creates a new instance of the pool with the layout of T.
Shorthand for a builder that keeps all other options at their default values.
Sourcepub fn object_layout(&self) -> Layout
pub fn object_layout(&self) -> Layout
The layout of objects stored in this pool.
All inserted objects must match this layout.
Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
The total capacity of the pool.
This is the maximum number of objects (including current contents) that the pool can contain without capacity extension. The pool will automatically extend its capacity if more than this many objects are inserted.
Sourcepub fn reserve(&self, additional: usize)
pub fn reserve(&self, additional: usize)
Ensures that the pool has capacity for at least additional more objects.
§Panics
Panics if the new capacity would exceed the size of virtual memory (usize::MAX).
Sourcepub fn shrink_to_fit(&self)
pub fn shrink_to_fit(&self)
Drops unused pool capacity to reduce memory usage.
There is no guarantee that any unused capacity can be dropped. The exact outcome depends on the specific pool structure and which objects remain in the pool.
Sourcepub fn insert<T: Send + 'static>(&self, value: T) -> PooledMut<T>
pub fn insert<T: Send + 'static>(&self, value: T) -> PooledMut<T>
Inserts an object into the pool and returns a handle to it.
§Panics
Panics if the layout of T does not match the object layout of the pool.
Sourcepub unsafe fn insert_unchecked<T: Send + 'static>(
&self,
value: T,
) -> PooledMut<T>
pub unsafe fn insert_unchecked<T: Send + 'static>( &self, value: T, ) -> PooledMut<T>
Inserts an object into the pool and returns a handle to it.
§Safety
The caller must ensure that the layout of T matches the pool’s object layout.
Sourcepub unsafe fn insert_with<T, F>(&self, f: F) -> PooledMut<T>
pub unsafe fn insert_with<T, F>(&self, f: F) -> PooledMut<T>
Inserts an object into the pool via closure and returns a handle to it.
This method allows the caller to partially initialize the object, skipping any MaybeUninit
fields that are intentionally not initialized at insertion time. This can make insertion of
objects containing MaybeUninit fields faster, although requires unsafe code to implement.
This method is NOT faster than insert() for fully initialized objects.
Prefer insert() for a better safety posture if you do not intend to
skip initialization of any MaybeUninit fields.
§Example
use std::mem::MaybeUninit;
use std::ptr;
use infinity_pool::OpaquePool;
struct DataBuffer {
id: u32,
data: MaybeUninit<[u8; 1024]>,
}
let mut pool = OpaquePool::with_layout_of::<DataBuffer>();
// Initialize only the id, leaving data uninitialized for performance.
let handle = unsafe {
pool.insert_with(|uninit: &mut MaybeUninit<DataBuffer>| {
let ptr = uninit.as_mut_ptr();
// SAFETY: We are writing to a correctly located field within the object.
unsafe {
ptr::addr_of_mut!((*ptr).id).write(42);
}
})
};
assert_eq!(handle.id, 42);§Panics
Panics if the layout of T does not match the object layout of the pool.
§Safety
The closure must correctly initialize the object. All fields that
are not MaybeUninit must be initialized when the closure returns.
Sourcepub unsafe fn insert_with_unchecked<T, F>(&self, f: F) -> PooledMut<T>
pub unsafe fn insert_with_unchecked<T, F>(&self, f: F) -> PooledMut<T>
Inserts an object into the pool via closure and returns a handle to it.
This method allows the caller to partially initialize the object, skipping any MaybeUninit
fields that are intentionally not initialized at insertion time. This can make insertion of
objects containing MaybeUninit fields faster, although requires unsafe code to implement.
This method is NOT faster than insert() for fully initialized objects.
Prefer insert() for a better safety posture if you do not intend to
skip initialization of any MaybeUninit fields.
This unchecked variant of the method skips the layout verification step, requiring the caller to ensure that the object has a matching layout with the pool.
§Safety
The caller must ensure that the layout of T matches the pool’s object layout.
The closure must correctly initialize the object. All fields that
are not MaybeUninit must be initialized when the closure returns.
Sourcepub fn with_iter<F, R>(&self, f: F) -> Rwhere
F: FnOnce(OpaquePoolIterator<'_>) -> R,
pub fn with_iter<F, R>(&self, f: F) -> Rwhere
F: FnOnce(OpaquePoolIterator<'_>) -> R,
Calls a closure with an iterator over all objects in the pool.
The iterator only yields pointers to the objects, not references, because the pool
does not have the authority to create references to its contents as user code may
concurrently be holding a conflicting exclusive reference via PooledMut<T>.
Therefore, obtaining actual references to pool contents via iteration is only possible by using the pointer to create such references in unsafe code and relies on the caller guaranteeing that no conflicting exclusive references exist.
The pool is locked for the entire duration of the closure, ensuring that objects cannot be removed while iteration is in progress. This guarantees that all pointers yielded by the iterator remain valid for the duration of the closure.
§Examples
let mut pool = OpaquePool::with_layout_of::<u32>();
let _handle1 = pool.insert(42u32);
let _handle2 = pool.insert(100u32);
let values: Vec<u32> = pool.with_iter(|iter| {
// SAFETY: We ensure that no conflicting references to the pooled objects
// exist. Simply look up - we just inserted the values, so there is nothing
// else that could have a conflicting exclusive reference to them.
iter.map(|ptr| unsafe { *ptr.cast::<u32>().as_ref() })
.collect()
});
assert_eq!(values.iter().sum::<u32>(), 142);