Skip to main content

ConcurrentAppendHive

Struct ConcurrentAppendHive 

Source
pub struct ConcurrentAppendHive<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.

get returns an ordinary &T after one Acquire slot-state load, with no guard or reference count. Published values can be changed, removed or moved only under &mut self, which excludes every reference borrowed from shared access. Prefer ConcurrentHive when removal must also be shared.

Pages stay allocated until shrink_to_fit frees the empty ones; shared inserts reuse freed pages later. Shared iteration is weakly consistent and may miss insertions in flight. len is approximate during insertion and exact when insertions have finished. Exclusive scans and conversions take O(index_bound) time. Conversions to and from Hive preserve live ids and stale-id history, but may change allocation and slot reuse order.

As with Hive, ids carry no container identity, generations never wrap, and stale ids stay dead within one allocation history. A panicking insert_with spends the id shown to its factory.

PAGE must be non-zero, fit in a u32, and fit a page in isize::MAX bytes. Uses only core and alloc.

use paged_collections::concurrent::ConcurrentAppendHive;

let mut hive = ConcurrentAppendHive::<&str, 4>::new();
let first = hive.insert("first");
let value = hive.get(first).unwrap();
let second = hive.insert("second");
assert_eq!(*value, "first");
assert_eq!(hive[second], "second");
assert_eq!(hive.remove(first), Some("first"));
assert!(hive.get(first).is_none());

Sharing requires both Send and Sync elements:

ⓘ
use paged_collections::concurrent::ConcurrentAppendHive;
use std::rc::Rc;
fn assert_sync<T: Sync>() {}
assert_sync::<ConcurrentAppendHive<Rc<()>>>();

Implementations§

Source§

impl<T, const PAGE: usize> ConcurrentAppendHive<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 panicking concurrent factory may make room.

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, its id’s generation is spent and that id stays dead. The slot becomes reusable unless its last generation was spent.

§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<&T>

The value of a matching live id, without a guard or reference count. Returns None for stale, invalid or unpublished ids.

Source

pub fn id_of(&self, value: &T) -> Option<Id>

The id of the element at value’s address, if value is a live element of this hive: the inverse of get.

Takes time linear in the directory’s page cells up to the highest installed page (with Flat, O(highest page number)): it compares the address with each installed page’s slot range, then checks that the slot found is published live and holds exactly that element. Anything else gives None. Uses address comparison only; no pointer is dereferenced.

use paged_collections::concurrent::ConcurrentAppendHive;

let hive = ConcurrentAppendHive::<u32, 4>::new();
let id = hive.insert(7);
let element = hive.get(id).unwrap();
assert_eq!(hive.id_of(element), Some(id));
assert_eq!(hive.id_of(&7), None);
Source

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

Whether this id is live at the instant of one state load.

Source

pub fn len(&self) -> usize

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

It sums per-thread counters (per page group without std), which only grow while shared, so it lies between the counts at the start and the end of the call.

Source

pub fn is_empty(&self) -> bool

Whether the hive is empty; approximate during shared insertion.

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) -> AppendIter<'_, T, PAGE> ⓘ

Iterates over (id, &value) in slot order, weakly consistently. Scans only indices below the reservation bound at iterator creation; may miss insertions in flight, but never yields an unpublished value.

Source

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

The matching live value, mutably, under exclusive access.

Source

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

Removes and returns a matching live value under exclusive access. The id stays dead; its slot is reused with a new generation or retired.

Source

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

Iterates over live (id, &mut value) pairs in slot order.

Source

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

Eagerly removes every live value, yielding owned (id, value) pairs in slot order. Dropping or forgetting the iterator leaves the hive empty. Pages and generation history stay allocated.

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. If the predicate or a destructor panics, prior changes remain and len stays exact.

Source

pub fn clear(&mut self)

Removes and drops every value, retaining pages and generation history.

Source

pub fn shrink_to_fit(&mut self)

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

A page is 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::ConcurrentAppendHive;

let mut hive = ConcurrentAppendHive::<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[ids[8]], 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 into_hive(self) -> Hive<T, PAGE>

Moves into a plain Hive, preserving live ids and stale-id history. Takes O(index_bound) time.

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 may still panic or abort. Values already moved are owned by the raw pages; this hive’s empty cells cannot drop them again, including if allocation unwinds.

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

Trait Implementations§

Source§

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

Clones via ConcurrentAppendHive::snapshot, preserving generations.

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 ConcurrentAppendHive<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 ConcurrentAppendHive<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 ConcurrentAppendHive<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 ConcurrentAppendHive<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 ConcurrentAppendHive<T, PAGE>

Moves a plain hive into shared append 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<T, const PAGE: usize> Index<Id> for ConcurrentAppendHive<T, PAGE>

Source§

fn index(&self, id: Id) -> &T

§Panics

Panics if id is not live.

Source§

type Output = T

The returned type after indexing.
Source§

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

Source§

type Item = (Id, &'a T)

The type of the elements being iterated over.
Source§

type IntoIter = AppendIter<'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 ConcurrentAppendHive<T, PAGE>

Source§

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

The type of the elements being iterated over.
Source§

type IntoIter = AppendIterMut<'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 ConcurrentAppendHive<T, PAGE>

Source§

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

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

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 ConcurrentAppendHive<T, PAGE>

Auto Trait Implementations§

§

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

§

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

§

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

§

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

§

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

§

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

§

impl<T, const PAGE: usize> UnwindSafe for ConcurrentAppendHive<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.