Skip to main content

paged_collections/
direct_map.rs

1//! [`PagedDirectMap`]: a direct-address map whose values live in place in a
2//! paged index.
3//!
4//! Each key's entry is stored in the slot [`Key::index`] names, in pages
5//! allocated on first use. There is no dense array, so a lookup is one page
6//! lookup and one slot read, entries never move, and iteration visits the
7//! entries in ascending slot-index order (for plain integer keys, key
8//! order). The cost is that iteration and
9//! [`clear`](PagedDirectMap::clear) scan every allocated page, occupied or
10//! not, and every allocated slot takes the space of an entry.
11//!
12//! Prefer it to [`PagedSparseMap`](crate::sparse_map::PagedSparseMap) when
13//! keys fill a few dense ranges, when you want slot order, or when lookups
14//! dominate; prefer the sparse map when keys are scattered thinly or when you
15//! need the entries as contiguous slices.
16//!
17//! | Operation | Cost |
18//! |---|---|
19//! | [`get`](PagedDirectMap::get), [`insert`](PagedDirectMap::insert), [`remove`](PagedDirectMap::remove) | O(1) (O(depth) with [`Radix`](crate::page::Radix), O(log pages) with [`Tree`](crate::page::Tree)); the first key in a page also allocates the page (and, with [`Flat`], grows the directory up to it) |
20//! | iteration, [`clear`](PagedDirectMap::clear), [`retain`](PagedDirectMap::retain) | O(allocated pages × `PAGE`), plus with [`Flat`] O(directory length) to skip unallocated pages |
21//! | [`range`](PagedDirectMap::range), [`next_occupant`](PagedDirectMap::next_occupant), [`first_key_value`](PagedDirectMap::first_key_value) and the other [ordered queries](self#ordered-queries) | reaching the first page of the range is O(1) (O(depth) with [`Radix`](crate::page::Radix), O(log pages) with [`Tree`](crate::page::Tree)); then the slots of the allocated pages in the range are scanned up to the entry wanted, plus with [`Flat`] the unallocated directory entries between them |
22//! | [`len`](PagedDirectMap::len) | O(1) |
23//!
24//! Pages are not freed when they empty, as `HashMap` keeps its capacity;
25//! [`shrink_to_fit`](PagedDirectMap::shrink_to_fit) frees empty pages and
26//! [`reset`](PagedDirectMap::reset) frees all of them.
27//!
28//! # Slots and generational keys
29//!
30//! The map holds at most one key per slot index (see [`crate::key`]), and the
31//! methods treat a slot held by a *different* key (another generation) as
32//! [`PagedSparseMap`](crate::sparse_map::PagedSparseMap) does:
33//! [`insert`](PagedDirectMap::insert) and
34//! [`get_or_insert_with`](PagedDirectMap::get_or_insert_with) evict it,
35//! [`replace`](PagedDirectMap::replace) evicts it and returns it, and
36//! [`try_insert`](PagedDirectMap::try_insert) refuses. An
37//! [`entry`](PagedDirectMap::entry) is occupied only by the key itself; a
38//! vacant entry's inserts evict another generation.
39//!
40//! # What a slot stores
41//!
42//! A slot holds the value and the key's [`DirectKey::Tag`]: the part of the
43//! key its slot index does not give. Plain integer keys have the tag `()`, so
44//! a slot of a `u32 -> u64` map is an `Option<((), u64)>` of 16 bytes, and
45//! one of a `u32 -> Box<T>` map takes only the pointer's 8 bytes. Iterators
46//! and lookups rebuild each key from its slot index and tag, so they yield
47//! keys by value (`(K, &V)`) rather than by reference.
48//!
49//! # Ordered queries
50//!
51//! Entries are ordered by slot index, so the map answers the questions an
52//! ordered map does, without keeping a tree:
53//! [`range`](PagedDirectMap::range) and
54//! [`range_mut`](PagedDirectMap::range_mut) iterate the entries between two
55//! keys, [`first_key_value`](PagedDirectMap::first_key_value),
56//! [`last_key_value`](PagedDirectMap::last_key_value),
57//! [`pop_first`](PagedDirectMap::pop_first) and
58//! [`pop_last`](PagedDirectMap::pop_last) reach the ends, and
59//! [`next_occupant`](PagedDirectMap::next_occupant) and
60//! [`prev_occupant`](PagedDirectMap::prev_occupant) find the nearest entry at
61//! or after, or at or before, a slot index. The order is that of
62//! [`Key::index`]: key order for plain integers, index order (whatever the
63//! generation) for generational keys.
64//!
65//! ```
66//! use paged_collections::direct_map::PagedDirectMap;
67//!
68//! let map: PagedDirectMap<u32, char> =
69//!     [(2, 'a'), (5, 'b'), (70_000, 'c')].into_iter().collect();
70//! let keys: Vec<u32> = map.range(3..=70_000).map(|(k, _)| k).collect();
71//! assert_eq!(keys, [5, 70_000]);
72//! assert_eq!(map.next_occupant(6), Some((70_000, &'c')));
73//! assert_eq!(map.prev_occupant(4), Some((2, &'a')));
74//! assert_eq!(map.last_key_value(), Some((70_000, &'c')));
75//! ```
76//!
77//! ```
78//! use paged_collections::direct_map::PagedDirectMap;
79//!
80//! let mut map: PagedDirectMap<u32, &str> = PagedDirectMap::new();
81//! map.insert(3_000_000, "far");
82//! map.insert(7, "near");
83//! assert_eq!(map.insert(7, "nearer"), Some("near"));
84//! assert_eq!(map.get(3_000_000), Some(&"far"));
85//! assert_eq!(map.allocated_pages(), 2);
86//!
87//! // Integer keys iterate in key order, whatever the insertion order.
88//! let keys: Vec<u32> = map.keys().collect();
89//! assert_eq!(keys, [7, 3_000_000]);
90//!
91//! map.remove(3_000_000);
92//! map.shrink_to_fit(); // frees the now-empty page
93//! assert_eq!(map.allocated_pages(), 1);
94//! ```
95//!
96//! With the `rayon` feature, borrowed parallel iterators are unindexed and
97//! visit entries page by page. Collecting into a `Vec` preserves slot-index
98//! order. The order of `for_each` is unspecified.
99//!
100//! ```rust
101//! # #[cfg(feature = "rayon")] {
102//! use paged_collections::direct_map::PagedDirectMap;
103//! use rayon::prelude::*;
104//!
105//! let mut map: PagedDirectMap<u32, i32, 4> =
106//!     [(9, 10), (2, 20)].into_iter().collect();
107//! map.par_iter_mut().for_each(|(_, value)| *value += 1);
108//! assert_eq!(map.par_iter().map(|(k, &v)| (k, v)).collect::<Vec<_>>(), [(2, 21), (9, 11)]);
109//! # }
110//! ```
111
112use alloc::boxed::Box;
113use alloc::vec::{self, Vec};
114use core::fmt;
115use core::hash::{Hash, Hasher};
116use core::iter::{Fuse, FusedIterator};
117use core::marker::PhantomData;
118use core::mem;
119use core::ops::{Bound, Index, RangeBounds};
120use core::slice;
121
122use crate::key::{DirectKey, Key};
123use crate::page::{DEFAULT_PAGE, Directory, Flat, PageStore, split};
124
125/// One slot of a [`PagedDirectMap`] page: the tag of the key held there and
126/// its value, if any.
127pub type Slot<K, V> = Option<(<K as DirectKey>::Tag, V)>;
128
129type Store<K, V, const PAGE: usize, D> = <D as Directory>::Store<Slot<K, V>, PAGE>;
130type Pages<'a, K, V, const PAGE: usize, D> =
131    <Store<K, V, PAGE, D> as PageStore<Slot<K, V>, PAGE>>::Pages<'a>;
132type PagesMut<'a, K, V, const PAGE: usize, D> =
133    <Store<K, V, PAGE, D> as PageStore<Slot<K, V>, PAGE>>::PagesMut<'a>;
134type IntoPages<K, V, const PAGE: usize, D> =
135    <Store<K, V, PAGE, D> as PageStore<Slot<K, V>, PAGE>>::IntoPages;
136
137/// A map from [`DirectKey`]s to values stored in place at each key's slot
138/// index.
139///
140/// - `PAGE` is the number of slots per page; it must be non-zero. Each slot
141///   takes `size_of::<Option<(K::Tag, V)>>()` bytes whether or not it is
142///   occupied; see [what a slot stores](self#what-a-slot-stores).
143/// - `D` is the page directory: [`Flat`] (default),
144///   [`Radix`](crate::page::Radix) for wide keys, or
145///   [`Tree`](crate::page::Tree). See [`crate::page`].
146///
147/// Entries are ordered by slot index. See the [module docs](self) for costs
148/// and for how methods treat a slot held by another generation of a key.
149pub struct PagedDirectMap<K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
150    // Invariant: `len` is the number of occupied slots across all pages.
151    // Every mutation below keeps it even when a user closure, `V::drop` or an
152    // allocation panics.
153    pages: Store<K, V, PAGE, D>,
154    len: usize,
155}
156
157impl<K: DirectKey, V, const PAGE: usize, D: Directory> PagedDirectMap<K, V, PAGE, D> {
158    /// Number of slots per page.
159    pub const PAGE_SIZE: usize = PAGE;
160
161    /// Creates an empty map. No memory is allocated until the first insert.
162    pub fn new() -> Self {
163        Self {
164            pages: Default::default(),
165            len: 0,
166        }
167    }
168
169    /// Number of entries in the map.
170    #[inline]
171    pub fn len(&self) -> usize {
172        self.len
173    }
174
175    /// Whether the map has no entries.
176    #[inline]
177    pub fn is_empty(&self) -> bool {
178        self.len == 0
179    }
180
181    /// Number of allocated pages.
182    #[inline]
183    pub fn allocated_pages(&self) -> usize {
184        self.pages.allocated()
185    }
186
187    #[inline]
188    fn slot(&self, index: usize) -> Option<&Slot<K, V>> {
189        let (page, offset) = split::<PAGE>(index);
190        self.pages.get(page).map(|page| &page[offset])
191    }
192
193    #[inline]
194    fn slot_mut(&mut self, index: usize) -> Option<&mut Slot<K, V>> {
195        let (page, offset) = split::<PAGE>(index);
196        self.pages.get_mut(page).map(|page| &mut page[offset])
197    }
198
199    /// The slot for `index`, allocating its page if needed, and the entry
200    /// count.
201    #[inline]
202    fn slot_or_alloc(&mut self, index: usize) -> (&mut Slot<K, V>, &mut usize) {
203        let (page, offset) = split::<PAGE>(index);
204        (&mut self.pages.get_or_alloc(page)[offset], &mut self.len)
205    }
206
207    /// Whether `key` is in the map.
208    #[inline]
209    pub fn contains_key(&self, key: K) -> bool {
210        self.get(key).is_some()
211    }
212
213    /// The value for `key`, if it is in the map.
214    #[inline]
215    pub fn get(&self, key: K) -> Option<&V> {
216        match self.slot(key.index())? {
217            Some((tag, value)) if *tag == key.tag() => Some(value),
218            _ => None,
219        }
220    }
221
222    /// Mutable access to the value for `key`, if it is in the map.
223    #[inline]
224    pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
225        match self.slot_mut(key.index())? {
226            Some((tag, value)) if *tag == key.tag() => Some(value),
227            _ => None,
228        }
229    }
230
231    /// The stored key equal to `key` and its value, if it is in the map.
232    #[inline]
233    pub fn get_key_value(&self, key: K) -> Option<(K, &V)> {
234        let index = key.index();
235        match self.slot(index)? {
236            Some((tag, value)) if *tag == key.tag() => Some((K::from_parts(index, *tag), value)),
237            _ => None,
238        }
239    }
240
241    /// The entry occupying slot `index`, if any.
242    ///
243    /// With generational keys this finds whichever generation is present.
244    #[inline]
245    pub fn occupant(&self, index: usize) -> Option<(K, &V)> {
246        let (tag, value) = self.slot(index)?.as_ref()?;
247        Some((K::from_parts(index, *tag), value))
248    }
249
250    /// The entry occupying slot `index`, with mutable access to its value.
251    #[inline]
252    pub fn occupant_mut(&mut self, index: usize) -> Option<(K, &mut V)> {
253        let (tag, value) = self.slot_mut(index)?.as_mut()?;
254        Some((K::from_parts(index, *tag), value))
255    }
256
257    /// Stores `value` for `key` and returns the value previously in `key`'s
258    /// slot.
259    ///
260    /// If `key` is present its value is replaced and the stored key is kept.
261    /// If the slot is held by a different key (another generation), that
262    /// entry is evicted and its value returned; use
263    /// [`replace`](Self::replace) to get the evicted key too, or
264    /// [`try_insert`](Self::try_insert) to refuse.
265    ///
266    /// # Panics
267    ///
268    /// Panics if the page or the directory cannot be allocated. The entries
269    /// are then unchanged, though the directory may have grown.
270    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
271        let tag = key.tag();
272        let (slot, len) = self.slot_or_alloc(key.index());
273        if let Some((stored, old)) = slot {
274            if *stored != tag {
275                *stored = tag;
276            }
277            return Some(mem::replace(old, value));
278        }
279        *slot = Some((tag, value));
280        *len += 1;
281        None
282    }
283
284    /// Stores `value` for `key` and returns the entry previously in `key`'s
285    /// slot, whether it was `key` itself or another generation.
286    ///
287    /// Unlike [`insert`](Self::insert), this stores `key` even when the old
288    /// key is equal to it.
289    ///
290    /// # Panics
291    ///
292    /// As [`insert`](Self::insert).
293    pub fn replace(&mut self, key: K, value: V) -> Option<(K, V)> {
294        let index = key.index();
295        let (slot, len) = self.slot_or_alloc(index);
296        let old = slot.replace((key.tag(), value));
297        if old.is_none() {
298            *len += 1;
299        }
300        old.map(|(tag, value)| (K::from_parts(index, tag), value))
301    }
302
303    /// Adds an entry if `key`'s slot is vacant and returns its value, or
304    /// returns `value` back and leaves the map unchanged if the slot is held
305    /// (by `key` or by another key with the same index).
306    ///
307    /// # Panics
308    ///
309    /// As [`insert`](Self::insert).
310    pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, V> {
311        let (slot, len) = self.slot_or_alloc(key.index());
312        if slot.is_some() {
313            return Err(value);
314        }
315        *len += 1;
316        let (_, value) = slot.insert((key.tag(), value));
317        Ok(value)
318    }
319
320    /// The value for `key`, inserting `make()` first if `key` is absent.
321    ///
322    /// If the slot is held by a different key, that entry is evicted, as by
323    /// [`insert`](Self::insert). `make` runs before the map changes, so if it
324    /// panics the entries are unchanged.
325    ///
326    /// # Panics
327    ///
328    /// As [`insert`](Self::insert).
329    pub fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> &mut V {
330        let (index, tag) = (key.index(), key.tag());
331        let held_by_key = matches!(self.slot(index), Some(Some((stored, _))) if *stored == tag);
332        if !held_by_key {
333            // `make` runs before anything is allocated or changed.
334            let value = make();
335            let (slot, len) = self.slot_or_alloc(index);
336            if slot.is_none() {
337                *len += 1;
338            }
339            // Drop an evicted entry only once the slot is consistent:
340            // `V::drop` may panic.
341            drop(slot.replace((tag, value)));
342        }
343        // The page exists now, so this allocates nothing.
344        let (slot, _) = self.slot_or_alloc(index);
345        match slot {
346            Some((_, value)) => value,
347            None => unreachable!("slot was just filled"),
348        }
349    }
350
351    /// Removes `key` and returns its value, if it was present.
352    pub fn remove(&mut self, key: K) -> Option<V> {
353        self.remove_entry(key).map(|(_, value)| value)
354    }
355
356    /// Removes `key` and returns the stored key and its value, if it was
357    /// present.
358    pub fn remove_entry(&mut self, key: K) -> Option<(K, V)> {
359        let index = key.index();
360        let slot = self.slot_mut(index)?;
361        if !matches!(slot, Some((stored, _)) if *stored == key.tag()) {
362            return None;
363        }
364        let (tag, value) = slot.take()?;
365        self.len -= 1;
366        Some((K::from_parts(index, tag), value))
367    }
368
369    /// Removes whichever entry occupies slot `index` and returns it.
370    pub fn remove_occupant(&mut self, index: usize) -> Option<(K, V)> {
371        let (tag, value) = self.slot_mut(index)?.take()?;
372        self.len -= 1;
373        Some((K::from_parts(index, tag), value))
374    }
375
376    /// Keeps only the entries for which `keep` returns `true`, visiting them
377    /// in slot-index order.
378    ///
379    /// If `keep` or a value's `drop` panics, the entries not yet visited are
380    /// kept and the map stays consistent.
381    pub fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) {
382        let mut remaining = self.len;
383        for (number, page) in self.pages.pages_mut() {
384            for (offset, slot) in page.iter_mut().enumerate() {
385                if remaining == 0 {
386                    return;
387                }
388                let Some((tag, value)) = slot else { continue };
389                remaining -= 1;
390                let key = K::from_parts(number * PAGE + offset, *tag);
391                if !keep(&key, value) {
392                    let removed = slot.take();
393                    self.len -= 1;
394                    drop(removed);
395                }
396            }
397        }
398    }
399
400    /// Removes every entry, dropping the values in slot-index order. Pages
401    /// stay allocated for reuse; use [`reset`](Self::reset) to free them.
402    ///
403    /// If a value's `drop` panics, the entries not yet dropped stay in the
404    /// map.
405    pub fn clear(&mut self) {
406        self.retain(|_, _| false);
407    }
408
409    /// Removes every entry and frees every page.
410    pub fn reset(&mut self) {
411        // Detach the pages before dropping them: `V::drop` may panic, and the
412        // map must be empty and consistent whatever the store's drop order.
413        let pages = mem::take(&mut self.pages);
414        self.len = 0;
415        drop(pages);
416    }
417
418    /// Frees every page that holds no entry and shrinks the page directory.
419    pub fn shrink_to_fit(&mut self) {
420        if self.len == 0 {
421            self.pages.clear();
422        } else {
423            let empty: Vec<usize> = self
424                .pages
425                .pages()
426                .filter(|(_, page)| page.iter().all(Option::is_none))
427                .map(|(number, _)| number)
428                .collect();
429            for number in empty {
430                self.pages.remove(number);
431            }
432        }
433        self.pages.shrink_to_fit();
434    }
435
436    /// Iterates over the entries in slot-index order.
437    #[inline]
438    pub fn iter(&self) -> Iter<'_, K, V, PAGE, D> {
439        Iter(Cursor::new(self.pages.pages(), self.len))
440    }
441
442    /// Iterates over the entries in slot-index order, with mutable access to
443    /// the values.
444    #[inline]
445    pub fn iter_mut(&mut self) -> IterMut<'_, K, V, PAGE, D> {
446        IterMut(Cursor::new(self.pages.pages_mut(), self.len))
447    }
448
449    /// Iterates over the keys in slot-index order.
450    #[inline]
451    pub fn keys(&self) -> Keys<'_, K, V, PAGE, D> {
452        Keys(self.iter())
453    }
454
455    /// Iterates over the values in slot-index order.
456    #[inline]
457    pub fn values(&self) -> Values<'_, K, V, PAGE, D> {
458        Values(self.iter())
459    }
460
461    /// Iterates mutably over the values in slot-index order.
462    #[inline]
463    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V, PAGE, D> {
464        ValuesMut(self.iter_mut())
465    }
466
467    /// Iterates over the entries whose slot index lies between the slot
468    /// indices of the bounds, in slot-index order.
469    ///
470    /// The bounds are keys, compared by [`Key::index`]: for plain integer
471    /// keys this is the usual key range. A generational key bounds by its
472    /// index only, so `range(id..=id)` yields whichever generation holds
473    /// `id`'s slot. An empty or inverted range yields nothing.
474    ///
475    /// See the [module docs](self) for the cost.
476    pub fn range(&self, keys: impl RangeBounds<K>) -> Range<'_, K, V, PAGE, D> {
477        self.slot_range(index_bounds(&keys))
478    }
479
480    /// Like [`range`](Self::range), with mutable access to the values.
481    pub fn range_mut(&mut self, keys: impl RangeBounds<K>) -> RangeMut<'_, K, V, PAGE, D> {
482        self.slot_range_mut(index_bounds(&keys))
483    }
484
485    /// Iterates over the entries whose slot index is in `indices`, in
486    /// slot-index order. An empty or inverted range yields nothing.
487    pub fn slot_range(&self, indices: impl RangeBounds<usize>) -> Range<'_, K, V, PAGE, D> {
488        let span = Span::new::<PAGE>(&indices, self.len);
489        Range(Cursor::new(
490            Trim {
491                pages: self.pages.pages_in(span.pages.clone()),
492                first: span.first,
493                last: span.last,
494            },
495            span.most,
496        ))
497    }
498
499    /// Like [`slot_range`](Self::slot_range), with mutable access to the
500    /// values.
501    pub fn slot_range_mut(
502        &mut self,
503        indices: impl RangeBounds<usize>,
504    ) -> RangeMut<'_, K, V, PAGE, D> {
505        let span = Span::new::<PAGE>(&indices, self.len);
506        RangeMut(Cursor::new(
507            Trim {
508                pages: self.pages.pages_in_mut(span.pages.clone()),
509                first: span.first,
510                last: span.last,
511            },
512            span.most,
513        ))
514    }
515
516    /// The first entry at slot `index` or after it, in slot-index order.
517    ///
518    /// For plain integer keys, the entry with the smallest key `>= index`.
519    #[inline]
520    pub fn next_occupant(&self, index: usize) -> Option<(K, &V)> {
521        self.slot_range(index..).next()
522    }
523
524    /// The last entry at slot `index` or before it, in slot-index order.
525    ///
526    /// For plain integer keys, the entry with the largest key `<= index`.
527    #[inline]
528    pub fn prev_occupant(&self, index: usize) -> Option<(K, &V)> {
529        self.slot_range(..=index).next_back()
530    }
531
532    /// The entry with the smallest slot index.
533    #[inline]
534    pub fn first_key_value(&self) -> Option<(K, &V)> {
535        self.iter().next()
536    }
537
538    /// The entry with the largest slot index.
539    #[inline]
540    pub fn last_key_value(&self) -> Option<(K, &V)> {
541        self.iter().next_back()
542    }
543
544    /// Removes and returns the entry with the smallest slot index.
545    pub fn pop_first(&mut self) -> Option<(K, V)> {
546        let index = self.first_key_value()?.0.index();
547        self.remove_occupant(index)
548    }
549
550    /// Removes and returns the entry with the largest slot index.
551    pub fn pop_last(&mut self) -> Option<(K, V)> {
552        let index = self.last_key_value()?.0.index();
553        self.remove_occupant(index)
554    }
555
556    /// Removes every entry and returns them in slot-index order. Pages stay
557    /// allocated, as with [`clear`](Self::clear).
558    ///
559    /// Entries are removed as the iterator yields them; dropping it removes
560    /// the rest. If it is leaked instead (`mem::forget`), or a value's `drop`
561    /// panics while the rest are removed, the entries not yet reached stay in
562    /// the map, which stays consistent.
563    ///
564    /// ```
565    /// use paged_collections::direct_map::PagedDirectMap;
566    ///
567    /// let mut map: PagedDirectMap<u32, char> = [(5, 'b'), (1, 'a')].into_iter().collect();
568    /// assert_eq!(map.drain().collect::<Vec<_>>(), [(1, 'a'), (5, 'b')]);
569    /// assert!(map.is_empty());
570    /// ```
571    pub fn drain(&mut self) -> Drain<'_, K, V, PAGE, D> {
572        Drain {
573            map: self,
574            next: Some(0),
575        }
576    }
577
578    /// Removes the entries for which `pred` returns `true` and yields them,
579    /// visiting the entries in slot-index order.
580    ///
581    /// Entries are tested and removed as the iterator advances: those it has
582    /// not reached when it is dropped stay in the map. Use
583    /// [`retain`](Self::retain) if the removed entries are not needed.
584    ///
585    /// ```
586    /// use paged_collections::direct_map::PagedDirectMap;
587    ///
588    /// let mut map: PagedDirectMap<u32, u32> = (0..6).map(|k| (k, k * 10)).collect();
589    /// let odd: Vec<(u32, u32)> = map.extract_if(|k, _| k % 2 == 1).collect();
590    /// assert_eq!(odd, [(1, 10), (3, 30), (5, 50)]);
591    /// assert_eq!(map.len(), 3);
592    /// ```
593    pub fn extract_if<F: FnMut(&K, &mut V) -> bool>(
594        &mut self,
595        pred: F,
596    ) -> ExtractIf<'_, K, V, F, PAGE, D> {
597        ExtractIf {
598            map: self,
599            next: Some(0),
600            pred,
601        }
602    }
603
604    /// The values of several keys at once, mutably: `None` for each key that
605    /// is not in the map. O(N log N) for N keys, plus stepping over the pages
606    /// between the smallest and largest key's.
607    ///
608    /// ```
609    /// use paged_collections::direct_map::PagedDirectMap;
610    ///
611    /// let mut map: PagedDirectMap<u32, u32> = [(1, 10), (9000, 20)].into_iter().collect();
612    /// if let [Some(a), None, Some(b)] = map.get_disjoint_mut([1, 2, 9000]) {
613    ///     core::mem::swap(a, b);
614    /// }
615    /// assert_eq!((map[1], map[9000]), (20, 10));
616    /// ```
617    ///
618    /// # Panics
619    ///
620    /// Panics if a key in the map is given twice.
621    pub fn get_disjoint_mut<const N: usize>(&mut self, keys: [K; N]) -> [Option<&mut V>; N] {
622        // The present keys as (slot index, position in `keys`).
623        let mut order = [(0, 0); N];
624        let mut n = 0;
625        for (i, &key) in keys.iter().enumerate() {
626            if self.get(key).is_some() {
627                order[n] = (key.index(), i);
628                n += 1;
629            }
630        }
631        let order = &mut order[..n];
632        order.sort_unstable();
633        for pair in order.windows(2) {
634            assert!(
635                pair[0].0 != pair[1].0,
636                "PagedDirectMap::get_disjoint_mut: key at positions {} and {} given twice",
637                pair[0].1,
638                pair[1].1
639            );
640        }
641        let mut out = [const { None }; N];
642        let (Some(&(lo, _)), Some(&(hi, _))) = (order.first(), order.last()) else {
643            return out;
644        };
645        // Walk the pages in order (each is borrowed once), splitting each
646        // wanted slot off the front of what is left of its page.
647        let mut want = order.iter().peekable();
648        for (number, page) in self
649            .pages
650            .pages_in_mut(split::<PAGE>(lo).0..=split::<PAGE>(hi).0)
651        {
652            let mut rest: &mut [Slot<K, V>] = page;
653            let mut start = 0;
654            while let Some(&&(index, i)) = want.peek() {
655                let (wanted, offset) = split::<PAGE>(index);
656                if wanted > number {
657                    break;
658                }
659                want.next();
660                if wanted < number {
661                    // Only a store that breaks the page contract skips a
662                    // page holding an entry just found.
663                    continue;
664                }
665                let (_, tail) = mem::take(&mut rest).split_at_mut(offset - start);
666                let (slot, tail) = tail.split_first_mut().expect("offsets are inside the page");
667                if let Some((_, value)) = slot {
668                    out[i] = Some(value);
669                }
670                rest = tail;
671                start = offset + 1;
672            }
673        }
674        out
675    }
676
677    /// The entry for `key`, for in-place access or insertion.
678    ///
679    /// The entry is [`Occupied`](Entry::Occupied) only if `key` itself is in
680    /// the map. A slot held by a different key (another generation) gives a
681    /// [`Vacant`](Entry::Vacant) entry, whose inserts evict that key as
682    /// [`insert`](Self::insert) does; [`VacantEntry::occupant`] shows it.
683    /// No page is allocated until a vacant entry is inserted into.
684    ///
685    /// ```
686    /// use paged_collections::direct_map::PagedDirectMap;
687    ///
688    /// let mut counts: PagedDirectMap<u32, u32> = PagedDirectMap::new();
689    /// for word in [3, 1, 3, 3] {
690    ///     *counts.entry(word).or_insert(0) += 1;
691    /// }
692    /// assert_eq!((counts[3], counts[1]), (3, 1));
693    /// ```
694    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, PAGE, D> {
695        let index = key.index();
696        let stored = match self.slot(index) {
697            Some(Some((stored, _))) if *stored == key.tag() => *stored,
698            _ => return Entry::Vacant(VacantEntry { map: self, key }),
699        };
700        let (page, offset) = split::<PAGE>(index);
701        match self.pages.get_mut(page) {
702            Some(page) => Entry::Occupied(OccupiedEntry {
703                key: K::from_parts(index, stored),
704                slot: &mut page[offset],
705                len: &mut self.len,
706            }),
707            None => unreachable!("the slot was just found"),
708        }
709    }
710
711    /// Consumes the map and returns its keys in slot-index order.
712    pub fn into_keys(self) -> IntoKeys<K, V, PAGE, D> {
713        IntoKeys(self.into_iter())
714    }
715
716    /// Consumes the map and returns its values in slot-index order.
717    pub fn into_values(self) -> IntoValues<K, V, PAGE, D> {
718        IntoValues(self.into_iter())
719    }
720}
721
722impl<K: DirectKey, V, const PAGE: usize, D: Directory> Default for PagedDirectMap<K, V, PAGE, D> {
723    fn default() -> Self {
724        Self::new()
725    }
726}
727
728impl<K: DirectKey, V: Clone, const PAGE: usize, D: Directory> Clone
729    for PagedDirectMap<K, V, PAGE, D>
730where
731    Store<K, V, PAGE, D>: Clone,
732{
733    fn clone(&self) -> Self {
734        Self {
735            pages: self.pages.clone(),
736            len: self.len,
737        }
738    }
739}
740
741impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
742    for PagedDirectMap<K, V, PAGE, D>
743{
744    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
745        f.debug_map().entries(self.iter()).finish()
746    }
747}
748
749/// Compares entries in [`iter`](PagedDirectMap::iter)'s slot-index order,
750/// across page sizes and directories.
751impl<
752    K: DirectKey,
753    V: PartialEq<W>,
754    W,
755    const PAGE: usize,
756    D: Directory,
757    const P2: usize,
758    D2: Directory,
759> PartialEq<PagedDirectMap<K, W, P2, D2>> for PagedDirectMap<K, V, PAGE, D>
760{
761    fn eq(&self, other: &PagedDirectMap<K, W, P2, D2>) -> bool {
762        self.len == other.len
763            && self
764                .iter()
765                .zip(other.iter())
766                .all(|((key, value), (other_key, other_value))| {
767                    key == other_key && value == other_value
768                })
769    }
770}
771
772/// Map [`PartialEq`] is an equivalence relation when the values implement [`Eq`].
773impl<K: DirectKey, V: Eq, const PAGE: usize, D: Directory> Eq for PagedDirectMap<K, V, PAGE, D> {}
774
775/// Hashes the length, then the entries in slot-index order, consistent with
776/// [`PartialEq`].
777impl<K: DirectKey + Hash, V: Hash, const PAGE: usize, D: Directory> Hash
778    for PagedDirectMap<K, V, PAGE, D>
779{
780    fn hash<H: Hasher>(&self, state: &mut H) {
781        state.write_usize(self.len);
782        for entry in self {
783            entry.hash(state);
784        }
785    }
786}
787
788/// `map[key]` returns the value for `key`.
789///
790/// # Panics
791///
792/// Panics if `key` is not in the map.
793impl<K: DirectKey, V, const PAGE: usize, D: Directory> Index<K> for PagedDirectMap<K, V, PAGE, D> {
794    type Output = V;
795
796    fn index(&self, key: K) -> &V {
797        self.get(key).expect("key not in PagedDirectMap")
798    }
799}
800
801/// Inserts each entry with [`insert`](PagedDirectMap::insert), so later
802/// entries overwrite earlier ones in the same slot.
803impl<K: DirectKey, V, const PAGE: usize, D: Directory> Extend<(K, V)>
804    for PagedDirectMap<K, V, PAGE, D>
805{
806    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
807        for (key, value) in iter {
808            self.insert(key, value);
809        }
810    }
811}
812
813impl<'a, K: DirectKey + 'a, V: Copy + 'a, const PAGE: usize, D: Directory> Extend<(&'a K, &'a V)>
814    for PagedDirectMap<K, V, PAGE, D>
815{
816    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
817        self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
818    }
819}
820
821impl<K: DirectKey, V, const PAGE: usize, D: Directory> FromIterator<(K, V)>
822    for PagedDirectMap<K, V, PAGE, D>
823{
824    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
825        let mut map = Self::new();
826        map.extend(iter);
827        map
828    }
829}
830
831impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> IntoIterator
832    for &'a PagedDirectMap<K, V, PAGE, D>
833{
834    type Item = (K, &'a V);
835    type IntoIter = Iter<'a, K, V, PAGE, D>;
836
837    fn into_iter(self) -> Self::IntoIter {
838        self.iter()
839    }
840}
841
842impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> IntoIterator
843    for &'a mut PagedDirectMap<K, V, PAGE, D>
844{
845    type Item = (K, &'a mut V);
846    type IntoIter = IterMut<'a, K, V, PAGE, D>;
847
848    fn into_iter(self) -> Self::IntoIter {
849        self.iter_mut()
850    }
851}
852
853impl<K: DirectKey, V, const PAGE: usize, D: Directory> IntoIterator
854    for PagedDirectMap<K, V, PAGE, D>
855{
856    type Item = (K, V);
857    type IntoIter = IntoIter<K, V, PAGE, D>;
858
859    fn into_iter(self) -> Self::IntoIter {
860        IntoIter(Cursor::new(self.pages.into_pages(), self.len))
861    }
862}
863
864// Iteration: a cursor flattens the page iterator into indexed slots, like
865// `Iterator::flatten`, rebuilds each entry's key from its slot index and tag,
866// and stops once it has yielded `remaining` entries so trailing empty slots
867// are not scanned.
868
869/// The slots of one page (or part of one), each with its slot index.
870#[derive(Clone, Default)]
871struct Indexed<S> {
872    /// The slot index of the next slot from the front.
873    start: usize,
874    slots: S,
875}
876
877impl<S: ExactSizeIterator + DoubleEndedIterator> Iterator for Indexed<S> {
878    type Item = (usize, S::Item);
879
880    #[inline]
881    fn next(&mut self) -> Option<Self::Item> {
882        let slot = self.slots.next()?;
883        let index = self.start;
884        // Wraps only past a slot at `usize::MAX`, the last one there is.
885        self.start = index.wrapping_add(1);
886        Some((index, slot))
887    }
888}
889
890impl<S: ExactSizeIterator + DoubleEndedIterator> DoubleEndedIterator for Indexed<S> {
891    #[inline]
892    fn next_back(&mut self) -> Option<Self::Item> {
893        let slot = self.slots.next_back()?;
894        Some((self.start.wrapping_add(self.slots.len()), slot))
895    }
896}
897
898/// Turns a page from a page iterator into an iterator over its indexed
899/// slots.
900trait PageSlots {
901    type Slots: DoubleEndedIterator + Default;
902    fn slots(self) -> Self::Slots;
903}
904
905/// The first slot index of page `number`. Only a store that breaks the page
906/// contract can make this wrap, which gives wrong keys but nothing worse.
907#[inline]
908fn page_start<const PAGE: usize>(number: usize) -> usize {
909    number.wrapping_mul(PAGE)
910}
911
912/// A part of a page cut by [`Trim`]: its first slot index and its slots.
913impl<'a, T> PageSlots for (usize, &'a [T]) {
914    type Slots = Indexed<slice::Iter<'a, T>>;
915    fn slots(self) -> Self::Slots {
916        Indexed {
917            start: self.0,
918            slots: self.1.iter(),
919        }
920    }
921}
922
923impl<'a, T> PageSlots for (usize, &'a mut [T]) {
924    type Slots = Indexed<slice::IterMut<'a, T>>;
925    fn slots(self) -> Self::Slots {
926        Indexed {
927            start: self.0,
928            slots: self.1.iter_mut(),
929        }
930    }
931}
932
933/// A whole page: its page number and its slots.
934impl<'a, T, const PAGE: usize> PageSlots for (usize, &'a [T; PAGE]) {
935    type Slots = Indexed<slice::Iter<'a, T>>;
936    fn slots(self) -> Self::Slots {
937        Indexed {
938            start: page_start::<PAGE>(self.0),
939            slots: self.1.iter(),
940        }
941    }
942}
943
944impl<'a, T, const PAGE: usize> PageSlots for (usize, &'a mut [T; PAGE]) {
945    type Slots = Indexed<slice::IterMut<'a, T>>;
946    fn slots(self) -> Self::Slots {
947        Indexed {
948            start: page_start::<PAGE>(self.0),
949            slots: self.1.iter_mut(),
950        }
951    }
952}
953
954impl<T, const PAGE: usize> PageSlots for (usize, Box<[T; PAGE]>) {
955    type Slots = Indexed<vec::IntoIter<T>>;
956    fn slots(self) -> Self::Slots {
957        let page: Box<[T]> = self.1;
958        Indexed {
959            start: page_start::<PAGE>(self.0),
960            slots: Vec::from(page).into_iter(),
961        }
962    }
963}
964
965/// Turns the slot at a slot index into the entry it holds, if any, with the
966/// key of type `K` rebuilt.
967trait SlotEntry<K> {
968    type Entry;
969    fn entry(self, index: usize) -> Option<Self::Entry>;
970}
971
972impl<'a, K: DirectKey, V: 'a> SlotEntry<K> for &'a Option<(K::Tag, V)> {
973    type Entry = (K, &'a V);
974    #[inline]
975    fn entry(self, index: usize) -> Option<Self::Entry> {
976        let (tag, value) = self.as_ref()?;
977        Some((K::from_parts(index, *tag), value))
978    }
979}
980
981impl<'a, K: DirectKey, V: 'a> SlotEntry<K> for &'a mut Option<(K::Tag, V)> {
982    type Entry = (K, &'a mut V);
983    #[inline]
984    fn entry(self, index: usize) -> Option<Self::Entry> {
985        let (tag, value) = self.as_mut()?;
986        Some((K::from_parts(index, *tag), value))
987    }
988}
989
990impl<K: DirectKey, V> SlotEntry<K> for Option<(K::Tag, V)> {
991    type Entry = (K, V);
992    #[inline]
993    fn entry(self, index: usize) -> Option<Self::Entry> {
994        let (tag, value) = self?;
995        Some((K::from_parts(index, tag), value))
996    }
997}
998
999struct Cursor<K, P, S> {
1000    pages: Fuse<P>,
1001    front: S,
1002    back: S,
1003    remaining: usize,
1004    key: PhantomData<fn() -> K>,
1005}
1006
1007impl<K, P: Clone, S: Clone> Clone for Cursor<K, P, S> {
1008    fn clone(&self) -> Self {
1009        Self {
1010            pages: self.pages.clone(),
1011            front: self.front.clone(),
1012            back: self.back.clone(),
1013            remaining: self.remaining,
1014            key: PhantomData,
1015        }
1016    }
1017}
1018
1019impl<K, P, S, X> Cursor<K, P, S>
1020where
1021    P: DoubleEndedIterator,
1022    P::Item: PageSlots<Slots = S>,
1023    S: DoubleEndedIterator<Item = (usize, X)> + Default,
1024    X: SlotEntry<K>,
1025{
1026    #[inline]
1027    fn len(&self) -> usize {
1028        self.remaining
1029    }
1030
1031    fn new(pages: P, remaining: usize) -> Self {
1032        Self {
1033            pages: pages.fuse(),
1034            front: S::default(),
1035            back: S::default(),
1036            remaining,
1037            key: PhantomData,
1038        }
1039    }
1040
1041    fn next(&mut self) -> Option<X::Entry> {
1042        while self.remaining > 0 {
1043            let (index, slot) = match self.front.next() {
1044                Some(slot) => slot,
1045                None => match self.pages.next() {
1046                    Some(page) => {
1047                        self.front = page.slots();
1048                        continue;
1049                    }
1050                    // The pages are used up; the rest is in `back`.
1051                    None => match self.back.next() {
1052                        Some(slot) => slot,
1053                        None => break,
1054                    },
1055                },
1056            };
1057            if let Some(entry) = slot.entry(index) {
1058                self.remaining -= 1;
1059                return Some(entry);
1060            }
1061        }
1062        // Only a store that breaks the page contract can end here with
1063        // `remaining > 0`; zero it so `len` stays truthful.
1064        self.remaining = 0;
1065        None
1066    }
1067
1068    fn next_back(&mut self) -> Option<X::Entry> {
1069        while self.remaining > 0 {
1070            let (index, slot) = match self.back.next_back() {
1071                Some(slot) => slot,
1072                None => match self.pages.next_back() {
1073                    Some(page) => {
1074                        self.back = page.slots();
1075                        continue;
1076                    }
1077                    None => match self.front.next_back() {
1078                        Some(slot) => slot,
1079                        None => break,
1080                    },
1081                },
1082            };
1083            if let Some(entry) = slot.entry(index) {
1084                self.remaining -= 1;
1085                return Some(entry);
1086            }
1087        }
1088        // Only a store that breaks the page contract can end here with
1089        // `remaining > 0`; zero it so `len` stays truthful.
1090        self.remaining = 0;
1091        None
1092    }
1093}
1094
1095/// The entries removed by [`PagedDirectMap::drain`], in slot-index order.
1096pub struct Drain<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1097    map: &'a mut PagedDirectMap<K, V, PAGE, D>,
1098    // The slot index to resume from; `None` once the last slot is passed.
1099    next: Option<usize>,
1100}
1101
1102impl<K: DirectKey, V, const PAGE: usize, D: Directory> Iterator for Drain<'_, K, V, PAGE, D> {
1103    type Item = (K, V);
1104
1105    fn next(&mut self) -> Option<(K, V)> {
1106        let start = self.next?;
1107        let Some((key, _)) = self.map.slot_range(start..).next() else {
1108            self.next = None;
1109            return None;
1110        };
1111        let index = key.index();
1112        self.next = index.checked_add(1);
1113        self.map.remove_occupant(index)
1114    }
1115
1116    fn size_hint(&self) -> (usize, Option<usize>) {
1117        // Every entry before the cursor has been removed.
1118        (self.map.len, Some(self.map.len))
1119    }
1120}
1121
1122impl<K: DirectKey, V, const PAGE: usize, D: Directory> ExactSizeIterator
1123    for Drain<'_, K, V, PAGE, D>
1124{
1125}
1126
1127impl<K: DirectKey, V, const PAGE: usize, D: Directory> FusedIterator for Drain<'_, K, V, PAGE, D> {}
1128
1129impl<K: DirectKey, V, const PAGE: usize, D: Directory> Drop for Drain<'_, K, V, PAGE, D> {
1130    fn drop(&mut self) {
1131        self.for_each(drop);
1132    }
1133}
1134
1135impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1136    for Drain<'_, K, V, PAGE, D>
1137{
1138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139        // Every entry still in the map is yet to be yielded.
1140        f.debug_list().entries(self.map.iter()).finish()
1141    }
1142}
1143
1144/// The entries removed by [`PagedDirectMap::extract_if`], in slot-index
1145/// order.
1146pub struct ExtractIf<'a, K: DirectKey, V, F, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat>
1147{
1148    map: &'a mut PagedDirectMap<K, V, PAGE, D>,
1149    next: Option<usize>,
1150    pred: F,
1151}
1152
1153impl<K: DirectKey, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> Iterator
1154    for ExtractIf<'_, K, V, F, PAGE, D>
1155{
1156    type Item = (K, V);
1157
1158    fn next(&mut self) -> Option<(K, V)> {
1159        loop {
1160            let start = self.next?;
1161            let Some((key, value)) = self.map.slot_range_mut(start..).next() else {
1162                self.next = None;
1163                return None;
1164            };
1165            let index = key.index();
1166            // Advance first: if `pred` panics, this entry stays.
1167            self.next = index.checked_add(1);
1168            if (self.pred)(&key, value) {
1169                return self.map.remove_occupant(index);
1170            }
1171        }
1172    }
1173
1174    fn size_hint(&self) -> (usize, Option<usize>) {
1175        (0, Some(if self.next.is_some() { self.map.len } else { 0 }))
1176    }
1177}
1178
1179impl<K: DirectKey, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> FusedIterator
1180    for ExtractIf<'_, K, V, F, PAGE, D>
1181{
1182}
1183
1184impl<K: DirectKey + fmt::Debug, V: fmt::Debug, F, const PAGE: usize, D: Directory> fmt::Debug
1185    for ExtractIf<'_, K, V, F, PAGE, D>
1186{
1187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188        f.debug_struct("ExtractIf")
1189            .field("next", &self.next)
1190            .finish_non_exhaustive()
1191    }
1192}
1193
1194/// The slot-index bounds of a key range.
1195fn index_bounds<K: Key>(keys: &impl RangeBounds<K>) -> (Bound<usize>, Bound<usize>) {
1196    (
1197        keys.start_bound().map(|key| key.index()),
1198        keys.end_bound().map(|key| key.index()),
1199    )
1200}
1201
1202/// A range of slot indices, resolved: the slots `first..=last`, the pages
1203/// that hold them, and the most entries they can hold. An empty range has
1204/// `first > last`, an empty page range and `most == 0`.
1205struct Span {
1206    first: usize,
1207    last: usize,
1208    pages: core::ops::RangeInclusive<usize>,
1209    most: usize,
1210}
1211
1212impl Span {
1213    /// Resolves `indices` for a map of `len` entries.
1214    fn new<const PAGE: usize>(indices: &impl RangeBounds<usize>, len: usize) -> Self {
1215        let first = match indices.start_bound() {
1216            Bound::Included(&index) => Some(index),
1217            Bound::Excluded(&index) => index.checked_add(1),
1218            Bound::Unbounded => Some(0),
1219        };
1220        let last = match indices.end_bound() {
1221            Bound::Included(&index) => Some(index),
1222            Bound::Excluded(&index) => index.checked_sub(1),
1223            Bound::Unbounded => Some(usize::MAX),
1224        };
1225        match (first, last) {
1226            (Some(first), Some(last)) if first <= last => Self {
1227                first,
1228                last,
1229                pages: split::<PAGE>(first).0..=split::<PAGE>(last).0,
1230                most: (last - first).saturating_add(1).min(len),
1231            },
1232            #[allow(clippy::reversed_empty_ranges)]
1233            _ => Self {
1234                first: 1,
1235                last: 0,
1236                pages: 1..=0,
1237                most: 0,
1238            },
1239        }
1240    }
1241}
1242
1243/// Cuts a page from a page iterator down to its slots in `first..=last`, with
1244/// the slot index of the first one.
1245trait Cut<const PAGE: usize> {
1246    type Part;
1247    fn cut(self, first: usize, last: usize) -> Self::Part;
1248}
1249
1250/// The offsets within page `number` of the slot indices `first..=last`.
1251fn offsets<const PAGE: usize>(number: usize, first: usize, last: usize) -> core::ops::Range<usize> {
1252    let base = number.saturating_mul(PAGE);
1253    let end = match last.checked_sub(base) {
1254        Some(offset) => offset.saturating_add(1).min(PAGE),
1255        // Only a store that breaks the page contract yields a page past
1256        // `last`.
1257        None => 0,
1258    };
1259    first.saturating_sub(base).min(end)..end
1260}
1261
1262impl<'a, T, const PAGE: usize> Cut<PAGE> for (usize, &'a [T; PAGE]) {
1263    type Part = (usize, &'a [T]);
1264    fn cut(self, first: usize, last: usize) -> Self::Part {
1265        let offsets = offsets::<PAGE>(self.0, first, last);
1266        let start = page_start::<PAGE>(self.0).wrapping_add(offsets.start);
1267        (start, &self.1[offsets])
1268    }
1269}
1270
1271impl<'a, T, const PAGE: usize> Cut<PAGE> for (usize, &'a mut [T; PAGE]) {
1272    type Part = (usize, &'a mut [T]);
1273    fn cut(self, first: usize, last: usize) -> Self::Part {
1274        let offsets = offsets::<PAGE>(self.0, first, last);
1275        let start = page_start::<PAGE>(self.0).wrapping_add(offsets.start);
1276        (start, &mut self.1[offsets])
1277    }
1278}
1279
1280/// A page iterator whose pages are cut down to the slots `first..=last`.
1281#[derive(Clone)]
1282struct Trim<P, const PAGE: usize> {
1283    pages: P,
1284    first: usize,
1285    last: usize,
1286}
1287
1288impl<P: Iterator, const PAGE: usize> Iterator for Trim<P, PAGE>
1289where
1290    P::Item: Cut<PAGE>,
1291{
1292    type Item = <P::Item as Cut<PAGE>>::Part;
1293
1294    fn next(&mut self) -> Option<Self::Item> {
1295        let page = self.pages.next()?;
1296        Some(page.cut(self.first, self.last))
1297    }
1298}
1299
1300impl<P: DoubleEndedIterator, const PAGE: usize> DoubleEndedIterator for Trim<P, PAGE>
1301where
1302    P::Item: Cut<PAGE>,
1303{
1304    fn next_back(&mut self) -> Option<Self::Item> {
1305        let page = self.pages.next_back()?;
1306        Some(page.cut(self.first, self.last))
1307    }
1308}
1309
1310macro_rules! range_iterator {
1311    (
1312        $(#[$doc:meta])*
1313        $name:ident, $pages:ident, $slots:ident, $item:ty
1314    ) => {
1315        $(#[$doc])*
1316        pub struct $name<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat>(
1317            Cursor<K, Trim<$pages<'a, K, V, PAGE, D>, PAGE>, Indexed<slice::$slots<'a, Slot<K, V>>>>,
1318        )
1319        where
1320            K: 'a,
1321            V: 'a,
1322            D: 'a;
1323
1324        impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> Iterator for $name<'a, K, V, PAGE, D> {
1325            type Item = $item;
1326
1327            #[inline]
1328            fn next(&mut self) -> Option<Self::Item> {
1329                self.0.next()
1330            }
1331
1332            /// The upper bound is loose: the smaller of the map's length
1333            /// and the number of slots in the range, less the entries
1334            /// already yielded.
1335            #[inline]
1336            fn size_hint(&self) -> (usize, Option<usize>) {
1337                (0, Some(self.0.remaining))
1338            }
1339        }
1340
1341        impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> DoubleEndedIterator
1342            for $name<'a, K, V, PAGE, D>
1343        {
1344            #[inline]
1345            fn next_back(&mut self) -> Option<Self::Item> {
1346                self.0.next_back()
1347            }
1348        }
1349
1350        impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> FusedIterator
1351            for $name<'a, K, V, PAGE, D>
1352        {
1353        }
1354
1355        impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> fmt::Debug for $name<'a, K, V, PAGE, D> {
1356            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1357                f.debug_struct(stringify!($name)).finish_non_exhaustive()
1358            }
1359        }
1360    };
1361}
1362
1363range_iterator!(
1364    /// Iterator over the entries of a [`PagedDirectMap`] in a range of slot
1365    /// indices, from [`range`](PagedDirectMap::range) or
1366    /// [`slot_range`](PagedDirectMap::slot_range).
1367    Range,
1368    Pages,
1369    Iter,
1370    (K, &'a V)
1371);
1372
1373range_iterator!(
1374    /// Iterator over the entries of a [`PagedDirectMap`] in a range of slot
1375    /// indices, with mutable values, from
1376    /// [`range_mut`](PagedDirectMap::range_mut) or
1377    /// [`slot_range_mut`](PagedDirectMap::slot_range_mut).
1378    RangeMut,
1379    PagesMut,
1380    IterMut,
1381    (K, &'a mut V)
1382);
1383
1384impl<K: DirectKey, V, const PAGE: usize, D: Directory> Clone for Range<'_, K, V, PAGE, D> {
1385    fn clone(&self) -> Self {
1386        Self(self.0.clone())
1387    }
1388}
1389
1390macro_rules! entry_iterator {
1391    (
1392        $(#[$doc:meta])*
1393        $name:ident<$($lt:lifetime,)? K, V, PAGE, D>,
1394        $inner:ty,
1395        $item:ty,
1396        |$entry:pat_param| $map:expr
1397    ) => {
1398        $(#[$doc])*
1399        pub struct $name<$($lt,)? K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat>($inner)
1400        where
1401            $(K: $lt, V: $lt, D: $lt)?;
1402
1403        impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> Iterator for $name<$($lt,)? K, V, PAGE, D>
1404        where
1405            $(K: $lt, V: $lt, D: $lt)?
1406        {
1407            type Item = $item;
1408
1409            #[inline]
1410            fn next(&mut self) -> Option<Self::Item> {
1411                self.0.next().map(|$entry| $map)
1412            }
1413
1414            #[inline]
1415            fn size_hint(&self) -> (usize, Option<usize>) {
1416                let len = self.len();
1417                (len, Some(len))
1418            }
1419        }
1420
1421        impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> DoubleEndedIterator
1422            for $name<$($lt,)? K, V, PAGE, D>
1423        where
1424            $(K: $lt, V: $lt, D: $lt)?
1425        {
1426            #[inline]
1427            fn next_back(&mut self) -> Option<Self::Item> {
1428                self.0.next_back().map(|$entry| $map)
1429            }
1430        }
1431
1432        impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> ExactSizeIterator
1433            for $name<$($lt,)? K, V, PAGE, D>
1434        where
1435            $(K: $lt, V: $lt, D: $lt)?
1436        {
1437            #[inline]
1438            fn len(&self) -> usize {
1439                self.0.len()
1440            }
1441        }
1442
1443        impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> FusedIterator
1444            for $name<$($lt,)? K, V, PAGE, D>
1445        where
1446            $(K: $lt, V: $lt, D: $lt)?
1447        {
1448        }
1449
1450        impl<$($lt,)? K: DirectKey, V, const PAGE: usize, D: Directory> fmt::Debug
1451            for $name<$($lt,)? K, V, PAGE, D>
1452        where
1453            $(K: $lt, V: $lt, D: $lt)?
1454        {
1455            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1456                f.debug_struct(stringify!($name))
1457                    .field("remaining", &self.len())
1458                    .finish_non_exhaustive()
1459            }
1460        }
1461    };
1462}
1463
1464entry_iterator!(
1465    /// Iterator over the entries of a [`PagedDirectMap`] in slot-index
1466    /// order, from [`iter`](PagedDirectMap::iter).
1467    Iter<'a, K, V, PAGE, D>,
1468    Cursor<K, Pages<'a, K, V, PAGE, D>, Indexed<slice::Iter<'a, Slot<K, V>>>>,
1469    (K, &'a V),
1470    |entry| entry
1471);
1472
1473entry_iterator!(
1474    /// Iterator over the entries of a [`PagedDirectMap`] with mutable
1475    /// values, from [`iter_mut`](PagedDirectMap::iter_mut).
1476    IterMut<'a, K, V, PAGE, D>,
1477    Cursor<K, PagesMut<'a, K, V, PAGE, D>, Indexed<slice::IterMut<'a, Slot<K, V>>>>,
1478    (K, &'a mut V),
1479    |entry| entry
1480);
1481
1482entry_iterator!(
1483    /// Owning iterator over the entries of a [`PagedDirectMap`] in
1484    /// slot-index order.
1485    IntoIter<K, V, PAGE, D>,
1486    Cursor<K, IntoPages<K, V, PAGE, D>, Indexed<vec::IntoIter<Slot<K, V>>>>,
1487    (K, V),
1488    |entry| entry
1489);
1490
1491entry_iterator!(
1492    /// Iterator over the keys of a [`PagedDirectMap`], from
1493    /// [`keys`](PagedDirectMap::keys).
1494    Keys<'a, K, V, PAGE, D>,
1495    Iter<'a, K, V, PAGE, D>,
1496    K,
1497    |(key, _)| key
1498);
1499
1500entry_iterator!(
1501    /// Iterator over the values of a [`PagedDirectMap`], from
1502    /// [`values`](PagedDirectMap::values).
1503    Values<'a, K, V, PAGE, D>,
1504    Iter<'a, K, V, PAGE, D>,
1505    &'a V,
1506    |(_, value)| value
1507);
1508
1509entry_iterator!(
1510    /// Mutable iterator over the values of a [`PagedDirectMap`], from
1511    /// [`values_mut`](PagedDirectMap::values_mut).
1512    ValuesMut<'a, K, V, PAGE, D>,
1513    IterMut<'a, K, V, PAGE, D>,
1514    &'a mut V,
1515    |(_, value)| value
1516);
1517
1518entry_iterator!(
1519    /// Owning iterator over the keys of a [`PagedDirectMap`], from
1520    /// [`into_keys`](PagedDirectMap::into_keys).
1521    IntoKeys<K, V, PAGE, D>,
1522    IntoIter<K, V, PAGE, D>,
1523    K,
1524    |(key, _)| key
1525);
1526
1527entry_iterator!(
1528    /// Owning iterator over the values of a [`PagedDirectMap`], from
1529    /// [`into_values`](PagedDirectMap::into_values).
1530    IntoValues<K, V, PAGE, D>,
1531    IntoIter<K, V, PAGE, D>,
1532    V,
1533    |(_, value)| value
1534);
1535
1536impl<K: DirectKey, V, const PAGE: usize, D: Directory> Clone for Iter<'_, K, V, PAGE, D> {
1537    fn clone(&self) -> Self {
1538        Self(self.0.clone())
1539    }
1540}
1541
1542impl<K: DirectKey, V, const PAGE: usize, D: Directory> Clone for Keys<'_, K, V, PAGE, D> {
1543    fn clone(&self) -> Self {
1544        Self(self.0.clone())
1545    }
1546}
1547
1548impl<K: DirectKey, V, const PAGE: usize, D: Directory> Clone for Values<'_, K, V, PAGE, D> {
1549    fn clone(&self) -> Self {
1550        Self(self.0.clone())
1551    }
1552}
1553
1554#[cfg(feature = "rayon")]
1555pub use rayon_impl::{ParIter, ParIterMut};
1556
1557#[cfg(feature = "rayon")]
1558mod rayon_impl {
1559    use super::*;
1560    use rayon::iter::plumbing::UnindexedConsumer;
1561    use rayon::prelude::*;
1562
1563    /// Unindexed parallel iterator over the entries of a [`PagedDirectMap`].
1564    pub struct ParIter<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE>(
1565        Vec<(usize, &'a [Slot<K, V>; PAGE])>,
1566    );
1567
1568    /// Unindexed parallel iterator over the entries of a [`PagedDirectMap`], with mutable values.
1569    pub struct ParIterMut<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE>(
1570        Vec<(usize, &'a mut [Slot<K, V>; PAGE])>,
1571    );
1572
1573    impl<'a, K: DirectKey + Send, V: Sync, const PAGE: usize, D: Directory> IntoParallelIterator
1574        for &'a PagedDirectMap<K, V, PAGE, D>
1575    where
1576        K::Tag: Sync,
1577        Store<K, V, PAGE, D>: Sync,
1578    {
1579        type Item = (K, &'a V);
1580        type Iter = ParIter<'a, K, V, PAGE>;
1581
1582        fn into_par_iter(self) -> Self::Iter {
1583            ParIter(self.pages.pages().collect())
1584        }
1585    }
1586
1587    impl<'a, K: DirectKey + Send, V: Send, const PAGE: usize, D: Directory> IntoParallelIterator
1588        for &'a mut PagedDirectMap<K, V, PAGE, D>
1589    where
1590        K::Tag: Send,
1591    {
1592        type Item = (K, &'a mut V);
1593        type Iter = ParIterMut<'a, K, V, PAGE>;
1594
1595        fn into_par_iter(self) -> Self::Iter {
1596            ParIterMut(self.pages.pages_mut().collect())
1597        }
1598    }
1599
1600    impl<'a, K: DirectKey + Send, V: Sync, const PAGE: usize> ParallelIterator
1601        for ParIter<'a, K, V, PAGE>
1602    where
1603        K::Tag: Sync,
1604    {
1605        type Item = (K, &'a V);
1606
1607        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
1608            self.0
1609                .into_par_iter()
1610                .flat_map_iter(|page| {
1611                    page.slots()
1612                        .filter_map(|(index, slot)| SlotEntry::<K>::entry(slot, index))
1613                })
1614                .drive_unindexed(consumer)
1615        }
1616    }
1617
1618    impl<'a, K: DirectKey + Send, V: Send, const PAGE: usize> ParallelIterator
1619        for ParIterMut<'a, K, V, PAGE>
1620    where
1621        K::Tag: Send,
1622    {
1623        type Item = (K, &'a mut V);
1624
1625        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
1626            self.0
1627                .into_par_iter()
1628                .flat_map_iter(|page| {
1629                    page.slots()
1630                        .filter_map(|(index, slot)| SlotEntry::<K>::entry(slot, index))
1631                })
1632                .drive_unindexed(consumer)
1633        }
1634    }
1635}
1636
1637#[cfg(feature = "serde")]
1638mod serde_impl {
1639    use super::*;
1640    use core::marker::PhantomData;
1641    use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
1642    use serde::ser::{Serialize, Serializer};
1643
1644    /// Serializes as a map from keys to values, in slot-index order.
1645    impl<K: DirectKey + Serialize, V: Serialize, const PAGE: usize, D: Directory> Serialize
1646        for PagedDirectMap<K, V, PAGE, D>
1647    {
1648        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1649            serializer.collect_map(self.iter())
1650        }
1651    }
1652
1653    /// Deserializes from a map. Entries are inserted in input order with
1654    /// [`insert`](PagedDirectMap::insert), so a later entry overwrites an
1655    /// earlier one in the same slot.
1656    ///
1657    /// Memory follows the key indices, not the input length: one key can
1658    /// allocate a page, and with [`Flat`] a directory up to that page. For
1659    /// untrusted input, use [`Radix`](crate::page::Radix) or
1660    /// [`Tree`](crate::page::Tree), or validate the keys first.
1661    impl<'de, K, V, const PAGE: usize, D> Deserialize<'de> for PagedDirectMap<K, V, PAGE, D>
1662    where
1663        K: DirectKey + Deserialize<'de>,
1664        V: Deserialize<'de>,
1665        D: Directory,
1666    {
1667        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1668            struct MapVisitor<K, V, const PAGE: usize, D>(PhantomData<(K, V, D)>);
1669
1670            impl<'de, K, V, const PAGE: usize, D> Visitor<'de> for MapVisitor<K, V, PAGE, D>
1671            where
1672                K: DirectKey + Deserialize<'de>,
1673                V: Deserialize<'de>,
1674                D: Directory,
1675            {
1676                type Value = PagedDirectMap<K, V, PAGE, D>;
1677
1678                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1679                    f.write_str("a map of keys to values")
1680                }
1681
1682                fn visit_map<A: MapAccess<'de>>(
1683                    self,
1684                    mut access: A,
1685                ) -> Result<Self::Value, A::Error> {
1686                    let mut map = PagedDirectMap::new();
1687                    while let Some((key, value)) = access.next_entry()? {
1688                        map.insert(key, value);
1689                    }
1690                    Ok(map)
1691                }
1692            }
1693
1694            deserializer.deserialize_map(MapVisitor::<K, V, PAGE, D>(PhantomData))
1695        }
1696    }
1697}
1698
1699/// A view into one key's place in a [`PagedDirectMap`], from
1700/// [`entry`](PagedDirectMap::entry).
1701pub enum Entry<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1702    /// The key is in the map.
1703    Occupied(OccupiedEntry<'a, K, V>),
1704    /// The key is not in the map; its slot is empty or held by another
1705    /// generation of the key.
1706    Vacant(VacantEntry<'a, K, V, PAGE, D>),
1707}
1708
1709/// An [`Entry`] for a key that is in the map.
1710pub struct OccupiedEntry<'a, K: DirectKey, V> {
1711    // Invariant: `*slot` is `Some`, `key` is the stored key (rebuilt from the
1712    // slot's index and tag), and `len` is the map's entry count.
1713    key: K,
1714    slot: &'a mut Slot<K, V>,
1715    len: &'a mut usize,
1716}
1717
1718/// An [`Entry`] for a key that is not in the map.
1719pub struct VacantEntry<'a, K: DirectKey, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1720    map: &'a mut PagedDirectMap<K, V, PAGE, D>,
1721    key: K,
1722}
1723
1724impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> Entry<'a, K, V, PAGE, D> {
1725    /// The entry's key: the stored key if occupied, else the key given to
1726    /// [`entry`](PagedDirectMap::entry).
1727    #[inline]
1728    pub fn key(&self) -> &K {
1729        match self {
1730            Entry::Occupied(entry) => entry.key(),
1731            Entry::Vacant(entry) => entry.key(),
1732        }
1733    }
1734
1735    /// The value, inserting `default` first if the key is absent (evicting
1736    /// another generation in its slot).
1737    #[inline]
1738    pub fn or_insert(self, default: V) -> &'a mut V {
1739        match self {
1740            Entry::Occupied(entry) => entry.into_mut(),
1741            Entry::Vacant(entry) => entry.insert(default),
1742        }
1743    }
1744
1745    /// The value, inserting `make()` first if the key is absent. `make` runs
1746    /// before the map changes, so if it panics the map is unchanged.
1747    #[inline]
1748    pub fn or_insert_with(self, make: impl FnOnce() -> V) -> &'a mut V {
1749        match self {
1750            Entry::Occupied(entry) => entry.into_mut(),
1751            Entry::Vacant(entry) => entry.insert(make()),
1752        }
1753    }
1754
1755    /// Like [`or_insert_with`](Self::or_insert_with), but `make` is given the
1756    /// key.
1757    #[inline]
1758    pub fn or_insert_with_key(self, make: impl FnOnce(&K) -> V) -> &'a mut V {
1759        match self {
1760            Entry::Occupied(entry) => entry.into_mut(),
1761            Entry::Vacant(entry) => {
1762                let value = make(&entry.key);
1763                entry.insert(value)
1764            }
1765        }
1766    }
1767
1768    /// The value, inserting `V::default()` first if the key is absent.
1769    #[inline]
1770    pub fn or_default(self) -> &'a mut V
1771    where
1772        V: Default,
1773    {
1774        self.or_insert_with(V::default)
1775    }
1776
1777    /// Calls `f` on the value if the key is present, and returns the entry.
1778    #[inline]
1779    pub fn and_modify(mut self, f: impl FnOnce(&mut V)) -> Self {
1780        if let Entry::Occupied(entry) = &mut self {
1781            f(entry.get_mut());
1782        }
1783        self
1784    }
1785
1786    /// Stores `value` for the key and returns the occupied entry. An occupied
1787    /// entry keeps its stored key; a vacant one evicts any other generation.
1788    #[inline]
1789    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
1790        match self {
1791            Entry::Occupied(mut entry) => {
1792                entry.insert(value);
1793                entry
1794            }
1795            Entry::Vacant(entry) => entry.insert_entry(value),
1796        }
1797    }
1798}
1799
1800impl<'a, K: DirectKey, V> OccupiedEntry<'a, K, V> {
1801    #[inline]
1802    fn pair(&self) -> &(K::Tag, V) {
1803        match &*self.slot {
1804            Some(pair) => pair,
1805            None => unreachable!("an occupied entry's slot is full"),
1806        }
1807    }
1808
1809    #[inline]
1810    fn pair_mut(&mut self) -> &mut (K::Tag, V) {
1811        match &mut *self.slot {
1812            Some(pair) => pair,
1813            None => unreachable!("an occupied entry's slot is full"),
1814        }
1815    }
1816
1817    /// The stored key.
1818    #[inline]
1819    pub fn key(&self) -> &K {
1820        &self.key
1821    }
1822
1823    /// The value.
1824    #[inline]
1825    pub fn get(&self) -> &V {
1826        &self.pair().1
1827    }
1828
1829    /// Mutable access to the value.
1830    #[inline]
1831    pub fn get_mut(&mut self) -> &mut V {
1832        &mut self.pair_mut().1
1833    }
1834
1835    /// Mutable access to the value, for the lifetime of the map borrow.
1836    #[inline]
1837    pub fn into_mut(self) -> &'a mut V {
1838        match self.slot {
1839            Some((_, value)) => value,
1840            None => unreachable!("an occupied entry's slot is full"),
1841        }
1842    }
1843
1844    /// Replaces the value and returns the old one; the stored key is kept.
1845    #[inline]
1846    pub fn insert(&mut self, value: V) -> V {
1847        mem::replace(self.get_mut(), value)
1848    }
1849
1850    /// Removes the entry and returns its value.
1851    #[inline]
1852    pub fn remove(self) -> V {
1853        self.remove_entry().1
1854    }
1855
1856    /// Removes the entry and returns the stored key and its value.
1857    pub fn remove_entry(self) -> (K, V) {
1858        match self.slot.take() {
1859            Some((_, value)) => {
1860                *self.len -= 1;
1861                (self.key, value)
1862            }
1863            None => unreachable!("an occupied entry's slot is full"),
1864        }
1865    }
1866}
1867
1868impl<'a, K: DirectKey, V, const PAGE: usize, D: Directory> VacantEntry<'a, K, V, PAGE, D> {
1869    /// The key given to [`entry`](PagedDirectMap::entry).
1870    #[inline]
1871    pub fn key(&self) -> &K {
1872        &self.key
1873    }
1874
1875    /// Gives the key back.
1876    #[inline]
1877    pub fn into_key(self) -> K {
1878        self.key
1879    }
1880
1881    /// The entry of another generation holding the key's slot, which an
1882    /// insert would evict.
1883    #[inline]
1884    pub fn occupant(&self) -> Option<(K, &V)> {
1885        self.map.occupant(self.key.index())
1886    }
1887
1888    /// Stores `value` for the key and returns it, evicting (and dropping)
1889    /// any other generation in the slot.
1890    ///
1891    /// # Panics
1892    ///
1893    /// As [`PagedDirectMap::insert`]. If an evicted value's `drop` panics,
1894    /// the new entry is already in place.
1895    #[inline]
1896    pub fn insert(self, value: V) -> &'a mut V {
1897        self.insert_entry(value).into_mut()
1898    }
1899
1900    /// Like [`insert`](Self::insert), but returns the occupied entry.
1901    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
1902        let VacantEntry { map, key } = self;
1903        let (slot, len) = map.slot_or_alloc(key.index());
1904        if slot.is_none() {
1905            *len += 1;
1906        }
1907        // Drop an evicted entry only once the slot is consistent: `V::drop`
1908        // may panic.
1909        drop(slot.replace((key.tag(), value)));
1910        OccupiedEntry { key, slot, len }
1911    }
1912}
1913
1914impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1915    for Entry<'_, K, V, PAGE, D>
1916{
1917    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1918        match self {
1919            Entry::Occupied(entry) => f.debug_tuple("Occupied").field(entry).finish(),
1920            Entry::Vacant(entry) => f.debug_tuple("Vacant").field(entry).finish(),
1921        }
1922    }
1923}
1924
1925impl<K: DirectKey + fmt::Debug, V: fmt::Debug> fmt::Debug for OccupiedEntry<'_, K, V> {
1926    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1927        f.debug_struct("OccupiedEntry")
1928            .field("key", self.key())
1929            .field("value", self.get())
1930            .finish()
1931    }
1932}
1933
1934impl<K: DirectKey + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1935    for VacantEntry<'_, K, V, PAGE, D>
1936{
1937    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1938        f.debug_struct("VacantEntry")
1939            .field("key", &self.key)
1940            .field("occupant", &self.occupant())
1941            .finish()
1942    }
1943}
1944
1945// The tests use `u32` keys, which implement `Key` only on 32- and 64-bit
1946// targets.
1947#[cfg(all(test, any(target_pointer_width = "32", target_pointer_width = "64")))]
1948mod tests {
1949    use super::*;
1950    use crate::page::Tree;
1951    use alloc::vec;
1952
1953    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
1954    struct Gen(u32);
1955
1956    impl Key for Gen {
1957        fn index(self) -> usize {
1958            (self.0 & 0xffff) as usize
1959        }
1960    }
1961
1962    impl DirectKey for Gen {
1963        type Tag = u16;
1964        fn tag(self) -> u16 {
1965            (self.0 >> 16) as u16
1966        }
1967        fn from_parts(index: usize, tag: u16) -> Self {
1968            Gen(index as u32 | u32::from(tag) << 16)
1969        }
1970    }
1971
1972    fn entries<K: DirectKey, V: Clone, const PAGE: usize, D: Directory>(
1973        map: &PagedDirectMap<K, V, PAGE, D>,
1974    ) -> Vec<(K, V)> {
1975        map.iter().map(|(k, v)| (k, v.clone())).collect()
1976    }
1977
1978    #[test]
1979    fn iterates_in_key_order_from_both_ends() {
1980        let map: PagedDirectMap<u32, u32, 4> =
1981            [(9, 90), (1, 10), (40, 400), (2, 20)].into_iter().collect();
1982        assert_eq!(map.len(), 4);
1983        assert_eq!(map.allocated_pages(), 3);
1984        assert_eq!(entries(&map), [(1, 10), (2, 20), (9, 90), (40, 400)]);
1985        let back: Vec<u32> = map.keys().rev().collect();
1986        assert_eq!(back, [40, 9, 2, 1]);
1987
1988        // Meeting in the middle yields each entry once.
1989        let mut it = map.iter();
1990        assert_eq!(it.len(), 4);
1991        assert_eq!(it.next(), Some((1, &10)));
1992        assert_eq!(it.next_back(), Some((40, &400)));
1993        assert_eq!(it.next_back(), Some((9, &90)));
1994        assert_eq!(it.next(), Some((2, &20)));
1995        assert_eq!(it.next(), None);
1996        assert_eq!(it.next_back(), None);
1997
1998        let owned: Vec<(u32, u32)> = map.clone().into_iter().rev().collect();
1999        assert_eq!(owned, [(40, 400), (9, 90), (2, 20), (1, 10)]);
2000        let values: Vec<u32> = map.into_values().collect();
2001        assert_eq!(values, [10, 20, 90, 400]);
2002    }
2003
2004    #[test]
2005    fn same_order_with_tree_directory() {
2006        let keys = [u32::MAX - 1, 5, 1 << 31, 6];
2007        let map: PagedDirectMap<u32, (), 1024, Tree> = keys.iter().map(|&k| (k, ())).collect();
2008        let got: Vec<u32> = map.keys().collect();
2009        assert_eq!(got, [5, 6, 1 << 31, u32::MAX - 1]);
2010        assert_eq!(map.allocated_pages(), 3);
2011    }
2012
2013    #[test]
2014    fn generations_compete_for_one_slot() {
2015        let mut map: PagedDirectMap<Gen, &str> = PagedDirectMap::new();
2016        let old = Gen(3);
2017        let new = Gen(3 | 1 << 16);
2018        assert_eq!(map.insert(old, "old"), None);
2019        assert_eq!(map.try_insert(new, "x"), Err("x"));
2020        assert_eq!(map.get(new), None);
2021        assert_eq!(map.occupant(3), Some((old, &"old")));
2022        // `insert` evicts the other generation.
2023        assert_eq!(map.insert(new, "new"), Some("old"));
2024        assert_eq!(map.get(old), None);
2025        assert_eq!(map.get(new), Some(&"new"));
2026        assert_eq!(map.len(), 1);
2027        // `replace` returns the evicted key too.
2028        assert_eq!(map.replace(old, "back"), Some((new, "new")));
2029        assert_eq!(map.remove(new), None);
2030        assert_eq!(map.remove_occupant(3), Some((old, "back")));
2031        assert!(map.is_empty());
2032    }
2033
2034    #[test]
2035    fn entry_occupied_and_vacant() {
2036        let mut map: PagedDirectMap<u32, i32> = PagedDirectMap::new();
2037        assert!(matches!(map.entry(9), Entry::Vacant(_)));
2038        assert_eq!(map.allocated_pages(), 0, "a vacant entry allocates nothing");
2039        *map.entry(9).or_insert(1) += 10;
2040        map.entry(9).and_modify(|v| *v *= 2).or_insert(-1);
2041        assert_eq!(map.get(9), Some(&22));
2042        assert_eq!(*map.entry(70_000).or_default(), 0);
2043        assert_eq!(*map.entry(5).or_insert_with_key(|&k| k as i32), 5);
2044        assert_eq!(map.len(), 3);
2045        match map.entry(9) {
2046            Entry::Occupied(mut e) => {
2047                assert_eq!((e.key(), e.get()), (&9, &22));
2048                assert_eq!(e.insert(4), 22);
2049                assert_eq!(e.remove_entry(), (9, 4));
2050            }
2051            Entry::Vacant(_) => panic!("9 is present"),
2052        }
2053        assert_eq!(map.len(), 2);
2054        assert_eq!(map.get(9), None);
2055        let e = map.entry(9).insert_entry(8);
2056        assert_eq!(e.remove(), 8);
2057        assert_eq!(entries(&map), [(5, 5), (70_000, 0)]);
2058    }
2059
2060    #[test]
2061    fn entry_treats_another_generation_as_vacant_and_evicts_it() {
2062        let mut map: PagedDirectMap<Gen, &str, 4, Tree> = PagedDirectMap::new();
2063        let (old, new) = (Gen(3), Gen(3 | 1 << 16));
2064        map.insert(old, "old");
2065        match map.entry(new) {
2066            Entry::Vacant(e) => {
2067                assert_eq!(e.occupant(), Some((old, &"old")));
2068                assert_eq!(*e.insert("new"), "new");
2069            }
2070            Entry::Occupied(_) => panic!("only `old` is present"),
2071        }
2072        assert_eq!(map.len(), 1);
2073        assert_eq!(entries(&map), [(new, "new")]);
2074        // An occupied entry keeps its stored key.
2075        assert_eq!(*map.entry(new).or_insert("x"), "new");
2076    }
2077
2078    #[cfg(feature = "std")]
2079    #[test]
2080    fn entry_or_insert_with_panic_leaves_map_unchanged() {
2081        let mut map: PagedDirectMap<u32, i32> = PagedDirectMap::new();
2082        let result = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
2083            map.entry(3).or_insert_with(|| panic!("make"));
2084        }));
2085        assert!(result.is_err());
2086        assert!(map.is_empty());
2087        assert_eq!(map.allocated_pages(), 0);
2088    }
2089
2090    #[test]
2091    fn get_or_insert_with_runs_make_only_when_absent() {
2092        let mut map: PagedDirectMap<u32, i32> = PagedDirectMap::new();
2093        *map.get_or_insert_with(4, || 1) += 10;
2094        *map.get_or_insert_with(4, || panic!("present")) += 100;
2095        assert_eq!(map[4], 111);
2096        assert_eq!(map.len(), 1);
2097    }
2098
2099    #[test]
2100    fn retain_clear_shrink_and_reset() {
2101        let mut map: PagedDirectMap<u32, u32, 4> = (0..12).map(|k| (k, k)).collect();
2102        map.retain(|&k, v| {
2103            *v *= 2;
2104            !(4..8).contains(&k)
2105        });
2106        assert_eq!(map.len(), 8);
2107        assert_eq!(map.get(9), Some(&18));
2108        assert_eq!(map.allocated_pages(), 3);
2109        map.shrink_to_fit();
2110        assert_eq!(map.allocated_pages(), 2);
2111        assert_eq!(map.get(9), Some(&18));
2112
2113        map.clear();
2114        assert!(map.is_empty());
2115        assert_eq!(map.iter().next(), None);
2116        assert_eq!(map.allocated_pages(), 2);
2117        map.reset();
2118        assert_eq!(map.allocated_pages(), 0);
2119    }
2120
2121    fn ordered_queries<D: Directory>() {
2122        let keys = [1_u32, 2, 9, 40, 41, 43];
2123        let mut map: PagedDirectMap<u32, u32, 4, D> = keys.iter().map(|&k| (k, k * 10)).collect();
2124        // Leave an allocated page with no entry in the middle.
2125        map.insert(20, 0);
2126        map.remove(20);
2127        let range = |r: (Bound<u32>, Bound<u32>)| -> Vec<u32> {
2128            let got: Vec<u32> = map.range(r).map(|(k, _)| k).collect();
2129            let mut back: Vec<u32> = map.range(r).rev().map(|(k, _)| k).collect();
2130            back.reverse();
2131            assert_eq!(got, back);
2132            got
2133        };
2134        use Bound::{Excluded as Ex, Included as In, Unbounded as Un};
2135        assert_eq!(range((Un, Un)), keys);
2136        assert_eq!(range((In(2), Ex(41))), [2, 9, 40]);
2137        assert_eq!(range((Ex(2), In(41))), [9, 40, 41]);
2138        assert_eq!(range((In(3), In(8))), [0_u32; 0]);
2139        assert_eq!(range((In(9), In(9))), [9]);
2140        assert_eq!(range((In(42), Un)), [43]);
2141        assert_eq!(range((In(44), Un)), [0_u32; 0]);
2142        assert_eq!(range((In(41), In(2))), [0_u32; 0]);
2143        assert_eq!(range((Ex(u32::MAX), Un)), [0_u32; 0]);
2144        assert_eq!(range((Un, Ex(0))), [0_u32; 0]);
2145        assert_eq!(map.slot_range(..).count(), keys.len());
2146        assert_eq!(map.slot_range((Ex(usize::MAX), Un)).next(), None);
2147        assert_eq!(map.slot_range(usize::MAX..).next(), None);
2148
2149        // Both ends meet inside one page without repeating an entry.
2150        {
2151            let mut it = map.range(40..=43);
2152            assert_eq!(it.size_hint(), (0, Some(4)));
2153            assert_eq!(it.next(), Some((40, &400)));
2154            assert_eq!(it.next_back(), Some((43, &430)));
2155            assert_eq!(it.clone().next_back(), Some((41, &410)));
2156            assert_eq!(it.next(), Some((41, &410)));
2157            assert_eq!(it.next(), None);
2158            assert_eq!(it.next_back(), None);
2159        }
2160
2161        assert_eq!(map.next_occupant(0), Some((1, &10)));
2162        assert_eq!(map.next_occupant(9), Some((9, &90)));
2163        assert_eq!(map.next_occupant(10), Some((40, &400)));
2164        assert_eq!(map.next_occupant(44), None);
2165        assert_eq!(map.prev_occupant(0), None);
2166        assert_eq!(map.prev_occupant(39), Some((9, &90)));
2167        assert_eq!(map.prev_occupant(usize::MAX), Some((43, &430)));
2168        assert_eq!(map.first_key_value(), Some((1, &10)));
2169        assert_eq!(map.last_key_value(), Some((43, &430)));
2170
2171        for (_, value) in map.range_mut(2..41) {
2172            *value += 1;
2173        }
2174        assert_eq!(
2175            entries(&map),
2176            [(1, 10), (2, 21), (9, 91), (40, 401), (41, 410), (43, 430)]
2177        );
2178        assert_eq!(map.slot_range_mut(40..).next_back(), Some((43, &mut 430)));
2179
2180        assert_eq!(map.pop_first(), Some((1, 10)));
2181        assert_eq!(map.pop_last(), Some((43, 430)));
2182        assert_eq!(map.len(), 4);
2183        assert_eq!(map.first_key_value(), Some((2, &21)));
2184        map.clear();
2185        assert_eq!(map.pop_first(), None);
2186        assert_eq!(map.pop_last(), None);
2187        assert_eq!(map.next_occupant(0), None);
2188        assert_eq!(map.range(..).next(), None);
2189    }
2190
2191    #[test]
2192    fn ordered_queries_with_both_directories() {
2193        ordered_queries::<Flat>();
2194        ordered_queries::<Tree>();
2195    }
2196
2197    #[test]
2198    fn a_range_bounds_generational_keys_by_index() {
2199        let mut map: PagedDirectMap<Gen, u8> = PagedDirectMap::new();
2200        let held = Gen(3 | 2 << 16);
2201        map.insert(held, 1);
2202        map.insert(Gen(7), 2);
2203        let other = Gen(3);
2204        assert_eq!(map.range(other..=other).next(), Some((held, &1)));
2205        assert_eq!(map.range(Gen(4 | 9 << 16)..).next(), Some((Gen(7), &2)));
2206    }
2207
2208    #[cfg(feature = "std")]
2209    #[test]
2210    fn eq_and_hash_ignore_pages() {
2211        use core::hash::BuildHasher;
2212        let a: PagedDirectMap<u32, u8, 4> = [(1, 1), (9, 9)].into_iter().collect();
2213        let mut b: PagedDirectMap<u32, u8, 4> = [(9, 9), (5, 5), (1, 1)].into_iter().collect();
2214        assert_ne!(a, b);
2215        b.remove(5);
2216        assert_eq!(a, b);
2217        let s = std::hash::RandomState::new();
2218        assert_eq!(s.hash_one(&a), s.hash_one(&b));
2219        assert_eq!(vec![(1, 1), (9, 9)], entries(&b));
2220    }
2221
2222    #[cfg(feature = "serde")]
2223    #[test]
2224    fn serde_round_trip() {
2225        let map: PagedDirectMap<u32, u8> = [(70_000, 7), (2, 2)].into_iter().collect();
2226        let json = serde_json::to_string(&map).unwrap();
2227        assert_eq!(json, r#"{"2":2,"70000":7}"#);
2228        let back: PagedDirectMap<u32, u8> = serde_json::from_str(&json).unwrap();
2229        assert_eq!(back, map);
2230    }
2231}