Skip to main content

paged_collections/
sparse_map.rs

1//! [`PagedSparseMap`]: a paged sparse set that stores one value per key.
2//!
3//! The map is a [`PagedSparseSet`] of keys plus a dense array of values kept
4//! parallel to the dense keys: the value at position `i` belongs to the key at
5//! position `i`. Both arrays are contiguous, so keys and values can be
6//! iterated, or handed out as slices, without touching the sparse index.
7//!
8//! | Operation | Cost |
9//! |---|---|
10//! | [`get`](PagedSparseMap::get), [`remove`](PagedSparseMap::remove) | O(1) (O(depth) with [`Radix`](crate::page::Radix), O(log pages) with [`Tree`](crate::page::Tree)) |
11//! | [`insert`](PagedSparseMap::insert) | as `get`, amortized over dense-array growth; the first key in a page also allocates the page (and, with [`Flat`], grows the directory up to it) |
12//! | [`clear`](PagedSparseMap::clear) | O(1) for the index, plus dropping the values |
13//! | iteration, [`value_slice`](PagedSparseMap::value_slice) | over the dense arrays only |
14//! | [`range`](PagedSparseMap::range), [`first_key_value`](PagedSparseMap::first_key_value), [`next_occupant`](PagedSparseMap::next_occupant), ... | in slot-index order, over the sparse pages and slots in the range (stale slots included) |
15//! | sorting | O(n log n) comparisons, O(n) swaps, then one index write per entry; allocates `n` indices |
16//! | [`binary_search_key`](PagedSparseMap::binary_search_key), [`binary_search_by`](PagedSparseMap::binary_search_by), [`partition_point`](PagedSparseMap::partition_point) | O(log n), on entries the caller keeps sorted |
17//!
18//! # Slots and generational keys
19//!
20//! Like the set, the map holds at most one key per slot index (see
21//! [`crate::key`]). With plain integer keys the map behaves like `HashMap`.
22//! With generational keys the methods differ in what they do when the slot is
23//! held by a *different* key:
24//!
25//! | Method | Slot held by another key |
26//! |---|---|
27//! | [`insert`](PagedSparseMap::insert), [`get_or_insert_with`](PagedSparseMap::get_or_insert_with) | evicts it |
28//! | [`entry`](PagedSparseMap::entry) | reports a vacant entry. Inserting through it evicts the other key |
29//! | [`replace`](PagedSparseMap::replace) | evicts it and returns the evicted entry |
30//! | [`try_insert`](PagedSparseMap::try_insert) | refuses, like [`PagedSparseSet::insert`] |
31//!
32//! `insert` evicts so that, as with `HashMap`, `get(key)` returns the new
33//! value afterwards. An evicted entry keeps its dense position.
34//!
35//! ```
36//! use paged_collections::sparse_map::PagedSparseMap;
37//!
38//! let mut map: PagedSparseMap<u32, &str> = PagedSparseMap::new();
39//! assert_eq!(map.insert(3_000_000, "far"), None);
40//! assert_eq!(map.insert(7, "near"), None);
41//! assert_eq!(map.insert(7, "nearer"), Some("near"));
42//! assert_eq!(map.get(3_000_000), Some(&"far"));
43//! assert_eq!(map.allocated_pages(), 2);
44//!
45//! assert_eq!(map.remove(3_000_000), Some("far"));
46//! assert_eq!(map.key_slice(), &[7]);
47//! assert_eq!(map.value_slice(), &["nearer"]);
48//! ```
49//!
50//! With the `rayon` feature, parallel iterators are indexed and follow
51//! dense order.
52//!
53//! ```rust
54//! # #[cfg(feature = "rayon")] {
55//! use paged_collections::sparse_map::PagedSparseMap;
56//! use rayon::prelude::*;
57//!
58//! let mut map: PagedSparseMap<u32, i32> = [(7, 10), (2, 20)].into_iter().collect();
59//! map.par_iter_mut().for_each(|(&key, value)| *value += key as i32);
60//! assert_eq!(map.par_iter().map(|(&k, &v)| (k, v)).collect::<Vec<_>>(), [(7, 17), (2, 22)]);
61//! assert_eq!(map.par_keys().copied().collect::<Vec<_>>(), [7, 2]);
62//! map.par_values_mut().for_each(|value| *value *= 2);
63//! assert_eq!(map.par_values().copied().collect::<Vec<_>>(), [34, 44]);
64//! # }
65//! ```
66
67use alloc::collections::TryReserveError;
68use alloc::vec::Vec;
69use core::cmp::Ordering;
70use core::fmt;
71use core::hash::{Hash, Hasher};
72use core::iter::{FusedIterator, Zip};
73use core::ops::{Index, RangeBounds};
74use core::slice;
75
76use crate::hash::hash_unordered;
77use crate::key::Key;
78use crate::page::{DEFAULT_PAGE, Directory, Flat};
79use crate::sparse_set::{self, PagedSparseSet, Positions, Slot, index_bounds};
80
81/// A map from [`Key`]s to values with O(1) insert, remove and lookup, and
82/// contiguous arrays of its keys and values.
83///
84/// `PAGE` and `D` are as for [`PagedSparseSet`]: slots per page of the
85/// sparse index, and the page directory ([`Flat`] by default,
86/// [`Radix`](crate::page::Radix) for wide keys, or
87/// [`Tree`](crate::page::Tree)). See [`crate::page`].
88///
89/// Entries are kept in insertion order until a removal, which moves the last
90/// entry into the gap. See the [module docs](self) for how methods treat a
91/// slot held by another generation of a key.
92pub struct PagedSparseMap<K, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
93    // Invariant: `values.len() == keys.len()`, and `values[i]` belongs to
94    // `keys.as_slice()[i]`. Every mutation below keeps it even when a
95    // user-supplied closure, `V::drop` or an allocation panics.
96    keys: PagedSparseSet<K, PAGE, D>,
97    values: Vec<V>,
98}
99
100impl<K: Key, V, const PAGE: usize, D: Directory> PagedSparseMap<K, V, PAGE, D> {
101    /// Number of slots per page of the sparse index.
102    pub const PAGE_SIZE: usize = PAGE;
103
104    /// Creates an empty map. No memory is allocated until the first insert.
105    pub fn new() -> Self {
106        Self {
107            keys: PagedSparseSet::new(),
108            values: Vec::new(),
109        }
110    }
111
112    /// Creates an empty map whose dense arrays can hold `capacity` entries
113    /// without reallocating. Pages are still allocated on demand.
114    pub fn with_capacity(capacity: usize) -> Self {
115        Self {
116            keys: PagedSparseSet::with_capacity(capacity),
117            values: Vec::with_capacity(capacity),
118        }
119    }
120
121    /// Number of entries in the map.
122    #[inline]
123    pub fn len(&self) -> usize {
124        self.values.len()
125    }
126
127    /// Whether the map has no entries.
128    #[inline]
129    pub fn is_empty(&self) -> bool {
130        self.values.is_empty()
131    }
132
133    /// Number of entries the dense arrays can hold without reallocating.
134    #[inline]
135    pub fn capacity(&self) -> usize {
136        self.keys.capacity().min(self.values.capacity())
137    }
138
139    /// Number of allocated pages in the sparse index.
140    #[inline]
141    pub fn allocated_pages(&self) -> usize {
142        self.keys.allocated_pages()
143    }
144
145    /// Reserves room in the dense arrays for at least `additional` more
146    /// entries.
147    pub fn reserve(&mut self, additional: usize) {
148        self.keys.reserve(additional);
149        self.values.reserve(additional);
150    }
151
152    /// Like [`reserve`](Self::reserve), but returns an error instead of
153    /// panicking or aborting when the capacity overflows or the allocation
154    /// fails. On error, one of the arrays may have grown.
155    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
156        self.keys.try_reserve(additional)?;
157        self.values.try_reserve(additional)
158    }
159
160    /// The keys as a set.
161    ///
162    /// Gives read access to the set's lookups, such as
163    /// [`occupant`](PagedSparseSet::occupant).
164    #[inline]
165    pub fn as_set(&self) -> &PagedSparseSet<K, PAGE, D> {
166        &self.keys
167    }
168
169    /// Dense position of `key`, if it is in the map.
170    ///
171    /// Positions index [`key_slice`](Self::key_slice) and
172    /// [`value_slice`](Self::value_slice), and change when entries are removed
173    /// or the map is sorted.
174    #[inline]
175    pub fn position(&self, key: K) -> Option<usize> {
176        self.keys.position(key)
177    }
178
179    /// Whether `key` is in the map.
180    #[inline]
181    pub fn contains_key(&self, key: K) -> bool {
182        self.keys.contains(key)
183    }
184
185    /// The value for `key`, if it is in the map.
186    #[inline]
187    pub fn get(&self, key: K) -> Option<&V> {
188        self.position(key).map(|pos| &self.values[pos])
189    }
190
191    /// Mutable access to the value for `key`, if it is in the map.
192    #[inline]
193    pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
194        self.position(key).map(|pos| &mut self.values[pos])
195    }
196
197    /// The stored key equal to `key` and its value, if it is in the map.
198    #[inline]
199    pub fn get_key_value(&self, key: K) -> Option<(&K, &V)> {
200        self.position(key).map(|pos| self.entry_at(pos))
201    }
202
203    /// The entry occupying slot `index`, if any.
204    ///
205    /// With generational keys this finds whichever generation is present.
206    #[inline]
207    pub fn occupant(&self, index: usize) -> Option<(&K, &V)> {
208        self.keys.occupant_pos(index).map(|pos| self.entry_at(pos))
209    }
210
211    /// The entry occupying slot `index`, with mutable access to its value.
212    #[inline]
213    pub fn occupant_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
214        let pos = self.keys.occupant_pos(index)?;
215        Some((&self.keys.as_slice()[pos], &mut self.values[pos]))
216    }
217
218    #[inline]
219    fn entry_at(&self, pos: usize) -> (&K, &V) {
220        (&self.keys.as_slice()[pos], &self.values[pos])
221    }
222
223    /// Appends an entry whose slot `index` the caller has checked is vacant,
224    /// and returns its dense position.
225    fn push_vacant(&mut self, key: K, index: usize, value: V) -> usize {
226        // Reserve first so the final push cannot fail: if anything before it
227        // panics, neither array has grown.
228        self.values.reserve(1);
229        self.keys.insert_vacant(key, index);
230        self.values.push(value);
231        self.values.len() - 1
232    }
233
234    /// Stores `value` for `key` and returns the value previously in `key`'s
235    /// slot.
236    ///
237    /// If `key` is present its value is replaced and the key is kept. If the
238    /// slot is held by a different key (another generation), that entry is
239    /// evicted and its value returned; use [`replace`](Self::replace) to get
240    /// the evicted key too, or [`try_insert`](Self::try_insert) to refuse.
241    ///
242    /// # Panics
243    ///
244    /// Panics if the map already holds `u32::MAX` entries, or if a page, the
245    /// directory or a dense array cannot be allocated. The entries are then
246    /// unchanged, though capacity or allocated pages may have grown.
247    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
248        let index = key.index();
249        match self.keys.occupant_pos(index) {
250            Some(pos) => {
251                // Keep a stored key that is equal to `key`, as `HashMap` does;
252                // overwrite only another generation.
253                if self.keys.as_slice()[pos] != key {
254                    self.keys.overwrite_at(pos, key);
255                }
256                Some(core::mem::replace(&mut self.values[pos], value))
257            }
258            None => {
259                self.push_vacant(key, index, value);
260                None
261            }
262        }
263    }
264
265    /// Stores `value` for `key` and returns the entry previously in `key`'s
266    /// slot, whether it was `key` itself or another generation.
267    ///
268    /// The new entry, key included, takes the old entry's dense position.
269    /// Unlike [`insert`](Self::insert), this stores `key` even when the old
270    /// key is equal to it.
271    ///
272    /// # Panics
273    ///
274    /// As [`insert`](Self::insert).
275    pub fn replace(&mut self, key: K, value: V) -> Option<(K, V)> {
276        let index = key.index();
277        match self.keys.occupant_pos(index) {
278            Some(pos) => {
279                let old_key = self.keys.overwrite_at(pos, key);
280                let old_value = core::mem::replace(&mut self.values[pos], value);
281                Some((old_key, old_value))
282            }
283            None => {
284                self.push_vacant(key, index, value);
285                None
286            }
287        }
288    }
289
290    /// Adds an entry if `key`'s slot is vacant and returns its value, or
291    /// returns `value` back and leaves the map unchanged if the slot is held
292    /// (by `key` or by another key with the same index).
293    ///
294    /// # Panics
295    ///
296    /// As [`insert`](Self::insert).
297    pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, V> {
298        let index = key.index();
299        if self.keys.occupant_pos(index).is_some() {
300            return Err(value);
301        }
302        let pos = self.push_vacant(key, index, value);
303        Ok(&mut self.values[pos])
304    }
305
306    /// The value for `key`, inserting `make()` first if `key` is absent.
307    ///
308    /// If the slot is held by a different key, that entry is evicted, as by
309    /// [`insert`](Self::insert). `make` runs before the map changes, so if it
310    /// panics the entries are unchanged.
311    ///
312    /// # Panics
313    ///
314    /// As [`insert`](Self::insert).
315    pub fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> &mut V {
316        self.entry(key).or_insert_with(make)
317    }
318
319    /// The entry for `key`, for in-place access or insertion.
320    ///
321    /// [`Entry::Occupied`] holds the exact stored key. If another generation
322    /// holds the slot, this returns [`Entry::Vacant`]. Inserting through it
323    /// evicts that generation and keeps its dense position, as
324    /// [`insert`](Self::insert) does.
325    ///
326    /// # Examples
327    ///
328    /// ```
329    /// use paged_collections::sparse_map::PagedSparseMap;
330    ///
331    /// let mut counts: PagedSparseMap<usize, u32> = PagedSparseMap::new();
332    /// for key in [3, 1, 3, 3] {
333    ///     counts.entry(key).and_modify(|n| *n += 1).or_insert(1);
334    /// }
335    /// assert_eq!((counts[3], counts[1]), (3, 1));
336    /// ```
337    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, PAGE, D> {
338        let index = key.index();
339        let occupant = self.keys.occupant_pos(index);
340        match occupant {
341            Some(pos) if self.keys.as_slice()[pos] == key => {
342                Entry::Occupied(OccupiedEntry { map: self, pos })
343            }
344            _ => Entry::Vacant(VacantEntry {
345                map: self,
346                key,
347                index,
348                occupant,
349            }),
350        }
351    }
352
353    /// Removes the entry at dense position `pos` by moving the last entry
354    /// into its place.
355    fn remove_at(&mut self, pos: usize) -> (K, V) {
356        let key = self.keys.remove_at(pos);
357        let value = self.values.swap_remove(pos);
358        (key, value)
359    }
360
361    /// Removes `key` and returns its value, if it was present.
362    ///
363    /// The last entry moves into the removed entry's position.
364    pub fn remove(&mut self, key: K) -> Option<V> {
365        self.remove_entry(key).map(|(_, value)| value)
366    }
367
368    /// Removes `key` and returns the stored key and its value, if it was
369    /// present.
370    pub fn remove_entry(&mut self, key: K) -> Option<(K, V)> {
371        self.position(key).map(|pos| self.remove_at(pos))
372    }
373
374    /// Removes whichever entry occupies slot `index` and returns it.
375    pub fn remove_occupant(&mut self, index: usize) -> Option<(K, V)> {
376        self.keys.occupant_pos(index).map(|pos| self.remove_at(pos))
377    }
378
379    /// Keeps only the entries for which `keep` returns `true`.
380    ///
381    /// `keep` is called once per entry. Kept entries may change position. If
382    /// `keep` or a value's `drop` panics, the entries not yet visited are
383    /// kept and the map stays consistent.
384    pub fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) {
385        let mut pos = 0;
386        while pos < self.values.len() {
387            let key = self.keys.as_slice()[pos];
388            if keep(&key, &mut self.values[pos]) {
389                pos += 1;
390            } else {
391                // The entry moved into `pos` has not been visited yet. The
392                // removed value drops at the end of this statement, after
393                // both arrays are updated.
394                self.remove_at(pos);
395            }
396        }
397    }
398
399    /// Removes every entry. The sparse index is cleared in O(1); the values
400    /// are dropped.
401    ///
402    /// Pages stay allocated for reuse; use [`reset`](Self::reset) to free
403    /// them.
404    pub fn clear(&mut self) {
405        // Keys first: `values.clear()` runs `V::drop`, which may panic, and
406        // `Vec::clear` sets the length to zero before dropping.
407        self.keys.clear();
408        self.values.clear();
409    }
410
411    /// Removes every entry and frees every page. The dense arrays keep their
412    /// capacity.
413    pub fn reset(&mut self) {
414        // Empty both dense arrays before freeing pages, so a panic in
415        // `V::drop` or in the page store cannot leave them out of step.
416        self.keys.clear();
417        self.values.clear();
418        self.keys.free_pages();
419    }
420
421    /// Shrinks the dense arrays and the page directory. Frees every page if
422    /// the map is empty.
423    pub fn shrink_to_fit(&mut self) {
424        self.keys.shrink_to_fit();
425        self.values.shrink_to_fit();
426    }
427
428    /// The keys as a slice, in dense order.
429    #[inline]
430    pub fn key_slice(&self) -> &[K] {
431        self.keys.as_slice()
432    }
433
434    /// The values as a slice, in dense order: `value_slice()[i]` belongs to
435    /// `key_slice()[i]`.
436    #[inline]
437    pub fn value_slice(&self) -> &[V] {
438        &self.values
439    }
440
441    /// The values as a mutable slice, in dense order.
442    #[inline]
443    pub fn value_slice_mut(&mut self) -> &mut [V] {
444        &mut self.values
445    }
446
447    /// Iterates over the keys in dense order.
448    #[inline]
449    pub fn keys(&self) -> slice::Iter<'_, K> {
450        self.keys.iter()
451    }
452
453    /// Iterates over the values in dense order.
454    #[inline]
455    pub fn values(&self) -> slice::Iter<'_, V> {
456        self.values.iter()
457    }
458
459    /// Iterates mutably over the values in dense order.
460    #[inline]
461    pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
462        self.values.iter_mut()
463    }
464
465    /// Iterates over the entries in dense order.
466    #[inline]
467    pub fn iter(&self) -> Iter<'_, K, V> {
468        Iter(self.keys.iter().zip(self.values.iter()))
469    }
470
471    /// Iterates over the entries in dense order, with mutable access to the
472    /// values.
473    #[inline]
474    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
475        IterMut(self.keys.iter().zip(self.values.iter_mut()))
476    }
477
478    /// Removes every entry and returns them in dense order.
479    ///
480    /// The map is empty as soon as this returns, even if the iterator is
481    /// leaked; dropping it drops the entries not yet yielded. Pages and the
482    /// dense arrays' capacity are kept, as with [`clear`](Self::clear).
483    ///
484    /// ```
485    /// use paged_collections::sparse_map::PagedSparseMap;
486    ///
487    /// let mut map: PagedSparseMap<u32, char> = [(5, 'a'), (1, 'b')].into_iter().collect();
488    /// assert_eq!(map.drain().collect::<Vec<_>>(), [(5, 'a'), (1, 'b')]);
489    /// assert!(map.is_empty() && map.get(5).is_none());
490    /// ```
491    pub fn drain(&mut self) -> Drain<'_, K, V> {
492        Drain(self.keys.drain().zip(self.values.drain(..)))
493    }
494
495    /// Removes the entries for which `pred` returns `true` and yields them.
496    ///
497    /// Each entry is tested exactly once. A removal moves the last entry into
498    /// the gap, so entries are tested in dense order except that a moved
499    /// entry is tested next. Entries not yet tested when the iterator is
500    /// dropped stay in the map; use [`retain`](Self::retain) if the removed
501    /// entries are not needed.
502    ///
503    /// ```
504    /// use paged_collections::sparse_map::PagedSparseMap;
505    ///
506    /// let mut map: PagedSparseMap<u32, u32> = (0..6).map(|k| (k, k * 10)).collect();
507    /// let mut big: Vec<(u32, u32)> = map.extract_if(|_, v| *v >= 30).collect();
508    /// big.sort();
509    /// assert_eq!(big, [(3, 30), (4, 40), (5, 50)]);
510    /// assert_eq!(map.len(), 3);
511    /// ```
512    pub fn extract_if<F: FnMut(&K, &mut V) -> bool>(
513        &mut self,
514        pred: F,
515    ) -> ExtractIf<'_, K, V, F, PAGE, D> {
516        ExtractIf {
517            map: self,
518            pos: 0,
519            pred,
520        }
521    }
522
523    /// The values of several keys at once, mutably: `None` for each key that
524    /// is not in the map. O(N log N) for N keys.
525    ///
526    /// ```
527    /// use paged_collections::sparse_map::PagedSparseMap;
528    ///
529    /// let mut map: PagedSparseMap<u32, u32> = [(1, 10), (2, 20)].into_iter().collect();
530    /// if let [Some(a), Some(b), None] = map.get_disjoint_mut([1, 2, 3]) {
531    ///     core::mem::swap(a, b);
532    /// }
533    /// assert_eq!((map[1], map[2]), (20, 10));
534    /// ```
535    ///
536    /// # Panics
537    ///
538    /// Panics if a key in the map is given twice.
539    pub fn get_disjoint_mut<const N: usize>(&mut self, keys: [K; N]) -> [Option<&mut V>; N] {
540        // The present keys as (dense position, position in `keys`).
541        let mut order = [(0, 0); N];
542        let mut n = 0;
543        for (i, &key) in keys.iter().enumerate() {
544            if let Some(pos) = self.position(key) {
545                order[n] = (pos, i);
546                n += 1;
547            }
548        }
549        let order = &mut order[..n];
550        order.sort_unstable();
551        for pair in order.windows(2) {
552            assert!(
553                pair[0].0 != pair[1].0,
554                "PagedSparseMap::get_disjoint_mut: key at positions {} and {} given twice",
555                pair[0].1,
556                pair[1].1
557            );
558        }
559        // Split each value off the front of what is left: the borrows are
560        // disjoint by construction.
561        let mut out = [const { None }; N];
562        let mut rest: &mut [V] = &mut self.values;
563        let mut start = 0;
564        for &(pos, i) in order.iter() {
565            let (_, tail) = core::mem::take(&mut rest).split_at_mut(pos - start);
566            let (value, tail) = tail
567                .split_first_mut()
568                .expect("positions are inside the dense array");
569            out[i] = Some(value);
570            rest = tail;
571            start = pos + 1;
572        }
573        out
574    }
575
576    /// Iterates over the entries whose slot index lies between the slot
577    /// indices of the bounds, in slot-index order.
578    ///
579    /// The bounds are keys, compared by [`Key::index`]: for plain integer
580    /// keys this is the usual key range, independent of dense order. A
581    /// generational key bounds by its index only. An empty or inverted range
582    /// yields nothing.
583    ///
584    /// This walks the sparse index: it costs O(pages and slots in the
585    /// range), including slots left stale by [`clear`](Self::clear) (which
586    /// [`reset`](Self::reset) frees), not O(entries yielded).
587    ///
588    /// ```
589    /// use paged_collections::sparse_map::PagedSparseMap;
590    ///
591    /// let map: PagedSparseMap<u32, char, 4> =
592    ///     [(9, 'c'), (2, 'a'), (30, 'd'), (5, 'b')].into_iter().collect();
593    /// let keys: Vec<u32> = map.range(3..).map(|(&k, _)| k).collect();
594    /// assert_eq!(keys, [5, 9, 30]);
595    /// assert_eq!(map.first_key_value(), Some((&2, &'a')));
596    /// assert_eq!(map.prev_occupant(8), Some((&5, &'b')));
597    /// ```
598    pub fn range(&self, keys: impl RangeBounds<K>) -> Range<'_, K, V, PAGE, D> {
599        self.range_of(&index_bounds(&keys))
600    }
601
602    fn range_of(&self, indices: &impl RangeBounds<usize>) -> Range<'_, K, V, PAGE, D> {
603        Range {
604            positions: self.keys.positions(indices),
605            values: &self.values,
606        }
607    }
608
609    /// The entry with the smallest slot index. Costs as
610    /// [`range`](Self::range).
611    pub fn first_key_value(&self) -> Option<(&K, &V)> {
612        self.range_of(&..).next()
613    }
614
615    /// The entry with the largest slot index. Costs as
616    /// [`range`](Self::range).
617    pub fn last_key_value(&self) -> Option<(&K, &V)> {
618        self.range_of(&..).next_back()
619    }
620
621    /// The entry at slot `index` or the first one after it.
622    pub fn next_occupant(&self, index: usize) -> Option<(&K, &V)> {
623        self.range_of(&(index..)).next()
624    }
625
626    /// The entry at slot `index` or the last one before it.
627    pub fn prev_occupant(&self, index: usize) -> Option<(&K, &V)> {
628        self.range_of(&(..=index)).next_back()
629    }
630
631    /// Removes and returns the entry with the smallest slot index.
632    pub fn pop_first(&mut self) -> Option<(K, V)> {
633        let pos = self.keys.positions(&..).next()?;
634        Some(self.remove_at(pos))
635    }
636
637    /// Removes and returns the entry with the largest slot index.
638    pub fn pop_last(&mut self) -> Option<(K, V)> {
639        let pos = self.keys.positions(&..).next_back()?;
640        Some(self.remove_at(pos))
641    }
642
643    /// Consumes the map and returns its keys in dense order.
644    pub fn into_keys(self) -> alloc::vec::IntoIter<K> {
645        self.keys.into_iter()
646    }
647
648    /// Consumes the map and returns its values in dense order.
649    pub fn into_values(self) -> alloc::vec::IntoIter<V> {
650        self.values.into_iter()
651    }
652
653    /// Reorders both dense arrays so that the entry at old position
654    /// `perm[i]` moves to position `i`, where `perm` is the identity sorted by
655    /// `order`. Then rewrites the index.
656    ///
657    /// `order` sees the entries before any of them move, so if it panics the
658    /// dense order and the key-value pairing are unchanged.
659    fn reorder_by(&mut self, order: impl FnOnce(&mut [usize], &[K], &[V])) {
660        let mut perm: Vec<usize> = (0..self.len()).collect();
661        order(&mut perm, self.keys.as_slice(), &self.values);
662        let values = &mut self.values;
663        self.keys
664            .reorder_dense(|keys| permute(&mut perm, keys, values));
665    }
666
667    /// Sorts the entries by `compare`, keeping the order of equal entries,
668    /// and updates the index.
669    ///
670    /// If `compare` panics, the dense order and the key-value pairing are
671    /// unchanged (values that `compare` changed through interior mutability
672    /// stay changed).
673    pub fn sort_by(&mut self, mut compare: impl FnMut((&K, &V), (&K, &V)) -> Ordering) {
674        self.reorder_by(|perm, keys, values| {
675            perm.sort_by(|&a, &b| compare((&keys[a], &values[a]), (&keys[b], &values[b])));
676        });
677    }
678
679    /// Sorts the entries by a key function, keeping the order of entries
680    /// with equal sort keys, and updates the index.
681    ///
682    /// `f` may be called more than once per entry. If it panics, the dense
683    /// order and the key-value pairing are unchanged.
684    pub fn sort_by_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
685        self.reorder_by(|perm, keys, values| {
686            perm.sort_by_key(|&i| f(&keys[i], &values[i]));
687        });
688    }
689
690    /// Sorts the entries by a key function that is called at most once per
691    /// entry (not at all when there is nothing to compare), keeping the order of entries with equal sort keys, and updates the
692    /// index. Use it when `f` is expensive.
693    ///
694    /// If `f` panics, the dense order and the key-value pairing are
695    /// unchanged.
696    pub fn sort_by_cached_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
697        self.reorder_by(|perm, keys, values| {
698            perm.sort_by_cached_key(|&i| f(&keys[i], &values[i]));
699        });
700    }
701
702    /// Sorts the entries by key in ascending order, keeping the order of
703    /// entries with equal keys, and updates the index.
704    ///
705    /// Stable, which matters only if equal keys can be told apart; prefer
706    /// [`sort_unstable_keys`](Self::sort_unstable_keys) otherwise.
707    pub fn sort_keys(&mut self)
708    where
709        K: Ord,
710    {
711        self.reorder_by(|perm, keys, _| perm.sort_by_key(|&i| keys[i]));
712    }
713
714    /// Binary searches the dense order for `key`, which must be sorted by
715    /// key in ascending order (as after
716    /// [`sort_unstable_keys`](Self::sort_unstable_keys)).
717    ///
718    /// Returns `Ok` with the dense position of an entry whose key equals
719    /// `key`, or `Err` with the position where such an entry would keep the
720    /// order. If the entries are not sorted the result is unspecified.
721    ///
722    /// For an exact lookup [`position`](Self::position) is O(1); this is for
723    /// the neighbours of a key that may be absent: the entries before the
724    /// returned position have smaller keys, those from it on have keys at
725    /// least as large.
726    pub fn binary_search_key(&self, key: &K) -> Result<usize, usize>
727    where
728        K: Ord,
729    {
730        self.keys.as_slice().binary_search(key)
731    }
732
733    /// Binary searches the dense order with a comparator, as
734    /// `[T]::binary_search_by`: `compare` returns the ordering of an
735    /// entry relative to the target. The entries must be sorted consistently
736    /// with it; otherwise the result is unspecified.
737    pub fn binary_search_by(
738        &self,
739        mut compare: impl FnMut(&K, &V) -> Ordering,
740    ) -> Result<usize, usize> {
741        let (keys, values) = (self.keys.as_slice(), &self.values);
742        // Search the positions: both arrays are indexed by them.
743        let mut size = keys.len();
744        let mut base = 0;
745        while size > 0 {
746            let half = size / 2;
747            let mid = base + half;
748            match compare(&keys[mid], &values[mid]) {
749                Ordering::Less => {
750                    base = mid + 1;
751                    size -= half + 1;
752                }
753                Ordering::Greater => size = half,
754                Ordering::Equal => return Ok(mid),
755            }
756        }
757        Err(base)
758    }
759
760    /// The dense position of the first entry for which `pred` is false,
761    /// assuming the entries are partitioned: `pred` holds for a prefix and
762    /// for nothing after it. As `[T]::partition_point`.
763    pub fn partition_point(&self, mut pred: impl FnMut(&K, &V) -> bool) -> usize {
764        self.binary_search_by(|key, value| {
765            if pred(key, value) {
766                Ordering::Less
767            } else {
768                Ordering::Greater
769            }
770        })
771        .unwrap_or_else(|pos| pos)
772    }
773
774    /// Sorts the entries by `compare` (unstable) and updates the index.
775    ///
776    /// If `compare` panics, the dense order and the key-value pairing are
777    /// unchanged (values that `compare` changed through interior mutability
778    /// stay changed).
779    pub fn sort_unstable_by(&mut self, mut compare: impl FnMut((&K, &V), (&K, &V)) -> Ordering) {
780        self.reorder_by(|perm, keys, values| {
781            perm.sort_unstable_by(|&a, &b| compare((&keys[a], &values[a]), (&keys[b], &values[b])));
782        });
783    }
784
785    /// Sorts the entries by a key function (unstable) and updates the index.
786    ///
787    /// `f` may be called more than once per entry. If it panics, the dense
788    /// order and the key-value pairing are unchanged.
789    pub fn sort_unstable_by_key<T: Ord>(&mut self, mut f: impl FnMut(&K, &V) -> T) {
790        self.reorder_by(|perm, keys, values| {
791            perm.sort_unstable_by_key(|&i| f(&keys[i], &values[i]));
792        });
793    }
794
795    /// Sorts the entries by key in ascending order (unstable) and updates
796    /// the index.
797    pub fn sort_unstable_keys(&mut self)
798    where
799        K: Ord,
800    {
801        self.reorder_by(|perm, keys, _| perm.sort_unstable_by_key(|&i| keys[i]));
802    }
803}
804
805/// Applies `perm` to `keys` and `values` in place: the elements at old
806/// position `perm[i]` end up at position `i`. Uses O(n) swaps and leaves
807/// `perm` as the identity.
808///
809/// `perm` must be a permutation of `0..n`, where `n` is the length of all
810/// three slices. Nothing here runs user code, so it cannot panic for a valid
811/// permutation.
812fn permute<K, V>(perm: &mut [usize], keys: &mut [K], values: &mut [V]) {
813    debug_assert!(perm.len() == keys.len() && perm.len() == values.len());
814    for start in 0..perm.len() {
815        // Follow the cycle through `start`, carrying the element that started
816        // there; positions already placed hold `perm[i] == i`.
817        let mut cur = start;
818        while perm[cur] != start {
819            let next = perm[cur];
820            keys.swap(cur, next);
821            values.swap(cur, next);
822            perm[cur] = cur;
823            cur = next;
824        }
825        perm[cur] = cur;
826    }
827}
828
829impl<K: Key, V, const PAGE: usize, D: Directory> Default for PagedSparseMap<K, V, PAGE, D> {
830    fn default() -> Self {
831        Self::new()
832    }
833}
834
835impl<K: Key, V: Clone, const PAGE: usize, D: Directory> Clone for PagedSparseMap<K, V, PAGE, D>
836where
837    D::Store<Slot, PAGE>: Clone,
838{
839    fn clone(&self) -> Self {
840        Self {
841            keys: self.keys.clone(),
842            values: self.values.clone(),
843        }
844    }
845}
846
847impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
848    for PagedSparseMap<K, V, PAGE, D>
849{
850    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851        f.debug_map().entries(self.iter()).finish()
852    }
853}
854
855/// Compares values by exact key using [`get`](PagedSparseMap::get), in any
856/// order and across page sizes and directories.
857impl<K: Key, V: PartialEq<W>, W, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
858    PartialEq<PagedSparseMap<K, W, P2, D2>> for PagedSparseMap<K, V, PAGE, D>
859{
860    fn eq(&self, other: &PagedSparseMap<K, W, P2, D2>) -> bool {
861        self.len() == other.len()
862            && self.iter().all(|(&key, value)| {
863                other
864                    .get(key)
865                    .is_some_and(|other_value| value == other_value)
866            })
867    }
868}
869
870/// Map [`PartialEq`] is an equivalence relation when the values implement [`Eq`].
871impl<K: Key, V: Eq, const PAGE: usize, D: Directory> Eq for PagedSparseMap<K, V, PAGE, D> {}
872
873/// Hashes the key-value pairs in any order, consistent with [`PartialEq`].
874impl<K: Key + Hash, V: Hash, const PAGE: usize, D: Directory> Hash
875    for PagedSparseMap<K, V, PAGE, D>
876{
877    fn hash<H: Hasher>(&self, state: &mut H) {
878        hash_unordered(self.iter(), state);
879    }
880}
881
882/// `map[key]` returns the value for `key`.
883///
884/// # Panics
885///
886/// Panics if `key` is not in the map.
887impl<K: Key, V, const PAGE: usize, D: Directory> Index<K> for PagedSparseMap<K, V, PAGE, D> {
888    type Output = V;
889
890    fn index(&self, key: K) -> &V {
891        self.get(key).expect("key not in PagedSparseMap")
892    }
893}
894
895/// Inserts each entry with [`insert`](PagedSparseMap::insert), so later
896/// entries overwrite earlier ones in the same slot.
897impl<K: Key, V, const PAGE: usize, D: Directory> Extend<(K, V)> for PagedSparseMap<K, V, PAGE, D> {
898    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
899        for (key, value) in iter {
900            self.insert(key, value);
901        }
902    }
903}
904
905impl<'a, K: Key + 'a, V: Copy + 'a, const PAGE: usize, D: Directory> Extend<(&'a K, &'a V)>
906    for PagedSparseMap<K, V, PAGE, D>
907{
908    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
909        self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
910    }
911}
912
913impl<K: Key, V, const PAGE: usize, D: Directory> FromIterator<(K, V)>
914    for PagedSparseMap<K, V, PAGE, D>
915{
916    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
917        let mut map = Self::new();
918        map.extend(iter);
919        map
920    }
921}
922
923impl<'a, K: Key, V, const PAGE: usize, D: Directory> IntoIterator
924    for &'a PagedSparseMap<K, V, PAGE, D>
925{
926    type Item = (&'a K, &'a V);
927    type IntoIter = Iter<'a, K, V>;
928
929    fn into_iter(self) -> Self::IntoIter {
930        self.iter()
931    }
932}
933
934impl<'a, K: Key, V, const PAGE: usize, D: Directory> IntoIterator
935    for &'a mut PagedSparseMap<K, V, PAGE, D>
936{
937    type Item = (&'a K, &'a mut V);
938    type IntoIter = IterMut<'a, K, V>;
939
940    fn into_iter(self) -> Self::IntoIter {
941        self.iter_mut()
942    }
943}
944
945impl<K: Key, V, const PAGE: usize, D: Directory> IntoIterator for PagedSparseMap<K, V, PAGE, D> {
946    type Item = (K, V);
947    type IntoIter = IntoIter<K, V>;
948
949    fn into_iter(self) -> Self::IntoIter {
950        IntoIter(self.keys.into_iter().zip(self.values))
951    }
952}
953
954macro_rules! zip_iterator {
955    ($(#[$doc:meta])* $name:ident<$($lt:lifetime,)? $k:ident, $v:ident>, $inner:ty, $item:ty) => {
956        $(#[$doc])*
957        #[derive(Debug)]
958        pub struct $name<$($lt,)? $k, $v>($inner);
959
960        impl<$($lt,)? $k, $v> Iterator for $name<$($lt,)? $k, $v> {
961            type Item = $item;
962
963            #[inline]
964            fn next(&mut self) -> Option<Self::Item> {
965                self.0.next()
966            }
967
968            #[inline]
969            fn size_hint(&self) -> (usize, Option<usize>) {
970                self.0.size_hint()
971            }
972        }
973
974        impl<$($lt,)? $k, $v> DoubleEndedIterator for $name<$($lt,)? $k, $v> {
975            #[inline]
976            fn next_back(&mut self) -> Option<Self::Item> {
977                self.0.next_back()
978            }
979        }
980
981        impl<$($lt,)? $k, $v> ExactSizeIterator for $name<$($lt,)? $k, $v> {}
982
983        impl<$($lt,)? $k, $v> FusedIterator for $name<$($lt,)? $k, $v> {}
984    };
985}
986
987zip_iterator!(
988    /// Iterator over the entries of a [`PagedSparseMap`], from
989    /// [`iter`](PagedSparseMap::iter).
990    Iter<'a, K, V>,
991    Zip<slice::Iter<'a, K>, slice::Iter<'a, V>>,
992    (&'a K, &'a V)
993);
994
995zip_iterator!(
996    /// Iterator over the entries of a [`PagedSparseMap`] with mutable
997    /// values, from [`iter_mut`](PagedSparseMap::iter_mut).
998    IterMut<'a, K, V>,
999    Zip<slice::Iter<'a, K>, slice::IterMut<'a, V>>,
1000    (&'a K, &'a mut V)
1001);
1002
1003zip_iterator!(
1004    /// Owning iterator over the entries of a [`PagedSparseMap`].
1005    IntoIter<K, V>,
1006    Zip<alloc::vec::IntoIter<K>, alloc::vec::IntoIter<V>>,
1007    (K, V)
1008);
1009
1010zip_iterator!(
1011    /// The entries removed by [`PagedSparseMap::drain`], in dense order.
1012    Drain<'a, K, V>,
1013    Zip<sparse_set::Drain<'a, K>, alloc::vec::Drain<'a, V>>,
1014    (K, V)
1015);
1016
1017/// The entries in a range of slot indices, from [`PagedSparseMap::range`].
1018pub struct Range<'a, K, V, const PAGE: usize = DEFAULT_PAGE, D: Directory + 'a = Flat> {
1019    positions: Positions<'a, K, PAGE, D>,
1020    values: &'a [V],
1021}
1022
1023impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> Iterator for Range<'a, K, V, PAGE, D> {
1024    type Item = (&'a K, &'a V);
1025
1026    #[inline]
1027    fn next(&mut self) -> Option<Self::Item> {
1028        let pos = self.positions.next()?;
1029        Some((&self.positions.dense()[pos], &self.values[pos]))
1030    }
1031
1032    #[inline]
1033    fn size_hint(&self) -> (usize, Option<usize>) {
1034        self.positions.size_hint()
1035    }
1036}
1037
1038impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> DoubleEndedIterator
1039    for Range<'a, K, V, PAGE, D>
1040{
1041    #[inline]
1042    fn next_back(&mut self) -> Option<Self::Item> {
1043        let pos = self.positions.next_back()?;
1044        Some((&self.positions.dense()[pos], &self.values[pos]))
1045    }
1046}
1047
1048impl<'a, K: Key, V, const PAGE: usize, D: Directory + 'a> FusedIterator
1049    for Range<'a, K, V, PAGE, D>
1050{
1051}
1052
1053impl<'a, K, V, const PAGE: usize, D: Directory + 'a> Clone for Range<'a, K, V, PAGE, D> {
1054    fn clone(&self) -> Self {
1055        Self {
1056            positions: self.positions.clone(),
1057            values: self.values,
1058        }
1059    }
1060}
1061
1062impl<'a, K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory + 'a> fmt::Debug
1063    for Range<'a, K, V, PAGE, D>
1064{
1065    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1066        f.debug_list().entries(self.clone()).finish()
1067    }
1068}
1069
1070/// A view into one key's place in a [`PagedSparseMap`], from
1071/// [`PagedSparseMap::entry`].
1072pub enum Entry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1073    /// The key is in the map.
1074    Occupied(OccupiedEntry<'a, K, V, PAGE, D>),
1075    /// The key's slot is empty or held by another generation.
1076    Vacant(VacantEntry<'a, K, V, PAGE, D>),
1077}
1078
1079/// An [`Entry`] for a key that is in the map.
1080pub struct OccupiedEntry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1081    map: &'a mut PagedSparseMap<K, V, PAGE, D>,
1082    pos: usize,
1083}
1084
1085/// An [`Entry`] for a key that is absent from the map.
1086pub struct VacantEntry<'a, K: Key, V, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1087    map: &'a mut PagedSparseMap<K, V, PAGE, D>,
1088    key: K,
1089    index: usize,
1090    occupant: Option<usize>,
1091}
1092
1093impl<'a, K: Key, V, const PAGE: usize, D: Directory> Entry<'a, K, V, PAGE, D> {
1094    /// The stored key if occupied, or the key given to [`PagedSparseMap::entry`].
1095    #[inline]
1096    pub fn key(&self) -> &K {
1097        match self {
1098            Entry::Occupied(entry) => entry.key(),
1099            Entry::Vacant(entry) => entry.key(),
1100        }
1101    }
1102
1103    /// The value, inserting `default` first if the key is absent.
1104    #[inline]
1105    pub fn or_insert(self, default: V) -> &'a mut V {
1106        match self {
1107            Entry::Occupied(entry) => entry.into_mut(),
1108            Entry::Vacant(entry) => entry.insert(default),
1109        }
1110    }
1111
1112    /// The value, inserting `make()` first if the key is absent. If `make`
1113    /// panics, the map is unchanged.
1114    #[inline]
1115    pub fn or_insert_with(self, make: impl FnOnce() -> V) -> &'a mut V {
1116        match self {
1117            Entry::Occupied(entry) => entry.into_mut(),
1118            Entry::Vacant(entry) => entry.insert(make()),
1119        }
1120    }
1121
1122    /// Like [`or_insert_with`](Self::or_insert_with), giving `make` the key.
1123    #[inline]
1124    pub fn or_insert_with_key(self, make: impl FnOnce(&K) -> V) -> &'a mut V {
1125        match self {
1126            Entry::Occupied(entry) => entry.into_mut(),
1127            Entry::Vacant(entry) => {
1128                let value = make(entry.key());
1129                entry.insert(value)
1130            }
1131        }
1132    }
1133
1134    /// The value, inserting `V::default()` first if the key is absent.
1135    #[inline]
1136    pub fn or_default(self) -> &'a mut V
1137    where
1138        V: Default,
1139    {
1140        self.or_insert_with(V::default)
1141    }
1142
1143    /// Calls `f` on the value if the key is present, and returns the entry.
1144    #[inline]
1145    pub fn and_modify(mut self, f: impl FnOnce(&mut V)) -> Self {
1146        if let Entry::Occupied(entry) = &mut self {
1147            f(entry.get_mut());
1148        }
1149        self
1150    }
1151
1152    /// Stores `value` for the key and returns the occupied entry. An occupied
1153    /// entry keeps its stored key. Inserting into a vacant entry evicts any
1154    /// other generation in the slot.
1155    #[inline]
1156    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, PAGE, D> {
1157        match self {
1158            Entry::Occupied(mut entry) => {
1159                entry.insert(value);
1160                entry
1161            }
1162            Entry::Vacant(entry) => entry.insert_entry(value),
1163        }
1164    }
1165}
1166
1167impl<'a, K: Key, V, const PAGE: usize, D: Directory> OccupiedEntry<'a, K, V, PAGE, D> {
1168    /// The stored key.
1169    #[inline]
1170    pub fn key(&self) -> &K {
1171        &self.map.keys.as_slice()[self.pos]
1172    }
1173
1174    /// The stored value.
1175    #[inline]
1176    pub fn get(&self) -> &V {
1177        &self.map.values[self.pos]
1178    }
1179
1180    /// Mutable access to the stored value.
1181    #[inline]
1182    pub fn get_mut(&mut self) -> &mut V {
1183        &mut self.map.values[self.pos]
1184    }
1185
1186    /// Mutable access to the value for the lifetime of the map borrow.
1187    #[inline]
1188    pub fn into_mut(self) -> &'a mut V {
1189        &mut self.map.values[self.pos]
1190    }
1191
1192    /// Replaces the value and returns the old one, keeping the stored key.
1193    #[inline]
1194    pub fn insert(&mut self, value: V) -> V {
1195        core::mem::replace(self.get_mut(), value)
1196    }
1197
1198    /// Removes the entry and returns its value.
1199    #[inline]
1200    pub fn remove(self) -> V {
1201        self.remove_entry().1
1202    }
1203
1204    /// Removes the entry and returns the stored key and its value.
1205    ///
1206    /// The last entry moves into the removed entry's position.
1207    pub fn remove_entry(self) -> (K, V) {
1208        self.map.remove_at(self.pos)
1209    }
1210}
1211
1212impl<'a, K: Key, V, const PAGE: usize, D: Directory> VacantEntry<'a, K, V, PAGE, D> {
1213    /// The key given to [`PagedSparseMap::entry`].
1214    #[inline]
1215    pub fn key(&self) -> &K {
1216        &self.key
1217    }
1218
1219    /// Returns the key without changing the map.
1220    #[inline]
1221    pub fn into_key(self) -> K {
1222        self.key
1223    }
1224
1225    /// Stores `value` for the key and returns mutable access to it, evicting
1226    /// and dropping any other generation in the slot.
1227    ///
1228    /// # Panics
1229    ///
1230    /// As [`PagedSparseMap::insert`]. If an evicted value's destructor panics,
1231    /// the new entry is already in place.
1232    #[inline]
1233    pub fn insert(self, value: V) -> &'a mut V {
1234        self.insert_entry(value).into_mut()
1235    }
1236
1237    fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, PAGE, D> {
1238        let Self {
1239            map,
1240            key,
1241            index,
1242            occupant,
1243        } = self;
1244        let pos = match occupant {
1245            Some(pos) => {
1246                map.keys.overwrite_at(pos, key);
1247                // Drop the evicted value only after both arrays agree.
1248                drop(core::mem::replace(&mut map.values[pos], value));
1249                pos
1250            }
1251            None => map.push_vacant(key, index, value),
1252        };
1253        OccupiedEntry { map, pos }
1254    }
1255}
1256
1257impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1258    for Entry<'_, K, V, PAGE, D>
1259{
1260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261        match self {
1262            Entry::Occupied(entry) => f.debug_tuple("Occupied").field(entry).finish(),
1263            Entry::Vacant(entry) => f.debug_tuple("Vacant").field(entry).finish(),
1264        }
1265    }
1266}
1267
1268impl<K: Key + fmt::Debug, V: fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
1269    for OccupiedEntry<'_, K, V, PAGE, D>
1270{
1271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1272        f.debug_struct("OccupiedEntry")
1273            .field("key", self.key())
1274            .field("value", self.get())
1275            .finish()
1276    }
1277}
1278
1279impl<K: Key + fmt::Debug, V, const PAGE: usize, D: Directory> fmt::Debug
1280    for VacantEntry<'_, K, V, PAGE, D>
1281{
1282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1283        f.debug_struct("VacantEntry")
1284            .field("key", self.key())
1285            .finish()
1286    }
1287}
1288
1289/// The entries removed by [`PagedSparseMap::extract_if`].
1290pub struct ExtractIf<'a, K, V, F, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1291    map: &'a mut PagedSparseMap<K, V, PAGE, D>,
1292    pos: usize,
1293    pred: F,
1294}
1295
1296impl<K: Key, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> Iterator
1297    for ExtractIf<'_, K, V, F, PAGE, D>
1298{
1299    type Item = (K, V);
1300
1301    fn next(&mut self) -> Option<(K, V)> {
1302        while self.pos < self.map.values.len() {
1303            let pos = self.pos;
1304            let key = self.map.keys.as_slice()[pos];
1305            // Advance first: if `pred` panics, this entry is not tested again.
1306            self.pos += 1;
1307            if (self.pred)(&key, &mut self.map.values[pos]) {
1308                // The last entry moves into `pos` and is tested next.
1309                self.pos = pos;
1310                return Some(self.map.remove_at(pos));
1311            }
1312        }
1313        None
1314    }
1315
1316    fn size_hint(&self) -> (usize, Option<usize>) {
1317        (0, Some(self.map.values.len() - self.pos))
1318    }
1319}
1320
1321impl<K: Key, V, F: FnMut(&K, &mut V) -> bool, const PAGE: usize, D: Directory> FusedIterator
1322    for ExtractIf<'_, K, V, F, PAGE, D>
1323{
1324}
1325
1326impl<K: Key + fmt::Debug, V: fmt::Debug, F, const PAGE: usize, D: Directory> fmt::Debug
1327    for ExtractIf<'_, K, V, F, PAGE, D>
1328{
1329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1330        let pos = self.pos;
1331        f.debug_struct("ExtractIf")
1332            .field("untested_keys", &&self.map.keys.as_slice()[pos..])
1333            .field("untested_values", &&self.map.values[pos..])
1334            .finish_non_exhaustive()
1335    }
1336}
1337
1338impl<K, V> Clone for Iter<'_, K, V> {
1339    fn clone(&self) -> Self {
1340        Self(self.0.clone())
1341    }
1342}
1343
1344impl<K: Clone, V: Clone> Clone for IntoIter<K, V> {
1345    fn clone(&self) -> Self {
1346        Self(self.0.clone())
1347    }
1348}
1349
1350#[cfg(feature = "rayon")]
1351mod rayon_impl {
1352    use super::*;
1353    use rayon::iter::Zip;
1354    use rayon::prelude::*;
1355    use rayon::slice::{Iter, IterMut};
1356
1357    impl<K: Key, V, const PAGE: usize, D: Directory> PagedSparseMap<K, V, PAGE, D> {
1358        /// Iterates in parallel over the keys in dense order.
1359        pub fn par_keys(&self) -> Iter<'_, K>
1360        where
1361            K: Sync,
1362        {
1363            self.key_slice().par_iter()
1364        }
1365
1366        /// Iterates in parallel over the values in dense order.
1367        pub fn par_values(&self) -> Iter<'_, V>
1368        where
1369            V: Sync,
1370        {
1371            self.value_slice().par_iter()
1372        }
1373
1374        /// Iterates in parallel over mutable values in dense order.
1375        pub fn par_values_mut(&mut self) -> IterMut<'_, V>
1376        where
1377            V: Send,
1378        {
1379            self.value_slice_mut().par_iter_mut()
1380        }
1381    }
1382
1383    impl<'a, K: Key + Sync, V: Sync, const PAGE: usize, D: Directory> IntoParallelIterator
1384        for &'a PagedSparseMap<K, V, PAGE, D>
1385    {
1386        type Item = (&'a K, &'a V);
1387        type Iter = Zip<Iter<'a, K>, Iter<'a, V>>;
1388
1389        fn into_par_iter(self) -> Self::Iter {
1390            self.par_keys().zip(self.par_values())
1391        }
1392    }
1393
1394    impl<'a, K: Key + Sync, V: Send, const PAGE: usize, D: Directory> IntoParallelIterator
1395        for &'a mut PagedSparseMap<K, V, PAGE, D>
1396    {
1397        type Item = (&'a K, &'a mut V);
1398        type Iter = Zip<Iter<'a, K>, IterMut<'a, V>>;
1399
1400        fn into_par_iter(self) -> Self::Iter {
1401            self.keys
1402                .as_slice()
1403                .par_iter()
1404                .zip(self.values.par_iter_mut())
1405        }
1406    }
1407}
1408
1409#[cfg(feature = "serde")]
1410mod serde_impl {
1411    use super::*;
1412    use core::marker::PhantomData;
1413    use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
1414    use serde::ser::{Serialize, Serializer};
1415
1416    /// Most entries to reserve from an untrusted size hint: 4096, and at
1417    /// most 1 MiB of dense storage.
1418    fn max_prealloc<K, V>() -> usize {
1419        let entry = core::mem::size_of::<K>() + core::mem::size_of::<V>();
1420        // `1 << 20` does not fit a 16-bit `usize`; the cap is then `usize::MAX`.
1421        usize::try_from(1_u32 << 20)
1422            .unwrap_or(usize::MAX)
1423            .checked_div(entry)
1424            .unwrap_or(usize::MAX)
1425            .min(4096)
1426    }
1427
1428    /// Serializes as a map from keys to values, in dense order.
1429    impl<K: Key + Serialize, V: Serialize, const PAGE: usize, D: Directory> Serialize
1430        for PagedSparseMap<K, V, PAGE, D>
1431    {
1432        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1433            serializer.collect_map(self.iter())
1434        }
1435    }
1436
1437    /// Deserializes from a map. Entries are inserted in input order with
1438    /// [`insert`](PagedSparseMap::insert), so a later entry overwrites an
1439    /// earlier one in the same slot, as `HashMap` keeps the last duplicate.
1440    ///
1441    /// Memory follows the key indices, not the input length: see the
1442    /// warning on [`PagedSparseSet`]'s `Deserialize` impl. For untrusted
1443    /// input, use [`Radix`](crate::page::Radix) or [`Tree`](crate::page::Tree),
1444    /// or validate the keys first.
1445    impl<'de, K, V, const PAGE: usize, D> Deserialize<'de> for PagedSparseMap<K, V, PAGE, D>
1446    where
1447        K: Key + Deserialize<'de>,
1448        V: Deserialize<'de>,
1449        D: Directory,
1450    {
1451        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1452            struct MapVisitor<K, V, const PAGE: usize, D>(PhantomData<(K, V, D)>);
1453
1454            impl<'de, K, V, const PAGE: usize, D> Visitor<'de> for MapVisitor<K, V, PAGE, D>
1455            where
1456                K: Key + Deserialize<'de>,
1457                V: Deserialize<'de>,
1458                D: Directory,
1459            {
1460                type Value = PagedSparseMap<K, V, PAGE, D>;
1461
1462                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1463                    f.write_str("a map of keys to values")
1464                }
1465
1466                fn visit_map<A: MapAccess<'de>>(
1467                    self,
1468                    mut access: A,
1469                ) -> Result<Self::Value, A::Error> {
1470                    // Cap the hint so a hostile length cannot force a huge
1471                    // allocation.
1472                    let hint = access.size_hint().unwrap_or(0).min(max_prealloc::<K, V>());
1473                    let mut map = PagedSparseMap::with_capacity(hint);
1474                    while let Some((key, value)) = access.next_entry()? {
1475                        map.insert(key, value);
1476                    }
1477                    Ok(map)
1478                }
1479            }
1480
1481            deserializer.deserialize_map(MapVisitor::<K, V, PAGE, D>(PhantomData))
1482        }
1483    }
1484}
1485
1486// The tests use `u32` keys, which implement `Key` only on 32- and 64-bit
1487// targets.
1488#[cfg(all(test, any(target_pointer_width = "32", target_pointer_width = "64")))]
1489mod tests {
1490    use super::*;
1491    use alloc::string::{String, ToString};
1492
1493    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
1494    struct Gen(u32);
1495
1496    impl Key for Gen {
1497        fn index(self) -> usize {
1498            (self.0 & 0xffff) as usize
1499        }
1500    }
1501
1502    fn assert_parallel<K: Key + fmt::Debug, V, const PAGE: usize, D: Directory>(
1503        map: &PagedSparseMap<K, V, PAGE, D>,
1504    ) {
1505        assert_eq!(map.key_slice().len(), map.value_slice().len());
1506        for (pos, &key) in map.key_slice().iter().enumerate() {
1507            assert_eq!(map.position(key), Some(pos), "{key:?}");
1508        }
1509    }
1510
1511    #[test]
1512    fn remove_moves_last_entry_with_its_value() {
1513        let mut map: PagedSparseMap<u32, char, 4> = [(1, 'a'), (2, 'b'), (3, 'c'), (40, 'd')]
1514            .into_iter()
1515            .collect();
1516        assert_eq!(map.remove(1), Some('a'));
1517        assert_eq!(map.key_slice(), &[40, 2, 3]);
1518        assert_eq!(map.value_slice(), &['d', 'b', 'c']);
1519        assert_eq!(map.remove(1), None);
1520        assert_eq!(map.remove_entry(3), Some((3, 'c')));
1521        assert_eq!(map[40], 'd');
1522        assert_parallel(&map);
1523    }
1524
1525    #[test]
1526    fn insert_updates_in_place() {
1527        let mut map: PagedSparseMap<u32, u32> = (0..5).map(|k| (k, k * 10)).collect();
1528        assert_eq!(map.insert(2, 99), Some(20));
1529        assert_eq!(map.position(2), Some(2));
1530        assert_eq!(map.value_slice(), &[0, 10, 99, 30, 40]);
1531        *map.get_mut(4).unwrap() += 1;
1532        assert_eq!(map.get(4), Some(&41));
1533    }
1534
1535    /// Equal keys that are not identical: `tag` is ignored by `==`.
1536    #[derive(Clone, Copy, Debug)]
1537    struct Tagged {
1538        id: u32,
1539        tag: u8,
1540    }
1541
1542    impl PartialEq for Tagged {
1543        fn eq(&self, other: &Self) -> bool {
1544            self.id == other.id
1545        }
1546    }
1547
1548    impl Eq for Tagged {}
1549
1550    impl Key for Tagged {
1551        fn index(self) -> usize {
1552            self.id as usize
1553        }
1554    }
1555
1556    #[test]
1557    fn insert_keeps_an_equal_stored_key_and_replace_does_not() {
1558        let mut map: PagedSparseMap<Tagged, u8> = PagedSparseMap::new();
1559        map.insert(Tagged { id: 3, tag: 1 }, 10);
1560        assert_eq!(map.insert(Tagged { id: 3, tag: 2 }, 20), Some(10));
1561        assert_eq!(map.key_slice()[0].tag, 1);
1562        let (old, _) = map.replace(Tagged { id: 3, tag: 3 }, 30).unwrap();
1563        assert_eq!(old.tag, 1);
1564        assert_eq!(map.key_slice()[0].tag, 3);
1565        assert_eq!(map.clone().into_keys().next().map(|k| k.tag), Some(3));
1566        assert_eq!(map.into_values().collect::<Vec<_>>(), [30]);
1567    }
1568
1569    #[test]
1570    fn generations_by_method() {
1571        let old = Gen(7);
1572        let new = Gen(7 | 1 << 16);
1573        let mut map: PagedSparseMap<Gen, &str> = PagedSparseMap::new();
1574        assert_eq!(map.try_insert(old, "old").copied(), Ok("old"));
1575        assert_eq!(map.try_insert(new, "new"), Err("new"));
1576        assert_eq!(map.try_insert(old, "again"), Err("again"));
1577        assert_eq!(map.get(new), None);
1578        assert_eq!(map.occupant(7), Some((&old, &"old")));
1579
1580        assert_eq!(map.replace(new, "new"), Some((old, "old")));
1581        assert_eq!(map.get(old), None);
1582        assert_eq!(map.insert(old, "back"), Some("new"));
1583        assert_eq!(map.get_or_insert_with(new, || "made"), &"made");
1584        assert_eq!(map.get_or_insert_with(new, || unreachable!()), &"made");
1585        assert_eq!(map.len(), 1);
1586
1587        assert_eq!(map.remove(old), None);
1588        if let Some((_, v)) = map.occupant_mut(7) {
1589            *v = "edited";
1590        }
1591        assert_eq!(map.remove_occupant(7), Some((new, "edited")));
1592        assert!(map.is_empty());
1593    }
1594
1595    #[test]
1596    fn clear_is_lazy_but_correct() {
1597        let mut map: PagedSparseMap<u32, String, 4> = (0..10).map(|k| (k, k.to_string())).collect();
1598        map.clear();
1599        assert!(map.is_empty());
1600        assert_eq!(map.allocated_pages(), 3);
1601        assert!((0..10).all(|k| !map.contains_key(k)));
1602        map.insert(9, "nine".into());
1603        assert_eq!(map.get(0), None);
1604        assert_eq!(map.position(9), Some(0));
1605        map.reset();
1606        assert_eq!(map.allocated_pages(), 0);
1607    }
1608
1609    #[test]
1610    fn retain_and_sort_move_values_with_keys() {
1611        let mut map: PagedSparseMap<u32, u32, 8> = [9, 3, 7, 1, 8, 2]
1612            .into_iter()
1613            .map(|k| (k, k * 100))
1614            .collect();
1615        map.retain(|&k, v| {
1616            *v += 1;
1617            k % 3 != 0
1618        });
1619        map.sort_unstable_keys();
1620        assert_eq!(map.key_slice(), &[1, 2, 7, 8]);
1621        assert_eq!(map.value_slice(), &[101, 201, 701, 801]);
1622        assert_parallel(&map);
1623
1624        map.sort_unstable_by(|(_, a), (_, b)| b.cmp(a));
1625        assert_eq!(map.key_slice(), &[8, 7, 2, 1]);
1626        map.sort_unstable_by_key(|&k, _| k % 7);
1627        assert_eq!(map.key_slice(), &[7, 8, 1, 2]);
1628        assert_eq!(map.value_slice(), &[701, 801, 101, 201]);
1629        assert_parallel(&map);
1630    }
1631
1632    #[test]
1633    fn stable_sorts_keep_ties_in_order_and_searches_find_positions() {
1634        let mut map: PagedSparseMap<u32, u32, 4> = [(5, 1), (9, 0), (2, 1), (7, 0), (40, 1)]
1635            .into_iter()
1636            .collect();
1637        map.sort_by_key(|_, &v| v);
1638        assert_eq!(map.key_slice(), &[9, 7, 5, 2, 40]);
1639        assert_eq!(map.value_slice(), &[0, 0, 1, 1, 1]);
1640        assert_parallel(&map);
1641        assert_eq!(map.partition_point(|_, &v| v == 0), 2);
1642        assert_eq!(map.partition_point(|_, _| true), 5);
1643        assert_eq!(map.partition_point(|_, _| false), 0);
1644
1645        map.sort_by(|(a, _), (b, _)| (a % 2).cmp(&(b % 2)));
1646        assert_eq!(map.key_slice(), &[2, 40, 9, 7, 5]);
1647        let mut calls = 0;
1648        map.sort_by_cached_key(|&k, _| {
1649            calls += 1;
1650            k / 10
1651        });
1652        assert_eq!(calls, 5);
1653        assert_eq!(map.key_slice(), &[2, 9, 7, 5, 40]);
1654        assert_parallel(&map);
1655
1656        map.sort_keys();
1657        assert_eq!(map.key_slice(), &[2, 5, 7, 9, 40]);
1658        assert_eq!(map.value_slice(), &[1, 1, 0, 0, 1]);
1659        assert_parallel(&map);
1660        assert_eq!(map.binary_search_key(&7), Ok(2));
1661        assert_eq!(map.binary_search_key(&0), Err(0));
1662        assert_eq!(map.binary_search_key(&8), Err(3));
1663        assert_eq!(map.binary_search_key(&41), Err(5));
1664        for (pos, &key) in map.key_slice().iter().enumerate() {
1665            assert_eq!(map.binary_search_by(|k, _| k.cmp(&key)), Ok(pos));
1666        }
1667        assert_eq!(map.binary_search_by(|k, _| k.cmp(&6)), Err(2));
1668        let empty: PagedSparseMap<u32, u32> = PagedSparseMap::new();
1669        assert_eq!(empty.binary_search_key(&1), Err(0));
1670        assert_eq!(empty.partition_point(|_, _| true), 0);
1671    }
1672
1673    #[test]
1674    fn permute_handles_every_permutation_of_four() {
1675        // Brute force: keep the 24 of the 256 index arrays that are
1676        // permutations.
1677        for a in 0..4 {
1678            for b in 0..4 {
1679                for c in 0..4 {
1680                    for d in 0..4 {
1681                        let p = [a, b, c, d];
1682                        if (0..4).any(|i| !p.contains(&i)) {
1683                            continue;
1684                        }
1685                        let mut perm = p;
1686                        let mut keys = [10, 11, 12, 13];
1687                        let mut values = ['a', 'b', 'c', 'd'];
1688                        permute(&mut perm, &mut keys, &mut values);
1689                        assert_eq!(keys, p.map(|i| 10 + i), "{p:?}");
1690                        assert_eq!(values, p.map(|i| ['a', 'b', 'c', 'd'][i]), "{p:?}");
1691                        assert_eq!(perm, [0, 1, 2, 3]);
1692                    }
1693                }
1694            }
1695        }
1696    }
1697
1698    #[test]
1699    fn equality_and_iterators() {
1700        let a: PagedSparseMap<u32, i32> = [(1, -1), (2, -2)].into_iter().collect();
1701        let mut b: PagedSparseMap<u32, i32> = [(2, -2), (1, -1)].into_iter().collect();
1702        assert_eq!(a, b);
1703        for (_, v) in &mut b {
1704            *v *= 2;
1705        }
1706        assert_ne!(a, b);
1707        assert_eq!(b.iter().rev().collect::<Vec<_>>(), [(&1, &-2), (&2, &-4)]);
1708        assert_eq!(b.iter().len(), 2);
1709        assert_eq!(b.into_iter().collect::<Vec<_>>(), [(2, -4), (1, -2)]);
1710    }
1711}