Skip to main content

AtomicIdMap

Struct AtomicIdMap 

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

A lock-free direct-address map from generational Ids to u32 values.

Each slot at id.index() stores generation << 32 | value. Generation is nonzero, so zero denotes an empty slot and all u32 values are storable. Lookups and remove match the generation. Unconditional insertion evicts any generation, while try_insert refuses any occupant.

Conditional updates view another generation as absent. Writing Some(v) installs the requested id and evicts any other generation; writing None removes only the requested id and succeeds without changing another generation. Filling an empty slot adds one to length, eviction leaves it unchanged, and removing this id subtracts one.

Slot loads use acquire ordering, successful read-modify-write operations use acquire-release, and failed compare-exchanges use acquire. Values may publish other data indexed by them. Slot operations are lock-free; page installation can allocate. The finite, Flat-like spine retains pages until shrink_to_fit, reset or destruction. Out-of-range lookups and removals return absent; inserting outside the spine range panics. PAGE must be nonzero and its atomic slot storage must fit in isize::MAX bytes.

Length uses wrapping counters, one per thread (per page group without std), updated after each occupancy change. A removal can be counted before the insertion it undoes, or on another counter; len reads their sum as signed and clamps negatives to zero. It is exact when no write is in flight. Traversals are weakly consistent, visit ascending indices and load each visited slot once; they do not provide a snapshot.

use core::num::NonZeroU32;
use paged_collections::{concurrent::AtomicIdMap, id_alloc::Id};
let map = AtomicIdMap::<4>::new();
let old = Id::new(3, NonZeroU32::new(1).unwrap());
let new = Id::new(3, NonZeroU32::new(2).unwrap());
map.insert(old, 10);
assert_eq!(map.replace(new, u32::MAX), Some((old, 10)));
assert_eq!(map.remove(old), None);
assert_eq!(map.get(new), Some(u32::MAX));

Implementations§

Source§

impl<const PAGE: usize> AtomicIdMap<PAGE>

Source

pub const PAGE_SIZE: usize = PAGE

Number of atomic slots per page.

Source

pub fn new() -> Self

Creates an empty map without allocating.

Panics if PAGE is zero or its atomic storage exceeds isize::MAX bytes.

Source

pub fn len(&self) -> usize

Number of entries; exact when no write is in flight.

Sums per-thread counters (per page group without std), reading the sum as signed and clamping negatives to zero. While writes are in flight, the counters may be read at different moments, so the result can differ from every count the map held, though it never exceeds the number of insertions.

Source

pub fn is_empty(&self) -> bool

Whether len() is zero, subject to concurrent writes.

Source

pub fn allocated_pages(&self) -> usize

Counts installed pages; weakly consistent during page installation.

Source

pub fn get(&self, id: Id) -> Option<u32>

Loads the value only if this generation holds the slot. Uses acquire ordering; out-of-range ids return None.

Source

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

Whether this id’s generation holds the slot.

Source

pub fn occupant(&self, index: u32) -> Option<(Id, u32)>

Loads whichever generation occupies index, with acquire ordering. Out-of-range indices return None.

Source

pub fn insert(&self, id: Id, value: u32) -> Option<u32>

Swaps in this id and value, returning the previous value from any generation. Panics if the index exceeds the spine range.

Source

pub fn replace(&self, id: Id, value: u32) -> Option<(Id, u32)>

Swaps in this id and value, returning the previous occupant from any generation. Panics if the index exceeds the spine range.

Source

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

Inserts only into an empty slot, returning any occupant on failure. Panics if the index exceeds the spine range.

Source

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

Removes only this generation, returning its value. A stale id never removes another generation. Out-of-range ids return None.

Source

pub fn remove_occupant(&self, index: u32) -> Option<(Id, u32)>

Swaps the slot to empty and returns any occupant. Out-of-range indices return None without allocating.

Source

pub fn compare_exchange( &self, id: Id, current: Option<u32>, new: Option<u32>, ) -> Result<Option<u32>, Option<u32>>

Stores new if this id’s value equals current, without spurious failure. Returns Ok(previous) or Err(actual) for this id only. None matches both an empty slot and another generation. Some(v) evicts any generation; None removes only this id and otherwise succeeds without changing the occupant. Eviction preserves length. A None write never allocates a page. A nonempty write installs its page before checking current; an out-of-range insertion panics.

