Skip to main content

paged_collections/
sparse_set.rs

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