Skip to main content

ConcurrentHive

Struct ConcurrentHive 

Source
pub struct ConcurrentHive<T, const PAGE: usize = DEFAULT_PAGE> { /* private fields */ }
Available on crate feature concurrent only.
Expand description

A paged container with stable addresses and shared insertion and removal.

get returns a guard instead of a bare reference. Removal invalidates the id immediately, but existing guards keep the value alive. Taking a value waits for its guards. A forgotten guard pins its slot until exclusive access or destruction. There is no mutable access while shared.

Pages stay allocated until shrink_to_fit frees the empty ones; shared inserts reuse freed pages later. Shared iteration is weakly consistent: it may miss concurrent insertions or removals. len is approximate during shared operations and exact when they have finished. Exclusive scans take O(index_bound) time.

Each successful lookup costs two atomic writes (guard acquisition and release). Prefer Hive when shared mutation is not needed. As with that type, ids carry no container identity, generations never wrap, and stale ids stay dead within one allocation history.

PAGE must be non-zero, fit in a u32, and fit a page in isize::MAX bytes. Uses only core and alloc; std enables yielding while waiting.

Implementations§

Source§

impl<T, const PAGE: usize> ConcurrentHive<T, PAGE>

Source

pub const PAGE: usize = PAGE

Number of slots per page.

Source

pub fn new() -> Self

An empty hive, without allocating.

§Panics

Panics if the page capacity is invalid; see the type’s documentation.

Source

pub fn insert(&self, value: T) -> Id

Inserts value and returns its id.

§Panics

Panics if all MAX_INDICES indices are occupied or retired, or a page cannot be allocated. A concurrent finalizer may make room later.

Source

pub fn try_insert(&self, value: T) -> Result<Id, T>

Like insert, returning the value on index exhaustion. Allocation failures may still panic or abort.

Source

pub fn insert_with(&self, f: impl FnOnce(Id) -> T) -> Id

Inserts the value f makes from its id.

If f panics, the slot is returned to the free stack and the generation of the id passed to f is spent, so that id stays dead.

§Panics

Panics on index exhaustion or if f panics; allocation may also fail.

Source

pub fn try_insert_with(&self, f: impl FnOnce(Id) -> T) -> Option<Id>

Like insert_with, returning None without calling f when no index is available.

Source

pub fn get(&self, id: Id) -> Option<Ref<'_, T, PAGE>>

Pins the value of a matching live id until the returned guard drops.

Returns None for a stale or removed id. Panics if the slot already has the maximum of 2²⁹ − 1 guards. Guards cannot be cloned.

Source

pub fn contains(&self, id: Id) -> bool

Whether this id is live at the instant of one state load. Does not pin the value against a subsequent removal.

Source

pub fn remove(&self, id: Id) -> bool

Logically removes a matching live id. Exactly one remover succeeds. Existing guards defer destruction until the last guard drops.

If immediate value destruction panics, the id is still removed and its slot is returned after drop glue finishes unwinding.

Source

pub fn take(&self, id: Id) -> Option<T>

Removes and returns a matching live value, waiting for its guards.

Blocks while any guard on this id lives; deadlocks if the calling thread holds one. A forgotten guard can block this call forever. Competing removes or takes return false/None once this call marks the id. The last guard never drops a value owned by a taker.

Source

pub fn len(&self) -> usize

Number of logically live values; approximate during shared operations. Exact when no operation is in flight; this is no publication barrier.

It sums per-thread counters (per page group without std). While operations are in flight it may combine counters read at different moments and differ from every count the hive held; it never exceeds the number of insertions.

Source

pub fn is_empty(&self) -> bool

Whether the hive is empty; approximate during shared operations.

Source

pub fn index_bound(&self) -> u32

One past the highest reserved index, including insertions in flight. A reserved index’s page may not have been installed yet.

Threads that contend for fresh indices reserve them in blocks of about one page, so the bound may exceed the indices handed out by up to one block per thread.

Source

pub fn iter(&self) -> Iter<'_, T, PAGE> ⓘ

Iterates over (id, guard) in slot order, weakly consistently. Scans only indices below the reservation bound at iterator creation.

