Skip to main content

paged_collections/concurrent/
direct.rs

1//! A direct-address map with one reader-writer lock per page.
2
3use alloc::boxed::Box;
4use alloc::vec::{IntoIter, Vec};
5use core::fmt;
6use core::mem;
7use core::ops::{Bound, Deref, DerefMut, RangeBounds};
8use core::slice;
9
10use super::count::StripedLen;
11use super::directory::{PageIterMut, SharedDirectory, SharedPages};
12use super::lock::{ReadGuard, RwLock, WriteGuard};
13use crate::direct_map::PagedDirectMap;
14use crate::key::DirectKey;
15use crate::page::{DEFAULT_PAGE, Flat};
16
17/// One slot: the tag of the key held there and its value, if any.
18type Slot<K, V> = Option<(<K as DirectKey>::Tag, V)>;
19
20struct Page<K: DirectKey, V> {
21    data: RwLock<PageData<K, V>>,
22}
23
24struct PageData<K: DirectKey, V> {
25    slots: Box<[Slot<K, V>]>,
26    occupied: usize,
27    // This page's directory number: its length stripe without `std`.
28    number: usize,
29}
30
31impl<K: DirectKey, V> PageData<K, V> {
32    fn replace(
33        &mut self,
34        offset: usize,
35        pair: (K::Tag, V),
36        len: &StripedLen,
37    ) -> Option<(K::Tag, V)> {
38        let old = self.slots[offset].replace(pair);
39        if old.is_none() {
40            self.occupied += 1;
41            len.increment(self.number);
42        }
43        old
44    }
45
46    fn remove(&mut self, offset: usize, len: &StripedLen) -> Option<(K::Tag, V)> {
47        let old = self.slots[offset].take();
48        if old.is_some() {
49            self.occupied -= 1;
50            len.decrement(self.number);
51        }
52        old
53    }
54}
55
56/// A shared direct-address map with one reader-writer lock per page.
57///
58/// Values live at [`Key::index`](crate::key::Key::index); each slot stores the key's
59/// [`DirectKey::Tag`], as in [`PagedDirectMap`], and keys are rebuilt from
60/// their slot index. Neighbouring keys on the same page contend;
61/// operations on different pages lock independently. Pages remain allocated
62/// until [`shrink_to_fit`](Self::shrink_to_fit), [`reset`](Self::reset) or
63/// destruction. The default [`Flat`] directory has O(1) page lookups and
64/// memory following the highest page. Its finite
65/// range makes out-of-range insertions panic; lookups and removals return
66/// absent. [`Radix`](crate::page::Radix) accepts any `usize` index, uses directory
67/// memory proportional to installed pages, and looks up pages in O(depth).
68/// `PAGE` must be nonzero.
69///
70/// Holding a guard or entry and calling any method that locks the same page
71/// from the same thread deadlocks (or panics on `std`). This also applies to
72/// `make`, `with`, `retain`, formatting and traversal callbacks touching the
73/// same map. Release guards before making another call on their page.
74/// Holding locks on two pages at once can also deadlock across threads: if
75/// one thread holds page A and waits for page B while another holds B and
76/// waits for A (for example, two factories each looking up the other's key).
77/// Nested calls must lock pages in one global order (such as ascending
78/// [`Key::index`](crate::key::Key::index)), or callbacks must not touch the map at all.
79///
80/// Traversals visit ascending slot indices, holding one page lock at a time.
81/// They are consistent per page only and weakly consistent across pages.
82/// Length is exact when no write is in flight (see [`len`](Self::len)). The `no_std` spin lock permits
83/// writer starvation; the `std` lock ignores poisoning because mutations keep
84/// slots and counts valid even when user code panics.
85///
86/// ```
87/// # #[cfg(feature = "concurrent")] {
88/// use paged_collections::{concurrent::ConcurrentDirectMap, page::Radix};
89/// let map = ConcurrentDirectMap::<usize, _, 4, Radix>::new();
90/// assert_eq!(map.insert(usize::MAX - 1, "wide"), None);
91/// assert_eq!(map.get_cloned(usize::MAX - 1), Some("wide"));
92/// # }
93/// ```
94pub struct ConcurrentDirectMap<
95    K: DirectKey,
96    V,
97    const PAGE: usize = DEFAULT_PAGE,
98    D: SharedDirectory = Flat,
99> {
100    // A GAT projection is invariant in K and V, as shared insertion requires.
101    pages: D::Pages<Page<K, V>>,
102    len: StripedLen,
103}
104
105// SAFETY: both sealed directories own stable pages and are Send when their
106// pages are Send. Moving the map transfers its stored tags, values and page
107// locks; keys are rebuilt from tags on whichever thread asks, so the stored
108// `K::Tag` must be Send as well as `K`.
109unsafe impl<K, V, const PAGE: usize, D> Send for ConcurrentDirectMap<K, V, PAGE, D>
110where
111    K: DirectKey + Send,
112    K::Tag: Send,
113    V: Send,
114    D: SharedDirectory,
115{
116}
117// SAFETY: both sealed directories publish pages safely; each page lock
118// synchronizes access to its tags and values, which shared calls insert from
119// one thread and read or take on another (hence Send + Sync for both `K`
120// and `K::Tag`). Shared access cannot free pages.
121unsafe impl<K, V, const PAGE: usize, D> Sync for ConcurrentDirectMap<K, V, PAGE, D>
122where
123    K: DirectKey + Send + Sync,
124    K::Tag: Send + Sync,
125    V: Send + Sync,
126    D: SharedDirectory,
127{
128}
129
130/// A value reference holding its page's read lock.
131///
132/// Calling another method that locks this page while holding the guard may
133/// deadlock or panic. See [`ConcurrentDirectMap`].
134pub struct DirectMapRef<'a, K: DirectKey, V> {
135    // Invariant: the slot at `offset` is `Some` and `key` is its stored key.
136    guard: ReadGuard<'a, PageData<K, V>>,
137    offset: usize,
138    key: K,
139}
140
141/// A mutable value reference holding its page's write lock.
142///
143/// Calling another method that locks this page while holding the guard
144/// deadlocks or panics. See [`ConcurrentDirectMap`].
145pub struct DirectMapRefMut<'a, K: DirectKey, V> {
146    // Invariant: as for `DirectMapRef`, except inside a `VacantEntry`, whose
147    // slot may be empty or hold another generation until it is inserted.
148    guard: WriteGuard<'a, PageData<K, V>>,
149    offset: usize,
150    key: K,
151}
152
153/// A page-write-locked view of a key, occupied only by that key itself.
154pub enum Entry<'a, K: DirectKey, V> {
155    /// The requested key is present.
156    Occupied(OccupiedEntry<'a, K, V>),
157    /// The slot is empty or holds another generation.
158    Vacant(VacantEntry<'a, K, V>),
159}
160
161/// An occupied entry holding its page's write lock.
162pub struct OccupiedEntry<'a, K: DirectKey, V> {
163    value: DirectMapRefMut<'a, K, V>,
164    len: &'a StripedLen,
165}
166
167/// A vacant entry holding its page's write lock, possibly over another generation.
168pub struct VacantEntry<'a, K: DirectKey, V> {
169    value: DirectMapRefMut<'a, K, V>,
170    len: &'a StripedLen,
171}
172
173impl<K: DirectKey, V, const PAGE: usize, D: SharedDirectory> ConcurrentDirectMap<K, V, PAGE, D> {
174    /// Clones a weakly consistent snapshot into a valid plain map, scanning
175    /// the directory and allocated slots. Includes entries that remain unchanged
176    /// throughout the call if their writes happen-before it.
177    ///
178    /// Value cloning runs under a page read lock. The callback must avoid
179    /// all access to that page, including reads, which can deadlock behind
180    /// a queued writer.
181    pub fn snapshot(&self) -> PagedDirectMap<K, V, PAGE, D>
182    where
183        V: Clone,
184    {
185        let mut map = PagedDirectMap::new();
186        self.for_each(|key, value| {
187            map.insert(*key, value.clone());
188        });
189        map
190    }
191
192    /// Number of slots protected by each page lock.
193    pub const PAGE_SIZE: usize = PAGE;
194
195    fn valid_page_capacity() -> bool {
196        PAGE > 0 && PAGE <= isize::MAX as usize / mem::size_of::<Slot<K, V>>()
197    }
198
199    /// Creates an empty map without allocating.
200    ///
201    /// # Panics
202    ///
203    /// Panics if `PAGE` is zero or its slot storage exceeds `isize::MAX` bytes.
204    pub fn new() -> Self {
205        assert!(
206            Self::valid_page_capacity(),
207            "ConcurrentDirectMap: invalid page capacity"
208        );
209        Self {
210            pages: D::Pages::<Page<K, V>>::new(),
211            len: StripedLen::new(),
212        }
213    }
214
215    /// Number of entries; exact when no write is in flight.
216    ///
217    /// The count is split over per-thread counters (per page group without
218    /// `std`) so that writers do not contend on one cache line. While writes
219    /// are in flight, the sum may combine counters read at different moments and
220    /// so differ from every count the map actually held (for example, 0 for
221    /// a map that was never empty), though it never exceeds the number of
222    /// entries inserted.
223    pub fn len(&self) -> usize {
224        self.len.get()
225    }
226
227    /// Whether `len()` is zero; like `len`, exact only with no write in flight.
228    pub fn is_empty(&self) -> bool {
229        self.len() == 0
230    }
231
232    /// Counts installed pages by scanning the directory without page locks.
233    /// Weakly consistent while pages are being installed.
234    pub fn allocated_pages(&self) -> usize {
235        self.pages.iter().count()
236    }
237
238    fn page(&self, index: usize) -> Option<&Page<K, V>> {
239        self.pages
240            .get(D::Pages::<Page<K, V>>::page_number::<PAGE>(index)?)
241    }
242
243    fn ensure_page(&self, index: usize) -> &Page<K, V> {
244        let number = D::Pages::<Page<K, V>>::page_number::<PAGE>(index)
245            .expect("ConcurrentDirectMap: key index exceeds direct spine range");
246        self.pages.get_or_insert_with(number, || {
247            Box::new(Page {
248                data: RwLock::new(PageData {
249                    slots: (0..PAGE).map(|_| None).collect(),
250                    occupied: 0,
251                    number,
252                }),
253            })
254        })
255    }
256
257    /// Whether the requested key itself is present.
258    pub fn contains_key(&self, key: K) -> bool {
259        self.get(key).is_some()
260    }
261
262    /// Acquires a read guard if this key itself is present.
263    /// An out-of-range index returns `None`.
264    pub fn get(&self, key: K) -> Option<DirectMapRef<'_, K, V>> {
265        let index = key.index();
266        let guard = self.page(index)?.data.read();
267        let offset = index % PAGE;
268        let tag = match &guard.slots[offset] {
269            Some((stored, _)) if *stored == key.tag() => *stored,
270            _ => return None,
271        };
272        let key = K::from_parts(index, tag);
273        Some(DirectMapRef { guard, offset, key })
274    }
275
276    /// Acquires a write guard if this key itself is present.
277    /// An out-of-range index returns `None`.
278    pub fn get_mut(&self, key: K) -> Option<DirectMapRefMut<'_, K, V>> {
279        let index = key.index();
280        let guard = self.page(index)?.data.write();
281        let offset = index % PAGE;
282        let tag = match &guard.slots[offset] {
283            Some((stored, _)) if *stored == key.tag() => *stored,
284            _ => return None,
285        };
286        let key = K::from_parts(index, tag);
287        Some(DirectMapRefMut { guard, offset, key })
288    }
289
290    /// Calls `f` under the page's read lock if this key is present.
291    pub fn with<R>(&self, key: K, f: impl FnOnce(&V) -> R) -> Option<R> {
292        self.get(key).map(|value| f(&value))
293    }
294
295    /// Clones a present value under its page's read lock.
296    pub fn get_cloned(&self, key: K) -> Option<V>
297    where
298        V: Clone,
299    {
300        self.with(key, V::clone)
301    }
302
303    /// Inserts a value, returning the old value from this slot, if any.
304    /// Keeps an equal stored key; evicts a different generation.
305    /// Panics for indices outside the Flat spine range or allocation overflow.
306    pub fn insert(&self, key: K, value: V) -> Option<V> {
307        let index = key.index();
308        let mut guard = self.ensure_page(index).data.write();
309        let offset = index % PAGE;
310        let tag = key.tag();
311        if let Some((stored, old)) = &mut guard.slots[offset] {
312            if *stored != tag {
313                *stored = tag;
314            }
315            let old = mem::replace(old, value);
316            drop(guard);
317            return Some(old);
318        }
319        let old = guard.replace(offset, (tag, value), &self.len);
320        drop(guard);
321        old.map(|(_, value)| value)
322    }
323
324    /// Replaces this slot, always storing `key`, and returns its previous pair.
325    /// Evicts another generation. With `Flat`, panics for an out-of-range insertion.
326    pub fn replace(&self, key: K, value: V) -> Option<(K, V)> {
327        let index = key.index();
328        let mut guard = self.ensure_page(index).data.write();
329        let old = guard.replace(index % PAGE, (key.tag(), value), &self.len);
330        drop(guard);
331        old.map(|(tag, value)| (K::from_parts(index, tag), value))
332    }
333
334    /// Inserts only into an empty slot; returns `value` if any generation holds it.
335    /// With `Flat`, panics for an out-of-range insertion.
336    pub fn try_insert(&self, key: K, value: V) -> Result<(), V> {
337        let index = key.index();
338        let mut guard = self.ensure_page(index).data.write();
339        let offset = index % PAGE;
340        if guard.slots[offset].is_some() {
341            drop(guard);
342            return Err(value);
343        }
344        let old = guard.replace(offset, (key.tag(), value), &self.len);
345        drop(guard);
346        drop(old);
347        Ok(())
348    }
349
350    /// Removes this key itself, returning its value after releasing the lock.
351    /// An out-of-range index returns `None`.
352    pub fn remove(&self, key: K) -> Option<V> {
353        self.remove_entry(key).map(|(_, value)| value)
354    }
355
356    /// Removes this key itself, returning its stored pair after releasing the lock.
357    /// An out-of-range index returns `None`.
358    pub fn remove_entry(&self, key: K) -> Option<(K, V)> {
359        let index = key.index();
360        let mut guard = self.page(index)?.data.write();
361        let offset = index % PAGE;
362        if !matches!(&guard.slots[offset], Some((stored, _)) if *stored == key.tag()) {
363            return None;
364        }
365        let old = guard.remove(offset, &self.len);
366        drop(guard);
367        old.map(|(tag, value)| (K::from_parts(index, tag), value))
368    }
369
370    /// Removes whichever generation occupies `index`, releasing the lock first.
371    /// An out-of-range index returns `None`.
372    pub fn remove_occupant(&self, index: usize) -> Option<(K, V)> {
373        let mut guard = self.page(index)?.data.write();
374        let old = guard.remove(index % PAGE, &self.len);
375        drop(guard);
376        old.map(|(tag, value)| (K::from_parts(index, tag), value))
377    }
378
379    /// Returns this key's value, constructing it under the page write lock if absent.
380    /// Another generation is evicted. A panicking factory leaves entries unchanged.
381    /// At most one competing factory runs before the key is removed or evicted.
382    /// With `Flat`, panics for an out-of-range insertion.
383    pub fn get_or_insert_with(
384        &self,
385        key: K,
386        make: impl FnOnce() -> V,
387    ) -> DirectMapRefMut<'_, K, V> {
388        self.entry(key).or_insert_with(make)
389    }
390
391    /// Locks the key's page for an entry operation, installing an empty page if needed.
392    /// Another generation makes the entry vacant; inserting through it evicts that pair.
393    /// With `Flat`, panics for an out-of-range index.
394    pub fn entry(&self, key: K) -> Entry<'_, K, V> {
395        let index = key.index();
396        let guard = self.ensure_page(index).data.write();
397        let offset = index % PAGE;
398        let stored = match &guard.slots[offset] {
399            Some((stored, _)) if *stored == key.tag() => Some(*stored),
400            _ => None,
401        };
402        match stored {
403            Some(tag) => Entry::Occupied(OccupiedEntry {
404                value: DirectMapRefMut {
405                    guard,
406                    offset,
407                    key: K::from_parts(index, tag),
408                },
409                len: &self.len,
410            }),
411            // The guard carries the query key until an insert stores it.
412            None => Entry::Vacant(VacantEntry {
413                value: DirectMapRefMut { guard, offset, key },
414                len: &self.len,
415            }),
416        }
417    }
418
419    /// Keeps entries for which `keep` returns true, in ascending slot order.
420    /// Holds one page write lock at a time; atomic only within each page.
421    /// Counts remain correct if the callback or a removed value's destructor panics.
422    pub fn retain(&self, mut keep: impl FnMut(&K, &mut V) -> bool) {
423        for (number, page) in self.pages.iter() {
424            let mut guard = page.data.write();
425            for offset in 0..guard.slots.len() {
426                let remove = match &mut guard.slots[offset] {
427                    Some((tag, value)) => {
428                        !keep(&K::from_parts(number * PAGE + offset, *tag), value)
429                    }
430                    None => false,
431                };
432                if remove {
433                    let old = guard.remove(offset, &self.len);
434                    drop(old);
435                }
436            }
437        }
438    }
439
440    /// Calls `f` in ascending slot order, holding one page read lock at a time.
441    /// Consistent per page only, weakly consistent across pages.
442    pub fn for_each(&self, f: impl FnMut(&K, &V)) {
443        self.range_for_each(.., f);
444    }
445
446    /// Calls `f` for a range bounded by [`Key::index`](crate::key::Key::index), in ascending slot order.
447    /// Empty or inverted ranges visit nothing. Holds one page read lock at a
448    /// time; consistent per page only, weakly consistent across pages.
449    pub fn range_for_each(&self, keys: impl RangeBounds<K>, mut f: impl FnMut(&K, &V)) {
450        self.try_range_for_each(keys, |key, value| {
451            f(key, value);
452            Ok::<_, core::convert::Infallible>(())
453        })
454        .unwrap();
455    }
456
457    fn try_range_for_each<E>(
458        &self,
459        keys: impl RangeBounds<K>,
460        mut f: impl FnMut(&K, &V) -> Result<(), E>,
461    ) -> Result<(), E> {
462        let start = match keys.start_bound() {
463            Bound::Included(key) => key.index(),
464            Bound::Excluded(key) => match key.index().checked_add(1) {
465                Some(index) => index,
466                None => return Ok(()),
467            },
468            Bound::Unbounded => 0,
469        };
470        let end = match keys.end_bound() {
471            Bound::Included(key) => key.index(),
472            Bound::Excluded(key) => match key.index().checked_sub(1) {
473                Some(index) => index,
474                None => return Ok(()),
475            },
476            Bound::Unbounded => usize::MAX,
477        };
478        if start > end {
479            return Ok(());
480        }
481        for (number, page) in self.pages.iter() {
482            if number < start / PAGE {
483                continue;
484            }
485            if number > end / PAGE {
486                break;
487            }
488            let first = if number == start / PAGE {
489                start % PAGE
490            } else {
491                0
492            };
493            let last = if number == end / PAGE {
494                end % PAGE + 1
495            } else {
496                PAGE
497            };
498            let guard = page.data.read();
499            let base = number * PAGE;
500            for (offset, slot) in guard.slots.iter().enumerate().take(last).skip(first) {
501                if let Some((tag, value)) = slot {
502                    f(&K::from_parts(base + offset, *tag), value)?;
503                }
504            }
505        }
506        Ok(())
507    }
508
509    /// Iterates exclusively in ascending slot order without acquiring page locks.
510    pub fn iter_mut(&mut self) -> DirectMapIterMut<'_, K, V, PAGE> {
511        DirectMapIterMut {
512            pages: self.pages.iter_mut(),
513            slots: slice::IterMut::default().enumerate(),
514            base: 0,
515            key: core::marker::PhantomData,
516        }
517    }
518
519    /// Removes entries without locking, retaining pages for reuse.
520    /// If a destructor panics, unvisited entries remain and counts stay correct.
521    pub fn clear(&mut self) {
522        for (_, page) in self.pages.iter_mut() {
523            let data = page.data.get_mut();
524            for offset in 0..data.slots.len() {
525                let old = data.remove(offset, &self.len);
526                drop(old);
527            }
528        }
529    }
530
531    /// Removes all entries and returns owned pairs in ascending key-index order.
532    /// Keeps allocated pages for reuse.
533    pub fn drain(&mut self) -> IntoIter<(K, V)> {
534        let mut entries = Vec::with_capacity(self.len());
535        for (number, page) in self.pages.iter_mut() {
536            let data = page.data.get_mut();
537            let base = number * PAGE;
538            for offset in 0..data.slots.len() {
539                if let Some((tag, _)) = &data.slots[offset] {
540                    // Rebuild the key before removing its slot: custom key
541                    // implementations can panic.
542                    let key = K::from_parts(base + offset, *tag);
543                    let (_, value) = data.remove(offset, &self.len).expect("slot is occupied");
544                    entries.push((key, value));
545                }
546            }
547        }
548        entries.into_iter()
549    }
550
551    /// Frees pages that contain no entries. Flat directory chunks stay allocated.
552    /// Shared insertions can allocate those pages again.
553    pub fn shrink_to_fit(&mut self) {
554        self.pages
555            .retain(|_, page| page.data.get_mut().occupied != 0);
556    }
557
558    /// Detaches and frees all pages. The map is empty even if a destructor panics.
559    pub fn reset(&mut self) {
560        let pages = mem::replace(&mut self.pages, D::Pages::<Page<K, V>>::new());
561        self.len.reset();
562        drop(pages);
563    }
564}
565
566impl<'a, K: DirectKey + 'a, V: 'a, const PAGE: usize, D: SharedDirectory> IntoIterator
567    for &'a mut ConcurrentDirectMap<K, V, PAGE, D>
568{
569    type Item = (K, &'a mut V);
570    type IntoIter = DirectMapIterMut<'a, K, V, PAGE>;
571
572    fn into_iter(self) -> Self::IntoIter {
573        self.iter_mut()
574    }
575}
576
577/// Iterates over a [`ConcurrentDirectMap`] in ascending key-index order,
578/// allowing each value to be mutated.
579#[must_use = "iterators are lazy and do nothing unless consumed"]
580pub struct DirectMapIterMut<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE> {
581    pages: PageIterMut<'a, Page<K, V>>,
582    slots: core::iter::Enumerate<slice::IterMut<'a, Slot<K, V>>>,
583    base: usize,
584    // Yielded keys are rebuilt from tags on the iterating thread, so the
585    // iterator is Send/Sync only when K is, like the map borrow.
586    key: core::marker::PhantomData<&'a mut K>,
587}
588
589impl<'a, K: DirectKey, V, const PAGE: usize> Iterator for DirectMapIterMut<'a, K, V, PAGE> {
590    type Item = (K, &'a mut V);
591
592    fn next(&mut self) -> Option<Self::Item> {
593        loop {
594            for (offset, slot) in self.slots.by_ref() {
595                if let Some((tag, value)) = slot {
596                    return Some((K::from_parts(self.base + offset, *tag), value));
597                }
598            }
599            let (number, page) = self.pages.next()?;
600            self.base = number * PAGE;
601            self.slots = page.data.get_mut().slots.iter_mut().enumerate();
602        }
603    }
604}
605
606impl<K: DirectKey, V, const PAGE: usize> fmt::Debug for DirectMapIterMut<'_, K, V, PAGE> {
607    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608        f.debug_struct("DirectMapIterMut").finish_non_exhaustive()
609    }
610}
611
612impl<K: DirectKey, V, const PAGE: usize, D: SharedDirectory> ConcurrentDirectMap<K, V, PAGE, D> {
613    /// Moves entries into a plain map in slot order, scanning allocated slots.
614    /// Each occupied entry is moved once; no values are cloned.
615    pub fn into_inner(mut self) -> PagedDirectMap<K, V, PAGE, D> {
616        let mut map = PagedDirectMap::new();
617        for (number, page) in self.pages.iter_mut() {
618            let lock = mem::replace(
619                &mut page.data,
620                RwLock::new(PageData {
621                    slots: Box::default(),
622                    occupied: 0,
623                    number,
624                }),
625            );
626            let base = number * PAGE;
627            let slots = lock.into_inner().slots.into_vec().into_iter().enumerate();
628            for (offset, slot) in slots {
629                if let Some((tag, value)) = slot {
630                    map.insert(K::from_parts(base + offset, tag), value);
631                }
632            }
633        }
634        map
635    }
636}
637
638impl<K: DirectKey, V> DirectMapRef<'_, K, V> {
639    /// The stored key, which may differ in representation from an equal query key.
640    pub fn key(&self) -> &K {
641        &self.key
642    }
643}
644
645impl<K: DirectKey, V> Deref for DirectMapRef<'_, K, V> {
646    type Target = V;
647
648    fn deref(&self) -> &V {
649        &self.guard.slots[self.offset].as_ref().unwrap().1
650    }
651}
652
653impl<K: DirectKey, V> DirectMapRefMut<'_, K, V> {
654    /// The stored key, which cannot be changed through the guard.
655    pub fn key(&self) -> &K {
656        &self.key
657    }
658}
659
660impl<K: DirectKey, V> Deref for DirectMapRefMut<'_, K, V> {
661    type Target = V;
662
663    fn deref(&self) -> &V {
664        &self.guard.slots[self.offset].as_ref().unwrap().1
665    }
666}
667
668impl<K: DirectKey, V> DerefMut for DirectMapRefMut<'_, K, V> {
669    fn deref_mut(&mut self) -> &mut V {
670        &mut self.guard.slots[self.offset].as_mut().unwrap().1
671    }
672}
673
674impl<'a, K: DirectKey, V> Entry<'a, K, V> {
675    /// The occupied stored key, or the query key for a vacant entry.
676    pub fn key(&self) -> &K {
677        match self {
678            Self::Occupied(entry) => entry.key(),
679            Self::Vacant(entry) => entry.key(),
680        }
681    }
682
683    /// Returns the value, inserting `default` if this key is absent.
684    pub fn or_insert(self, default: V) -> DirectMapRefMut<'a, K, V> {
685        match self {
686            Self::Occupied(entry) => entry.into_ref(),
687            Self::Vacant(entry) => entry.insert(default),
688        }
689    }
690
691    /// Returns the value, calling `make` under the page write lock only if absent.
692    /// A panicking factory leaves the slot unchanged.
693    pub fn or_insert_with(self, make: impl FnOnce() -> V) -> DirectMapRefMut<'a, K, V> {
694        match self {
695            Self::Occupied(entry) => entry.into_ref(),
696            Self::Vacant(entry) => {
697                let value = make();
698                entry.insert(value)
699            }
700        }
701    }
702
703    /// Like [`or_insert_with`](Self::or_insert_with), passing the query key to `make`.
704    pub fn or_insert_with_key(self, make: impl FnOnce(&K) -> V) -> DirectMapRefMut<'a, K, V> {
705        match self {
706            Self::Occupied(entry) => entry.into_ref(),
707            Self::Vacant(entry) => {
708                let value = make(entry.key());
709                entry.insert(value)
710            }
711        }
712    }
713
714    /// Returns the value, inserting its default under the lock if absent.
715    pub fn or_default(self) -> DirectMapRefMut<'a, K, V>
716    where
717        V: Default,
718    {
719        self.or_insert_with(V::default)
720    }
721
722    /// Modifies an occupied value and returns this entry. A panic keeps it occupied.
723    pub fn and_modify(mut self, f: impl FnOnce(&mut V)) -> Self {
724        if let Self::Occupied(entry) = &mut self {
725            f(entry.get_mut());
726        }
727        self
728    }
729}
730
731impl<'a, K: DirectKey, V> OccupiedEntry<'a, K, V> {
732    /// The stored key.
733    pub fn key(&self) -> &K {
734        self.value.key()
735    }
736
737    /// The stored value.
738    pub fn get(&self) -> &V {
739        &self.value
740    }
741
742    /// Mutable access to the value under the page write lock.
743    pub fn get_mut(&mut self) -> &mut V {
744        &mut self.value
745    }
746
747    /// Converts the entry into a mutable guard, retaining the page write lock.
748    pub fn into_ref(self) -> DirectMapRefMut<'a, K, V> {
749        self.value
750    }
751
752    /// Replaces only the value, returning the previous value and keeping the stored key.
753    pub fn insert(&mut self, value: V) -> V {
754        mem::replace(self.get_mut(), value)
755    }
756
757    /// Removes the pair and returns its value after releasing the page lock.
758    pub fn remove(self) -> V {
759        self.remove_entry().1
760    }
761
762    /// Removes the pair and returns it after releasing the page lock.
763    pub fn remove_entry(mut self) -> (K, V) {
764        let offset = self.value.offset;
765        let (_, value) = self.value.guard.remove(offset, self.len).unwrap();
766        let key = self.value.key;
767        drop(self);
768        (key, value)
769    }
770}
771
772impl<'a, K: DirectKey, V> VacantEntry<'a, K, V> {
773    /// The query key, which may share its slot with another generation.
774    pub fn key(&self) -> &K {
775        &self.value.key
776    }
777
778    /// Releases the lock and returns the query key without changing the slot.
779    pub fn into_key(self) -> K {
780        self.value.key
781    }
782
783    /// The pair from another generation that insertion would evict.
784    pub fn occupant(&self) -> Option<(K, &V)> {
785        let (tag, value) = self.value.guard.slots[self.value.offset].as_ref()?;
786        Some((K::from_parts(self.value.key.index(), *tag), value))
787    }
788
789    /// Inserts this key and returns a mutable guard, evicting another generation.
790    /// The slot and counts are consistent before an evicted value is dropped.
791    pub fn insert(mut self, value: V) -> DirectMapRefMut<'a, K, V> {
792        let offset = self.value.offset;
793        let tag = self.value.key.tag();
794        let old = self.value.guard.replace(offset, (tag, value), self.len);
795        drop(old);
796        self.value
797    }
798}
799
800/// Clones via [`ConcurrentDirectMap::snapshot`]. Value cloning runs under
801/// a page read lock and must avoid all access to that page.
802impl<K: DirectKey, V: Clone, const PAGE: usize, D: SharedDirectory> Clone
803    for ConcurrentDirectMap<K, V, PAGE, D>
804{
805    fn clone(&self) -> Self {
806        Self::from(self.snapshot())
807    }
808}
809
810impl<K: DirectKey, V, const PAGE: usize, D: SharedDirectory> Default
811    for ConcurrentDirectMap<K, V, PAGE, D>
812{
813    fn default() -> Self {
814        Self::new()
815    }
816}
817
818impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: SharedDirectory> fmt::Debug
819    for ConcurrentDirectMap<K, V, PAGE, D>
820{
821    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
822        let mut map = f.debug_map();
823        self.for_each(|key, value| {
824            map.entry(key, value);
825        });
826        map.finish()
827    }
828}
829
830impl<K: DirectKey, V, const PAGE: usize, D: SharedDirectory> FromIterator<(K, V)>
831    for ConcurrentDirectMap<K, V, PAGE, D>
832{
833    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
834        let mut map = Self::new();
835        map.extend(iter);
836        map
837    }
838}
839
840impl<K: DirectKey, V, const PAGE: usize, D: SharedDirectory> Extend<(K, V)>
841    for ConcurrentDirectMap<K, V, PAGE, D>
842{
843    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
844        for (key, value) in iter {
845            self.insert(key, value);
846        }
847    }
848}
849
850impl<K: DirectKey, V, const PAGE: usize, D: SharedDirectory> From<PagedDirectMap<K, V, PAGE, D>>
851    for ConcurrentDirectMap<K, V, PAGE, D>
852{
853    fn from(map: PagedDirectMap<K, V, PAGE, D>) -> Self {
854        map.into_iter().collect()
855    }
856}
857
858#[cfg(feature = "serde")]
859mod serde_impl {
860    use super::*;
861    use crate::concurrent::serde::deserialize_map;
862    use serde::de::{Deserialize, Deserializer, Error};
863    use serde::ser::{Serialize, SerializeMap, Serializer};
864
865    /// Serializes a weakly consistent snapshot as a valid plain map in
866    /// slot order, with the same consistency as
867    /// [`ConcurrentDirectMap::snapshot`]. Scans the directory and allocated
868    /// slots. JSON, CBOR and serializers that buffer unknown-length
869    /// MessagePack maps can accept the missing length. For serializers
870    /// that require the length upfront, such as bincode, serialize
871    /// [`snapshot()`](ConcurrentDirectMap::snapshot) instead.
872    ///
873    /// User `Serialize` runs under a page read lock. The callback must
874    /// avoid all access to that page, including reads, which can deadlock
875    /// behind a queued writer.
876    impl<K: DirectKey + Serialize, V: Serialize, const PAGE: usize, D: SharedDirectory> Serialize
877        for ConcurrentDirectMap<K, V, PAGE, D>
878    {
879        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
880            let mut map = serializer.serialize_map(None)?;
881            self.try_range_for_each(.., |key, value| map.serialize_entry(key, value))?;
882            map.end()
883        }
884    }
885
886    /// Reads the plain [`PagedDirectMap`] format, rejecting indices outside
887    /// the concurrent directory's range before allocating a page.
888    impl<
889        'de,
890        K: DirectKey + Deserialize<'de>,
891        V: Deserialize<'de>,
892        const PAGE: usize,
893        D: SharedDirectory,
894    > Deserialize<'de> for ConcurrentDirectMap<K, V, PAGE, D>
895    {
896        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
897            if !Self::valid_page_capacity() {
898                return Err(De::Error::custom(
899                    "ConcurrentDirectMap: invalid page capacity",
900                ));
901            }
902            deserialize_map(deserializer, Self::new(), |map, key: K, value: V| {
903                if D::Pages::<Page<K, V>>::page_number::<PAGE>(key.index()).is_none() {
904                    return Err("ConcurrentDirectMap: key index exceeds direct spine range");
905                }
906                map.insert(key, value);
907                Ok(())
908            })
909        }
910    }
911}
912
913#[cfg(all(test, not(loom)))]
914mod tests {
915    use super::ConcurrentDirectMap;
916    use alloc::string::String;
917
918    #[test]
919    fn map_is_send_and_sync() {
920        fn assert_traits<T: Send + Sync>() {}
921        assert_traits::<ConcurrentDirectMap<u32, String>>();
922    }
923
924    #[test]
925    #[should_panic(expected = "invalid page capacity")]
926    fn zero_page_is_rejected() {
927        let _ = ConcurrentDirectMap::<usize, (), 0>::new();
928    }
929
930    #[test]
931    #[should_panic(expected = "key index exceeds direct spine range")]
932    fn out_of_range_insertion_panics() {
933        ConcurrentDirectMap::<usize, (), 1>::new().insert(usize::MAX, ());
934    }
935
936    #[test]
937    fn out_of_range_lookups_are_absent() {
938        let map = ConcurrentDirectMap::<usize, (), 1>::new();
939        assert!(!map.contains_key(usize::MAX));
940        assert!(map.get(usize::MAX).is_none());
941        assert!(map.get_mut(usize::MAX).is_none());
942        assert_eq!(map.with(usize::MAX, |_| ()), None);
943        assert_eq!(map.get_cloned(usize::MAX), None);
944        assert_eq!(map.remove(usize::MAX), None);
945        assert_eq!(map.remove_entry(usize::MAX), None);
946        assert_eq!(map.remove_occupant(usize::MAX), None);
947        assert_eq!(map.allocated_pages(), 0);
948    }
949}