Skip to main content

AtomicDirectMap

Struct AtomicDirectMap 

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

A lock-free direct-address map from slot indices to one-word values.

The key is the slot index itself; callers with u32 keys pass key as usize. No key or generation is stored. Use AtomicIdMap for generational keys. Values are encoded as value + 1, reserving zero for an empty slot: u64::MAX cannot be stored; see MAX_VALUE.

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. Pages remain until shrink_to_fit, reset or destruction. The default Flat directory has O(1) page lookups and memory following the highest page; its finite range rejects out-of-range inserts with a panic and makes lookups/removals return absent. Radix accepts any usize index, uses directory memory proportional to installed pages, and looks up pages in O(depth). PAGE must be nonzero and its atomic 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 slots and load each visited slot once; they do not provide a snapshot.

use paged_collections::concurrent::AtomicDirectMap;
let counters = AtomicDirectMap::<4>::new();
// Increment a counter, initializing an absent counter to zero first.
assert_eq!(counters.fetch_update(7, |old| Some(Some(old.unwrap_or(0) + 1))), Ok(None));
assert_eq!(counters.fetch_update(7, |old| Some(Some(old.unwrap_or(0) + 1))), Ok(Some(1)));
assert_eq!(counters.get(7), Some(2));
use paged_collections::{concurrent::AtomicDirectMap, page::Radix};
let map = AtomicDirectMap::<4, Radix>::new();
assert_eq!(map.insert(usize::MAX - 1, 42), None);
assert_eq!(map.get(usize::MAX - 1), Some(42));

Implementations§

Source§

impl<const PAGE: usize, D: SharedDirectory> AtomicDirectMap<PAGE, D>

Source

pub const PAGE_SIZE: usize = PAGE

Number of atomic slots per page.

Source

pub const MAX_VALUE: u64

Largest storable value; u64::MAX is reserved by the encoding.

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, key: usize) -> Option<u64>

Loads a value with acquire ordering. Out-of-range keys return None.

Source

pub fn contains_key(&self, key: usize) -> bool

Whether this slot is occupied.

Source

pub fn insert(&self, key: usize, value: u64) -> Option<u64>

Swaps in value, returning the previous value. Panics if value == u64::MAX or a Flat key exceeds the spine range.

Source

pub fn try_insert(&self, key: usize, value: u64) -> Result<(), u64>

Inserts into an empty slot, or returns Err(current). Panics if value == u64::MAX or a Flat key exceeds the spine range.

Source

pub fn remove(&self, key: usize) -> Option<u64>

Swaps the slot to empty, returning its previous value. Out-of-range keys return None without allocating.

Source

pub fn compare_exchange( &self, key: usize, current: Option<u64>, new: Option<u64>, ) -> Result<Option<u64>, Option<u64>>

Stores new only if the current value equals current, without spurious failure. None means empty. Returns Ok(previous) on success or Err(actual) on mismatch. A None write never allocates a page. Panics if new == Some(u64::MAX) or an inserting Flat key exceeds the spine range. A nonempty write installs its page before checking current.

Source

pub fn fetch_update( &self, key: usize, f: impl FnMut(Option<u64>) -> Option<Option<u64>>, ) -> Result<Option<u64>, Option<u64>>

Repeatedly calls f with the current value until a change succeeds or f returns None. Returns Ok(previous) after storing Some(new); Some(None) removes the entry. Returning None stops with Err(current). The callback may run several times, but only one change is committed. Removing from an absent page does not allocate it. Panics if f requests storing u64::MAX, or a Flat insertion exceeds the spine range. A panicking callback leaves the slot unchanged by this call.

Source

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

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

Source

pub fn range( &self, keys: impl RangeBounds<usize>, ) -> impl Iterator<Item = (usize, u64)>

Iterates over a key range in ascending order, loading 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. Flat directory chunks stay allocated. 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 snapshot(&self) -> PagedDirectMap<usize, u64, PAGE, D>

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

Source

pub fn into_inner(self) -> PagedDirectMap<usize, u64, PAGE, D>

Moves entries into a plain map with the same directory in slot order.

Source

pub fn reset(&mut self)

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

Trait Implementations§

Source§

impl<const PAGE: usize, D: SharedDirectory> Clone for AtomicDirectMap<PAGE, D>

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, D: SharedDirectory> Debug for AtomicDirectMap<PAGE, D>

Source§

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

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

impl<const PAGE: usize, D: SharedDirectory> Default for AtomicDirectMap<PAGE, D>

Source§

fn default() -> Self

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

impl<'de, const PAGE: usize, D: SharedDirectory> Deserialize<'de> for AtomicDirectMap<PAGE, D>

Reads the plain PagedDirectMap format, rejecting u64::MAX values and 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, D: SharedDirectory> Extend<(usize, u64)> for AtomicDirectMap<PAGE, D>

Source§

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

Inserts entries, panicking if a value is u64::MAX or a Flat key exceeds the spine range. Entries inserted before a panic remain in the map.

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, D: SharedDirectory> From<PagedDirectMap<usize, u64, PAGE, D>> for AtomicDirectMap<PAGE, D>

Source§

fn from(map: PagedDirectMap<usize, u64, PAGE, D>) -> Self

Panics if a value is u64::MAX or a Flat index exceeds the spine range.

Source§

impl<const PAGE: usize, D: SharedDirectory> FromIterator<(usize, u64)> for AtomicDirectMap<PAGE, D>

Source§

fn from_iter<T: IntoIterator<Item = (usize, u64)>>(iter: T) -> Self

Collects entries, panicking if a value is u64::MAX or a Flat key exceeds the spine range. Later entries replace earlier values at the same key.

Source§

impl<'a, const PAGE: usize, D: SharedDirectory> IntoIterator for &'a AtomicDirectMap<PAGE, D>

Source§

type Item = (usize, u64)

The type of the elements being iterated over.
Source§

type IntoIter = AtomicDirectMapIter<'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, D: SharedDirectory> Serialize for AtomicDirectMap<PAGE, D>

Serializes a weakly consistent snapshot as a valid plain map in slot order, with the same consistency as AtomicDirectMap::snapshot. Scans the directory and allocated slots, buffering entries to supply the exact serialized length.

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, D = Flat> !Freeze for AtomicDirectMap<PAGE, D>

§

impl<const PAGE: usize, D> Forget for AtomicDirectMap<PAGE, D>

§

impl<const PAGE: usize, D> Move for AtomicDirectMap<PAGE, D>

§

impl<const PAGE: usize, D> RefUnwindSafe for AtomicDirectMap<PAGE, D>
where Words<PAGE, D>: RefUnwindSafe,

§

impl<const PAGE: usize, D> Send for AtomicDirectMap<PAGE, D>
where Words<PAGE, D>: Send,

§

impl<const PAGE: usize, D> Sync for AtomicDirectMap<PAGE, D>
where Words<PAGE, D>: Sync,

§

impl<const PAGE: usize, D> Unpin for AtomicDirectMap<PAGE, D>
where Words<PAGE, D>: Unpin,

§

impl<const PAGE: usize, D> UnsafeUnpin for AtomicDirectMap<PAGE, D>
where Words<PAGE, D>: UnsafeUnpin,

§

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