pub struct AtomicIdMap<const PAGE: usize = DEFAULT_PAGE> { /* private fields */ }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>
impl<const PAGE: usize> AtomicIdMap<PAGE>
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates an empty map without allocating.
Panics if PAGE is zero or its atomic storage exceeds isize::MAX bytes.
Sourcepub fn len(&self) -> usize
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.
Sourcepub fn allocated_pages(&self) -> usize
pub fn allocated_pages(&self) -> usize
Counts installed pages; weakly consistent during page installation.
Sourcepub fn get(&self, id: Id) -> Option<u32>
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.
Sourcepub fn contains_key(&self, id: Id) -> bool
pub fn contains_key(&self, id: Id) -> bool
Whether this id’s generation holds the slot.
Sourcepub fn occupant(&self, index: u32) -> Option<(Id, u32)>
pub fn occupant(&self, index: u32) -> Option<(Id, u32)>
Loads whichever generation occupies index, with acquire ordering.
Out-of-range indices return None.
Sourcepub fn insert(&self, id: Id, value: u32) -> Option<u32>
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.
Sourcepub fn replace(&self, id: Id, value: u32) -> Option<(Id, u32)>
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.
Sourcepub fn try_insert(&self, id: Id, value: u32) -> Result<(), (Id, u32)>
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.
Sourcepub fn remove(&self, id: Id) -> Option<u32>
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.
Sourcepub fn remove_occupant(&self, index: u32) -> Option<(Id, u32)>
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.
Sourcepub fn compare_exchange(
&self,
id: Id,
current: Option<u32>,
new: Option<u32>,
) -> Result<Option<u32>, Option<u32>>
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.
Sourcepub fn fetch_update(
&self,
id: Id,
f: impl FnMut(Option<u32>) -> Option<Option<u32>>,
) -> Result<Option<u32>, Option<u32>>
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.
Sourcepub fn iter(&self) -> AtomicIdMapIter<'_, PAGE> ⓘ
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.
Sourcepub fn range(
&self,
indices: impl RangeBounds<u32>,
) -> impl Iterator<Item = (Id, u32)>
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.
Sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Frees pages that contain no entries, keeping directory chunks. Shared insertions can allocate those pages again.
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.
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§impl<const PAGE: usize> Debug for AtomicIdMap<PAGE>
impl<const PAGE: usize> Debug for AtomicIdMap<PAGE>
Source§impl<const PAGE: usize> Default for AtomicIdMap<PAGE>
impl<const PAGE: usize> Default for AtomicIdMap<PAGE>
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.
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>
fn deserialize<De: Deserializer<'de>>( deserializer: De, ) -> Result<Self, De::Error>
Source§impl<const PAGE: usize> Extend<(Id, u32)> for AtomicIdMap<PAGE>
impl<const PAGE: usize> Extend<(Id, u32)> for AtomicIdMap<PAGE>
Source§fn extend<T: IntoIterator<Item = (Id, u32)>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = (Id, u32)>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: T)
fn extend_one(&mut self, item: T)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)Source§impl<const PAGE: usize> FromIterator<(Id, u32)> for AtomicIdMap<PAGE>
impl<const PAGE: usize> FromIterator<(Id, u32)> for AtomicIdMap<PAGE>
Source§impl<'a, const PAGE: usize> IntoIterator for &'a AtomicIdMap<PAGE>
impl<'a, const PAGE: usize> IntoIterator for &'a AtomicIdMap<PAGE>
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.
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.
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>
impl<const PAGE: usize> Sync for AtomicIdMap<PAGE>
impl<const PAGE: usize> Unpin for AtomicIdMap<PAGE>
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> 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