Skip to main content

paged_collections/concurrent/
atomic_map.rs

1//! Lock-free direct-address maps whose values fit in one atomic word.
2//!
3//! Slots use acquire loads and acquire-release read-modify-write operations;
4//! failed compare-exchanges use acquire ordering. A value can therefore
5//! publish data indexed by that value. Pages remain allocated during shared
6//! access, and slot operations never wait for another thread to release a lock.
7
8use alloc::boxed::Box;
9use core::fmt;
10use core::mem;
11use core::num::NonZeroU32;
12use core::ops::{Bound, RangeBounds};
13use core::slice;
14
15use super::atomic::{AtomicU64, Ordering};
16use super::count::StripedLen;
17use super::directory::{PageIter, SharedDirectory, SharedPages};
18use crate::direct_map::PagedDirectMap;
19use crate::id_alloc::Id;
20use crate::page::{DEFAULT_PAGE, Flat};
21
22struct Page {
23    slots: Box<[AtomicU64]>,
24}
25
26struct Words<const PAGE: usize, D: SharedDirectory> {
27    pages: D::Pages<Page>,
28    len: StripedLen,
29}
30
31// SAFETY: both sealed directories own their pages, which contain only atomic
32// slots; moving Words transfers ownership and its counters are also atomic.
33unsafe impl<const PAGE: usize, D: SharedDirectory> Send for Words<PAGE, D> {}
34// SAFETY: both sealed directories synchronize page publication; all shared
35// slot and counter accesses are atomic, and page reclamation is exclusive.
36unsafe impl<const PAGE: usize, D: SharedDirectory> Sync for Words<PAGE, D> {}
37
38impl<const PAGE: usize, D: SharedDirectory> Words<PAGE, D> {
39    fn valid_page_capacity() -> bool {
40        PAGE > 0 && PAGE <= isize::MAX as usize / mem::size_of::<AtomicU64>()
41    }
42
43    fn new(name: &str) -> Self {
44        assert!(Self::valid_page_capacity(), "{name}: invalid page capacity");
45        Self {
46            pages: D::Pages::<Page>::new(),
47            len: StripedLen::new(),
48        }
49    }
50
51    fn slot(&self, index: usize) -> Option<&AtomicU64> {
52        self.pages
53            .get(D::Pages::<Page>::page_number::<PAGE>(index)?)
54            .map(|page| &page.slots[index % PAGE])
55    }
56
57    fn ensure_slot(&self, index: usize, name: &str) -> &AtomicU64 {
58        let number = D::Pages::<Page>::page_number::<PAGE>(index)
59            .unwrap_or_else(|| panic!("{name}: key index exceeds direct spine range"));
60        let page = self.pages.get_or_insert_with(number, || {
61            Box::new(Page {
62                slots: (0..PAGE).map(|_| AtomicU64::new(0)).collect(),
63            })
64        });
65        &page.slots[index % PAGE]
66    }
67
68    fn load(&self, index: usize) -> u64 {
69        self.slot(index)
70            .map_or(0, |slot| slot.load(Ordering::Acquire))
71    }
72
73    fn count_change(&self, index: usize, old: u64, new: u64) {
74        // Count after the slot's linearization point. A removal can reach
75        // the counters before the insertion it undoes; they wrap.
76        match (old == 0, new == 0) {
77            (true, false) => self.len.increment(index / PAGE),
78            (false, true) => self.len.decrement(index / PAGE),
79            _ => {}
80        }
81    }
82
83    fn len(&self) -> usize {
84        self.len.get()
85    }
86
87    fn swap(&self, index: usize, new: u64, name: &str) -> u64 {
88        let slot = if new == 0 {
89            let Some(slot) = self.slot(index) else {
90                return 0;
91            };
92            slot
93        } else {
94            self.ensure_slot(index, name)
95        };
96        let old = slot.swap(new, Ordering::AcqRel);
97        self.count_change(index, old, new);
98        old
99    }
100
101    fn try_insert(&self, index: usize, new: u64, name: &str) -> Result<(), u64> {
102        let slot = self.ensure_slot(index, name);
103        match slot.compare_exchange(0, new, Ordering::AcqRel, Ordering::Acquire) {
104            Ok(old) => {
105                self.count_change(index, old, new);
106                Ok(())
107            }
108            Err(actual) => Err(actual),
109        }
110    }
111
112    fn update(
113        &self,
114        index: usize,
115        name: &str,
116        install: bool,
117        mut f: impl FnMut(u64) -> Option<u64>,
118    ) -> Result<u64, u64> {
119        let mut slot = if install {
120            Some(self.ensure_slot(index, name))
121        } else {
122            self.slot(index)
123        };
124        let mut old = slot.map_or(0, |slot| slot.load(Ordering::Acquire));
125        loop {
126            let Some(new) = f(old) else {
127                return Err(old);
128            };
129            let target = match slot {
130                Some(slot) => slot,
131                None => {
132                    // Recheck after the callback: it may itself have installed
133                    // this page. A no-op on a still absent page needs no CAS
134                    // and linearizes at this directory lookup.
135                    let found = if new == 0 {
136                        self.slot(index)
137                    } else {
138                        Some(self.ensure_slot(index, name))
139                    };
140                    let Some(found) = found else {
141                        return Ok(0);
142                    };
143                    slot = Some(found);
144                    found
145                }
146            };
147            match target.compare_exchange(old, new, Ordering::AcqRel, Ordering::Acquire) {
148                Ok(previous) => {
149                    self.count_change(index, previous, new);
150                    return Ok(previous);
151                }
152                Err(actual) => old = actual,
153            }
154        }
155    }
156
157    fn range(&self, start: usize, end: usize) -> WordsIter<'_, PAGE> {
158        WordsIter {
159            pages: self.pages.iter(),
160            slots: slice::Iter::default().enumerate(),
161            base: 0,
162            start,
163            end,
164        }
165    }
166
167    fn shrink_to_fit(&mut self) {
168        self.pages.retain(|_, page| {
169            // Exclusive access rules out slot changes during the scan.
170            page.slots
171                .iter()
172                .any(|slot| slot.load(Ordering::Relaxed) != 0)
173        });
174    }
175
176    fn clear(&mut self) {
177        for (_, page) in self.pages.iter_mut() {
178            for slot in page.slots.iter() {
179                slot.store(0, Ordering::Relaxed);
180            }
181        }
182        self.len.reset();
183    }
184
185    fn reset(&mut self) {
186        self.pages.clear();
187        self.len.reset();
188    }
189}
190
191struct WordsIter<'a, const PAGE: usize> {
192    pages: PageIter<'a, Page>,
193    slots: core::iter::Enumerate<slice::Iter<'a, AtomicU64>>,
194    base: usize,
195    start: usize,
196    end: usize,
197}
198
199impl<const PAGE: usize> Iterator for WordsIter<'_, PAGE> {
200    type Item = (usize, u64);
201
202    fn next(&mut self) -> Option<Self::Item> {
203        while self.start <= self.end {
204            for (offset, slot) in self.slots.by_ref() {
205                let word = slot.load(Ordering::Acquire);
206                if word != 0 {
207                    return Some((self.base + offset, word));
208                }
209            }
210            let (number, page) = self.pages.next()?;
211            if number < self.start / PAGE {
212                continue;
213            }
214            if number > self.end / PAGE {
215                self.start = 1;
216                self.end = 0;
217                return None;
218            }
219            let first = if number == self.start / PAGE {
220                self.start % PAGE
221            } else {
222                0
223            };
224            // The end bound prevents overflow in a partial final page.
225            let last = if number == self.end / PAGE {
226                self.end % PAGE + 1
227            } else {
228                PAGE
229            };
230            self.base = number * PAGE + first;
231            self.slots = page.slots[first..last].iter().enumerate();
232        }
233        None
234    }
235}
236
237fn index_bounds(keys: impl RangeBounds<usize>) -> (usize, usize) {
238    let start = match keys.start_bound() {
239        Bound::Included(&index) => index,
240        Bound::Excluded(&index) => match index.checked_add(1) {
241            Some(index) => index,
242            None => return (1, 0),
243        },
244        Bound::Unbounded => 0,
245    };
246    let end = match keys.end_bound() {
247        Bound::Included(&index) => index,
248        Bound::Excluded(&index) => match index.checked_sub(1) {
249            Some(index) => index,
250            None => return (1, 0),
251        },
252        Bound::Unbounded => usize::MAX,
253    };
254    (start, end)
255}
256
257fn encode_direct(value: u64) -> u64 {
258    value
259        .checked_add(1)
260        .expect("AtomicDirectMap: u64::MAX cannot be stored")
261}
262
263fn decode_direct(word: u64) -> Option<u64> {
264    word.checked_sub(1)
265}
266
267/// A lock-free direct-address map from slot indices to one-word values.
268///
269/// The key is the slot index itself; callers with `u32` keys pass `key as
270/// usize`. No key or generation is stored. Use [`AtomicIdMap`] for
271/// generational keys. Values are encoded as `value + 1`, reserving zero for
272/// an empty slot: `u64::MAX` cannot be stored; see [`MAX_VALUE`](Self::MAX_VALUE).
273///
274/// Slot loads use acquire ordering, successful read-modify-write operations
275/// use acquire-release, and failed compare-exchanges use acquire. Values may
276/// publish other data indexed by them. Slot operations are lock-free; page
277/// installation can allocate. Pages remain until
278/// [`shrink_to_fit`](Self::shrink_to_fit), [`reset`](Self::reset) or destruction. The default [`Flat`] directory has O(1) page lookups and
279/// memory following the highest page; its finite range rejects out-of-range
280/// inserts with a panic and makes lookups/removals return absent.
281/// [`Radix`](crate::page::Radix) accepts any `usize` index, uses directory memory
282/// proportional to installed pages, and looks up pages in O(depth). `PAGE`
283/// must be nonzero and its atomic storage must fit in `isize::MAX` bytes.
284///
285/// Length uses wrapping counters, one per thread (per page group without
286/// `std`), updated after each occupancy change. A removal can be counted
287/// before the insertion it undoes, or on another counter; [`len`](Self::len)
288/// 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
289/// slots and load each visited slot once; they do not provide a snapshot.
290///
291/// ```
292/// # #[cfg(feature = "concurrent")] {
293/// use paged_collections::concurrent::AtomicDirectMap;
294/// let counters = AtomicDirectMap::<4>::new();
295/// // Increment a counter, initializing an absent counter to zero first.
296/// assert_eq!(counters.fetch_update(7, |old| Some(Some(old.unwrap_or(0) + 1))), Ok(None));
297/// assert_eq!(counters.fetch_update(7, |old| Some(Some(old.unwrap_or(0) + 1))), Ok(Some(1)));
298/// assert_eq!(counters.get(7), Some(2));
299/// # }
300/// ```
301///
302/// ```
303/// # #[cfg(feature = "concurrent")] {
304/// use paged_collections::{concurrent::AtomicDirectMap, page::Radix};
305/// let map = AtomicDirectMap::<4, Radix>::new();
306/// assert_eq!(map.insert(usize::MAX - 1, 42), None);
307/// assert_eq!(map.get(usize::MAX - 1), Some(42));
308/// # }
309/// ```
310pub struct AtomicDirectMap<const PAGE: usize = DEFAULT_PAGE, D: SharedDirectory = Flat> {
311    words: Words<PAGE, D>,
312}
313
314impl<const PAGE: usize, D: SharedDirectory> AtomicDirectMap<PAGE, D> {
315    /// Number of atomic slots per page.
316    pub const PAGE_SIZE: usize = PAGE;
317
318    /// Largest storable value; `u64::MAX` is reserved by the encoding.
319    pub const MAX_VALUE: u64 = u64::MAX - 1;
320
321    /// Creates an empty map without allocating.
322    ///
323    /// Panics if `PAGE` is zero or its atomic storage exceeds `isize::MAX` bytes.
324    pub fn new() -> Self {
325        Self {
326            words: Words::new("AtomicDirectMap"),
327        }
328    }
329
330    /// Number of entries; exact when no write is in flight.
331    ///
332    /// Sums per-thread counters (per page group without `std`), reading the
333    /// sum as signed and clamping negatives to zero. While writes are in
334    /// flight, the counters may be
335    /// read at different moments, so the result can differ from every count
336    /// the map held, though it never exceeds the number of insertions.
337    pub fn len(&self) -> usize {
338        self.words.len()
339    }
340
341    /// Whether `len()` is zero, subject to concurrent writes.
342    pub fn is_empty(&self) -> bool {
343        self.len() == 0
344    }
345
346    /// Counts installed pages; weakly consistent during page installation.
347    pub fn allocated_pages(&self) -> usize {
348        self.words.pages.iter().count()
349    }
350
351    /// Loads a value with acquire ordering. Out-of-range keys return `None`.
352    pub fn get(&self, key: usize) -> Option<u64> {
353        decode_direct(self.words.load(key))
354    }
355
356    /// Whether this slot is occupied.
357    pub fn contains_key(&self, key: usize) -> bool {
358        self.get(key).is_some()
359    }
360
361    /// Swaps in `value`, returning the previous value.
362    /// Panics if `value == u64::MAX` or a `Flat` key exceeds the spine range.
363    pub fn insert(&self, key: usize, value: u64) -> Option<u64> {
364        decode_direct(
365            self.words
366                .swap(key, encode_direct(value), "AtomicDirectMap"),
367        )
368    }
369
370    /// Inserts into an empty slot, or returns `Err(current)`.
371    /// Panics if `value == u64::MAX` or a `Flat` key exceeds the spine range.
372    pub fn try_insert(&self, key: usize, value: u64) -> Result<(), u64> {
373        self.words
374            .try_insert(key, encode_direct(value), "AtomicDirectMap")
375            .map_err(|word| decode_direct(word).unwrap())
376    }
377
378    /// Swaps the slot to empty, returning its previous value.
379    /// Out-of-range keys return `None` without allocating.
380    pub fn remove(&self, key: usize) -> Option<u64> {
381        decode_direct(self.words.swap(key, 0, "AtomicDirectMap"))
382    }
383
384    /// Stores `new` only if the current value equals `current`, without
385    /// spurious failure. `None` means empty. Returns `Ok(previous)` on success
386    /// or `Err(actual)` on mismatch. A `None` write never allocates a page.
387    /// Panics if `new == Some(u64::MAX)` or an inserting `Flat` key exceeds the spine
388    /// range. A nonempty write installs its page before checking `current`.
389    pub fn compare_exchange(
390        &self,
391        key: usize,
392        current: Option<u64>,
393        new: Option<u64>,
394    ) -> Result<Option<u64>, Option<u64>> {
395        let word = new.map_or(0, encode_direct);
396        self.words
397            .update(key, "AtomicDirectMap", new.is_some(), |old| {
398                (decode_direct(old) == current).then_some(word)
399            })
400            .map(decode_direct)
401            .map_err(decode_direct)
402    }
403
404    /// Repeatedly calls `f` with the current value until a change succeeds or
405    /// `f` returns `None`. Returns `Ok(previous)` after storing `Some(new)`;
406    /// `Some(None)` removes the entry. Returning `None` stops with `Err(current)`.
407    /// The callback may run several times, but only one change is committed.
408    /// Removing from an absent page does not allocate it.
409    /// Panics if `f` requests storing `u64::MAX`, or a `Flat` insertion exceeds the
410    /// spine range. A panicking callback leaves the slot unchanged by this call.
411    pub fn fetch_update(
412        &self,
413        key: usize,
414        mut f: impl FnMut(Option<u64>) -> Option<Option<u64>>,
415    ) -> Result<Option<u64>, Option<u64>> {
416        self.words
417            .update(key, "AtomicDirectMap", false, |old| {
418                f(decode_direct(old)).map(|new| new.map_or(0, encode_direct))
419            })
420            .map(decode_direct)
421            .map_err(decode_direct)
422    }
423
424    /// Iterates in ascending slot order, loading each slot once with acquire
425    /// ordering. Weakly consistent under mutation; not a snapshot.
426    pub fn iter(&self) -> AtomicDirectMapIter<'_, PAGE> {
427        AtomicDirectMapIter {
428            inner: self.words.range(0, usize::MAX),
429        }
430    }
431
432    /// Iterates over a key range in ascending order, loading each visited slot
433    /// once with acquire ordering. Weakly consistent under mutation. Empty or
434    /// inverted ranges yield nothing.
435    pub fn range(&self, keys: impl RangeBounds<usize>) -> impl Iterator<Item = (usize, u64)> {
436        let (start, end) = index_bounds(keys);
437        self.words
438            .range(start, end)
439            .map(|(key, word)| (key, word - 1))
440    }
441
442    /// Frees pages that contain no entries. Flat directory chunks stay allocated.
443    /// Shared insertions can allocate those pages again.
444    pub fn shrink_to_fit(&mut self) {
445        self.words.shrink_to_fit();
446    }
447
448    /// Empties the map, retaining pages for reuse. Requires exclusive access.
449    pub fn clear(&mut self) {
450        self.words.clear();
451    }
452
453    /// Copies a weakly consistent snapshot into a valid plain map,
454    /// scanning the directory and allocated slots. Includes entries that remain
455    /// unchanged throughout the call if their writes happen-before it.
456    pub fn snapshot(&self) -> PagedDirectMap<usize, u64, PAGE, D> {
457        self.iter().collect()
458    }
459
460    /// Moves entries into a plain map with the same directory in slot order.
461    pub fn into_inner(self) -> PagedDirectMap<usize, u64, PAGE, D> {
462        self.iter().collect()
463    }
464
465    /// Frees all pages and directory chunks, leaving an empty map.
466    pub fn reset(&mut self) {
467        self.words.reset();
468    }
469}
470
471fn encode_id(id: Id, value: u32) -> u64 {
472    (u64::from(id.generation().get()) << 32) | u64::from(value)
473}
474
475fn decode_id(index: u32, word: u64) -> Option<(Id, u32)> {
476    let generation = NonZeroU32::new((word >> 32) as u32)?;
477    Some((Id::new(index, generation), word as u32))
478}
479
480fn id_value(id: Id, word: u64) -> Option<u32> {
481    ((word >> 32) as u32 == id.generation().get()).then_some(word as u32)
482}
483
484fn id_update(id: Id, old: u64, new: Option<u32>) -> u64 {
485    match new {
486        Some(value) => encode_id(id, value),
487        None if id_value(id, old).is_some() => 0,
488        None => old,
489    }
490}
491
492/// A lock-free direct-address map from generational [`Id`]s to `u32` values.
493///
494/// Each slot at `id.index()` stores `generation << 32 | value`. Generation is
495/// nonzero, so zero denotes an empty slot and all `u32` values are storable.
496/// Lookups and [`remove`](Self::remove) match the generation. Unconditional
497/// insertion evicts any generation, while [`try_insert`](Self::try_insert)
498/// refuses any occupant.
499///
500/// Conditional updates view another generation as absent. Writing `Some(v)`
501/// installs the requested id and evicts any other generation; writing `None`
502/// removes only the requested id and succeeds without changing another
503/// generation. Filling an empty slot adds one to length, eviction leaves it
504/// unchanged, and removing this id subtracts one.
505///
506/// Slot loads use acquire ordering, successful read-modify-write operations
507/// use acquire-release, and failed compare-exchanges use acquire. Values may
508/// publish other data indexed by them. Slot operations are lock-free; page
509/// installation can allocate. The finite, Flat-like spine retains pages until
510/// [`shrink_to_fit`](Self::shrink_to_fit), [`reset`](Self::reset) or destruction. Out-of-range lookups and removals
511/// return absent; inserting outside the spine range panics. `PAGE` must be
512/// nonzero and its atomic slot storage must fit in `isize::MAX` bytes.
513///
514/// Length uses wrapping counters, one per thread (per page group without
515/// `std`), updated after each occupancy change. A removal can be counted
516/// before the insertion it undoes, or on another counter; [`len`](Self::len)
517/// 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
518/// indices and load each visited slot once; they do not provide a snapshot.
519///
520/// ```
521/// # #[cfg(feature = "concurrent")] {
522/// use core::num::NonZeroU32;
523/// use paged_collections::{concurrent::AtomicIdMap, id_alloc::Id};
524/// let map = AtomicIdMap::<4>::new();
525/// let old = Id::new(3, NonZeroU32::new(1).unwrap());
526/// let new = Id::new(3, NonZeroU32::new(2).unwrap());
527/// map.insert(old, 10);
528/// assert_eq!(map.replace(new, u32::MAX), Some((old, 10)));
529/// assert_eq!(map.remove(old), None);
530/// assert_eq!(map.get(new), Some(u32::MAX));
531/// # }
532/// ```
533pub struct AtomicIdMap<const PAGE: usize = DEFAULT_PAGE> {
534    words: Words<PAGE, Flat>,
535}
536
537impl<const PAGE: usize> AtomicIdMap<PAGE> {
538    /// Number of atomic slots per page.
539    pub const PAGE_SIZE: usize = PAGE;
540
541    /// Creates an empty map without allocating.
542    ///
543    /// Panics if `PAGE` is zero or its atomic storage exceeds `isize::MAX` bytes.
544    pub fn new() -> Self {
545        Self {
546            words: Words::new("AtomicIdMap"),
547        }
548    }
549
550    /// Number of entries; exact when no write is in flight.
551    ///
552    /// Sums per-thread counters (per page group without `std`), reading the
553    /// sum as signed and clamping negatives to zero. While writes are in
554    /// flight, the counters may be
555    /// read at different moments, so the result can differ from every count
556    /// the map held, though it never exceeds the number of insertions.
557    pub fn len(&self) -> usize {
558        self.words.len()
559    }
560
561    /// Whether `len()` is zero, subject to concurrent writes.
562    pub fn is_empty(&self) -> bool {
563        self.len() == 0
564    }
565
566    /// Counts installed pages; weakly consistent during page installation.
567    pub fn allocated_pages(&self) -> usize {
568        self.words.pages.iter().count()
569    }
570
571    /// Loads the value only if this generation holds the slot.
572    /// Uses acquire ordering; out-of-range ids return `None`.
573    pub fn get(&self, id: Id) -> Option<u32> {
574        id_value(id, self.words.load(id.index() as usize))
575    }
576
577    /// Whether this id's generation holds the slot.
578    pub fn contains_key(&self, id: Id) -> bool {
579        self.get(id).is_some()
580    }
581
582    /// Loads whichever generation occupies `index`, with acquire ordering.
583    /// Out-of-range indices return `None`.
584    pub fn occupant(&self, index: u32) -> Option<(Id, u32)> {
585        decode_id(index, self.words.load(index as usize))
586    }
587
588    /// Swaps in this id and value, returning the previous value from any
589    /// generation. Panics if the index exceeds the spine range.
590    pub fn insert(&self, id: Id, value: u32) -> Option<u32> {
591        self.replace(id, value).map(|(_, value)| value)
592    }
593
594    /// Swaps in this id and value, returning the previous occupant from any
595    /// generation. Panics if the index exceeds the spine range.
596    pub fn replace(&self, id: Id, value: u32) -> Option<(Id, u32)> {
597        let old = self
598            .words
599            .swap(id.index() as usize, encode_id(id, value), "AtomicIdMap");
600        decode_id(id.index(), old)
601    }
602
603    /// Inserts only into an empty slot, returning any occupant on failure.
604    /// Panics if the index exceeds the spine range.
605    pub fn try_insert(&self, id: Id, value: u32) -> Result<(), (Id, u32)> {
606        self.words
607            .try_insert(id.index() as usize, encode_id(id, value), "AtomicIdMap")
608            .map_err(|word| decode_id(id.index(), word).unwrap())
609    }
610
611    /// Removes only this generation, returning its value. A stale id never
612    /// removes another generation. Out-of-range ids return `None`.
613    pub fn remove(&self, id: Id) -> Option<u32> {
614        self.words
615            .update(id.index() as usize, "AtomicIdMap", false, |old| {
616                id_value(id, old).map(|_| 0)
617            })
618            .ok()
619            .and_then(|old| id_value(id, old))
620    }
621
622    /// Swaps the slot to empty and returns any occupant.
623    /// Out-of-range indices return `None` without allocating.
624    pub fn remove_occupant(&self, index: u32) -> Option<(Id, u32)> {
625        decode_id(index, self.words.swap(index as usize, 0, "AtomicIdMap"))
626    }
627
628    /// Stores `new` if this id's value equals `current`, without spurious
629    /// failure. Returns `Ok(previous)` or `Err(actual)` for this id only.
630    /// `None` matches both an empty slot and another generation. `Some(v)`
631    /// evicts any generation; `None` removes only this id and otherwise
632    /// succeeds without changing the occupant. Eviction preserves length.
633    /// A `None` write never allocates a page. A nonempty write installs its
634    /// page before checking `current`; an out-of-range insertion panics.
635    pub fn compare_exchange(
636        &self,
637        id: Id,
638        current: Option<u32>,
639        new: Option<u32>,
640    ) -> Result<Option<u32>, Option<u32>> {
641        self.words
642            .update(id.index() as usize, "AtomicIdMap", new.is_some(), |old| {
643                (id_value(id, old) == current).then(|| id_update(id, old, new))
644            })
645            .map(|old| id_value(id, old))
646            .map_err(|actual| id_value(id, actual))
647    }
648
649    /// Repeatedly calls `f` with this id's value until a change succeeds or
650    /// `f` returns `None`. Another generation is presented as absent.
651    /// `Some(Some(v))` stores this id and evicts any generation; `Some(None)`
652    /// removes only this id, leaving another generation unchanged. Eviction
653    /// preserves length. Returns `Ok(previous)` on success or `Err(current)`
654    /// if `f` stops. The callback may run several times, even if its argument
655    /// remains `None` while other generations change; only one change commits.
656    /// Removing from an absent page does not allocate it. An out-of-range
657    /// insertion panics. A panicking callback leaves the slot unchanged by
658    /// this call.
659    pub fn fetch_update(
660        &self,
661        id: Id,
662        mut f: impl FnMut(Option<u32>) -> Option<Option<u32>>,
663    ) -> Result<Option<u32>, Option<u32>> {
664        self.words
665            .update(id.index() as usize, "AtomicIdMap", false, |old| {
666                f(id_value(id, old)).map(|new| id_update(id, old, new))
667            })
668            .map(|old| id_value(id, old))
669            .map_err(|actual| id_value(id, actual))
670    }
671
672    /// Iterates in ascending index order, loading each slot once with acquire
673    /// ordering. Weakly consistent under mutation; not a snapshot.
674    pub fn iter(&self) -> AtomicIdMapIter<'_, PAGE> {
675        AtomicIdMapIter {
676            inner: self.words.range(0, usize::MAX),
677        }
678    }
679
680    /// Iterates over an index range in ascending order, independent of
681    /// generation. Loads each visited slot once with acquire ordering;
682    /// weakly consistent under mutation. Empty or inverted ranges yield nothing.
683    pub fn range(&self, indices: impl RangeBounds<u32>) -> impl Iterator<Item = (Id, u32)> {
684        let bounds = (
685            indices.start_bound().map(|&index| index as usize),
686            indices.end_bound().map(|&index| index as usize),
687        );
688        let (start, end) = index_bounds(bounds);
689        self.words
690            .range(start, end)
691            .filter_map(|(index, word)| decode_id(index as u32, word))
692    }
693
694    /// Frees pages that contain no entries, keeping directory chunks.
695    /// Shared insertions can allocate those pages again.
696    pub fn shrink_to_fit(&mut self) {
697        self.words.shrink_to_fit();
698    }
699
700    /// Empties the map, retaining pages for reuse. Requires exclusive access.
701    pub fn clear(&mut self) {
702        self.words.clear();
703    }
704
705    /// Frees all pages and directory chunks, leaving an empty map.
706    pub fn reset(&mut self) {
707        self.words.reset();
708    }
709}
710
711impl<'a, const PAGE: usize, D: SharedDirectory> IntoIterator for &'a AtomicDirectMap<PAGE, D> {
712    type Item = (usize, u64);
713    type IntoIter = AtomicDirectMapIter<'a, PAGE>;
714
715    fn into_iter(self) -> Self::IntoIter {
716        self.iter()
717    }
718}
719
720impl<'a, const PAGE: usize> IntoIterator for &'a AtomicIdMap<PAGE> {
721    type Item = (Id, u32);
722    type IntoIter = AtomicIdMapIter<'a, PAGE>;
723
724    fn into_iter(self) -> Self::IntoIter {
725        self.iter()
726    }
727}
728
729/// Weakly consistent iterator over entries of an [`AtomicDirectMap`] in key order.
730#[must_use = "iterators are lazy and do nothing unless consumed"]
731pub struct AtomicDirectMapIter<'a, const PAGE: usize = DEFAULT_PAGE> {
732    inner: WordsIter<'a, PAGE>,
733}
734
735impl<const PAGE: usize> Iterator for AtomicDirectMapIter<'_, PAGE> {
736    type Item = (usize, u64);
737
738    fn next(&mut self) -> Option<Self::Item> {
739        self.inner.next().map(|(key, word)| (key, word - 1))
740    }
741}
742
743impl<const PAGE: usize> fmt::Debug for AtomicDirectMapIter<'_, PAGE> {
744    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
745        f.debug_struct("AtomicDirectMapIter")
746            .finish_non_exhaustive()
747    }
748}
749
750/// Weakly consistent iterator over entries of an [`AtomicIdMap`] in index order.
751#[must_use = "iterators are lazy and do nothing unless consumed"]
752pub struct AtomicIdMapIter<'a, const PAGE: usize = DEFAULT_PAGE> {
753    inner: WordsIter<'a, PAGE>,
754}
755
756impl<const PAGE: usize> Iterator for AtomicIdMapIter<'_, PAGE> {
757    type Item = (Id, u32);
758
759    fn next(&mut self) -> Option<Self::Item> {
760        self.inner
761            .find_map(|(index, word)| decode_id(index as u32, word))
762    }
763}
764
765impl<const PAGE: usize> fmt::Debug for AtomicIdMapIter<'_, PAGE> {
766    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
767        f.debug_struct("AtomicIdMapIter").finish_non_exhaustive()
768    }
769}
770
771/// Copies via [`AtomicDirectMap::snapshot`].
772impl<const PAGE: usize, D: SharedDirectory> Clone for AtomicDirectMap<PAGE, D> {
773    fn clone(&self) -> Self {
774        Self::from(self.snapshot())
775    }
776}
777
778impl<const PAGE: usize, D: SharedDirectory> Default for AtomicDirectMap<PAGE, D> {
779    fn default() -> Self {
780        Self::new()
781    }
782}
783
784impl<const PAGE: usize, D: SharedDirectory> fmt::Debug for AtomicDirectMap<PAGE, D> {
785    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786        f.debug_map().entries(self.iter()).finish()
787    }
788}
789
790impl<const PAGE: usize, D: SharedDirectory> FromIterator<(usize, u64)>
791    for AtomicDirectMap<PAGE, D>
792{
793    /// Collects entries, panicking if a value is `u64::MAX` or a `Flat` key
794    /// exceeds the spine range. Later entries replace earlier values at the same key.
795    fn from_iter<T: IntoIterator<Item = (usize, u64)>>(iter: T) -> Self {
796        let mut map = Self::new();
797        map.extend(iter);
798        map
799    }
800}
801
802impl<const PAGE: usize, D: SharedDirectory> Extend<(usize, u64)> for AtomicDirectMap<PAGE, D> {
803    /// Inserts entries, panicking if a value is `u64::MAX` or a `Flat` key
804    /// exceeds the spine range. Entries inserted before a panic remain in the map.
805    fn extend<T: IntoIterator<Item = (usize, u64)>>(&mut self, iter: T) {
806        for (key, value) in iter {
807            self.insert(key, value);
808        }
809    }
810}
811
812impl<const PAGE: usize, D: SharedDirectory> From<PagedDirectMap<usize, u64, PAGE, D>>
813    for AtomicDirectMap<PAGE, D>
814{
815    /// Panics if a value is `u64::MAX` or a `Flat` index exceeds the spine range.
816    fn from(map: PagedDirectMap<usize, u64, PAGE, D>) -> Self {
817        map.into_iter().collect()
818    }
819}
820
821/// Copies a weakly consistent view, scanning the directory and allocated slots.
822/// Includes entries that remain unchanged throughout the call if their writes
823/// happen-before it.
824impl<const PAGE: usize> Clone for AtomicIdMap<PAGE> {
825    fn clone(&self) -> Self {
826        self.iter().collect()
827    }
828}
829
830impl<const PAGE: usize> Default for AtomicIdMap<PAGE> {
831    fn default() -> Self {
832        Self::new()
833    }
834}
835
836impl<const PAGE: usize> fmt::Debug for AtomicIdMap<PAGE> {
837    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838        f.debug_map().entries(self.iter()).finish()
839    }
840}
841
842impl<const PAGE: usize> FromIterator<(Id, u32)> for AtomicIdMap<PAGE> {
843    fn from_iter<T: IntoIterator<Item = (Id, u32)>>(iter: T) -> Self {
844        let mut map = Self::new();
845        map.extend(iter);
846        map
847    }
848}
849
850impl<const PAGE: usize> Extend<(Id, u32)> for AtomicIdMap<PAGE> {
851    fn extend<T: IntoIterator<Item = (Id, u32)>>(&mut self, iter: T) {
852        for (id, value) in iter {
853            self.insert(id, value);
854        }
855    }
856}
857
858#[cfg(feature = "serde")]
859mod serde_impl {
860    use super::*;
861    use crate::concurrent::serde::deserialize_map;
862    use alloc::vec::Vec;
863    use serde::de::{Deserialize, Deserializer, Error};
864    use serde::ser::{Serialize, Serializer};
865
866    /// Serializes a weakly consistent snapshot as a valid plain map in slot
867    /// order, with the same consistency as [`AtomicDirectMap::snapshot`].
868    /// Scans the directory and allocated slots, buffering entries to
869    /// supply the exact serialized length.
870    impl<const PAGE: usize, D: SharedDirectory> Serialize for AtomicDirectMap<PAGE, D> {
871        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
872            serializer.collect_map(self.iter().collect::<Vec<_>>())
873        }
874    }
875
876    /// Reads the plain [`PagedDirectMap`] format, rejecting `u64::MAX`
877    /// values and indices outside the concurrent directory's range.
878    impl<'de, const PAGE: usize, D: SharedDirectory> Deserialize<'de> for AtomicDirectMap<PAGE, D> {
879        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
880            if !Words::<PAGE, D>::valid_page_capacity() {
881                return Err(De::Error::custom("AtomicDirectMap: invalid page capacity"));
882            }
883            deserialize_map(deserializer, Self::new(), |map, index, value| {
884                if value > Self::MAX_VALUE {
885                    return Err("AtomicDirectMap: u64::MAX cannot be stored");
886                }
887                if D::Pages::<Page>::page_number::<PAGE>(index).is_none() {
888                    return Err("AtomicDirectMap: key index exceeds direct spine range");
889                }
890                map.insert(index, value);
891                Ok(())
892            })
893        }
894    }
895
896    /// Serializes a weakly consistent snapshot as a valid `Id` to `u32`
897    /// map in slot order. Scans the directory and allocated slots,
898    /// buffering entries to supply the exact serialized length. Includes
899    /// entries that remain unchanged throughout the call if their writes
900    /// happen-before it.
901    impl<const PAGE: usize> Serialize for AtomicIdMap<PAGE> {
902        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
903            serializer.collect_map(self.iter().collect::<Vec<_>>())
904        }
905    }
906
907    /// Reads an `Id` to `u32` map in O(len) entry insertions. The
908    /// last entry for each index wins, as with [`FromIterator`]. Rejects
909    /// indices outside the concurrent directory's range.
910    impl<'de, const PAGE: usize> Deserialize<'de> for AtomicIdMap<PAGE> {
911        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
912            if !Words::<PAGE, Flat>::valid_page_capacity() {
913                return Err(De::Error::custom("AtomicIdMap: invalid page capacity"));
914            }
915            deserialize_map(deserializer, Self::new(), |map, id: Id, value| {
916                if <Flat as SharedDirectory>::Pages::<Page>::page_number::<PAGE>(id.index() as usize)
917                    .is_none()
918                {
919                    return Err("AtomicIdMap: id index exceeds direct spine range");
920                }
921                map.insert(id, value);
922                Ok(())
923            })
924        }
925    }
926}