Source

pub fn get_mut(&mut self, id: Id) -> Option<&mut T>

The matching live value, mutably, under exclusive access. Forgotten guard counts at this slot are reset. A marked value is finalized and is never returned, even for a different requested id.

Source

pub fn take_mut(&mut self, id: Id) -> Option<T>

Removes and returns a live value without waiting for forgotten guards. Finalizes a marked value at this slot without returning it.

Source

pub fn iter_mut(&mut self) -> IterMut<'_, T, PAGE> ⓘ

Iterates over live (id, &mut value) pairs in slot order. Finalizes all marked values and resets forgotten counts before yielding.

Source

pub fn clear(&mut self)

Removes and drops every value, retaining pages and generation history. Forgotten guards do not pin values under exclusive access.

Source

pub fn drain(&mut self) -> Drain<'_, T, PAGE> ⓘ

Eagerly removes every live value, yielding owned (id, value) pairs in slot order. Dropping or forgetting the iterator leaves the hive empty. Marked values are finalized and not yielded. Pages and generations stay.

Source

pub fn retain(&mut self, keep: impl FnMut(Id, &mut T) -> bool)

Keeps values for which keep(id, value) returns true, in slot order. Finalizes marked values and resets forgotten counts before calling keep. If the predicate or a destructor panics, prior changes remain and len stays exact.

Source

pub fn shrink_to_fit(&mut self)

Frees every page that holds no value, under exclusive access. Takes O(index_bound) time.

Marked values are finalized and forgotten guard counts reset first. A page is then freed if it lies wholly below the reservation bound and all its slots are vacant and reusable (a page with a retired slot is kept). It remembers its highest version, so ids it issued stay dead: shared inserts reuse freed pages, lowest first, after the free slots of the remaining pages, with generations above every earlier one. That order is exact only for one inserter that has not contended with others: a thread first uses up a block of fresh indices it reserved under contention, and while one insert is relinking a reused page, a concurrent insert can take a fresh index instead (and fail at the index limit even though slots are about to be freed). The free slots are relinked in index order. The page directory’s own small arrays stay allocated.

use paged_collections::concurrent::ConcurrentHive;

let mut hive = ConcurrentHive::<u32, 4>::new();
let ids: Vec<_> = (0..12).map(|v| hive.insert(v)).collect();
for &id in &ids[..8] {
    hive.remove(id);
}
hive.shrink_to_fit(); // frees the first two pages
assert_eq!(*hive.get(ids[8]).unwrap(), 8);
let new = hive.insert(99); // reuses a freed page
assert!(new.index() < 8 && !ids.contains(&new));
assert!(hive.get(ids[0]).is_none());
Source

pub fn snapshot(&self) -> Hive<T, PAGE>
where T: Clone,

Clones a weakly consistent snapshot into a plain Hive. Insertions that happen-before the call are included if the entry stays live throughout it. Ids whose removal happens-before the call stay dead. The raw pages always validate. Scans up to index_bound with a floor lookup per page.

Each value stays guarded while its Clone runs. Taking that id in the callback, or waiting there for another thread to take it, deadlocks.

Source

pub fn into_hive(self) -> Hive<T, PAGE>

Moves into a plain Hive, preserving live ids and stale-id history. Takes O(index_bound) time; pages and reuse order may change.

Marked values are finalized and not carried over. Forgotten guards are released: their counts are reset before any live value is moved. Every slot below the bound is represented explicitly: zero states become retired vacancies, even versions become reusable vacancies, and odd versions keep their values. Indices reserved for a thread’s block but never handed out become reusable vacancies at version 2. A page freed by shrink_to_fit becomes an empty raw page with its floor; other floors are zero. Offsets beyond the bound have never issued ids and need no history.

Raw-page validation cannot fail by construction: all versions have the required parity, all pages fit PAGE, and indices are below MAX_INDICES. Allocation or a marked value’s destructor may panic; allocation may also abort. Values already moved are owned by the raw pages; this hive’s empty cells cannot drop them again, including if allocation unwinds.

§Examples
use paged_collections::concurrent::ConcurrentHive;

