Skip to main content

paged_collections/
bit_set.rs

1//! [`PagedBitSet`]: a set that stores one bit per key slot in fixed-size pages.
2//!
3//! Each page is allocated on first use. A lookup reads one bit at the slot
4//! [`Key::index`] names, and iteration visits set bits in ascending slot-index
5//! order. The default page holds 512 words (4 KiB, or 32,768 bits).
6//!
7//! The slot index must determine the whole key (`DirectKey<Tag = ()>`).
8//! Use [`PagedSparseSet`](crate::sparse_set::PagedSparseSet) for generational
9//! keys or for keys scattered thinly across pages.
10//!
11//! | Operation | Cost |
12//! |---|---|
13//! | [`contains`](PagedBitSet::contains), [`insert`](PagedBitSet::insert), [`remove`](PagedBitSet::remove), [`toggle`](PagedBitSet::toggle) | One page lookup, then one word access. A newly allocated page takes O(`PAGE`) to initialize. |
14//! | Iteration, [`clear`](PagedBitSet::clear), [`retain`](PagedBitSet::retain) | Scan allocated words, plus gaps in a [`Flat`] directory. Iteration and retain also visit each set bit. |
15//! | [`range`](PagedBitSet::range), [`count_range`](PagedBitSet::count_range), ordered queries | Seek to the first or last page of the range and scan words in the range as needed. |
16//! | [`len`](PagedBitSet::len) | O(1) |
17//!
18//! Empty pages stay allocated for reuse. [`shrink_to_fit`](PagedBitSet::shrink_to_fit)
19//! frees empty pages and [`reset`](PagedBitSet::reset) frees every page.
20//!
21//! ```
22//! use paged_collections::bit_set::PagedBitSet;
23//!
24//! let mut set: PagedBitSet<usize, 1> = [130, 2, 5].into_iter().collect();
25//! assert_eq!(set.iter().collect::<Vec<_>>(), [2, 5, 130]);
26//! assert_eq!(set.next_occupant(3), Some(5));
27//! assert_eq!(set.pop_last(), Some(130));
28//! assert_eq!(set.allocated_pages(), 2);
29//! set.shrink_to_fit();
30//! assert_eq!(set.allocated_pages(), 1);
31//! ```
32
33use alloc::vec::Vec;
34use core::cmp::Ordering;
35use core::fmt;
36use core::hash::{Hash, Hasher};
37use core::iter::{Flatten, Fuse, FusedIterator, Peekable, once};
38use core::marker::PhantomData;
39use core::ops::{self, Bound, Deref, RangeBounds, RangeInclusive};
40
41use crate::key::{DirectKey, Key};
42use crate::page::{Directory, Flat, PageStore, split};
43
44/// The default number of 64-bit words in a bit-set page (4 KiB).
45pub const DEFAULT_BIT_PAGE: usize = 512;
46
47const WORD_BITS: usize = u64::BITS as usize;
48
49type Store<const PAGE: usize, D> = <D as Directory>::Store<u64, PAGE>;
50type Pages<'a, const PAGE: usize, D> = <Store<PAGE, D> as PageStore<u64, PAGE>>::Pages<'a>;
51type IntoPages<const PAGE: usize, D> = <Store<PAGE, D> as PageStore<u64, PAGE>>::IntoPages;
52
53/// A set of keys stored as bits at their slot indices.
54///
55/// - `PAGE` is the number of 64-bit words per page. It must be non-zero.
56/// - `D` is the page directory: [`Flat`] (default),
57///   [`Radix`](crate::page::Radix) for wide keys, or [`Tree`](crate::page::Tree).
58///
59/// The key's [`DirectKey::Tag`] must be `()`. Use
60/// [`PagedSparseSet`](crate::sparse_set::PagedSparseSet) for generational keys.
61/// Set algebra and equality accept different directories with the same `PAGE`.
62pub struct PagedBitSet<K, const PAGE: usize = DEFAULT_BIT_PAGE, D: Directory = Flat> {
63    // Invariant: len is the number of set bits across all pages. Commit
64    // the word and its count together before allocating or calling user code.
65    pages: Store<PAGE, D>,
66    len: usize,
67    _key: PhantomData<fn() -> K>,
68}
69
70impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> PagedBitSet<K, PAGE, D> {
71    /// The number of 64-bit words per page.
72    pub const PAGE_SIZE: usize = PAGE;
73
74    /// The number of bits per page. The product must fit in `usize`.
75    pub const BITS_PER_PAGE: usize = PAGE * WORD_BITS;
76
77    /// Creates an empty set. The first insertion allocates the first page.
78    pub fn new() -> Self {
79        Self {
80            pages: Default::default(),
81            len: 0,
82            _key: PhantomData,
83        }
84    }
85
86    /// Returns the number of keys in the set.
87    #[inline]
88    pub fn len(&self) -> usize {
89        self.len
90    }
91
92    /// Returns whether the set holds no keys.
93    #[inline]
94    pub fn is_empty(&self) -> bool {
95        self.len == 0
96    }
97
98    /// Returns the number of allocated pages, including empty ones.
99    pub fn allocated_pages(&self) -> usize {
100        self.pages.allocated()
101    }
102
103    /// Returns whether the set contains `key`.
104    pub fn contains(&self, key: K) -> bool {
105        let (number, offset, mask) = locate::<PAGE>(key.index());
106        self.pages
107            .get(number)
108            .is_some_and(|page| page[offset] & mask != 0)
109    }
110
111    /// Inserts `key` and returns whether it was newly added.
112    pub fn insert(&mut self, key: K) -> bool {
113        let (number, offset, mask) = locate::<PAGE>(key.index());
114        let word = &mut self.pages.get_or_alloc(number)[offset];
115        if *word & mask != 0 {
116            return false;
117        }
118        let len = checked_len(self.len, 1);
119        *word |= mask;
120        self.len = len;
121        true
122    }
123
124    /// Removes `key` and returns whether it was present.
125    pub fn remove(&mut self, key: K) -> bool {
126        let (number, offset, mask) = locate::<PAGE>(key.index());
127        let Some(page) = self.pages.get_mut(number) else {
128            return false;
129        };
130        let word = &mut page[offset];
131        if *word & mask == 0 {
132            return false;
133        }
134        *word &= !mask;
135        self.len -= 1;
136        true
137    }
138
139    /// Flips the bit for `key` and returns whether it is now present.
140    pub fn toggle(&mut self, key: K) -> bool {
141        let (number, offset, mask) = locate::<PAGE>(key.index());
142        let word = &mut self.pages.get_or_alloc(number)[offset];
143        let present = *word & mask == 0;
144        let len = if present {
145            checked_len(self.len, 1)
146        } else {
147            self.len - 1
148        };
149        *word ^= mask;
150        self.len = len;
151        present
152    }
153
154    /// Sets the bits in the range and returns the number of newly added keys.
155    ///
156    /// The bounds refer to [`Key::index`]. Every slot in the range must
157    /// represent a valid key of type `K`. Unbounded endpoints refer to slot
158    /// zero and `usize::MAX`; use an explicit upper bound for narrow keys.
159    /// An empty or inverted range adds zero keys.
160    ///
161    /// # Panics
162    ///
163    /// Panics if the set would contain more than `usize::MAX` keys or the
164    /// directory cannot allocate a page.
165    ///
166    /// ```
167    /// use paged_collections::bit_set::PagedBitSet;
168    ///
169    /// let mut set: PagedBitSet<u8, 1> = PagedBitSet::new();
170    /// assert_eq!(set.insert_range(63..=66), 4);
171    /// assert_eq!(set.insert_range(64..=66), 0);
172    /// assert_eq!(set.count_range(..=64), 2);
173    /// assert_eq!(set.remove_range(65..), 2);
174    /// assert_eq!(set.range(..).collect::<Vec<_>>(), [63, 64]);
175    /// ```
176    pub fn insert_range(&mut self, keys: impl RangeBounds<K>) -> usize {
177        let Some(span) = Span::new(&index_bounds(&keys)) else {
178            return 0;
179        };
180        let before = self.len;
181        // The full slot domain has one more slot than len can represent.
182        checked_len(span.last - span.first, 1);
183        for number in span.pages::<PAGE>() {
184            let page = self.pages.get_or_alloc(number);
185            let start = page_start::<PAGE>(number);
186            for offset in span.offsets(start, PAGE) {
187                let word = &mut page[offset];
188                let new = *word | span.mask(start + offset);
189                write_word(&mut self.len, word, new);
190            }
191        }
192        self.len - before
193    }
194
195    /// Clears the bits in the range and returns the number of removed keys.
196    ///
197    /// The bounds refer to [`Key::index`]. An empty or inverted range removes
198    /// zero keys. Pages stay allocated.
199    pub fn remove_range(&mut self, keys: impl RangeBounds<K>) -> usize {
200        let Some(span) = Span::new(&index_bounds(&keys)) else {
201            return 0;
202        };
203        let before = self.len;
204        for (number, page) in self.pages.pages_in_mut(span.pages::<PAGE>()) {
205            let start = page_start::<PAGE>(number);
206            for offset in span.offsets(start, PAGE) {
207                let word = &mut page[offset];
208                let new = *word & !span.mask(start + offset);
209                write_word(&mut self.len, word, new);
210            }
211        }
212        before - self.len
213    }
214
215    /// Counts the set bits in the range.
216    ///
217    /// The bounds refer to [`Key::index`]. An empty or inverted range has
218    /// count zero.
219    pub fn count_range(&self, keys: impl RangeBounds<K>) -> usize {
220        let Some(span) = Span::new(&index_bounds(&keys)) else {
221            return 0;
222        };
223        WordPages {
224            pages: self.pages.pages_in(span.pages::<PAGE>()),
225            span,
226        }
227        .flatten()
228        .map(|word| word.bits.count_ones() as usize)
229        .sum()
230    }
231
232    /// Iterates over the keys in the range in ascending slot-index order.
233    ///
234    /// The bounds refer to [`Key::index`]. An empty or inverted range yields
235    /// no keys.
236    pub fn range(&self, keys: impl RangeBounds<K>) -> Range<'_, K, PAGE, D> {
237        self.slot_range(&index_bounds(&keys))
238    }
239
240    fn slot_range(&self, indices: &impl RangeBounds<usize>) -> Range<'_, K, PAGE, D> {
241        let span = Span::new(indices);
242        let numbers = span.map_or_else(|| RangeInclusive::new(1, 0), Span::pages::<PAGE>);
243        let remaining = if span.is_some() { self.len } else { 0 };
244        let words = WordPages {
245            pages: self.pages.pages_in(numbers),
246            span: span.unwrap_or(Span::FULL),
247        };
248        Range(Cursor::new(words.flatten(), remaining), PhantomData)
249    }
250
251    /// Returns the key with the smallest slot index.
252    pub fn first(&self) -> Option<K> {
253        self.iter().next()
254    }
255
256    /// Returns the key with the largest slot index.
257    pub fn last(&self) -> Option<K> {
258        self.iter().next_back()
259    }
260
261    /// Removes and returns the key with the smallest slot index.
262    pub fn pop_first(&mut self) -> Option<K> {
263        let key = self.first()?;
264        self.remove(key);
265        Some(key)
266    }
267
268    /// Removes and returns the key with the largest slot index.
269    pub fn pop_last(&mut self) -> Option<K> {
270        let key = self.last()?;
271        self.remove(key);
272        Some(key)
273    }
274
275    /// Returns the first key at slot `index` or after it.
276    pub fn next_occupant(&self, index: usize) -> Option<K> {
277        self.slot_range(&(index..)).next()
278    }
279
280    /// Returns the last key at slot `index` or before it.
281    pub fn prev_occupant(&self, index: usize) -> Option<K> {
282        self.slot_range(&(..=index)).next_back()
283    }
284
285    /// Keeps keys for which `keep` returns true, visiting them in ascending
286    /// slot-index order.
287    ///
288    /// If `keep` panics, the current key and those still to be visited stay
289    /// in the set.
290    pub fn retain(&mut self, mut keep: impl FnMut(K) -> bool) {
291        let mut remaining = self.len;
292        for (number, page) in self.pages.pages_mut() {
293            let start = page_start::<PAGE>(number);
294            for (offset, word) in page.iter_mut().enumerate() {
295                if remaining == 0 {
296                    return;
297                }
298                let mut bits = *word;
299                while bits != 0 {
300                    let bit = bits.trailing_zeros();
301                    let mask = 1 << bit;
302                    if !keep(K::from_parts(bit_index(start + offset, bit), ())) {
303                        *word &= !mask;
304                        self.len -= 1;
305                    }
306                    bits &= !mask;
307                    remaining -= 1;
308                }
309            }
310        }
311    }
312
313    /// Removes every key and returns them in ascending slot-index order.
314    /// Pages stay allocated, as with [`clear`](Self::clear).
315    ///
316    /// Keys are removed as the iterator yields them; dropping it removes the
317    /// rest. If it is leaked instead (`mem::forget`), the keys not yet
318    /// yielded stay in the set.
319    pub fn drain(&mut self) -> Drain<'_, K, PAGE, D> {
320        Drain {
321            set: self,
322            next: Some(0),
323        }
324    }
325
326    /// Removes the keys for which `pred` returns `true` and yields them,
327    /// visiting the keys in ascending slot-index order.
328    ///
329    /// Keys are tested and removed as the iterator advances: those it has not
330    /// reached when it is dropped stay in the set. Use
331    /// [`retain`](Self::retain) if the removed keys are not needed.
332    ///
333    /// ```
334    /// use paged_collections::bit_set::PagedBitSet;
335    ///
336    /// let mut set: PagedBitSet<u32> = (0..6).collect();
337    /// assert_eq!(set.extract_if(|k| k % 2 == 1).collect::<Vec<_>>(), [1, 3, 5]);
338    /// assert_eq!(set.drain().collect::<Vec<_>>(), [0, 2, 4]);
339    /// assert!(set.is_empty());
340    /// ```
341    pub fn extract_if<F: FnMut(K) -> bool>(&mut self, pred: F) -> ExtractIf<'_, K, F, PAGE, D> {
342        ExtractIf {
343            set: self,
344            next: Some(0),
345            pred,
346        }
347    }
348
349    /// Removes all keys, keeping the allocated pages for reuse.
350    pub fn clear(&mut self) {
351        for (_, page) in self.pages.pages_mut() {
352            let removed: usize = page
353                .iter_mut()
354                .map(|word| core::mem::take(word).count_ones() as usize)
355                .sum();
356            self.len -= removed;
357        }
358    }
359
360    /// Removes all keys and frees all pages.
361    pub fn reset(&mut self) {
362        let pages = core::mem::take(&mut self.pages);
363        self.len = 0;
364        drop(pages);
365    }
366
367    /// Frees empty pages and shrinks the page directory.
368    pub fn shrink_to_fit(&mut self) {
369        if self.is_empty() {
370            self.pages.clear();
371        } else {
372            let empty: Vec<_> = self
373                .pages
374                .pages()
375                .filter(|(_, page)| page.iter().all(|&word| word == 0))
376                .map(|(number, _)| number)
377                .collect();
378            for number in empty {
379                self.pages.remove(number);
380            }
381        }
382        self.pages.shrink_to_fit();
383    }
384
385    /// Iterates over all keys in ascending slot-index order.
386    pub fn iter(&self) -> Iter<'_, K, PAGE, D> {
387        let words = WordPages {
388            pages: self.pages.pages(),
389            span: Span::FULL,
390        };
391        Iter(Cursor::new(words.flatten(), self.len), PhantomData)
392    }
393}
394
395fn locate<const PAGE: usize>(index: usize) -> (usize, usize, u64) {
396    let (number, offset) = split::<PAGE>(index / WORD_BITS);
397    (number, offset, 1 << (index % WORD_BITS))
398}
399
400fn page_start<const PAGE: usize>(number: usize) -> usize {
401    // Pages are allocated only for real slot indices, so their first word
402    // always has a representable word and bit index.
403    debug_assert!(number <= usize::MAX / WORD_BITS / PAGE);
404    number * PAGE
405}
406
407fn bit_index(word: usize, bit: u32) -> usize {
408    // A set bit came from a real slot index. Range masks also clip the last
409    // page to the last representable word.
410    debug_assert!(word <= usize::MAX / WORD_BITS && bit < u64::BITS);
411    word * WORD_BITS + bit as usize
412}
413
414fn checked_len(len: usize, added: usize) -> usize {
415    len.checked_add(added).expect("PagedBitSet length overflow")
416}
417
418fn write_word(len: &mut usize, word: &mut u64, new: u64) {
419    let updated = checked_len(*len - word.count_ones() as usize, new.count_ones() as usize);
420    *word = new;
421    *len = updated;
422}
423
424fn index_bounds<K: Key>(keys: &impl RangeBounds<K>) -> (Bound<usize>, Bound<usize>) {
425    (
426        keys.start_bound().map(|key| key.index()),
427        keys.end_bound().map(|key| key.index()),
428    )
429}
430
431// The inclusive slot bounds avoid a special case for an end at usize::MAX.
432#[derive(Clone, Copy)]
433struct Span {
434    first: usize,
435    last: usize,
436}
437
438impl Span {
439    const FULL: Self = Self {
440        first: 0,
441        last: usize::MAX,
442    };
443
444    fn new(indices: &impl RangeBounds<usize>) -> Option<Self> {
445        let first = match indices.start_bound() {
446            Bound::Included(&index) => index,
447            Bound::Excluded(&index) => index.checked_add(1)?,
448            Bound::Unbounded => 0,
449        };
450        let last = match indices.end_bound() {
451            Bound::Included(&index) => index,
452            Bound::Excluded(&index) => index.checked_sub(1)?,
453            Bound::Unbounded => usize::MAX,
454        };
455        (first <= last).then_some(Self { first, last })
456    }
457
458    fn pages<const PAGE: usize>(self) -> RangeInclusive<usize> {
459        let (first, _) = split::<PAGE>(self.first / WORD_BITS);
460        let (last, _) = split::<PAGE>(self.last / WORD_BITS);
461        first..=last
462    }
463
464    fn offsets(self, start: usize, page_len: usize) -> ops::Range<usize> {
465        let first = (self.first / WORD_BITS).saturating_sub(start).min(page_len);
466        let end = (self.last / WORD_BITS + 1)
467            .saturating_sub(start)
468            .min(page_len);
469        first..end
470    }
471
472    fn mask(self, word: usize) -> u64 {
473        let mut mask = u64::MAX;
474        if word == self.first / WORD_BITS {
475            mask &= u64::MAX << (self.first % WORD_BITS);
476        }
477        if word == self.last / WORD_BITS {
478            mask &= u64::MAX >> (WORD_BITS - 1 - self.last % WORD_BITS);
479        }
480        mask
481    }
482}
483
484#[derive(Clone, Copy, Default)]
485struct WordBits {
486    index: usize,
487    bits: u64,
488}
489
490impl Iterator for WordBits {
491    type Item = usize;
492
493    fn next(&mut self) -> Option<usize> {
494        if self.bits == 0 {
495            return None;
496        }
497        let bit = self.bits.trailing_zeros();
498        self.bits &= self.bits - 1;
499        Some(bit_index(self.index, bit))
500    }
501}
502
503impl DoubleEndedIterator for WordBits {
504    fn next_back(&mut self) -> Option<usize> {
505        if self.bits == 0 {
506            return None;
507        }
508        let bit = u64::BITS - 1 - self.bits.leading_zeros();
509        self.bits &= !(1 << bit);
510        Some(bit_index(self.index, bit))
511    }
512}
513
514#[derive(Clone)]
515struct PageWords<P, const PAGE: usize> {
516    page: P,
517    start: usize,
518    offsets: ops::Range<usize>,
519    span: Span,
520}
521
522impl<P: Deref<Target = [u64; PAGE]>, const PAGE: usize> PageWords<P, PAGE> {
523    fn new(number: usize, page: P, span: Span) -> Self {
524        let start = page_start::<PAGE>(number);
525        Self {
526            page,
527            start,
528            offsets: span.offsets(start, PAGE),
529            span,
530        }
531    }
532
533    fn word(&self, offset: usize) -> WordBits {
534        let index = self.start + offset;
535        WordBits {
536            index,
537            bits: self.page[offset] & self.span.mask(index),
538        }
539    }
540}
541
542impl<P: Deref<Target = [u64; PAGE]>, const PAGE: usize> Iterator for PageWords<P, PAGE> {
543    type Item = WordBits;
544
545    fn next(&mut self) -> Option<WordBits> {
546        let offset = self.offsets.next()?;
547        Some(self.word(offset))
548    }
549}
550
551impl<P: Deref<Target = [u64; PAGE]>, const PAGE: usize> DoubleEndedIterator for PageWords<P, PAGE> {
552    fn next_back(&mut self) -> Option<WordBits> {
553        let offset = self.offsets.next_back()?;
554        Some(self.word(offset))
555    }
556}
557
558#[derive(Clone)]
559struct WordPages<I, const PAGE: usize> {
560    pages: I,
561    span: Span,
562}
563
564impl<I, P, const PAGE: usize> Iterator for WordPages<I, PAGE>
565where
566    I: Iterator<Item = (usize, P)>,
567    P: Deref<Target = [u64; PAGE]>,
568{
569    type Item = PageWords<P, PAGE>;
570
571    fn next(&mut self) -> Option<Self::Item> {
572        let (number, page) = self.pages.next()?;
573        Some(PageWords::new(number, page, self.span))
574    }
575}
576
577impl<I, P, const PAGE: usize> DoubleEndedIterator for WordPages<I, PAGE>
578where
579    I: DoubleEndedIterator<Item = (usize, P)>,
580    P: Deref<Target = [u64; PAGE]>,
581{
582    fn next_back(&mut self) -> Option<Self::Item> {
583        let (number, page) = self.pages.next_back()?;
584        Some(PageWords::new(number, page, self.span))
585    }
586}
587
588#[derive(Clone)]
589struct Cursor<W: Iterator<Item = WordBits>> {
590    // Flatten shares the last page and the last word between the front and
591    // back. Each WordBits value clears yielded bits from that shared copy.
592    bits: Flatten<W>,
593    remaining: usize,
594}
595
596impl<W: DoubleEndedIterator<Item = WordBits>> Cursor<W> {
597    fn new(words: W, remaining: usize) -> Self {
598        Self {
599            bits: words.flatten(),
600            remaining,
601        }
602    }
603
604    fn next(&mut self) -> Option<usize> {
605        if self.remaining == 0 {
606            return None;
607        }
608        let index = self.bits.next();
609        self.remaining = if index.is_some() {
610            self.remaining - 1
611        } else {
612            0
613        };
614        index
615    }
616
617    fn next_back(&mut self) -> Option<usize> {
618        if self.remaining == 0 {
619            return None;
620        }
621        let index = self.bits.next_back();
622        self.remaining = if index.is_some() {
623            self.remaining - 1
624        } else {
625            0
626        };
627        index
628    }
629}
630
631/// The keys removed by [`PagedBitSet::drain`], in slot-index order.
632pub struct Drain<
633    'a,
634    K: DirectKey<Tag = ()>,
635    const PAGE: usize = DEFAULT_BIT_PAGE,
636    D: Directory = Flat,
637> {
638    set: &'a mut PagedBitSet<K, PAGE, D>,
639    // The slot index to resume from; `None` once the last slot is passed.
640    next: Option<usize>,
641}
642
643impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> Iterator for Drain<'_, K, PAGE, D> {
644    type Item = K;
645
646    fn next(&mut self) -> Option<K> {
647        let Some(key) = self.set.next_occupant(self.next?) else {
648            self.next = None;
649            return None;
650        };
651        let next = key.index().checked_add(1);
652        self.set.remove(key);
653        // Commit the cursor only after the removal, so that every key
654        // before it is gone even if a custom `Key::index` panics.
655        self.next = next;
656        Some(key)
657    }
658
659    fn size_hint(&self) -> (usize, Option<usize>) {
660        // Every key before the cursor has been removed.
661        (self.set.len, Some(self.set.len))
662    }
663}
664
665impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> ExactSizeIterator
666    for Drain<'_, K, PAGE, D>
667{
668}
669
670impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> FusedIterator
671    for Drain<'_, K, PAGE, D>
672{
673}
674
675impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> Drop for Drain<'_, K, PAGE, D> {
676    fn drop(&mut self) {
677        self.for_each(drop);
678    }
679}
680
681impl<K: DirectKey<Tag = ()> + fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
682    for Drain<'_, K, PAGE, D>
683{
684    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
685        // Every key still in the set is yet to be yielded.
686        f.debug_list().entries(self.set.iter()).finish()
687    }
688}
689
690/// The keys removed by [`PagedBitSet::extract_if`], in slot-index order.
691pub struct ExtractIf<
692    'a,
693    K: DirectKey<Tag = ()>,
694    F,
695    const PAGE: usize = DEFAULT_BIT_PAGE,
696    D: Directory = Flat,
697> {
698    set: &'a mut PagedBitSet<K, PAGE, D>,
699    next: Option<usize>,
700    pred: F,
701}
702
703impl<K: DirectKey<Tag = ()>, F: FnMut(K) -> bool, const PAGE: usize, D: Directory> Iterator
704    for ExtractIf<'_, K, F, PAGE, D>
705{
706    type Item = K;
707
708    fn next(&mut self) -> Option<K> {
709        loop {
710            let Some(key) = self.set.next_occupant(self.next?) else {
711                self.next = None;
712                return None;
713            };
714            // Advance first: if `pred` panics, this key stays.
715            self.next = key.index().checked_add(1);
716            if (self.pred)(key) {
717                self.set.remove(key);
718                return Some(key);
719            }
720        }
721    }
722
723    fn size_hint(&self) -> (usize, Option<usize>) {
724        (0, Some(if self.next.is_some() { self.set.len } else { 0 }))
725    }
726}
727
728impl<K: DirectKey<Tag = ()>, F: FnMut(K) -> bool, const PAGE: usize, D: Directory> FusedIterator
729    for ExtractIf<'_, K, F, PAGE, D>
730{
731}
732
733impl<K: DirectKey<Tag = ()>, F, const PAGE: usize, D: Directory> fmt::Debug
734    for ExtractIf<'_, K, F, PAGE, D>
735{
736    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737        f.debug_struct("ExtractIf")
738            .field("next", &self.next)
739            .finish_non_exhaustive()
740    }
741}
742
743/// A borrowed iterator over all the keys of a [`PagedBitSet`], in slot-index order.
744pub struct Iter<'a, K, const PAGE: usize = DEFAULT_BIT_PAGE, D: Directory = Flat>(
745    Cursor<Flatten<WordPages<Pages<'a, PAGE, D>, PAGE>>>,
746    PhantomData<fn() -> K>,
747)
748where
749    D: 'a;
750
751/// A borrowed iterator over the keys in a range, in slot-index order.
752pub struct Range<'a, K, const PAGE: usize = DEFAULT_BIT_PAGE, D: Directory = Flat>(
753    Cursor<Flatten<WordPages<Pages<'a, PAGE, D>, PAGE>>>,
754    PhantomData<fn() -> K>,
755)
756where
757    D: 'a;
758
759/// An owning iterator over all the keys of a [`PagedBitSet`], in slot-index order.
760pub struct IntoIter<K, const PAGE: usize = DEFAULT_BIT_PAGE, D: Directory = Flat>(
761    Cursor<Flatten<WordPages<IntoPages<PAGE, D>, PAGE>>>,
762    PhantomData<fn() -> K>,
763);
764
765macro_rules! impl_iterator {
766    ($name:ident $(<$lt:lifetime>)?, $exact:literal) => {
767        impl<$($lt,)? K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> Iterator
768            for $name<$($lt,)? K, PAGE, D>
769            $(where D: $lt)?
770        {
771            type Item = K;
772
773            fn next(&mut self) -> Option<K> {
774                self.0.next().map(|index| K::from_parts(index, ()))
775            }
776
777            fn size_hint(&self) -> (usize, Option<usize>) {
778                let remaining = self.0.remaining;
779                (if $exact { remaining } else { 0 }, Some(remaining))
780            }
781        }
782
783        impl<$($lt,)? K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> DoubleEndedIterator
784            for $name<$($lt,)? K, PAGE, D>
785            $(where D: $lt)?
786        {
787            fn next_back(&mut self) -> Option<K> {
788                self.0.next_back().map(|index| K::from_parts(index, ()))
789            }
790        }
791
792        impl<$($lt,)? K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> FusedIterator
793            for $name<$($lt,)? K, PAGE, D>
794            $(where D: $lt)?
795        {}
796    };
797}
798
799impl_iterator!(Iter<'a>, true);
800impl_iterator!(Range<'a>, false);
801impl_iterator!(IntoIter, true);
802
803impl<'a, K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> ExactSizeIterator
804    for Iter<'a, K, PAGE, D>
805where
806    D: 'a,
807{
808}
809
810impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> ExactSizeIterator
811    for IntoIter<K, PAGE, D>
812{
813}
814
815impl<'a, K, const PAGE: usize, D: Directory> Clone for Iter<'a, K, PAGE, D>
816where
817    D: 'a,
818{
819    fn clone(&self) -> Self {
820        Self(self.0.clone(), PhantomData)
821    }
822}
823
824impl<'a, K, const PAGE: usize, D: Directory> Clone for Range<'a, K, PAGE, D>
825where
826    D: 'a,
827{
828    fn clone(&self) -> Self {
829        Self(self.0.clone(), PhantomData)
830    }
831}
832
833impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> Default for PagedBitSet<K, PAGE, D> {
834    fn default() -> Self {
835        Self::new()
836    }
837}
838
839impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> Clone for PagedBitSet<K, PAGE, D>
840where
841    Store<PAGE, D>: Clone,
842{
843    fn clone(&self) -> Self {
844        Self {
845            pages: self.pages.clone(),
846            len: self.len,
847            _key: PhantomData,
848        }
849    }
850}
851
852impl<K: DirectKey<Tag = ()> + fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
853    for PagedBitSet<K, PAGE, D>
854{
855    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856        f.debug_set().entries(self).finish()
857    }
858}
859
860impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> Extend<K>
861    for PagedBitSet<K, PAGE, D>
862{
863    fn extend<I: IntoIterator<Item = K>>(&mut self, iter: I) {
864        for key in iter {
865            self.insert(key);
866        }
867    }
868}
869
870impl<'a, K: DirectKey<Tag = ()> + 'a, const PAGE: usize, D: Directory> Extend<&'a K>
871    for PagedBitSet<K, PAGE, D>
872{
873    fn extend<I: IntoIterator<Item = &'a K>>(&mut self, iter: I) {
874        self.extend(iter.into_iter().copied());
875    }
876}
877
878impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> FromIterator<K>
879    for PagedBitSet<K, PAGE, D>
880{
881    fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
882        let mut set = Self::new();
883        set.extend(iter);
884        set
885    }
886}
887
888impl<'a, K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> IntoIterator
889    for &'a PagedBitSet<K, PAGE, D>
890{
891    type Item = K;
892    type IntoIter = Iter<'a, K, PAGE, D>;
893
894    fn into_iter(self) -> Self::IntoIter {
895        self.iter()
896    }
897}
898
899impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> IntoIterator
900    for PagedBitSet<K, PAGE, D>
901{
902    type Item = K;
903    type IntoIter = IntoIter<K, PAGE, D>;
904
905    fn into_iter(self) -> Self::IntoIter {
906        let words = WordPages {
907            pages: self.pages.into_pages(),
908            span: Span::FULL,
909        };
910        IntoIter(Cursor::new(words.flatten(), self.len), PhantomData)
911    }
912}
913
914#[derive(Clone, Copy)]
915enum Algebra {
916    Union,
917    Intersection,
918    Difference,
919    SymmetricDifference,
920}
921
922impl Algebra {
923    fn word(self, left: u64, right: u64) -> u64 {
924        match self {
925            Self::Union => left | right,
926            Self::Intersection => left & right,
927            Self::Difference => left & !right,
928            Self::SymmetricDifference => left ^ right,
929        }
930    }
931}
932
933type Page<'a, const PAGE: usize> = (usize, &'a [u64; PAGE]);
934
935struct PageMerge<'a, const PAGE: usize, D: Directory, D2: Directory>
936where
937    D: 'a,
938    D2: 'a,
939{
940    left: Peekable<Fuse<Pages<'a, PAGE, D>>>,
941    right: Peekable<Fuse<Pages<'a, PAGE, D2>>>,
942    op: Algebra,
943}
944
945impl<'a, const PAGE: usize, D: Directory, D2: Directory> Clone for PageMerge<'a, PAGE, D, D2>
946where
947    D: 'a,
948    D2: 'a,
949{
950    fn clone(&self) -> Self {
951        Self {
952            left: self.left.clone(),
953            right: self.right.clone(),
954            op: self.op,
955        }
956    }
957}
958
959impl<'a, const PAGE: usize, D: Directory, D2: Directory> PageMerge<'a, PAGE, D, D2>
960where
961    D: 'a,
962    D2: 'a,
963{
964    fn new(left: Pages<'a, PAGE, D>, right: Pages<'a, PAGE, D2>, op: Algebra) -> Self {
965        Self {
966            left: left.fuse().peekable(),
967            right: right.fuse().peekable(),
968            op,
969        }
970    }
971}
972
973#[derive(Clone)]
974struct CombinedWords<'a, const PAGE: usize> {
975    number: usize,
976    left: Option<&'a [u64; PAGE]>,
977    right: Option<&'a [u64; PAGE]>,
978    op: Algebra,
979    offsets: ops::Range<usize>,
980}
981
982impl<const PAGE: usize> Iterator for CombinedWords<'_, PAGE> {
983    type Item = (usize, u64);
984
985    fn next(&mut self) -> Option<Self::Item> {
986        let offset = self.offsets.next()?;
987        let left = self.left.map_or(0, |page| page[offset]);
988        let right = self.right.map_or(0, |page| page[offset]);
989        Some((offset, self.op.word(left, right)))
990    }
991}
992
993impl<'a, const PAGE: usize, D: Directory, D2: Directory> Iterator for PageMerge<'a, PAGE, D, D2>
994where
995    D: 'a,
996    D2: 'a,
997{
998    type Item = CombinedWords<'a, PAGE>;
999
1000    fn next(&mut self) -> Option<Self::Item> {
1001        loop {
1002            let (left, right): (Option<Page<'a, PAGE>>, Option<Page<'a, PAGE>>) =
1003                match (self.left.peek(), self.right.peek()) {
1004                    (Some((left, _)), Some((right, _))) => match left.cmp(right) {
1005                        Ordering::Less => (self.left.next(), None),
1006                        Ordering::Equal => (self.left.next(), self.right.next()),
1007                        Ordering::Greater => (None, self.right.next()),
1008                    },
1009                    (Some(_), None) => (self.left.next(), None),
1010                    (None, Some(_)) => (None, self.right.next()),
1011                    (None, None) => return None,
1012                };
1013            let number = left.or(right)?.0;
1014            match self.op {
1015                Algebra::Intersection if left.is_none() || right.is_none() => continue,
1016                Algebra::Difference if left.is_none() => continue,
1017                _ => {}
1018            }
1019            return Some(CombinedWords {
1020                number,
1021                left: left.map(|(_, page)| page),
1022                right: right.map(|(_, page)| page),
1023                op: self.op,
1024                offsets: 0..PAGE,
1025            });
1026        }
1027    }
1028}
1029
1030struct AlgebraIter<'a, K, const PAGE: usize, D: Directory, D2: Directory>
1031where
1032    D: 'a,
1033    D2: 'a,
1034{
1035    pages: PageMerge<'a, PAGE, D, D2>,
1036    words: Option<CombinedWords<'a, PAGE>>,
1037    bits: WordBits,
1038    key: PhantomData<fn() -> K>,
1039}
1040
1041impl<'a, K, const PAGE: usize, D: Directory, D2: Directory> Clone
1042    for AlgebraIter<'a, K, PAGE, D, D2>
1043where
1044    D: 'a,
1045    D2: 'a,
1046{
1047    fn clone(&self) -> Self {
1048        Self {
1049            pages: self.pages.clone(),
1050            words: self.words.clone(),
1051            bits: self.bits,
1052            key: PhantomData,
1053        }
1054    }
1055}
1056
1057impl<'a, K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory, D2: Directory> Iterator
1058    for AlgebraIter<'a, K, PAGE, D, D2>
1059where
1060    D: 'a,
1061    D2: 'a,
1062{
1063    type Item = K;
1064
1065    fn next(&mut self) -> Option<K> {
1066        loop {
1067            if let Some(index) = self.bits.next() {
1068                return Some(K::from_parts(index, ()));
1069            }
1070            if let Some(words) = &mut self.words {
1071                if let Some((offset, bits)) = words.find(|&(_, bits)| bits != 0) {
1072                    self.bits = WordBits {
1073                        index: page_start::<PAGE>(words.number) + offset,
1074                        bits,
1075                    };
1076                    continue;
1077                }
1078            }
1079            self.words = Some(self.pages.next()?);
1080        }
1081    }
1082}
1083
1084impl<'a, K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory, D2: Directory> FusedIterator
1085    for AlgebraIter<'a, K, PAGE, D, D2>
1086where
1087    D: 'a,
1088    D2: 'a,
1089{
1090}
1091
1092macro_rules! algebra_iterator {
1093    ($($(#[$doc:meta])* $name:ident,)*) => {$(
1094        $(#[$doc])*
1095        pub struct $name<'a, K, const PAGE: usize, D: Directory, D2: Directory>(
1096            AlgebraIter<'a, K, PAGE, D, D2>,
1097        )
1098        where
1099            D: 'a,
1100            D2: 'a;
1101
1102        impl<'a, K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory, D2: Directory> Iterator
1103            for $name<'a, K, PAGE, D, D2>
1104        where
1105            D: 'a,
1106            D2: 'a,
1107        {
1108            type Item = K;
1109
1110            #[inline]
1111            fn next(&mut self) -> Option<K> {
1112                self.0.next()
1113            }
1114        }
1115
1116        impl<'a, K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory, D2: Directory>
1117            FusedIterator for $name<'a, K, PAGE, D, D2>
1118        where
1119            D: 'a,
1120            D2: 'a,
1121        {
1122        }
1123
1124        impl<'a, K, const PAGE: usize, D: Directory, D2: Directory> Clone
1125            for $name<'a, K, PAGE, D, D2>
1126        where
1127            D: 'a,
1128            D2: 'a,
1129        {
1130            fn clone(&self) -> Self {
1131                Self(self.0.clone())
1132            }
1133        }
1134
1135        impl<'a, K, const PAGE: usize, D: Directory, D2: Directory> fmt::Debug
1136            for $name<'a, K, PAGE, D, D2>
1137        where
1138            D: 'a,
1139            D2: 'a,
1140        {
1141            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1142                f.debug_struct(stringify!($name)).finish_non_exhaustive()
1143            }
1144        }
1145    )*};
1146}
1147
1148algebra_iterator! {
1149    /// Iterator over the keys in either of two [`PagedBitSet`]s, in ascending
1150    /// slot-index order, from [`PagedBitSet::union`].
1151    Union,
1152    /// Iterator over the keys in both of two [`PagedBitSet`]s, in ascending
1153    /// slot-index order, from [`PagedBitSet::intersection`].
1154    Intersection,
1155    /// Iterator over the keys in one [`PagedBitSet`] and not another, in
1156    /// ascending slot-index order, from [`PagedBitSet::difference`].
1157    Difference,
1158    /// Iterator over the keys in exactly one of two [`PagedBitSet`]s, in
1159    /// ascending slot-index order, from [`PagedBitSet::symmetric_difference`].
1160    SymmetricDifference,
1161}
1162
1163impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> PagedBitSet<K, PAGE, D> {
1164    /// Returns whether the two sets have no key in common.
1165    pub fn is_disjoint<D2: Directory>(&self, other: &PagedBitSet<K, PAGE, D2>) -> bool {
1166        self.pages.pages().all(|(number, left)| {
1167            other
1168                .pages
1169                .get(number)
1170                .is_none_or(|right| left.iter().zip(right).all(|(a, b)| a & b == 0))
1171        })
1172    }
1173
1174    /// Returns whether every key in this set is also in `other`.
1175    pub fn is_subset<D2: Directory>(&self, other: &PagedBitSet<K, PAGE, D2>) -> bool {
1176        self.len <= other.len
1177            && self.pages.pages().all(|(number, left)| {
1178                if let Some(right) = other.pages.get(number) {
1179                    left.iter().zip(right).all(|(a, b)| a & !b == 0)
1180                } else {
1181                    left.iter().all(|&word| word == 0)
1182                }
1183            })
1184    }
1185
1186    /// Returns whether every key in `other` is also in this set.
1187    pub fn is_superset<D2: Directory>(&self, other: &PagedBitSet<K, PAGE, D2>) -> bool {
1188        other.is_subset(self)
1189    }
1190
1191    /// Iterates over keys in either set, in ascending slot-index order.
1192    ///
1193    /// ```
1194    /// use paged_collections::bit_set::PagedBitSet;
1195    /// use paged_collections::page::Tree;
1196    ///
1197    /// let a: PagedBitSet<usize, 2> = [1, 5].into_iter().collect();
1198    /// let b: PagedBitSet<usize, 2, Tree> = [2, 5].into_iter().collect();
1199    /// assert_eq!(a.union(&b).collect::<Vec<_>>(), [1, 2, 5]);
1200    /// assert_eq!((&a & &b).iter().collect::<Vec<_>>(), [5]);
1201    /// ```
1202    pub fn union<'a, D2: Directory>(
1203        &'a self,
1204        other: &'a PagedBitSet<K, PAGE, D2>,
1205    ) -> Union<'a, K, PAGE, D, D2> {
1206        Union(self.algebra(other, Algebra::Union))
1207    }
1208
1209    /// Iterates over keys in both sets, in ascending slot-index order.
1210    pub fn intersection<'a, D2: Directory>(
1211        &'a self,
1212        other: &'a PagedBitSet<K, PAGE, D2>,
1213    ) -> Intersection<'a, K, PAGE, D, D2> {
1214        Intersection(self.algebra(other, Algebra::Intersection))
1215    }
1216
1217    /// Iterates over keys in this set that are absent from `other`, in
1218    /// ascending slot-index order.
1219    pub fn difference<'a, D2: Directory>(
1220        &'a self,
1221        other: &'a PagedBitSet<K, PAGE, D2>,
1222    ) -> Difference<'a, K, PAGE, D, D2> {
1223        Difference(self.algebra(other, Algebra::Difference))
1224    }
1225
1226    /// Iterates over keys in exactly one set, in ascending slot-index order.
1227    pub fn symmetric_difference<'a, D2: Directory>(
1228        &'a self,
1229        other: &'a PagedBitSet<K, PAGE, D2>,
1230    ) -> SymmetricDifference<'a, K, PAGE, D, D2> {
1231        SymmetricDifference(self.algebra(other, Algebra::SymmetricDifference))
1232    }
1233
1234    fn algebra<'a, D2: Directory>(
1235        &'a self,
1236        other: &'a PagedBitSet<K, PAGE, D2>,
1237        op: Algebra,
1238    ) -> AlgebraIter<'a, K, PAGE, D, D2> {
1239        AlgebraIter {
1240            pages: PageMerge::new(self.pages.pages(), other.pages.pages(), op),
1241            words: None,
1242            bits: WordBits::default(),
1243            key: PhantomData,
1244        }
1245    }
1246
1247    fn combined<D2: Directory>(&self, other: &PagedBitSet<K, PAGE, D2>, op: Algebra) -> Self {
1248        let mut result = Self::new();
1249        for words in PageMerge::<PAGE, D, D2>::new(self.pages.pages(), other.pages.pages(), op) {
1250            let number = words.number;
1251            let mut nonzero = words.filter(|&(_, word)| word != 0);
1252            if let Some(first) = nonzero.next() {
1253                let page = result.pages.get_or_alloc(number);
1254                for (offset, word) in once(first).chain(nonzero) {
1255                    write_word(&mut result.len, &mut page[offset], word);
1256                }
1257            }
1258        }
1259        result
1260    }
1261
1262    fn assign<D2: Directory>(&mut self, other: &PagedBitSet<K, PAGE, D2>, op: Algebra) {
1263        match op {
1264            Algebra::Union | Algebra::SymmetricDifference => {
1265                for (number, right) in other.pages.pages() {
1266                    if right.iter().all(|&word| word == 0) {
1267                        continue;
1268                    }
1269                    let left = self.pages.get_or_alloc(number);
1270                    for (word, &right) in left.iter_mut().zip(right) {
1271                        let new = op.word(*word, right);
1272                        write_word(&mut self.len, word, new);
1273                    }
1274                }
1275            }
1276            Algebra::Intersection | Algebra::Difference => {
1277                for (number, left) in self.pages.pages_mut() {
1278                    let right = other.pages.get(number);
1279                    if right.is_none() && matches!(op, Algebra::Difference) {
1280                        continue;
1281                    }
1282                    for (offset, word) in left.iter_mut().enumerate() {
1283                        let new = op.word(*word, right.map_or(0, |page| page[offset]));
1284                        write_word(&mut self.len, word, new);
1285                    }
1286                }
1287            }
1288        }
1289    }
1290}
1291
1292macro_rules! impl_algebra {
1293    ($binary:ident, $binary_fn:ident, $assign:ident, $assign_fn:ident, $op:ident) => {
1294        impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory, D2: Directory>
1295            ops::$binary<&PagedBitSet<K, PAGE, D2>> for &PagedBitSet<K, PAGE, D>
1296        {
1297            type Output = PagedBitSet<K, PAGE, D>;
1298
1299            fn $binary_fn(self, other: &PagedBitSet<K, PAGE, D2>) -> Self::Output {
1300                self.combined(other, Algebra::$op)
1301            }
1302        }
1303
1304        impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory, D2: Directory>
1305            ops::$assign<&PagedBitSet<K, PAGE, D2>> for PagedBitSet<K, PAGE, D>
1306        {
1307            fn $assign_fn(&mut self, other: &PagedBitSet<K, PAGE, D2>) {
1308                self.assign(other, Algebra::$op);
1309            }
1310        }
1311    };
1312}
1313
1314impl_algebra!(BitOr, bitor, BitOrAssign, bitor_assign, Union);
1315impl_algebra!(BitAnd, bitand, BitAndAssign, bitand_assign, Intersection);
1316impl_algebra!(Sub, sub, SubAssign, sub_assign, Difference);
1317impl_algebra!(
1318    BitXor,
1319    bitxor,
1320    BitXorAssign,
1321    bitxor_assign,
1322    SymmetricDifference
1323);
1324
1325/// Compares the set bits, ignoring empty pages and the directory layout.
1326impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory, D2: Directory>
1327    PartialEq<PagedBitSet<K, PAGE, D2>> for PagedBitSet<K, PAGE, D>
1328{
1329    fn eq(&self, other: &PagedBitSet<K, PAGE, D2>) -> bool {
1330        self.len == other.len && self.is_subset(other)
1331    }
1332}
1333
1334impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> Eq for PagedBitSet<K, PAGE, D> {}
1335
1336/// Hashes the length and the nonzero words in ascending word-index order.
1337impl<K: DirectKey<Tag = ()>, const PAGE: usize, D: Directory> Hash for PagedBitSet<K, PAGE, D> {
1338    fn hash<H: Hasher>(&self, state: &mut H) {
1339        self.len.hash(state);
1340        for (number, page) in self.pages.pages() {
1341            let start = page_start::<PAGE>(number);
1342            for (offset, &word) in page.iter().enumerate() {
1343                if word != 0 {
1344                    (start + offset, word).hash(state);
1345                }
1346            }
1347        }
1348    }
1349}
1350
1351#[cfg(feature = "rayon")]
1352pub use rayon_impl::ParIter;
1353
1354#[cfg(feature = "rayon")]
1355mod rayon_impl {
1356    use super::*;
1357    use rayon::iter::plumbing::UnindexedConsumer;
1358    use rayon::prelude::*;
1359
1360    /// An unindexed parallel iterator over the keys of a [`PagedBitSet`].
1361    ///
1362    /// Iteration splits by page. Collecting into a `Vec` preserves
1363    /// slot-index order.
1364    pub struct ParIter<'a, K, const PAGE: usize = DEFAULT_BIT_PAGE> {
1365        pages: Vec<Page<'a, PAGE>>,
1366        key: PhantomData<fn() -> K>,
1367    }
1368
1369    impl<'a, K: DirectKey<Tag = ()> + Send, const PAGE: usize, D: Directory> IntoParallelIterator
1370        for &'a PagedBitSet<K, PAGE, D>
1371    {
1372        type Item = K;
1373        type Iter = ParIter<'a, K, PAGE>;
1374
1375        fn into_par_iter(self) -> Self::Iter {
1376            ParIter {
1377                pages: self.pages.pages().collect(),
1378                key: PhantomData,
1379            }
1380        }
1381    }
1382
1383    impl<K: DirectKey<Tag = ()> + Send, const PAGE: usize> ParallelIterator for ParIter<'_, K, PAGE> {
1384        type Item = K;
1385
1386        fn drive_unindexed<C: UnindexedConsumer<K>>(self, consumer: C) -> C::Result {
1387            self.pages
1388                .into_par_iter()
1389                .flat_map_iter(|(number, page)| {
1390                    PageWords::new(number, page, Span::FULL)
1391                        .flatten()
1392                        .map(|index| K::from_parts(index, ()))
1393                })
1394                .drive_unindexed(consumer)
1395        }
1396    }
1397}
1398
1399#[cfg(feature = "serde")]
1400mod serde_impl {
1401    use super::*;
1402    use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
1403    use serde::ser::{Serialize, Serializer};
1404
1405    /// Serializes as a sequence of keys in ascending slot-index order.
1406    impl<K: DirectKey<Tag = ()> + Serialize, const PAGE: usize, D: Directory> Serialize
1407        for PagedBitSet<K, PAGE, D>
1408    {
1409        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1410            serializer.collect_seq(self.iter())
1411        }
1412    }
1413
1414    /// Deserializes from a sequence of keys, skipping duplicates.
1415    ///
1416    /// Memory follows the key indices. With the [`Flat`] directory one large
1417    /// index allocates a directory entry for every page below it. For
1418    /// untrusted input, use [`Radix`](crate::page::Radix) or
1419    /// [`Tree`](crate::page::Tree), or validate the keys first.
1420    impl<'de, K: DirectKey<Tag = ()> + Deserialize<'de>, const PAGE: usize, D: Directory>
1421        Deserialize<'de> for PagedBitSet<K, PAGE, D>
1422    {
1423        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1424            struct SeqVisitor<K, const PAGE: usize, D>(PhantomData<(K, D)>);
1425
1426            impl<'de, K: DirectKey<Tag = ()> + Deserialize<'de>, const PAGE: usize, D: Directory>
1427                Visitor<'de> for SeqVisitor<K, PAGE, D>
1428            {
1429                type Value = PagedBitSet<K, PAGE, D>;
1430
1431                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1432                    f.write_str("a sequence of keys")
1433                }
1434
1435                fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
1436                    let mut set = PagedBitSet::new();
1437                    while let Some(key) = seq.next_element()? {
1438                        set.insert(key);
1439                    }
1440                    Ok(set)
1441                }
1442            }
1443
1444            deserializer.deserialize_seq(SeqVisitor::<K, PAGE, D>(PhantomData))
1445        }
1446    }
1447}