pub struct ConcurrentHive<T, const PAGE: usize = DEFAULT_PAGE> { /* private fields */ }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>
impl<T, const PAGE: usize> ConcurrentHive<T, PAGE>
Sourcepub fn new() -> Self
pub fn new() -> Self
An empty hive, without allocating.
§Panics
Panics if the page capacity is invalid; see the type’s documentation.
Sourcepub fn insert(&self, value: T) -> Id
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.
Sourcepub fn try_insert(&self, value: T) -> Result<Id, T>
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.
Sourcepub fn insert_with(&self, f: impl FnOnce(Id) -> T) -> Id
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.
Sourcepub fn try_insert_with(&self, f: impl FnOnce(Id) -> T) -> Option<Id>
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.
Sourcepub fn get(&self, id: Id) -> Option<Ref<'_, T, PAGE>>
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.
Sourcepub fn contains(&self, id: Id) -> bool
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.
Sourcepub fn remove(&self, id: Id) -> bool
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.
Sourcepub fn take(&self, id: Id) -> Option<T>
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.
Sourcepub fn len(&self) -> usize
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.
Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Whether the hive is empty; approximate during shared operations.
Sourcepub fn index_bound(&self) -> u32
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.
Sourcepub fn iter(&self) -> Iter<'_, T, PAGE> ⓘ
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.
Sourcepub fn get_mut(&mut self, id: Id) -> Option<&mut T>
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.
Sourcepub fn take_mut(&mut self, id: Id) -> Option<T>
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.
Sourcepub fn iter_mut(&mut self) -> IterMut<'_, T, PAGE> ⓘ
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.
Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Removes and drops every value, retaining pages and generation history. Forgotten guards do not pin values under exclusive access.
Sourcepub fn drain(&mut self) -> Drain<'_, T, PAGE> ⓘ
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.
Sourcepub fn retain(&mut self, keep: impl FnMut(Id, &mut T) -> bool)
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.
Sourcepub fn shrink_to_fit(&mut self)
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());Sourcepub fn snapshot(&self) -> Hive<T, PAGE>where
T: Clone,
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.
Sourcepub fn into_hive(self) -> Hive<T, PAGE>
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.
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§impl<T, const PAGE: usize> Debug for ConcurrentHive<T, PAGE>
impl<T, const PAGE: usize> Debug for ConcurrentHive<T, PAGE>
Source§impl<T, const PAGE: usize> Default for ConcurrentHive<T, PAGE>
impl<T, const PAGE: usize> Default for ConcurrentHive<T, PAGE>
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).
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>
fn deserialize<De: Deserializer<'de>>( deserializer: De, ) -> Result<Self, De::Error>
Source§impl<T, const PAGE: usize> Drop for ConcurrentHive<T, PAGE>
impl<T, const PAGE: usize> Drop for ConcurrentHive<T, PAGE>
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.
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§impl<'a, T, const PAGE: usize> IntoIterator for &'a ConcurrentHive<T, PAGE>
impl<'a, T, const PAGE: usize> IntoIterator for &'a ConcurrentHive<T, PAGE>
Source§impl<'a, T, const PAGE: usize> IntoIterator for &'a mut ConcurrentHive<T, PAGE>
impl<'a, T, const PAGE: usize> IntoIterator for &'a mut ConcurrentHive<T, PAGE>
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.
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.
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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