Skip to main content

paged_collections/concurrent/
sparse.rs

1//! Insert-only shared sparse collections; editing requires exclusive access.
2
3use alloc::boxed::Box;
4use alloc::vec::{IntoIter, Vec};
5use core::fmt;
6use core::iter::FusedIterator;
7
8use super::append::{AppendLog, DenseIter};
9use super::atomic::{AtomicU32, Ordering};
10use super::directory::{SharedDirectory, SharedPages};
11use super::index::retry;
12use super::vec::VecIterMut;
13use crate::key::Key;
14use crate::page::{DEFAULT_PAGE, Flat};
15use crate::sparse_map::PagedSparseMap;
16use crate::sparse_set::PagedSparseSet;
17
18const RESERVED: u32 = u32::MAX;
19// 0 is empty and u32::MAX is RESERVED: encodings 1..u32::MAX are positions.
20const DENSE_LIMIT: usize = (u32::MAX - 1) as usize;
21
22struct IndexPage {
23    slots: Box<[AtomicU32]>,
24}
25
26struct Index<const PAGE: usize, D: SharedDirectory = Flat> {
27    pages: D::Pages<IndexPage>,
28}
29
30/// Only a successful 0 -> RESERVED CAS creates this guard. It restores 0 on
31/// any unwind, including factory/allocation panics, or publishes one position.
32struct Reservation<'a> {
33    slot: &'a AtomicU32,
34    armed: bool,
35}
36
37impl Reservation<'_> {
38    fn publish(mut self, pos: usize) {
39        // Release publishes the dense write AND its ready bit. Point lookups
40        // acquire this slot and need no check against the committed prefix.
41        self.slot.store(pos as u32 + 1, Ordering::Release);
42        self.armed = false;
43    }
44}
45
46impl Drop for Reservation<'_> {
47    fn drop(&mut self) {
48        if self.armed {
49            // Release ends this claim. Waiters must retry 0, not spin forever
50            // waiting for a position after a panicking factory/full log.
51            self.slot.store(0, Ordering::Release);
52        }
53    }
54}
55
56impl<const PAGE: usize, D: SharedDirectory> Index<PAGE, D> {
57    fn valid_page_capacity() -> bool {
58        PAGE > 0 && PAGE <= isize::MAX as usize / core::mem::size_of::<AtomicU32>()
59    }
60
61    fn new() -> Self {
62        assert!(
63            Self::valid_page_capacity(),
64            "ConcurrentSparse: invalid page capacity"
65        );
66        Self {
67            pages: D::Pages::<IndexPage>::new(),
68        }
69    }
70
71    fn page_number(index: usize) -> usize {
72        D::Pages::<IndexPage>::page_number::<PAGE>(index)
73            .expect("ConcurrentSparse: key index exceeds sparse spine range")
74    }
75
76    fn slot(&self, index: usize) -> Option<&AtomicU32> {
77        self.pages
78            .get(Self::page_number(index))
79            .map(|page| &page.slots[index % PAGE])
80    }
81
82    fn ensure_slot(&self, index: usize) -> &AtomicU32 {
83        let page = self.pages.get_or_insert_with(Self::page_number(index), || {
84            Box::new(IndexPage {
85                slots: (0..PAGE).map(|_| AtomicU32::new(0)).collect(),
86            })
87        });
88        &page.slots[index % PAGE]
89    }
90
91    /// Drops index pages with no occupied slot. Exclusive access means no
92    /// insertion holds a reservation, so every slot is empty or a position.
93    fn shrink_to_fit(&mut self) {
94        self.pages.retain(|_, page| {
95            page.slots
96                .iter()
97                // Relaxed: exclusive access excludes concurrent slot writers.
98                .any(|slot| slot.load(Ordering::Relaxed) != 0)
99        });
100    }
101
102    fn position(&self, index: usize) -> Option<usize> {
103        // Acquire observes the dense entry written before position publication.
104        match self.slot(index)?.load(Ordering::Acquire) {
105            0 | RESERVED => None,
106            word => Some(word as usize - 1),
107        }
108    }
109
110    /// One attempt to reserve the slot, never waiting.
111    fn try_claim(slot: &AtomicU32) -> Claim<'_> {
112        // Acquire sees the winning entry or a rollback from RESERVED to 0.
113        match slot.load(Ordering::Acquire) {
114            0 => {
115                // AcqRel grants one caller ownership and observes any
116                // previous rollback; failure acquires the competing state.
117                match slot.compare_exchange(0, RESERVED, Ordering::AcqRel, Ordering::Acquire) {
118                    Ok(_) => Claim::Owned(Reservation { slot, armed: true }),
119                    // Failure means the slot is no longer 0.
120                    Err(RESERVED) => Claim::Busy,
121                    Err(word) => Claim::Present(word as usize - 1),
122                }
123            }
124            RESERVED => Claim::Busy,
125            word => Claim::Present(word as usize - 1),
126        }
127    }
128
129    fn claim(&self, index: usize) -> Result<Reservation<'_>, usize> {
130        let slot = self.ensure_slot(index);
131        let mut spins = 0;
132        loop {
133            match Self::try_claim(slot) {
134                Claim::Owned(owner) => return Ok(owner),
135                Claim::Present(pos) => return Err(pos),
136                // Same-slot insertions wait for publication or rollback.
137                // Other slots proceed independently. A factory must not
138                // recursively insert into its own reserved slot.
139                Claim::Busy => retry(&mut spins),
140            }
141        }
142    }
143}
144
145enum Claim<'a> {
146    Owned(Reservation<'a>),
147    Present(usize),
148    Busy,
149}
150
151/// Keys per batch reservation in [`ConcurrentSparseSet::insert_many`] and
152/// [`ConcurrentSparseMap::try_insert_many`]: large enough to amortize the
153/// shared append counters, small enough to bound held reservations.
154const BATCH: usize = 256;
155
156/// Loom coverage: counts batch items deferred because another writer held
157/// their slot. Plain std atomic, outside the model.
158#[cfg(all(test, loom))]
159pub(super) static BATCH_BUSY: std::sync::atomic::AtomicUsize =
160    std::sync::atomic::AtomicUsize::new(0);
161
162/// Inserts `items` in batches. Each batch claims vacant slots without
163/// waiting, appends all claimed entries with one reservation, then publishes
164/// their positions. Slots another writer holds (including an earlier
165/// duplicate in this batch) are deferred and inserted one at a time with the
166/// waiting path once this batch holds no reservations, so two batches never
167/// wait on each other. Returns the number inserted.
168fn insert_batched<'a, K: Key, T, const PAGE: usize, D: SharedDirectory>(
169    index: &'a Index<PAGE, D>,
170    dense: &AppendLog<T, PAGE>,
171    items: impl IntoIterator<Item = T>,
172    key_of: impl Fn(&T) -> K,
173    insert_one: impl Fn(T) -> bool,
174    full: &str,
175) -> usize {
176    let mut items = items.into_iter();
177    let mut inserted = 0;
178    // Keep user values in buffers declared before the reservation guards,
179    // including while the dense log prepares storage. A value's destructor
180    // may insert into a slot that this batch reserved.
181    let mut pending = Vec::with_capacity(BATCH);
182    let mut deferred = Vec::new();
183    let mut entries: Vec<T> = Vec::with_capacity(BATCH);
184    let mut owners: Vec<Reservation<'a>> = Vec::with_capacity(BATCH);
185    loop {
186        // Run the iterator, validate keys and allocate sparse slots before
187        // claiming anything. A panic here leaves earlier batches intact.
188        for item in items.by_ref().take(BATCH) {
189            let key_index = key_of(&item).index();
190            let slot = index.ensure_slot(key_index);
191            pending.push((key_index, slot, Some(item)));
192        }
193        let taken = pending.len();
194        // Reserve space before claiming so that moving values cannot panic
195        // on a buffer allocation. Rejected values stay in `pending`.
196        deferred.reserve(taken);
197        for &mut (key_index, slot, ref mut item) in &mut pending {
198            // A later copy of a deferred key is deferred too: if the other
199            // writer rolls back, the earlier copy must still win.
200            if deferred.iter().any(|(key, _)| *key == key_index) {
201                deferred.push((key_index, item.take().expect("prepared item")));
202            } else {
203                match Index::<PAGE, D>::try_claim(slot) {
204                    Claim::Owned(owner) => {
205                        owners.push(owner);
206                        entries.push(item.take().expect("prepared item"));
207                    }
208                    Claim::Present(_) => {}
209                    Claim::Busy => {
210                        #[cfg(all(test, loom))]
211                        BATCH_BUSY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
212                        deferred.push((key_index, item.take().expect("prepared item")));
213                    }
214                }
215            }
216        }
217        if !owners.is_empty() {
218            let Some(start) = dense.push_many_from(&mut entries, DENSE_LIMIT) else {
219                panic!("{full}");
220            };
221            inserted += owners.len();
222            for (i, owner) in owners.drain(..).enumerate() {
223                owner.publish(start + i);
224            }
225        }
226        // No reservation is held from here on.
227        pending.clear();
228        for (_, item) in deferred.drain(..) {
229            inserted += usize::from(insert_one(item));
230        }
231        // Only an exhausted input ends the loop: a batch of present keys
232        // claims nothing but more input may follow.
233        if taken < BATCH {
234            return inserted;
235        }
236    }
237}
238
239/// A paged sparse set with shared insertion and stable shared references.
240///
241/// At most one key occupies each [`Key::index`]. An occupied slot refuses
242/// both duplicates and other generations. Same-slot insertions wait for the
243/// winning insertion; lookups do not wait. Removing or clearing requires
244/// exclusive access and can move the last dense key into a removed position.
245///
246/// Iteration and pages snapshot the hole-free committed prefix. Its length
247/// can lag behind completed insertions while an earlier append is in flight;
248/// lookups see every completed insertion. With no insertion in flight the
249/// prefix contains every entry.
250///
251/// The default [`Flat`] directory has O(1) page lookups and memory following
252/// the highest page; indices outside its finite spine range panic.
253/// [`Radix`](crate::page::Radix) accepts any `usize` index, uses directory
254/// memory proportional to installed pages, and looks up pages in O(depth). At most
255/// `u32::MAX - 1` entries fit because one encoding is reserved for writers.
256/// Pages are retained until destruction. Uses only `core` and `alloc`.
257///
258/// ```
259/// # #[cfg(feature = "concurrent")] {
260/// use paged_collections::{concurrent::ConcurrentSparseSet, page::Radix};
261/// let set = ConcurrentSparseSet::<usize, 4, Radix>::new();
262/// assert!(set.insert(usize::MAX - 1));
263/// assert!(set.contains(usize::MAX - 1));
264/// # }
265/// ```
266pub struct ConcurrentSparseSet<K: Key, const PAGE: usize = DEFAULT_PAGE, D: SharedDirectory = Flat>
267{
268    index: Index<PAGE, D>,
269    // AppendLog stores keys in UnsafeCell, keeping K invariant.
270    dense: AppendLog<K, PAGE>,
271}
272
273// SAFETY: moving the set transfers owned keys; no reference outlives its borrow.
274unsafe impl<K: Key + Send, const PAGE: usize, D: SharedDirectory> Send
275    for ConcurrentSparseSet<K, PAGE, D>
276{
277}
278// SAFETY: RESERVED gives each slot one writer, the append log owns distinct
279// writes, and shared lookups acquire publication and expose only shared keys.
280unsafe impl<K: Key + Send + Sync, const PAGE: usize, D: SharedDirectory> Sync
281    for ConcurrentSparseSet<K, PAGE, D>
282{
283}
284
285impl<K: Key, const PAGE: usize, D: SharedDirectory> ConcurrentSparseSet<K, PAGE, D> {
286    /// Number of slots per sparse page and keys per dense page.
287    pub const PAGE_SIZE: usize = PAGE;
288
289    /// Creates an empty set without allocating.
290    ///
291    /// # Panics
292    ///
293    /// Panics if `PAGE` is zero or page storage exceeds `isize::MAX` bytes.
294    pub fn new() -> Self {
295        Self {
296            index: Index::new(),
297            dense: AppendLog::new(),
298        }
299    }
300
301    /// Adds `key`, returning `false` if any key already holds its slot.
302    /// Waits for an insertion already reserving the same slot to finish.
303    ///
304    /// # Panics
305    ///
306    /// Panics at `u32::MAX - 1` entries, for indices outside the `Flat` spine
307    /// range, or on allocation capacity overflow. Allocation can also fail.
308    pub fn insert(&self, key: K) -> bool {
309        let Ok(owner) = self.index.claim(key.index()) else {
310            return false;
311        };
312        match self.dense.push(key, DENSE_LIMIT) {
313            Ok(pos) => owner.publish(pos),
314            Err(_) => {
315                drop(owner);
316                panic!("ConcurrentSparseSet cannot hold more than u32::MAX - 1 keys");
317            }
318        }
319        true
320    }
321
322    /// Adds every key whose slot is vacant, returning how many were added.
323    /// Earlier duplicates win. Batches share one dense reservation, which
324    /// scales across threads far better than repeated [`insert`](Self::insert).
325    /// Positions need not follow input order.
326    ///
327    /// Each batch is read and its keys validated before any slots are reserved.
328    /// If the iterator panics, earlier batches stay inserted.
329    ///
330    /// # Panics
331    ///
332    /// As [`insert`](Self::insert).
333    pub fn insert_many(&self, keys: impl IntoIterator<Item = K>) -> usize {
334        insert_batched(
335            &self.index,
336            &self.dense,
337            keys,
338            |&key| key,
339            |key| self.insert(key),
340            "ConcurrentSparseSet cannot hold more than u32::MAX - 1 keys",
341        )
342    }
343
344    /// Dense position of this key, including a completed insertion beyond
345    /// the committed prefix. Positions can change under exclusive removal.
346    /// With `Flat`, panics if the key index exceeds the sparse spine range.
347    pub fn position(&self, key: K) -> Option<usize> {
348        let pos = self.index.position(key.index())?;
349        // The acquired sparse position follows the write and ready bit. get
350        // checks readiness independently, never bounds it by committed.
351        self.dense
352            .get(pos)
353            .filter(|&&stored| stored == key)
354            .map(|_| pos)
355    }
356
357    /// Whether this key is present. Does not wait for an in-flight insertion.
358    /// With `Flat`, panics if the key index exceeds the sparse spine range.
359    pub fn contains(&self, key: K) -> bool {
360        self.position(key).is_some()
361    }
362
363    /// Length of the committed prefix; can lag while an earlier append runs.
364    pub fn len(&self) -> usize {
365        self.dense.len()
366    }
367
368    /// Whether the committed prefix is empty, subject to the lag of `len`.
369    pub fn is_empty(&self) -> bool {
370        self.len() == 0
371    }
372
373    /// Iterates over a snapshot of the committed keys in dense order.
374    pub fn iter(&self) -> DenseIter<'_, K, PAGE> {
375        self.dense.iter()
376    }
377
378    /// Nonempty page slices of a snapshot of the committed dense prefix.
379    /// Every page but the last is full.
380    pub fn pages(
381        &self,
382    ) -> impl DoubleEndedIterator<Item = &[K]> + ExactSizeIterator + FusedIterator {
383        self.dense.pages()
384    }
385
386    /// Removes a matching key, moving the last key into its position.
387    /// Requires exclusive access. With `Flat`, panics for an out-of-range key index.
388    pub fn remove(&mut self, key: K) -> bool {
389        let Some(pos) = self.position(key) else {
390            return false;
391        };
392        let last = self.dense.len() - 1;
393        // Read all user-supplied indices and find slots before any mutation.
394        let removed = self
395            .index
396            .slot(key.index())
397            .expect("present key has a slot");
398        let moved = if pos == last {
399            None
400        } else {
401            Some(
402                self.index
403                    .slot(self.dense.get(last).expect("last key exists").index())
404                    .expect("moved key has a slot"),
405            )
406        };
407        self.dense.swap_remove(pos);
408        // Relaxed: exclusive access excludes readers and slot writers.
409        removed.store(0, Ordering::Relaxed);
410        if let Some(slot) = moved {
411            // Relaxed: moved key is already written, and access is exclusive.
412            slot.store(pos as u32 + 1, Ordering::Relaxed);
413        }
414        true
415    }
416
417    /// Removes every key and clears readiness, retaining allocated pages.
418    /// Takes O(len) time.
419    pub fn clear(&mut self) {
420        while self.pop_key().is_some() {}
421    }
422
423    /// Frees index pages with no key and dense pages beyond the last key,
424    /// keeping directory chunks. Stored keys keep their addresses and
425    /// positions. Shared inserts can allocate the released pages again.
426    ///
427    /// # Examples
428    ///
429    /// ```
430    /// use paged_collections::concurrent::ConcurrentSparseSet;
431    ///
432    /// let mut set: ConcurrentSparseSet<usize, 4> = (0..64).collect();
433    /// for key in 2..64 {
434    ///     set.remove(key);
435    /// }
436    /// set.shrink_to_fit();
437    /// assert_eq!(set.pages().count(), 1);
438    /// assert!(set.insert(40));
439    /// ```
440    pub fn shrink_to_fit(&mut self) {
441        self.index.shrink_to_fit();
442        self.dense.shrink_to_fit();
443    }
444
445    /// Removes all keys and returns them in dense order. Keeps allocated pages.
446    /// Takes O(len) time and temporary storage.
447    pub fn drain(&mut self) -> IntoIter<K> {
448        let mut keys = Vec::with_capacity(self.len());
449        while let Some(key) = self.pop_key() {
450            keys.push(key);
451        }
452        keys.reverse();
453        keys.into_iter()
454    }
455
456    fn pop_key(&mut self) -> Option<K> {
457        let last = self.dense.len().checked_sub(1)?;
458        let key = *self.dense.get(last).expect("last key exists");
459        let slot = self
460            .index
461            .slot(key.index())
462            .expect("present key has a slot");
463        let key = self.dense.pop();
464        // Relaxed: exclusive access; no lookup can observe the change.
465        slot.store(0, Ordering::Relaxed);
466        key
467    }
468
469    /// Copies the committed prefix into a plain set in O(prefix length).
470    /// Like [`len`](Self::len) and [`iter`](Self::iter), this can omit
471    /// completed inserts beyond an earlier unpublished reservation. The keys
472    /// form a valid plain set.
473    pub fn snapshot(&self) -> PagedSparseSet<K, PAGE, D> {
474        self.iter().copied().collect()
475    }
476
477    /// Moves keys into the plain set with the same directory in dense order, in O(len).
478    pub fn into_inner(self) -> PagedSparseSet<K, PAGE, D> {
479        self.dense.into_inner().into_iter().collect()
480    }
481}
482
483impl<'a, K: Key, const PAGE: usize, D: SharedDirectory> IntoIterator
484    for &'a ConcurrentSparseSet<K, PAGE, D>
485{
486    type Item = &'a K;
487    type IntoIter = DenseIter<'a, K, PAGE>;
488
489    fn into_iter(self) -> Self::IntoIter {
490        self.iter()
491    }
492}
493
494/// Copies the committed prefix via [`ConcurrentSparseSet::snapshot`],
495/// which can omit completed inserts beyond an unpublished reservation.
496impl<K: Key, const PAGE: usize, D: SharedDirectory> Clone for ConcurrentSparseSet<K, PAGE, D> {
497    fn clone(&self) -> Self {
498        Self::from(self.snapshot())
499    }
500}
501
502impl<K: Key, const PAGE: usize, D: SharedDirectory> Default for ConcurrentSparseSet<K, PAGE, D> {
503    fn default() -> Self {
504        Self::new()
505    }
506}
507
508impl<K: Key + fmt::Debug, const PAGE: usize, D: SharedDirectory> fmt::Debug
509    for ConcurrentSparseSet<K, PAGE, D>
510{
511    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512        f.debug_set().entries(self.iter()).finish()
513    }
514}
515
516impl<K: Key, const PAGE: usize, D: SharedDirectory> FromIterator<K>
517    for ConcurrentSparseSet<K, PAGE, D>
518{
519    fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
520        let mut result = Self::new();
521        result.extend(iter);
522        result
523    }
524}
525
526/// Inserts keys in input order, keeping the first occupant of each slot.
527impl<K: Key, const PAGE: usize, D: SharedDirectory> Extend<K> for ConcurrentSparseSet<K, PAGE, D> {
528    fn extend<I: IntoIterator<Item = K>>(&mut self, iter: I) {
529        for key in iter {
530            self.insert(key);
531        }
532    }
533}
534
535impl<K: Key, const PAGE: usize, D: SharedDirectory> From<PagedSparseSet<K, PAGE, D>>
536    for ConcurrentSparseSet<K, PAGE, D>
537{
538    fn from(inner: PagedSparseSet<K, PAGE, D>) -> Self {
539        inner.into_iter().collect()
540    }
541}
542
543/// A paged sparse map with insert-only shared access and exclusive editing.
544///
545/// Slots, prefix snapshots and directory selection follow
546/// [`ConcurrentSparseSet`]. An occupied slot refuses a new entry, including
547/// another generation. Existing values are never replaced while shared, so
548/// lookups return stable `&V` references without guards. Shared insertion can
549/// interleave dense order; exclusive removal uses swap-remove.
550///
551/// Same-slot insertions wait for the winning writer, including its factory.
552/// Factories must not recursively insert into their own reserved slot, and
553/// factories on two threads that each insert the other's pending key
554/// deadlock (each waits on the other's reservation). `Sync`
555/// requires both `K` and `V` to be `Send + Sync`. Uses `core` and `alloc` only.
556///
557/// With [`Flat`], memory follows the highest page and lookups cost O(1);
558/// its finite index range can panic. [`Radix`](crate::page::Radix) accepts any
559/// `usize` index, uses directory memory proportional to installed pages, and
560/// looks up pages in O(depth).
561///
562/// ```
563/// # #[cfg(feature = "concurrent")] {
564/// use paged_collections::{concurrent::ConcurrentSparseMap, page::Radix};
565/// let map = ConcurrentSparseMap::<usize, _, 4, Radix>::new();
566/// assert_eq!(map.try_insert(usize::MAX - 1, "wide"), Ok(&"wide"));
567/// assert_eq!(map.get(&(usize::MAX - 1)), Some(&"wide"));
568/// # }
569/// ```
570pub struct ConcurrentSparseMap<
571    K: Key,
572    V,
573    const PAGE: usize = DEFAULT_PAGE,
574    D: SharedDirectory = Flat,
575> {
576    index: Index<PAGE, D>,
577    // AppendLog stores entries in UnsafeCell, keeping K and V invariant.
578    dense: AppendLog<(K, V), PAGE>,
579}
580
581// SAFETY: moving the map transfers all owned keys/values and their drops;
582// no reference can outlive the borrow from which it was obtained.
583unsafe impl<K: Key + Send, V: Send, const PAGE: usize, D: SharedDirectory> Send
584    for ConcurrentSparseMap<K, V, PAGE, D>
585{
586}
587// SAFETY: RESERVED uniquely owns each insertion; acquiring sparse publication
588// exposes initialized immutable entries, and removal/mutation is exclusive.
589unsafe impl<K: Key + Send + Sync, V: Send + Sync, const PAGE: usize, D: SharedDirectory> Sync
590    for ConcurrentSparseMap<K, V, PAGE, D>
591{
592}
593
594impl<K: Key, V, const PAGE: usize, D: SharedDirectory> ConcurrentSparseMap<K, V, PAGE, D> {
595    /// Number of slots per sparse page and entries per dense page.
596    pub const PAGE_SIZE: usize = PAGE;
597
598    /// Creates an empty map without allocating.
599    ///
600    /// # Panics
601    ///
602    /// Panics if `PAGE` is zero or page storage exceeds `isize::MAX` bytes.
603    pub fn new() -> Self {
604        Self {
605            index: Index::new(),
606            dense: AppendLog::new(),
607        }
608    }
609
610    fn position(&self, key: &K) -> Option<usize> {
611        let pos = self.index.position(key.index())?;
612        self.dense
613            .get(pos)
614            .filter(|(stored, _)| stored == key)
615            .map(|_| pos)
616    }
617
618    fn append(&self, reservation: Reservation<'_>, key: K, value: V) -> &V {
619        let mut entry = Some((key, value));
620        // This guard must unwind before the entry if dense preparation panics.
621        let owner = reservation;
622        let Some(pos) = self.dense.push_from(&mut entry, DENSE_LIMIT) else {
623            panic!("ConcurrentSparseMap cannot hold more than u32::MAX - 1 entries");
624        };
625        owner.publish(pos);
626        &self.dense.get(pos).expect("published entry is ready").1
627    }
628
629    /// Adds an entry if its slot is vacant, returning a shared value reference.
630    /// Returns `Err((key, value))` for a duplicate or another generation.
631    /// Waits for a writer already reserving that slot to publish or roll back.
632    ///
633    /// # Panics
634    ///
635    /// Panics at `u32::MAX - 1` entries, for indices outside the `Flat` spine
636    /// range, or on allocation capacity overflow. Allocation can also fail.
637    pub fn try_insert(&self, key: K, value: V) -> Result<&V, (K, V)> {
638        match self.index.claim(key.index()) {
639            Ok(owner) => Ok(self.append(owner, key, value)),
640            Err(_) => Err((key, value)),
641        }
642    }
643
644    /// Adds every entry whose slot is vacant, dropping the others, and returns
645    /// how many were added. Existing entries and earlier duplicates win.
646    /// Batches share one dense reservation, which scales across threads far
647    /// better than repeated [`try_insert`](Self::try_insert).
648    ///
649    /// Each batch is read and its keys validated before any slots are reserved.
650    /// If the iterator panics, earlier batches stay inserted.
651    ///
652    /// # Panics
653    ///
654    /// As [`try_insert`](Self::try_insert).
655    pub fn try_insert_many(&self, entries: impl IntoIterator<Item = (K, V)>) -> usize {
656        insert_batched(
657            &self.index,
658            &self.dense,
659            entries,
660            |(key, _)| *key,
661            |(key, value)| self.try_insert(key, value).is_ok(),
662            "ConcurrentSparseMap cannot hold more than u32::MAX - 1 entries",
663        )
664    }
665
666    /// The value for this key, including completed appends beyond `len`.
667    /// Does not wait for in-flight insertions. With `Flat`, panics for an out-of-range index.
668    pub fn get(&self, key: &K) -> Option<&V> {
669        self.position(key)
670            .map(|pos| &self.dense.get(pos).expect("published entry is ready").1)
671    }
672
673    /// Whether this exact key is present, without waiting for insertions.
674    /// With `Flat`, panics for an out-of-range key index.
675    pub fn contains_key(&self, key: &K) -> bool {
676        self.position(key).is_some()
677    }
678
679    /// Gets this key's value, or inserts `make()` if its slot is vacant.
680    /// Returns `None` only if another generation occupies the slot.
681    ///
682    /// Only the RESERVED winner calls `make`, at most once per call. If it
683    /// panics, a guard restores the slot to empty and other writers may retry.
684    /// The factory must not insert recursively into this same slot: it would
685    /// wait on its own reservation. Nor may two threads' factories insert
686    /// each other's pending keys: each would wait on the other's
687    /// reservation. Factories run before dense reservation.
688    ///
689    /// # Panics
690    ///
691    /// As [`try_insert`](Self::try_insert), or if `make` panics.
692    pub fn get_or_insert_with(&self, key: K, make: impl FnOnce() -> V) -> Option<&V> {
693        match self.index.claim(key.index()) {
694            Ok(owner) => {
695                let value = make();
696                Some(self.append(owner, key, value))
697            }
698            Err(pos) => {
699                let (stored, value) = self.dense.get(pos).expect("published entry is ready");
700                (stored == &key).then_some(value)
701            }
702        }
703    }
704
705    /// Length of the committed prefix; can lag while an earlier append runs.
706    pub fn len(&self) -> usize {
707        self.dense.len()
708    }
709
710    /// Whether the committed prefix is empty, subject to the lag of `len`.
711    pub fn is_empty(&self) -> bool {
712        self.len() == 0
713    }
714
715    /// Iterates over a snapshot of committed `(&key, &value)` pairs.
716    pub fn iter(&self) -> SparseMapIter<'_, K, V, PAGE> {
717        SparseMapIter {
718            inner: self.dense.iter(),
719        }
720    }
721
722    /// Mutable access to a matching key's value under exclusive access.
723    /// With `Flat`, panics for an out-of-range key index.
724    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
725        let pos = self.position(key)?;
726        self.dense.get_mut(pos).map(|(_, value)| value)
727    }
728
729    /// Removes a matching entry and returns its value, moving the last entry
730    /// into its position. With `Flat`, panics for an out-of-range key index.
731    pub fn remove(&mut self, key: &K) -> Option<V> {
732        let pos = self.position(key)?;
733        let last = self.dense.len() - 1;
734        let removed = self
735            .index
736            .slot(key.index())
737            .expect("present key has a slot");
738        let moved = if pos == last {
739            None
740        } else {
741            Some(
742                self.index
743                    .slot(self.dense.get(last).expect("last entry exists").0.index())
744                    .expect("moved key has a slot"),
745            )
746        };
747        let (_, value) = self.dense.swap_remove(pos);
748        // Relaxed: exclusive access excludes readers and slot writers.
749        removed.store(0, Ordering::Relaxed);
750        if let Some(slot) = moved {
751            // Relaxed: the moved entry is written and access is exclusive.
752            slot.store(pos as u32 + 1, Ordering::Relaxed);
753        }
754        Some(value)
755    }
756
757    /// Iterates over `(&key, &mut value)` pairs under exclusive access.
758    /// Keys cannot be changed, preserving the sparse index.
759    pub fn iter_mut(&mut self) -> SparseMapIterMut<'_, K, V> {
760        SparseMapIterMut {
761            inner: VecIterMut::new(&mut self.dense),
762        }
763    }
764
765    /// Drops every entry and clears readiness, retaining pages. Takes O(len).
766    /// If a destructor panics, that entry is gone; remaining entries keep
767    /// their sparse positions and may still be used.
768    pub fn clear(&mut self) {
769        while let Some(entry) = self.pop_entry() {
770            drop(entry);
771        }
772    }
773
774    /// Frees index pages with no entry and dense pages beyond the last entry,
775    /// keeping directory chunks. Stored entries keep their addresses and
776    /// positions. Shared inserts can allocate the released pages again.
777    pub fn shrink_to_fit(&mut self) {
778        self.index.shrink_to_fit();
779        self.dense.shrink_to_fit();
780    }
781
782    /// Removes all entries and returns them as `(key, value)` pairs in dense order.
783    /// Keeps allocated pages. Takes O(len) time and temporary storage.
784    pub fn drain(&mut self) -> IntoIter<(K, V)> {
785        let mut entries = Vec::with_capacity(self.len());
786        while let Some(entry) = self.pop_entry() {
787            entries.push(entry);
788        }
789        entries.reverse();
790        entries.into_iter()
791    }
792
793    fn pop_entry(&mut self) -> Option<(K, V)> {
794        let last = self.dense.len().checked_sub(1)?;
795        let key = self.dense.get(last).expect("last entry exists").0;
796        let slot = self
797            .index
798            .slot(key.index())
799            .expect("present key has a slot");
800        let entry = self.dense.pop();
801        // Relaxed: exclusive access; clear the slot before user drop code.
802        slot.store(0, Ordering::Relaxed);
803        entry
804    }
805
806    /// Clones the committed prefix into a plain map in O(prefix length).
807    /// Like [`len`](Self::len) and [`iter`](Self::iter), this can omit
808    /// completed inserts beyond an earlier unpublished reservation. The
809    /// entries form a valid plain map.
810    pub fn snapshot(&self) -> PagedSparseMap<K, V, PAGE, D>
811    where
812        V: Clone,
813    {
814        self.iter()
815            .map(|(key, value)| (*key, value.clone()))
816            .collect()
817    }
818
819    /// Moves entries into a plain map with the same directory in dense order, in O(len).
820    /// Values move without cloning; their addresses can change.
821    pub fn into_inner(self) -> PagedSparseMap<K, V, PAGE, D> {
822        self.dense.into_inner().into_iter().collect()
823    }
824}
825
826impl<'a, K: Key, V, const PAGE: usize, D: SharedDirectory> IntoIterator
827    for &'a ConcurrentSparseMap<K, V, PAGE, D>
828{
829    type Item = (&'a K, &'a V);
830    type IntoIter = SparseMapIter<'a, K, V, PAGE>;
831
832    fn into_iter(self) -> Self::IntoIter {
833        self.iter()
834    }
835}
836
837impl<'a, K: Key, V, const PAGE: usize, D: SharedDirectory> IntoIterator
838    for &'a mut ConcurrentSparseMap<K, V, PAGE, D>
839{
840    type Item = (&'a K, &'a mut V);
841    type IntoIter = SparseMapIterMut<'a, K, V>;
842
843    fn into_iter(self) -> Self::IntoIter {
844        self.iter_mut()
845    }
846}
847
848/// Iterates over the committed entries of a [`ConcurrentSparseMap`] in dense order.
849#[must_use = "iterators are lazy and do nothing unless consumed"]
850pub struct SparseMapIter<'a, K, V, const PAGE: usize = DEFAULT_PAGE> {
851    inner: DenseIter<'a, (K, V), PAGE>,
852}
853
854impl<'a, K, V, const PAGE: usize> Iterator for SparseMapIter<'a, K, V, PAGE> {
855    type Item = (&'a K, &'a V);
856
857    fn next(&mut self) -> Option<Self::Item> {
858        self.nth(0)
859    }
860
861    fn nth(&mut self, n: usize) -> Option<Self::Item> {
862        self.inner.nth(n).map(|(key, value)| (key, value))
863    }
864
865    fn size_hint(&self) -> (usize, Option<usize>) {
866        self.inner.size_hint()
867    }
868}
869
870impl<K, V, const PAGE: usize> DoubleEndedIterator for SparseMapIter<'_, K, V, PAGE> {
871    fn next_back(&mut self) -> Option<Self::Item> {
872        self.nth_back(0)
873    }
874
875    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
876        self.inner.nth_back(n).map(|(key, value)| (key, value))
877    }
878}
879
880impl<K, V, const PAGE: usize> ExactSizeIterator for SparseMapIter<'_, K, V, PAGE> {}
881impl<K, V, const PAGE: usize> FusedIterator for SparseMapIter<'_, K, V, PAGE> {}
882
883impl<K, V, const PAGE: usize> fmt::Debug for SparseMapIter<'_, K, V, PAGE> {
884    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885        f.debug_struct("SparseMapIter")
886            .field("inner", &self.inner)
887            .finish()
888    }
889}
890
891/// Iterates over the entries of a [`ConcurrentSparseMap`] in dense order,
892/// allowing each value to be mutated.
893#[must_use = "iterators are lazy and do nothing unless consumed"]
894pub struct SparseMapIterMut<'a, K, V> {
895    inner: VecIterMut<'a, (K, V)>,
896}
897
898impl<'a, K, V> Iterator for SparseMapIterMut<'a, K, V> {
899    type Item = (&'a K, &'a mut V);
900
901    fn next(&mut self) -> Option<Self::Item> {
902        self.inner.next().map(|(key, value)| (&*key, value))
903    }
904
905    fn size_hint(&self) -> (usize, Option<usize>) {
906        self.inner.size_hint()
907    }
908}
909
910impl<K, V> fmt::Debug for SparseMapIterMut<'_, K, V> {
911    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912        f.debug_struct("SparseMapIterMut").finish_non_exhaustive()
913    }
914}
915
916/// Clones the committed prefix via [`ConcurrentSparseMap::snapshot`],
917/// which can omit completed inserts beyond an unpublished reservation.
918impl<K: Key, V: Clone, const PAGE: usize, D: SharedDirectory> Clone
919    for ConcurrentSparseMap<K, V, PAGE, D>
920{
921    fn clone(&self) -> Self {
922        Self::from(self.snapshot())
923    }
924}
925
926impl<K: Key, V, const PAGE: usize, D: SharedDirectory> Default
927    for ConcurrentSparseMap<K, V, PAGE, D>
928{
929    fn default() -> Self {
930        Self::new()
931    }
932}
933
934impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: SharedDirectory> fmt::Debug
935    for ConcurrentSparseMap<K, V, PAGE, D>
936{
937    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
938        f.debug_map().entries(self.iter()).finish()
939    }
940}
941
942impl<K: Key, V, const PAGE: usize, D: SharedDirectory> From<PagedSparseMap<K, V, PAGE, D>>
943    for ConcurrentSparseMap<K, V, PAGE, D>
944{
945    fn from(inner: PagedSparseMap<K, V, PAGE, D>) -> Self {
946        inner.into_iter().collect()
947    }
948}
949
950/// Collects entries in input order, keeping the first occupant of each slot.
951impl<K: Key, V, const PAGE: usize, D: SharedDirectory> FromIterator<(K, V)>
952    for ConcurrentSparseMap<K, V, PAGE, D>
953{
954    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
955        let mut result = Self::new();
956        result.extend(iter);
957        result
958    }
959}
960
961/// Inserts entries in input order, keeping the first occupant of each slot.
962impl<K: Key, V, const PAGE: usize, D: SharedDirectory> Extend<(K, V)>
963    for ConcurrentSparseMap<K, V, PAGE, D>
964{
965    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
966        for (key, value) in iter {
967            let _ = self.try_insert(key, value);
968        }
969    }
970}
971
972#[cfg(feature = "serde")]
973mod serde_impl {
974    use super::*;
975    use crate::concurrent::serde::deserialize_map;
976    use core::marker::PhantomData;
977    use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor};
978    use serde::ser::{Serialize, Serializer};
979
980    fn check_index<const PAGE: usize, D: SharedDirectory>(
981        index: usize,
982    ) -> Result<(), &'static str> {
983        if D::Pages::<IndexPage>::page_number::<PAGE>(index).is_none() {
984            return Err("ConcurrentSparse: key index exceeds sparse spine range");
985        }
986        Ok(())
987    }
988
989    fn can_append_at<T, const PAGE: usize>(len: usize) -> bool {
990        len < DENSE_LIMIT && AppendLog::<T, PAGE>::can_append_at(len)
991    }
992
993    /// Serializes the committed keys in dense order as a valid plain set
994    /// sequence in O(prefix length). The prefix can omit completed inserts
995    /// beyond an earlier unpublished reservation, as in [`ConcurrentSparseSet::iter`].
996    impl<K: Key + Serialize, const PAGE: usize, D: SharedDirectory> Serialize
997        for ConcurrentSparseSet<K, PAGE, D>
998    {
999        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1000            serializer.collect_seq(self.iter())
1001        }
1002    }
1003
1004    /// Reads the plain [`PagedSparseSet`] format, rejecting keys and lengths
1005    /// outside the concurrent set's capacity.
1006    impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: SharedDirectory> Deserialize<'de>
1007        for ConcurrentSparseSet<K, PAGE, D>
1008    {
1009        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1010            struct SetVisitor<K, const PAGE: usize, D>(PhantomData<(K, D)>);
1011
1012            impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: SharedDirectory> Visitor<'de>
1013                for SetVisitor<K, PAGE, D>
1014            {
1015                type Value = ConcurrentSparseSet<K, PAGE, D>;
1016
1017                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1018                    f.write_str("a sequence of keys")
1019                }
1020
1021                fn visit_seq<A: SeqAccess<'de>>(
1022                    self,
1023                    mut access: A,
1024                ) -> Result<Self::Value, A::Error> {
1025                    let set = ConcurrentSparseSet::new();
1026                    while let Some(key) = access.next_element::<K>()? {
1027                        let index = key.index();
1028                        check_index::<PAGE, D>(index).map_err(A::Error::custom)?;
1029                        if !can_append_at::<K, PAGE>(set.len())
1030                            && set.index.position(index).is_none()
1031                        {
1032                            return Err(A::Error::custom(
1033                                "ConcurrentSparseSet: dense capacity exceeded",
1034                            ));
1035                        }
1036                        set.insert(key);
1037                    }
1038                    Ok(set)
1039                }
1040            }
1041
1042            if !Index::<PAGE, D>::valid_page_capacity()
1043                || !AppendLog::<K, PAGE>::valid_page_capacity()
1044            {
1045                return Err(De::Error::custom(
1046                    "ConcurrentSparseSet: invalid page capacity",
1047                ));
1048            }
1049            deserializer.deserialize_seq(SetVisitor::<K, PAGE, D>(PhantomData))
1050        }
1051    }
1052
1053    /// Serializes the committed entries in dense order as a valid plain map
1054    /// in O(prefix length). The prefix can omit completed inserts beyond an
1055    /// earlier unpublished reservation, as in [`ConcurrentSparseMap::iter`].
1056    impl<K: Key + Serialize, V: Serialize, const PAGE: usize, D: SharedDirectory> Serialize
1057        for ConcurrentSparseMap<K, V, PAGE, D>
1058    {
1059        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1060            serializer.collect_map(self.iter())
1061        }
1062    }
1063
1064    /// Reads the plain [`PagedSparseMap`] format, rejecting keys and lengths
1065    /// outside the concurrent map's capacity. Later entries replace earlier
1066    /// entries at the same index in place, as in the plain map.
1067    impl<'de, K: Key + Deserialize<'de>, V: Deserialize<'de>, const PAGE: usize, D: SharedDirectory>
1068        Deserialize<'de> for ConcurrentSparseMap<K, V, PAGE, D>
1069    {
1070        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1071            if !Index::<PAGE, D>::valid_page_capacity()
1072                || !AppendLog::<(K, V), PAGE>::valid_page_capacity()
1073            {
1074                return Err(De::Error::custom(
1075                    "ConcurrentSparseMap: invalid page capacity",
1076                ));
1077            }
1078            deserialize_map(deserializer, Self::new(), |map, key: K, value: V| {
1079                let index = key.index();
1080                check_index::<PAGE, D>(index)?;
1081                if let Some(pos) = map.index.position(index) {
1082                    let (stored, old) = map.dense.get_mut(pos).expect("published entry is ready");
1083                    if *stored != key {
1084                        *stored = key;
1085                    }
1086                    *old = value;
1087                } else {
1088                    if !can_append_at::<(K, V), PAGE>(map.len()) {
1089                        return Err("ConcurrentSparseMap: dense capacity exceeded");
1090                    }
1091                    let _ = map.try_insert(key, value);
1092                }
1093                Ok(())
1094            })
1095        }
1096    }
1097}
1098
1099#[cfg(all(test, not(loom), feature = "std"))]
1100mod tests {
1101    use super::*;
1102    use std::panic::{AssertUnwindSafe, catch_unwind};
1103
1104    #[test]
1105    fn bounded_log_failure_rolls_back_sparse_reservation() {
1106        let index = Index::<2>::new();
1107        let dense = AppendLog::<u32, 2>::new();
1108        let owner = index.claim(1).ok().unwrap();
1109        assert_eq!(dense.push(1, 0), Err(1));
1110        drop(owner);
1111        assert_eq!(index.position(1), None);
1112        let owner = index.claim(1).ok().unwrap();
1113        owner.publish(dense.push(1, 1).unwrap());
1114        assert_eq!(index.position(1), Some(0));
1115    }
1116
1117    #[test]
1118    fn unwinding_before_dense_claim_does_not_leave_reserved() {
1119        let index = Index::<2>::new();
1120        let result = catch_unwind(AssertUnwindSafe(|| {
1121            let _owner = index.claim(1).ok().unwrap();
1122            panic!("simulated allocation failure before dense claim");
1123        }));
1124        assert!(result.is_err());
1125        assert!(index.claim(1).is_ok());
1126    }
1127}