Source

pub fn fetch_update( &self, id: Id, f: impl FnMut(Option<u32>) -> Option<Option<u32>>, ) -> Result<Option<u32>, Option<u32>>

Repeatedly calls f with this id’s value until a change succeeds or f returns None. Another generation is presented as absent. Some(Some(v)) stores this id and evicts any generation; Some(None) removes only this id, leaving another generation unchanged. Eviction preserves length. Returns Ok(previous) on success or Err(current) if f stops. The callback may run several times, even if its argument remains None while other generations change; only one change commits. Removing from an absent page does not allocate it. An out-of-range insertion panics. A panicking callback leaves the slot unchanged by this call.

Source

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

Iterates in ascending index order, loading each slot once with acquire ordering. Weakly consistent under mutation; not a snapshot.

Source

pub fn range( &self, indices: impl RangeBounds<u32>, ) -> impl Iterator<Item = (Id, u32)>

Iterates over an index range in ascending order, independent of generation. Loads each visited slot once with acquire ordering; weakly consistent under mutation. Empty or inverted ranges yield nothing.

Source

pub fn shrink_to_fit(&mut self)

Frees pages that contain no entries, keeping directory chunks. Shared insertions can allocate those pages again.

Source

pub fn clear(&mut self)

Empties the map, retaining pages for reuse. Requires exclusive access.

Source

pub fn reset(&mut self)

Frees all pages and directory chunks, leaving an empty map.

Trait Implementations§

Source§

impl<const PAGE: usize> Clone for AtomicIdMap<PAGE>

Copies a weakly consistent view, scanning the directory and allocated slots. Includes entries that remain unchanged throughout the call if their writes happen-before it.

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<const PAGE: usize> Debug for AtomicIdMap<PAGE>

Source§

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

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

impl<const PAGE: usize> Default for AtomicIdMap<PAGE>

Source§

fn default() -> Self

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

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

Reads an Id to u32 map in O(len) entry insertions. The last entry for each index wins, as with FromIterator. Rejects indices outside the concurrent directory’s range.

Source§

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

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

impl<const PAGE: usize> Extend<(Id, u32)> for AtomicIdMap<PAGE>

Source§

fn extend<T: IntoIterator<Item = (Id, u32)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<const PAGE: usize> FromIterator<(Id, u32)> for AtomicIdMap<PAGE>

Source§

fn from_iter<T: IntoIterator<Item = (Id, u32)>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

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

Source§

type Item = (Id, u32)

The type of the elements being iterated over.
Source§

type IntoIter = AtomicIdMapIter<'a, 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<const PAGE: usize> Serialize for AtomicIdMap<PAGE>

Serializes a weakly consistent snapshot as a valid Id to u32 map in slot order. Scans the directory and allocated slots, buffering entries to supply the exact serialized length. Includes entries that remain unchanged throughout the call if their writes happen-before it.

Source§

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

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<const PAGE: usize = DEFAULT_PAGE> !Freeze for AtomicIdMap<PAGE>

§

impl<const PAGE: usize> Forget for AtomicIdMap<PAGE>

§

impl<const PAGE: usize> Move for AtomicIdMap<PAGE>

§

impl<const PAGE: usize> RefUnwindSafe for AtomicIdMap<PAGE>
where Words<PAGE, Flat>: RefUnwindSafe,

§

impl<const PAGE: usize> Send for AtomicIdMap<PAGE>
where Words<PAGE, Flat>: Send,

§

impl<const PAGE: usize> Sync for AtomicIdMap<PAGE>
where Words<PAGE, Flat>: Sync,

§

impl<const PAGE: usize> Unpin for AtomicIdMap<PAGE>
where Words<PAGE, Flat>: Unpin,

§

impl<const PAGE: usize> UnsafeUnpin for AtomicIdMap<PAGE>
where Words<PAGE, Flat>: UnsafeUnpin,

§

impl<const PAGE: usize> UnwindSafe for AtomicIdMap<PAGE>
where Words<PAGE, Flat>: 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.