RawOpaquePool

Struct RawOpaquePool 

Source
pub struct RawOpaquePool { /* private fields */ }
Expand description

A pool of objects with uniform memory layout.

Stores objects of any 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.

§Thread safety

The pool is nominally single-threaded because the compiler cannot know what types of objects are stored inside a given instance, so it must default to assuming they are single-threaded objects.

If all the objects inserted are Send then the owner of the pool is allowed to treat the pool itself as thread-safe (Send and Sync) but must do so using unsafe code, such as via a wrapper type that explicitly implements Send and Sync.

§Example: unique object ownership

use std::fmt::Display;

use infinity_pool::RawOpaquePool;

let mut pool = RawOpaquePool::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 allows us to create exclusive references to the target object.
// SAFETY: We promise to keep the pool alive for the duration of this reference.
let value_mut = unsafe { handle.as_mut() };
value_mut.push_str(" Welcome to Infinity Pool!");

println!("Updated value: {value_mut}");

// This is optional - we could also just drop the pool.
// SAFETY: We promise that this handle really is for an object present in this pool.
unsafe {
    pool.remove(handle);
}

§Example: shared object ownership

use std::fmt::Display;

use infinity_pool::RawOpaquePool;

let mut pool = RawOpaquePool::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 copies of the handle to be created.
let shared_handle = handle.into_shared();
let shared_handle_copy = shared_handle;

// Shared handles allow only shared references to be created.
// SAFETY: We promise to keep the pool alive for the duration of this reference.
let value_ref = unsafe { shared_handle.as_ref() };

println!("Shared access to value: {value_ref}");

// This is optional - we could also just drop the pool.
// SAFETY: We promise that the object has not already been removed
// via a different shared handle - look up to verify that.
unsafe {
    pool.remove(shared_handle);
}

Implementations§

Source§

impl RawOpaquePool

Source

pub fn builder() -> RawOpaquePoolBuilder

Starts configuring and creating a new instance of the pool.

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

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(&mut 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(&mut 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: 'static>(&mut self, value: T) -> RawPooledMut<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.

Source

pub unsafe fn insert_unchecked<T: 'static>( &mut self, value: T, ) -> RawPooledMut<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>(&mut self, f: F) -> RawPooledMut<T>
where F: FnOnce(&mut MaybeUninit<T>), T: 'static,

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::RawOpaquePool;

struct DataBuffer {
    id: u32,
    data: MaybeUninit<[u8; 1024]>,
}

let mut pool = RawOpaquePool::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);
        }
    })
};

// SAFETY: We promise that the pool is not dropped while we hold this reference.
let item = unsafe { handle.as_ref() };
assert_eq!(item.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>(&mut self, f: F) -> RawPooledMut<T>
where F: FnOnce(&mut MaybeUninit<T>), T: 'static,

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.

Source

pub unsafe fn remove<T: ?Sized>(&mut self, handle: impl Into<RawPooled<T>>)

Removes an object from the pool, dropping the object.

§Safety

The caller must guarantee that the handle is for an object currently present in this pool.

Source

pub unsafe fn remove_unpin<T: Unpin>( &mut self, handle: impl Into<RawPooled<T>>, ) -> T

Removes an object from the pool and returns the object.

§Safety

The caller must guarantee that the handle is for an object currently present in this pool.

Source

pub fn iter(&self) -> RawOpaquePoolIterator<'_>

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

Trait Implementations§

Source§

impl Debug for RawOpaquePool

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'p> IntoIterator for &'p RawOpaquePool

Source§

type Item = NonNull<()>

The type of the elements being iterated over.
Source§

type IntoIter = RawOpaquePoolIterator<'p>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. 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> 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, 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.