let hive = ConcurrentHive::<String, 4>::new();
let id = hive.insert(String::from("hello"));
let plain = hive.into_hive();
assert_eq!(plain.get(id).map(String::as_str), Some("hello"));
assert_eq!(plain.len(), 1);

Trait Implementations§

Source§

impl<T: Clone, const PAGE: usize> Clone for ConcurrentHive<T, PAGE>

Clones via ConcurrentHive::snapshot, preserving generations. Each value stays guarded while its Clone runs, so taking that id or waiting for its taker from the callback deadlocks.

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T, const PAGE: usize> Debug for ConcurrentHive<T, PAGE>

Source§

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

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

impl<T, const PAGE: usize> Default for ConcurrentHive<T, PAGE>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, T: Deserialize<'de>, const PAGE: usize> Deserialize<'de> for ConcurrentHive<T, PAGE>

Validates the plain Hive format and converts in O(index bound).

Source§

fn deserialize<De: Deserializer<'de>>( deserializer: De, ) -> Result<Self, De::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T, const PAGE: usize> Drop for ConcurrentHive<T, PAGE>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl<T, const PAGE: usize> From<Hive<T, PAGE>> for ConcurrentHive<T, PAGE>

Moves a plain hive into shared storage without changing live ids. Takes O(the source hive’s index bound) time; pages and reuse order may change.

The new reservation bound ends after the last explicit raw slot or the last page with a nonzero floor, whichever is later. The untouched suffix of floor-zero pages is left to fresh reservation. Omitted offsets below this bound become reusable vacancies at their page floor. For floor-zero holes only, generation 1 is spent and the vacancy starts at version 2: a popped zero state must always mean retired. Nonzero floors retain their exact next generation, floor / 2 + 1. Explicit retired zeros are never pushed. Thus no previously issued dead id can revive.

Versions are copied before draining values, since draining advances the source versions. Occupied states are published only after their values have moved; unwinding during allocation cannot expose uninitialized cells to this hive’s destructor.

Source§

fn from(hive: Hive<T, PAGE>) -> Self

Converts to this type from the input type.
Source§

impl<'a, T, const PAGE: usize> IntoIterator for &'a ConcurrentHive<T, PAGE>

Source§

type Item = (Id, Ref<'a, T, PAGE>)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, T, PAGE>

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

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T, const PAGE: usize> IntoIterator for &'a mut ConcurrentHive<T, PAGE>

Source§

type Item = (Id, &'a mut T)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, T, PAGE>

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

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T: Send, const PAGE: usize> Send for ConcurrentHive<T, PAGE>

Source§

impl<T: Serialize, const PAGE: usize> Serialize for ConcurrentHive<T, PAGE>

Serializes a weakly consistent snapshot in the plain Hive format. Uses the same consistency as ConcurrentHive::snapshot and scans to the initial index bound with one floor lookup per page. The resulting pages always pass Hive’s validation.

Each value stays guarded while its Serialize runs. Taking that id in the callback, or waiting there for another thread to take it, deadlocks.

Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl<T: Send + Sync, const PAGE: usize> Sync for ConcurrentHive<T, PAGE>

Auto Trait Implementations§

§

impl<T, const PAGE: usize = DEFAULT_PAGE> !Freeze for ConcurrentHive<T, PAGE>

§

impl<T, const PAGE: usize = DEFAULT_PAGE> !RefUnwindSafe for ConcurrentHive<T, PAGE>

§

impl<T, const PAGE: usize> Forget for ConcurrentHive<T, PAGE>

§

impl<T, const PAGE: usize> Move for ConcurrentHive<T, PAGE>

§

impl<T, const PAGE: usize> Unpin for ConcurrentHive<T, PAGE>
where Spine<Page<T>, CHUNKS>: Unpin,

§

impl<T, const PAGE: usize> UnsafeUnpin for ConcurrentHive<T, PAGE>
where Spine<Page<T>, CHUNKS>: UnsafeUnpin,

§

impl<T, const PAGE: usize> UnwindSafe for ConcurrentHive<T, PAGE>
where Spine<Page<T>, CHUNKS>: UnwindSafe,

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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 = !

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

fn try_from(value: U) -> Result<T, !>

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.