OpaquePool

Struct OpaquePool 

Source
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

use infinity_pool::OpaquePool;

fn work_with_displayable<T: std::fmt::Display + Send + 'static>(value: T) {
    let mut pool = OpaquePool::with_layout_of::<T>();

    // Insert an object into the pool
    let handle = pool.insert(value);

    // Access the object through the handle
    println!("Stored: {}", &*handle);

    // The object is automatically removed when the handle is dropped
}

work_with_displayable("Hello, world!");
work_with_displayable(42);

§Pool clones 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());
let _handle = pool1.insert(42_i32);
assert_eq!(pool1.len(), pool2.len());

Implementations§

Source§

impl OpaquePool

Source

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.

Source

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.

§Panics

Panics if T is a zero-sized type.

Source

pub fn object_layout(&self) -> Layout

The layout of objects stored in this pool.

All inserted objects must match this layout.

Source

pub fn len(&self) -> usize

The number of objects currently in the pool.

Source

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.

Source

pub fn is_empty(&self) -> bool

Whether the pool contains zero objects.

Source

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).

Source

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.

Source

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.

§Example
use infinity_pool::OpaquePool;

let mut pool = OpaquePool::with_layout_of::<String>();

// Insert an object into the pool
let mut handle = pool.insert("Hello".to_string());

// Mutate the object via the unique handle
handle.push_str(", Opaque World!");
assert_eq!(&*handle, "Hello, Opaque World!");

// Transform the unique handle into a shared handle
let shared_handle = handle.into_shared();

// After transformation, you can only immutably dereference the object
assert_eq!(&*shared_handle, "Hello, Opaque World!");
// shared_handle.push_str("!"); // This would not compile

// The object is removed when the handle is dropped
drop(shared_handle); // Explicitly drop to remove from pool
assert_eq!(pool.len(), 0);
Source

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.

Source

pub unsafe fn insert_with<T, F>(&self, f: F) -> PooledMut<T>
where T: Send + 'static, F: FnOnce(&mut MaybeUninit<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 infinity_pool::OpaquePool;

struct DataBuffer {
    id: u32,
    data: MaybeUninit<[u8; 1024]>, // Large buffer to skip initializing
}

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: Writing to the id field within allocated space
        unsafe {
            std::ptr::addr_of_mut!((*ptr).id).write(42);
            // data field is intentionally left uninitialized
        }
    })
};

// ID is accessible, data remains uninitialized
let id = unsafe { std::ptr::addr_of!((*handle).id).read() };
assert_eq!(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.

Source

pub unsafe fn insert_with_unchecked<T, F>(&self, f: F) -> PooledMut<T>
where T: Send + 'static, F: FnOnce(&mut MaybeUninit<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 infinity_pool::OpaquePool;

struct DataBuffer {
    id: u32,
    data: MaybeUninit<[u8; 1024]>, // Large buffer to skip initializing
}

let mut pool = OpaquePool::with_layout_of::<DataBuffer>();

// Initialize only the id, leaving data uninitialized for performance
let handle = unsafe {
    pool.insert_with_unchecked(|uninit: &mut MaybeUninit<DataBuffer>| {
        let ptr = uninit.as_mut_ptr();
        // SAFETY: Writing to the id field within allocated space
        unsafe {
            std::ptr::addr_of_mut!((*ptr).id).write(42);
            // data field is intentionally left uninitialized
        }
    })
};

// ID is accessible, data remains uninitialized
let id = unsafe { std::ptr::addr_of!((*handle).id).read() };
assert_eq!(id, 42);
§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.

Source

pub fn with_iter<F, R>(&self, f: F) -> R
where F: FnOnce(OpaquePoolIterator<'_>) -> R,

Calls a closure with an iterator over all objects in the pool.

The iterator yields untyped pointers (NonNull<()>) to the objects stored in the pool. It is the caller’s responsibility to cast these pointers to the appropriate type.

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);

// Safe iteration with guaranteed pointer validity
pool.with_iter(|iter| {
    for ptr in iter {
        // SAFETY: We know these are u32 pointers from this pool
        let value = unsafe { *ptr.cast::<u32>().as_ref() };
        println!("Value: {}", value);
    }
});

// Collect values safely
let values: Vec<u32> = pool.with_iter(|iter| {
    iter.map(|ptr| unsafe { *ptr.cast::<u32>().as_ref() })
        .collect()
});

Trait Implementations§

Source§

impl Clone for OpaquePool

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for OpaquePool

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.