Skip to main content

paged_collections/
page.rs

1//! Page directories: where the pages of a paged index live.
2//!
3//! A paged index splits slot indices into a page number and an offset
4//! (`index / PAGE`, `index % PAGE`). Pages are fixed-size arrays allocated on
5//! first write. The *directory* maps page numbers to pages and comes in three
6//! strategies, picked at the type level with a [`Directory`] marker:
7//!
8//! | Marker | Store | Page lookup | Directory memory |
9//! |---|---|---|---|
10//! | [`Flat`] | `Vec<Option<Box<[T; PAGE]>>>` | O(1), one indirection | one pointer per page up to the highest page used |
11//! | [`Radix`] | flat window for low page numbers, then a path-compressed 64-ary trie | O(1) in the window, else O(depth), at most ceil(usize bits / 6) branches | proportional to the peak allocated page count (the window does not shrink below its highest live page) |
12//! | [`Tree`] | `BTreeMap<usize, Box<[T; PAGE]>>` | O(log pages) | proportional to allocated pages only |
13//!
14//! Use [`Flat`] (the default) when indices stay below a few billion, for
15//! example `u32` keys: the directory then holds at most `ceil(2^32 / PAGE)`
16//! pointer-sized entries (32 MiB for the default page size, plus up to as
17//! much again in `Vec` growth capacity until
18//! [`shrink_to_fit`](PageStore::shrink_to_fit)). Use [`Radix`]
19//! for indices spread over the 64-bit range, where a flat directory would be
20//! too large to allocate. Use [`Tree`] for a standard B-tree structure, or
21//! when benchmarks show it wins for your key pattern.
22
23use alloc::boxed::Box;
24use alloc::collections::{BTreeMap, btree_map};
25use alloc::vec::Vec;
26use core::fmt;
27use core::iter::{Enumerate, FilterMap, Map, Zip};
28use core::ops::{Bound, Range, RangeInclusive};
29use core::slice;
30
31/// Default number of slots per page.
32///
33/// With 4-byte slots this makes 4 KiB pages, the usual OS page size.
34pub const DEFAULT_PAGE: usize = 1024;
35
36/// Splits a slot index into `(page number, offset within the page)`.
37///
38/// Fails to compile when `PAGE` is zero.
39#[inline]
40pub const fn split<const PAGE: usize>(index: usize) -> (usize, usize) {
41    const { assert!(PAGE > 0, "page size must be non-zero") };
42    (index / PAGE, index % PAGE)
43}
44
45/// Allocates one page with every slot set to `T::default()`.
46///
47/// The page is built directly on the heap, so large pages never pass through
48/// the stack.
49fn new_page<T: Default, const PAGE: usize>() -> Box<[T; PAGE]> {
50    let slots: Box<[T]> = (0..PAGE).map(|_| T::default()).collect();
51    match slots.try_into() {
52        Ok(page) => page,
53        Err(_) => unreachable!("iterator yielded exactly PAGE slots"),
54    }
55}
56
57/// Storage for the pages of one paged index.
58///
59/// Implemented by [`FlatPages`], [`RadixPages`] and [`TreePages`];
60/// collections reach them through a [`Directory`] marker.
61///
62/// # Contract for other implementations
63///
64/// [`get`](Self::get), [`get_mut`](Self::get_mut) and
65/// [`allocated`](Self::allocated) must not panic. Collections call them while
66/// they update their dense arrays and index together, where a panic would
67/// leave the two out of step. As with [`Key`](crate::key::Key), breaking this
68/// cannot cause undefined behaviour, only wrong results or panics.
69///
70/// The page iterators ([`pages`](Self::pages), [`pages_mut`](Self::pages_mut),
71/// [`pages_in`](Self::pages_in), [`pages_in_mut`](Self::pages_in_mut),
72/// [`into_pages`](Self::into_pages)) must yield every allocated page (for the
73/// `_in` ones, every allocated page numbered in the range, and no other)
74/// exactly once, in ascending page-number order: ordered collections rely on
75/// it.
76pub trait PageStore<T, const PAGE: usize>: Default {
77    /// Iterator over `(page number, page)` from [`pages`](Self::pages).
78    type Pages<'a>: DoubleEndedIterator<Item = (usize, &'a [T; PAGE])> + Clone
79    where
80        Self: 'a,
81        T: 'a;
82
83    /// Iterator over `(page number, page)` from [`pages_mut`](Self::pages_mut).
84    type PagesMut<'a>: DoubleEndedIterator<Item = (usize, &'a mut [T; PAGE])>
85    where
86        Self: 'a,
87        T: 'a;
88
89    /// Owning iterator over `(page number, page)` from
90    /// [`into_pages`](Self::into_pages).
91    type IntoPages: DoubleEndedIterator<Item = (usize, Box<[T; PAGE]>)>;
92
93    /// The page with this number, if it is allocated.
94    fn get(&self, page: usize) -> Option<&[T; PAGE]>;
95
96    /// Mutable access to the page with this number, if it is allocated.
97    fn get_mut(&mut self, page: usize) -> Option<&mut [T; PAGE]>;
98
99    /// The page with this number, allocating it (all slots `T::default()`)
100    /// if needed.
101    ///
102    /// # Panics
103    ///
104    /// Panics if `T::default()` panics, or if the directory cannot grow to hold this page number (for
105    /// [`FlatPages`], when the directory length would overflow `usize` or
106    /// the allocation fails).
107    fn get_or_alloc(&mut self, page: usize) -> &mut [T; PAGE]
108    where
109        T: Default;
110
111    /// Removes the page with this number and returns it, if it was allocated.
112    fn remove(&mut self, page: usize) -> Option<Box<[T; PAGE]>>;
113
114    /// Frees every page.
115    fn clear(&mut self);
116
117    /// Number of allocated pages.
118    fn allocated(&self) -> usize;
119
120    /// Releases directory memory that no allocated page needs.
121    fn shrink_to_fit(&mut self);
122
123    /// The allocated pages in ascending page-number order.
124    fn pages(&self) -> Self::Pages<'_>;
125
126    /// The allocated pages in ascending page-number order, mutably.
127    fn pages_mut(&mut self) -> Self::PagesMut<'_>;
128
129    /// The allocated pages numbered in `numbers`, in ascending order. An
130    /// empty range (start above end, or exhausted by iteration) yields
131    /// nothing.
132    ///
133    /// Reaching the first page costs O(1) for [`FlatPages`] and O(log pages)
134    /// for [`TreePages`], and O(depth) for [`RadixPages`]; [`FlatPages`] then
135    /// steps over the unallocated directory entries in the range.
136    fn pages_in(&self, numbers: RangeInclusive<usize>) -> Self::Pages<'_>;
137
138    /// Like [`pages_in`](Self::pages_in), mutably.
139    fn pages_in_mut(&mut self, numbers: RangeInclusive<usize>) -> Self::PagesMut<'_>;
140
141    /// Consumes the store and returns its pages in ascending page-number
142    /// order.
143    fn into_pages(self) -> Self::IntoPages;
144}
145
146/// Chooses the page store a collection uses.
147///
148/// This is a type-level switch: the collection names a marker ([`Flat`],
149/// [`Radix`] or [`Tree`]) and the marker names the store type for any slot
150/// type and page size.
151pub trait Directory {
152    /// The page store for slots of type `T` in pages of `PAGE` slots.
153    type Store<T, const PAGE: usize>: PageStore<T, PAGE>;
154}
155
156/// Marker for the flat, vector-backed directory ([`FlatPages`]).
157#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
158pub struct Flat;
159
160/// Marker for the tree-backed directory ([`TreePages`]).
161#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
162pub struct Tree;
163
164/// Marker for the path-compressed radix directory ([`RadixPages`]).
165#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
166pub struct Radix;
167
168impl Directory for Radix {
169    type Store<T, const PAGE: usize> = RadixPages<T, PAGE>;
170}
171
172impl Directory for Flat {
173    type Store<T, const PAGE: usize> = FlatPages<T, PAGE>;
174}
175
176impl Directory for Tree {
177    type Store<T, const PAGE: usize> = TreePages<T, PAGE>;
178}
179
180/// Pages in a vector indexed by page number.
181pub struct FlatPages<T, const PAGE: usize> {
182    pages: Vec<Option<Box<[T; PAGE]>>>,
183    allocated: usize,
184}
185
186impl<T, const PAGE: usize> Default for FlatPages<T, PAGE> {
187    fn default() -> Self {
188        Self {
189            pages: Vec::new(),
190            allocated: 0,
191        }
192    }
193}
194
195impl<T: Clone, const PAGE: usize> Clone for FlatPages<T, PAGE> {
196    fn clone(&self) -> Self {
197        Self {
198            pages: self.pages.clone(),
199            allocated: self.allocated,
200        }
201    }
202}
203
204impl<T, const PAGE: usize> fmt::Debug for FlatPages<T, PAGE> {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        f.debug_struct("FlatPages")
207            .field("page_size", &PAGE)
208            .field("directory_len", &self.pages.len())
209            .field("allocated", &self.allocated)
210            .finish()
211    }
212}
213
214type FlatEntry<T, const PAGE: usize> = Option<Box<[T; PAGE]>>;
215
216impl<T, const PAGE: usize> FlatPages<T, PAGE> {
217    /// The directory positions of the page numbers in `numbers`.
218    fn span(&self, numbers: RangeInclusive<usize>) -> Range<usize> {
219        // An exhausted range keeps its endpoints, so check it first.
220        if numbers.is_empty() {
221            return 0..0;
222        }
223        let end = numbers.end().saturating_add(1).min(self.pages.len());
224        (*numbers.start()).min(end)..end
225    }
226}
227
228impl<T, const PAGE: usize> PageStore<T, PAGE> for FlatPages<T, PAGE> {
229    type Pages<'a>
230        = FilterMap<
231        Zip<Range<usize>, slice::Iter<'a, FlatEntry<T, PAGE>>>,
232        fn((usize, &'a FlatEntry<T, PAGE>)) -> Option<(usize, &'a [T; PAGE])>,
233    >
234    where
235        T: 'a;
236
237    type PagesMut<'a>
238        = FilterMap<
239        Zip<Range<usize>, slice::IterMut<'a, FlatEntry<T, PAGE>>>,
240        fn((usize, &'a mut FlatEntry<T, PAGE>)) -> Option<(usize, &'a mut [T; PAGE])>,
241    >
242    where
243        T: 'a;
244
245    type IntoPages = FilterMap<
246        Enumerate<alloc::vec::IntoIter<FlatEntry<T, PAGE>>>,
247        fn((usize, FlatEntry<T, PAGE>)) -> Option<(usize, Box<[T; PAGE]>)>,
248    >;
249
250    #[inline]
251    fn get(&self, page: usize) -> Option<&[T; PAGE]> {
252        self.pages.get(page)?.as_deref()
253    }
254
255    #[inline]
256    fn get_mut(&mut self, page: usize) -> Option<&mut [T; PAGE]> {
257        self.pages.get_mut(page)?.as_deref_mut()
258    }
259
260    fn get_or_alloc(&mut self, page: usize) -> &mut [T; PAGE]
261    where
262        T: Default,
263    {
264        if page >= self.pages.len() {
265            let len = page.checked_add(1).expect("page directory overflow");
266            self.pages.resize_with(len, || None);
267        }
268        let entry = &mut self.pages[page];
269        if entry.is_none() {
270            // Build the page first: `T::default()` may panic.
271            *entry = Some(new_page::<T, PAGE>());
272            self.allocated += 1;
273        }
274        match entry {
275            Some(page) => page,
276            None => unreachable!("page was just allocated"),
277        }
278    }
279
280    fn remove(&mut self, page: usize) -> Option<Box<[T; PAGE]>> {
281        let removed = self.pages.get_mut(page)?.take();
282        if removed.is_some() {
283            self.allocated -= 1;
284        }
285        removed
286    }
287
288    fn clear(&mut self) {
289        // Reset the count first: dropping a page runs `T::drop`, which may
290        // panic after the vector is already emptied.
291        self.allocated = 0;
292        self.pages.clear();
293    }
294
295    #[inline]
296    fn allocated(&self) -> usize {
297        self.allocated
298    }
299
300    fn shrink_to_fit(&mut self) {
301        while matches!(self.pages.last(), Some(None)) {
302            self.pages.pop();
303        }
304        self.pages.shrink_to_fit();
305    }
306
307    fn pages(&self) -> Self::Pages<'_> {
308        self.pages_in(0..=usize::MAX)
309    }
310
311    fn pages_mut(&mut self) -> Self::PagesMut<'_> {
312        self.pages_in_mut(0..=usize::MAX)
313    }
314
315    fn pages_in(&self, numbers: RangeInclusive<usize>) -> Self::Pages<'_> {
316        let span = self.span(numbers);
317        span.clone()
318            .zip(self.pages[span].iter())
319            .filter_map(|(n, page)| Some((n, page.as_deref()?)))
320    }
321
322    fn pages_in_mut(&mut self, numbers: RangeInclusive<usize>) -> Self::PagesMut<'_> {
323        let span = self.span(numbers);
324        span.clone()
325            .zip(self.pages[span].iter_mut())
326            .filter_map(|(n, page)| Some((n, page.as_deref_mut()?)))
327    }
328
329    fn into_pages(self) -> Self::IntoPages {
330        self.pages
331            .into_iter()
332            .enumerate()
333            .filter_map(|(n, page)| Some((n, page?)))
334    }
335}
336
337/// `numbers` as bounds `BTreeMap::range` accepts: it panics on a start above
338/// the end, so an empty range becomes `0..0`.
339fn nonempty(numbers: RangeInclusive<usize>) -> (Bound<usize>, Bound<usize>) {
340    if numbers.is_empty() {
341        (Bound::Included(0), Bound::Excluded(0))
342    } else {
343        (
344            Bound::Included(*numbers.start()),
345            Bound::Included(*numbers.end()),
346        )
347    }
348}
349
350/// Pages in a B-tree keyed by page number.
351pub struct TreePages<T, const PAGE: usize> {
352    pages: BTreeMap<usize, Box<[T; PAGE]>>,
353}
354
355impl<T, const PAGE: usize> Default for TreePages<T, PAGE> {
356    fn default() -> Self {
357        Self {
358            pages: BTreeMap::new(),
359        }
360    }
361}
362
363impl<T: Clone, const PAGE: usize> Clone for TreePages<T, PAGE> {
364    fn clone(&self) -> Self {
365        Self {
366            pages: self.pages.clone(),
367        }
368    }
369}
370
371impl<T, const PAGE: usize> fmt::Debug for TreePages<T, PAGE> {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        f.debug_struct("TreePages")
374            .field("page_size", &PAGE)
375            .field("allocated", &self.pages.len())
376            .finish()
377    }
378}
379
380impl<T, const PAGE: usize> PageStore<T, PAGE> for TreePages<T, PAGE> {
381    type Pages<'a>
382        = Map<
383        btree_map::Range<'a, usize, Box<[T; PAGE]>>,
384        fn((&'a usize, &'a Box<[T; PAGE]>)) -> (usize, &'a [T; PAGE]),
385    >
386    where
387        T: 'a;
388
389    type PagesMut<'a>
390        = Map<
391        btree_map::RangeMut<'a, usize, Box<[T; PAGE]>>,
392        fn((&'a usize, &'a mut Box<[T; PAGE]>)) -> (usize, &'a mut [T; PAGE]),
393    >
394    where
395        T: 'a;
396
397    type IntoPages = btree_map::IntoIter<usize, Box<[T; PAGE]>>;
398
399    #[inline]
400    fn get(&self, page: usize) -> Option<&[T; PAGE]> {
401        self.pages.get(&page).map(|p| &**p)
402    }
403
404    #[inline]
405    fn get_mut(&mut self, page: usize) -> Option<&mut [T; PAGE]> {
406        self.pages.get_mut(&page).map(|p| &mut **p)
407    }
408
409    fn get_or_alloc(&mut self, page: usize) -> &mut [T; PAGE]
410    where
411        T: Default,
412    {
413        self.pages.entry(page).or_insert_with(new_page::<T, PAGE>)
414    }
415
416    fn remove(&mut self, page: usize) -> Option<Box<[T; PAGE]>> {
417        self.pages.remove(&page)
418    }
419
420    fn clear(&mut self) {
421        self.pages.clear();
422    }
423
424    #[inline]
425    fn allocated(&self) -> usize {
426        self.pages.len()
427    }
428
429    fn shrink_to_fit(&mut self) {}
430
431    fn pages(&self) -> Self::Pages<'_> {
432        self.pages_in(0..=usize::MAX)
433    }
434
435    fn pages_mut(&mut self) -> Self::PagesMut<'_> {
436        self.pages_in_mut(0..=usize::MAX)
437    }
438
439    fn pages_in(&self, numbers: RangeInclusive<usize>) -> Self::Pages<'_> {
440        self.pages
441            .range(nonempty(numbers))
442            .map(|(&n, page)| (n, &**page))
443    }
444
445    fn pages_in_mut(&mut self, numbers: RangeInclusive<usize>) -> Self::PagesMut<'_> {
446        self.pages
447            .range_mut(nonempty(numbers))
448            .map(|(&n, page)| (n, &mut **page))
449    }
450
451    fn into_pages(self) -> Self::IntoPages {
452        self.pages.into_iter()
453    }
454}
455
456/// The radix tree behind [`RadixPages`]: a bitmapped, path-compressed trie.
457///
458/// Page numbers may use the full `usize` range. Each branch examines six
459/// bits, and shared paths are compressed, so lookup costs O(depth) and
460/// directory memory is proportional to the number of allocated pages. The
461/// last six bits are resolved by a table of 64 page pointers, indexed
462/// directly, as soon as two pages share a group of 64.
463pub(crate) struct RadixTree<T, const PAGE: usize> {
464    root: Option<Child<T, PAGE>>,
465    allocated: usize,
466}
467
468/// A table slot: the page with that number, if allocated.
469type PageSlot<T, const PAGE: usize> = Option<Box<[T; PAGE]>>;
470
471/// Pointers to the pages of one aligned group of 64 page numbers.
472type Slots<T, const PAGE: usize> = [PageSlot<T, PAGE>; 64];
473
474#[derive(Clone)]
475enum Child<T, const PAGE: usize> {
476    /// A single page, at any depth (lazy expansion).
477    Leaf {
478        number: usize,
479        page: Box<[T; PAGE]>,
480    },
481    /// Pages `group * 64 .. group * 64 + 64`, at least two of them present
482    /// (`len` counts them). Replaces a branch on the lowest six bits.
483    Table {
484        group: usize,
485        len: u32,
486        slots: Box<Slots<T, PAGE>>,
487    },
488    // Inline, not boxed: a lookup then pays one dependent load per level
489    // (the parent's children buffer) instead of two.
490    Node(Node<T, PAGE>),
491}
492
493/// A branch on bits `shift .. shift + 6`; `shift` is a nonzero multiple of 6.
494#[derive(Clone)]
495struct Node<T, const PAGE: usize> {
496    shift: u32,
497    prefix: usize,
498    bitmap: u64,
499    children: Vec<Child<T, PAGE>>,
500}
501
502fn chunk(number: usize, shift: u32) -> u32 {
503    ((number >> shift) & 63) as u32
504}
505
506fn prefix(number: usize, shift: u32) -> usize {
507    // Two shifts, each below `usize::BITS`, so no overflow check is needed;
508    // for the top node the result is 0, as with a checked shift.
509    number >> shift >> 6
510}
511
512#[inline]
513fn position(bitmap: u64, chunk: u32) -> usize {
514    // Full nodes (the common case for dense page numbers) skip the popcount,
515    // which is a software routine unless the target has `popcnt`.
516    if bitmap == u64::MAX {
517        chunk as usize
518    } else {
519        (bitmap & ((1_u64 << chunk) - 1)).count_ones() as usize
520    }
521}
522
523impl<T, const PAGE: usize> Node<T, PAGE> {
524    /// Children whose chunks can contain page numbers in these bounds.
525    fn span(&self, lo: usize, hi: usize) -> Range<usize> {
526        let low = self.prefix.checked_shl(self.shift + 6).unwrap_or(0);
527        let mask = usize::MAX
528            .checked_shr(usize::BITS.saturating_sub(self.shift + 6))
529            .unwrap_or(0);
530        let high = low | mask;
531        if hi < low || lo > high {
532            return 0..0;
533        }
534        let first = if lo > low { chunk(lo, self.shift) } else { 0 };
535        let last = if hi < high { chunk(hi, self.shift) } else { 63 };
536        let start = position(self.bitmap, first);
537        let end = (self.bitmap & (u64::MAX >> (63 - last))).count_ones() as usize;
538        start..end
539    }
540}
541
542/// Slots of the table for `group` that can hold page numbers in these
543/// bounds, as a range of offsets.
544fn slot_span(group: usize, lo: usize, hi: usize) -> RangeInclusive<usize> {
545    let base = group << 6;
546    let top = base | 63;
547    if hi < base || lo > top {
548        #[allow(clippy::reversed_empty_ranges)]
549        return 1..=0;
550    }
551    lo.saturating_sub(base)..=hi.min(top) - base
552}
553
554impl<T, const PAGE: usize> Child<T, PAGE> {
555    /// A number with the same prefix as every leaf below this child.
556    fn representative(&self) -> usize {
557        match self {
558            Self::Leaf { number, .. } => *number,
559            Self::Table { group, .. } => group << 6,
560            Self::Node(node) => node.prefix.checked_shl(node.shift + 6).unwrap_or(0),
561        }
562    }
563
564    #[inline]
565    fn get(&self, number: usize) -> Option<&[T; PAGE]> {
566        let mut child = self;
567        loop {
568            match child {
569                Self::Node(node) => {
570                    let c = chunk(number, node.shift);
571                    if prefix(number, node.shift) != node.prefix || node.bitmap & (1_u64 << c) == 0
572                    {
573                        return None;
574                    }
575                    child = &node.children[position(node.bitmap, c)];
576                }
577                Self::Table { group, slots, .. } => {
578                    return if number >> 6 == *group {
579                        slots[number & 63].as_deref()
580                    } else {
581                        None
582                    };
583                }
584                Self::Leaf { number: n, page } => return (*n == number).then_some(page),
585            }
586        }
587    }
588
589    #[inline]
590    fn get_mut(&mut self, number: usize) -> Option<&mut [T; PAGE]> {
591        let mut child = self;
592        loop {
593            match child {
594                Self::Node(node) => {
595                    let c = chunk(number, node.shift);
596                    if prefix(number, node.shift) != node.prefix || node.bitmap & (1_u64 << c) == 0
597                    {
598                        return None;
599                    }
600                    child = &mut node.children[position(node.bitmap, c)];
601                }
602                Self::Table { group, slots, .. } => {
603                    return if number >> 6 == *group {
604                        slots[number & 63].as_deref_mut()
605                    } else {
606                        None
607                    };
608                }
609                Self::Leaf { number: n, page } => return (*n == number).then_some(page),
610            }
611        }
612    }
613
614    /// The page of a leaf child.
615    fn leaf_page(&mut self) -> &mut [T; PAGE] {
616        match self {
617            Self::Leaf { page, .. } => page,
618            _ => unreachable!("child was just inserted as a leaf"),
619        }
620    }
621
622    /// Inserts an absent page, after its defaults have all been built, and
623    /// returns it.
624    fn insert(&mut self, number: usize, page: Box<[T; PAGE]>) -> &mut [T; PAGE] {
625        // Decide first, so the borrow of `self` below ends on every path.
626        let descend = match self {
627            Self::Node(node) => prefix(number, node.shift) == node.prefix,
628            Self::Table { group, .. } => number >> 6 == *group,
629            Self::Leaf { .. } => false,
630        };
631        if descend {
632            match self {
633                Self::Node(node) => {
634                    let c = chunk(number, node.shift);
635                    let pos = position(node.bitmap, c);
636                    if node.bitmap & (1_u64 << c) == 0 {
637                        node.children.insert(pos, Self::Leaf { number, page });
638                        node.bitmap |= 1_u64 << c;
639                        return node.children[pos].leaf_page();
640                    }
641                    return node.children[pos].insert(number, page);
642                }
643                Self::Table { len, slots, .. } => {
644                    *len += 1;
645                    return slots[number & 63].insert(page);
646                }
647                Self::Leaf { .. } => unreachable!("leaves never descend"),
648            }
649        }
650
651        let existing = self.representative();
652        let shift = (usize::BITS - 1 - (existing ^ number).leading_zeros()) / 6 * 6;
653        if shift == 0 {
654            // Same group of 64. Only a leaf can get here: a table of this
655            // group would have descended, and a node's representative
656            // differs from every number outside it above bit `shift + 6`.
657            // Allocate before replacing the leaf; no user code runs below.
658            let slots = Box::new([const { None }; 64]);
659            let old = core::mem::replace(
660                self,
661                Self::Table {
662                    group: number >> 6,
663                    len: 2,
664                    slots,
665                },
666            );
667            let (
668                Self::Leaf {
669                    number: m,
670                    page: old_page,
671                },
672                Self::Table { slots, .. },
673            ) = (old, self)
674            else {
675                unreachable!("a leaf was just replaced by a table")
676            };
677            slots[m & 63] = Some(old_page);
678            return slots[number & 63].insert(page);
679        }
680        let old_chunk = chunk(existing, shift);
681        let new_chunk = chunk(number, shift);
682        // Allocate before replacing the old child. No user code runs while
683        // the new branch is being linked into the directory.
684        let branch = Node {
685            shift,
686            prefix: prefix(number, shift),
687            bitmap: (1_u64 << old_chunk) | (1_u64 << new_chunk),
688            children: Vec::with_capacity(2),
689        };
690        let old = core::mem::replace(self, Self::Node(branch));
691        let Self::Node(node) = self else {
692            unreachable!("branch was just installed")
693        };
694        let new = Self::Leaf { number, page };
695        let pos = if old_chunk < new_chunk {
696            node.children.push(old);
697            node.children.push(new);
698            1
699        } else {
700            node.children.push(new);
701            node.children.push(old);
702            0
703        };
704        node.children[pos].leaf_page()
705    }
706
707    /// Removes a known leaf and collapses every branch left with one child,
708    /// and every table left with one page.
709    fn remove(self, number: usize) -> (Option<Self>, Box<[T; PAGE]>) {
710        match self {
711            Self::Leaf { page, .. } => (None, page),
712            Self::Table {
713                group,
714                len,
715                mut slots,
716            } => {
717                let page = slots[number & 63].take().expect("page is allocated");
718                if len > 2 {
719                    let table = Self::Table {
720                        group,
721                        len: len - 1,
722                        slots,
723                    };
724                    return (Some(table), page);
725                }
726                let (offset, last) = slots
727                    .iter_mut()
728                    .enumerate()
729                    .find_map(|(offset, slot)| Some((offset, slot.take()?)))
730                    .expect("a table holds at least two pages");
731                let leaf = Self::Leaf {
732                    number: group << 6 | offset,
733                    page: last,
734                };
735                (Some(leaf), page)
736            }
737            Self::Node(mut node) => {
738                let c = chunk(number, node.shift);
739                let pos = position(node.bitmap, c);
740                let (replacement, page) = node.children.remove(pos).remove(number);
741                if let Some(child) = replacement {
742                    node.children.insert(pos, child);
743                } else {
744                    node.bitmap &= !(1_u64 << c);
745                }
746                let remaining = if node.children.len() == 1 {
747                    node.children.pop()
748                } else {
749                    Some(Self::Node(node))
750                };
751                (remaining, page)
752            }
753        }
754    }
755
756    fn shrink_to_fit(&mut self) {
757        if let Self::Node(node) = self {
758            for child in &mut node.children {
759                child.shrink_to_fit();
760            }
761            node.children.shrink_to_fit();
762        }
763    }
764
765    fn depth(&self) -> usize {
766        match self {
767            Self::Leaf { .. } => 0,
768            Self::Table { .. } => 1,
769            Self::Node(node) => 1 + node.children.iter().map(Self::depth).max().unwrap_or(0),
770        }
771    }
772
773    fn into_pages(self, pages: &mut Vec<(usize, Box<[T; PAGE]>)>) {
774        match self {
775            Self::Leaf { number, page } => pages.push((number, page)),
776            Self::Table { group, slots, .. } => {
777                for (offset, slot) in (*slots).into_iter().enumerate() {
778                    if let Some(page) = slot {
779                        pages.push((group << 6 | offset, page));
780                    }
781                }
782            }
783            Self::Node(node) => {
784                for child in node.children {
785                    child.into_pages(pages);
786                }
787            }
788        }
789    }
790}
791
792impl<T, const PAGE: usize> Default for RadixTree<T, PAGE> {
793    fn default() -> Self {
794        Self {
795            root: None,
796            allocated: 0,
797        }
798    }
799}
800
801impl<T: Clone, const PAGE: usize> Clone for RadixTree<T, PAGE> {
802    fn clone(&self) -> Self {
803        Self {
804            root: self.root.clone(),
805            allocated: self.allocated,
806        }
807    }
808}
809
810impl<T, const PAGE: usize> fmt::Debug for RadixTree<T, PAGE> {
811    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
812        f.debug_struct("RadixTree")
813            .field("page_size", &PAGE)
814            .field("allocated", &self.allocated)
815            .field("depth", &self.root.as_ref().map_or(0, Child::depth))
816            .finish()
817    }
818}
819
820/// Most slice iterators a radix walker holds at once: the root slice plus one
821/// per node on each end's current path. Node shifts strictly decrease along a
822/// path and are multiples of six, so a path has at most `ceil(BITS / 6)`
823/// nodes.
824const LEVELS: usize = 2 * (usize::BITS as usize).div_ceil(6) + 1;
825
826/// Fixed-capacity deque of slice iterators, so creating a walker (which
827/// `next_occupant`, `pop_first` and friends do on every call) never
828/// allocates.
829#[derive(Clone)]
830struct Chain<I> {
831    slots: [Option<I>; LEVELS],
832    head: usize,
833    len: usize,
834}
835
836impl<I> Chain<I> {
837    fn new() -> Self {
838        Self {
839            slots: [const { None }; LEVELS],
840            head: 0,
841            len: 0,
842        }
843    }
844
845    fn back_index(&self) -> usize {
846        (self.head + self.len - 1) % LEVELS
847    }
848
849    fn front_mut(&mut self) -> Option<&mut I> {
850        if self.len == 0 {
851            return None;
852        }
853        self.slots[self.head].as_mut()
854    }
855
856    fn back_mut(&mut self) -> Option<&mut I> {
857        if self.len == 0 {
858            return None;
859        }
860        let back = self.back_index();
861        self.slots[back].as_mut()
862    }
863
864    fn push_front(&mut self, iter: I) {
865        assert!(self.len < LEVELS, "radix walker deeper than the key width");
866        self.head = (self.head + LEVELS - 1) % LEVELS;
867        self.slots[self.head] = Some(iter);
868        self.len += 1;
869    }
870
871    fn push_back(&mut self, iter: I) {
872        assert!(self.len < LEVELS, "radix walker deeper than the key width");
873        self.len += 1;
874        let back = self.back_index();
875        self.slots[back] = Some(iter);
876    }
877
878    fn pop_front(&mut self) {
879        if self.len > 0 {
880            self.slots[self.head] = None;
881            self.head = (self.head + 1) % LEVELS;
882            self.len -= 1;
883        }
884    }
885
886    fn pop_back(&mut self) {
887        if self.len > 0 {
888            let back = self.back_index();
889            self.slots[back] = None;
890            self.len -= 1;
891        }
892    }
893}
894
895/// Shared iterator over radix pages in ascending page-number order.
896///
897/// The two ends share a chain of slice iterators, so interleaving `next`
898/// and `next_back` visits each page exactly once. The chain is stored
899/// inline: creating or cloning the iterator never allocates.
900pub struct RadixIter<'a, T, const PAGE: usize> {
901    levels: Walk<'a, T, PAGE>,
902    lo: usize,
903    hi: usize,
904    done: bool,
905}
906
907/// One step of a walker's path: a node's children, or a table's slots
908/// together with the page number of the first slot left in `iter`'s range
909/// (the walker slices tables down to the range, so slot numbers come from
910/// the slice offset).
911#[derive(Clone)]
912enum Level<C, S> {
913    Children(C),
914    Slots { first: usize, iter: Enumerate<S> },
915}
916
917type Walk<'a, T, const PAGE: usize> =
918    Chain<Level<slice::Iter<'a, Child<T, PAGE>>, slice::Iter<'a, PageSlot<T, PAGE>>>>;
919type WalkMut<'a, T, const PAGE: usize> =
920    Chain<Level<slice::IterMut<'a, Child<T, PAGE>>, slice::IterMut<'a, PageSlot<T, PAGE>>>>;
921
922impl<T, const PAGE: usize> Clone for RadixIter<'_, T, PAGE> {
923    fn clone(&self) -> Self {
924        Self {
925            levels: self.levels.clone(),
926            lo: self.lo,
927            hi: self.hi,
928            done: self.done,
929        }
930    }
931}
932
933/// Mutable iterator over radix pages in ascending page-number order.
934///
935/// Pages yielded from either end are disjoint, including when `next` and
936/// `next_back` are interleaved. The chain is stored inline: creating the
937/// iterator never allocates.
938pub struct RadixIterMut<'a, T, const PAGE: usize> {
939    levels: WalkMut<'a, T, PAGE>,
940    lo: usize,
941    hi: usize,
942    done: bool,
943}
944
945// Both walkers split slices through their iterators. In particular, the
946// mutable walker never borrows a child again after yielding one of its pages.
947macro_rules! radix_iterator {
948    ($name:ident, $lt:lifetime, $reference:ty, $iter:ident, $deref:ident) => {
949        impl<$lt, T, const PAGE: usize> $name<$lt, T, PAGE> {
950            fn step(&mut self, back: bool) -> Option<(usize, $reference)> {
951                while !self.done {
952                    let level = if back {
953                        self.levels.back_mut()
954                    } else {
955                        self.levels.front_mut()
956                    };
957                    let Some(level) = level else {
958                        self.done = true;
959                        return None;
960                    };
961                    let child = match level {
962                        Level::Children(children) => {
963                            if back {
964                                children.next_back()
965                            } else {
966                                children.next()
967                            }
968                        }
969                        Level::Slots { first, iter } => {
970                            let slot = if back { iter.next_back() } else { iter.next() };
971                            match slot {
972                                Some((offset, slot)) => {
973                                    if let Some(page) = slot.$deref() {
974                                        return Some((*first + offset, page));
975                                    }
976                                    continue;
977                                }
978                                None => None,
979                            }
980                        }
981                    };
982                    let Some(child) = child else {
983                        if back {
984                            self.levels.pop_back();
985                        } else {
986                            self.levels.pop_front();
987                        }
988                        continue;
989                    };
990                    let pushed = match child {
991                        Child::Leaf { number, page } => {
992                            if (!back && *number > self.hi) || (back && *number < self.lo) {
993                                self.done = true;
994                                return None;
995                            }
996                            if *number >= self.lo && *number <= self.hi {
997                                return Some((*number, page));
998                            }
999                            continue;
1000                        }
1001                        Child::Table { group, slots, .. } => {
1002                            let span = slot_span(*group, self.lo, self.hi);
1003                            if span.is_empty() {
1004                                continue;
1005                            }
1006                            Level::Slots {
1007                                first: (*group << 6) + *span.start(),
1008                                iter: slots[span].$iter().enumerate(),
1009                            }
1010                        }
1011                        Child::Node(node) => {
1012                            let span = node.span(self.lo, self.hi);
1013                            if span.is_empty() {
1014                                continue;
1015                            }
1016                            Level::Children(node.children[span].$iter())
1017                        }
1018                    };
1019                    if back {
1020                        self.levels.push_back(pushed);
1021                    } else {
1022                        self.levels.push_front(pushed);
1023                    }
1024                }
1025                None
1026            }
1027        }
1028
1029        impl<$lt, T, const PAGE: usize> Iterator for $name<$lt, T, PAGE> {
1030            type Item = (usize, $reference);
1031
1032            fn next(&mut self) -> Option<Self::Item> {
1033                self.step(false)
1034            }
1035        }
1036
1037        impl<T, const PAGE: usize> DoubleEndedIterator for $name<'_, T, PAGE> {
1038            fn next_back(&mut self) -> Option<Self::Item> {
1039                self.step(true)
1040            }
1041        }
1042    };
1043}
1044
1045radix_iterator!(RadixIter, 'a, &'a [T; PAGE], iter, as_deref);
1046radix_iterator!(RadixIterMut, 'a, &'a mut [T; PAGE], iter_mut, as_deref_mut);
1047
1048impl<T, const PAGE: usize> PageStore<T, PAGE> for RadixTree<T, PAGE> {
1049    type Pages<'a>
1050        = RadixIter<'a, T, PAGE>
1051    where
1052        T: 'a;
1053    type PagesMut<'a>
1054        = RadixIterMut<'a, T, PAGE>
1055    where
1056        T: 'a;
1057    type IntoPages = alloc::vec::IntoIter<(usize, Box<[T; PAGE]>)>;
1058
1059    #[inline]
1060    fn get(&self, page: usize) -> Option<&[T; PAGE]> {
1061        self.root.as_ref()?.get(page)
1062    }
1063
1064    #[inline]
1065    fn get_mut(&mut self, page: usize) -> Option<&mut [T; PAGE]> {
1066        self.root.as_mut()?.get_mut(page)
1067    }
1068
1069    fn get_or_alloc(&mut self, page: usize) -> &mut [T; PAGE]
1070    where
1071        T: Default,
1072    {
1073        if self.get(page).is_some() {
1074            return self.get_mut(page).expect("page was just found");
1075        }
1076        // Build the page first: `T::default()` may panic.
1077        let new = new_page::<T, PAGE>();
1078        // Count the page only once it is linked: inserting can allocate
1079        // (and so panic, with unwinding OOM handlers).
1080        let page = if self.root.is_none() {
1081            self.root
1082                .insert(Child::Leaf {
1083                    number: page,
1084                    page: new,
1085                })
1086                .leaf_page()
1087        } else {
1088            match &mut self.root {
1089                Some(root) => root.insert(page, new),
1090                None => unreachable!("root checked above"),
1091            }
1092        };
1093        self.allocated += 1;
1094        page
1095    }
1096
1097    fn remove(&mut self, page: usize) -> Option<Box<[T; PAGE]>> {
1098        self.get(page)?;
1099        let root = self.root.take().expect("page is allocated");
1100        let (remaining, removed) = root.remove(page);
1101        self.root = remaining;
1102        self.allocated -= 1;
1103        Some(removed)
1104    }
1105
1106    fn clear(&mut self) {
1107        // Empty the store before dropping pages: `T::drop()` may panic.
1108        self.allocated = 0;
1109        let root = self.root.take();
1110        drop(root);
1111    }
1112
1113    #[inline]
1114    fn allocated(&self) -> usize {
1115        self.allocated
1116    }
1117
1118    fn shrink_to_fit(&mut self) {
1119        if let Some(root) = &mut self.root {
1120            root.shrink_to_fit();
1121        }
1122    }
1123
1124    fn pages(&self) -> Self::Pages<'_> {
1125        self.pages_in(0..=usize::MAX)
1126    }
1127
1128    fn pages_mut(&mut self) -> Self::PagesMut<'_> {
1129        self.pages_in_mut(0..=usize::MAX)
1130    }
1131
1132    fn pages_in(&self, numbers: RangeInclusive<usize>) -> Self::Pages<'_> {
1133        let mut levels = Chain::new();
1134        if let Some(root) = self.root.as_ref().filter(|_| !numbers.is_empty()) {
1135            levels.push_back(Level::Children(slice::from_ref(root).iter()));
1136        }
1137        RadixIter {
1138            levels,
1139            lo: *numbers.start(),
1140            hi: *numbers.end(),
1141            done: numbers.is_empty(),
1142        }
1143    }
1144
1145    fn pages_in_mut(&mut self, numbers: RangeInclusive<usize>) -> Self::PagesMut<'_> {
1146        let mut levels = Chain::new();
1147        if let Some(root) = self.root.as_mut().filter(|_| !numbers.is_empty()) {
1148            levels.push_back(Level::Children(slice::from_mut(root).iter_mut()));
1149        }
1150        RadixIterMut {
1151            levels,
1152            lo: *numbers.start(),
1153            hi: *numbers.end(),
1154            done: numbers.is_empty(),
1155        }
1156    }
1157
1158    fn into_pages(self) -> Self::IntoPages {
1159        let mut pages = Vec::with_capacity(self.allocated);
1160        if let Some(root) = self.root {
1161            root.into_pages(&mut pages);
1162        }
1163        pages.into_iter()
1164    }
1165}
1166
1167/// Pages in a dense flat window followed by a bitmapped, path-compressed
1168/// radix tree.
1169///
1170/// Page numbers may use the full `usize` range. Low page numbers live in a
1171/// flat window (`Vec<Option<Box<[T; PAGE]>>>`, as in [`FlatPages`]), so a
1172/// lookup there costs one bounds check and one indirection. Every page at or
1173/// above the window's length lives in the radix tree: each branch examines
1174/// six bits, shared paths are compressed, and the last six bits are resolved
1175/// by a table of 64 page pointers, so lookup costs O(depth).
1176///
1177/// The window only grows to cover a new page `p` when `p` is below
1178/// `8 * (allocated + 1) + 64`; pages of the tree it then covers move into it.
1179/// Its length is therefore at most eight pointers per allocated page (at the
1180/// time it grew) plus 64, so directory memory stays proportional to the
1181/// pages allocated, as with the tree alone. Removing pages does not shrink
1182/// the window; [`shrink_to_fit`](PageStore::shrink_to_fit) drops its empty
1183/// tail.
1184pub struct RadixPages<T, const PAGE: usize> {
1185    /// Pages `0 .. window.pages.len()`.
1186    window: FlatPages<T, PAGE>,
1187    /// Pages at or above `window.pages.len()`.
1188    tree: RadixTree<T, PAGE>,
1189}
1190
1191/// Window pointers allowed per allocated page, and the window's free length.
1192const WINDOW_SLACK: usize = 8;
1193const WINDOW_MIN: usize = 64;
1194
1195impl<T, const PAGE: usize> Default for RadixPages<T, PAGE> {
1196    fn default() -> Self {
1197        Self {
1198            window: FlatPages::default(),
1199            tree: RadixTree::default(),
1200        }
1201    }
1202}
1203
1204impl<T: Clone, const PAGE: usize> Clone for RadixPages<T, PAGE> {
1205    fn clone(&self) -> Self {
1206        Self {
1207            window: self.window.clone(),
1208            tree: self.tree.clone(),
1209        }
1210    }
1211}
1212
1213impl<T, const PAGE: usize> fmt::Debug for RadixPages<T, PAGE> {
1214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215        f.debug_struct("RadixPages")
1216            .field("page_size", &PAGE)
1217            .field("window_len", &self.window.pages.len())
1218            .field("allocated", &self.allocated())
1219            .finish()
1220    }
1221}
1222
1223impl<T, const PAGE: usize> RadixPages<T, PAGE> {
1224    /// Whether the window may grow to cover `page`.
1225    fn admits(&self, page: usize) -> bool {
1226        let limit = WINDOW_SLACK
1227            .saturating_mul(self.allocated().saturating_add(1))
1228            .saturating_add(WINDOW_MIN);
1229        page < limit
1230    }
1231
1232    /// Grows the window to cover `page` and moves the tree's pages it now
1233    /// covers into it. Runs no user code.
1234    #[cold]
1235    #[inline(never)]
1236    fn grow_window(&mut self, page: usize) {
1237        let old = self.window.pages.len();
1238        self.window.pages.resize_with(page + 1, || None);
1239        let moved: Vec<usize> = self.tree.pages_in(old..=page).map(|(n, _)| n).collect();
1240        for n in moved {
1241            let taken = self.tree.remove(n).expect("page was just listed");
1242            self.window.pages[n] = Some(taken);
1243            self.window.allocated += 1;
1244        }
1245    }
1246}
1247
1248impl<T, const PAGE: usize> PageStore<T, PAGE> for RadixPages<T, PAGE> {
1249    type Pages<'a>
1250        = core::iter::Chain<
1251        <FlatPages<T, PAGE> as PageStore<T, PAGE>>::Pages<'a>,
1252        RadixIter<'a, T, PAGE>,
1253    >
1254    where
1255        T: 'a;
1256
1257    type PagesMut<'a>
1258        = core::iter::Chain<
1259        <FlatPages<T, PAGE> as PageStore<T, PAGE>>::PagesMut<'a>,
1260        RadixIterMut<'a, T, PAGE>,
1261    >
1262    where
1263        T: 'a;
1264
1265    type IntoPages = core::iter::Chain<
1266        <FlatPages<T, PAGE> as PageStore<T, PAGE>>::IntoPages,
1267        alloc::vec::IntoIter<(usize, Box<[T; PAGE]>)>,
1268    >;
1269
1270    #[inline]
1271    fn get(&self, page: usize) -> Option<&[T; PAGE]> {
1272        match self.window.pages.get(page) {
1273            Some(entry) => entry.as_deref(),
1274            None => self.tree.get(page),
1275        }
1276    }
1277
1278    #[inline]
1279    fn get_mut(&mut self, page: usize) -> Option<&mut [T; PAGE]> {
1280        match self.window.pages.get_mut(page) {
1281            Some(entry) => entry.as_deref_mut(),
1282            None => self.tree.get_mut(page),
1283        }
1284    }
1285
1286    fn get_or_alloc(&mut self, page: usize) -> &mut [T; PAGE]
1287    where
1288        T: Default,
1289    {
1290        if page >= self.window.pages.len() {
1291            if self.tree.get(page).is_some() {
1292                return self.tree.get_mut(page).expect("page was just found");
1293            }
1294            if !self.admits(page) {
1295                return self.tree.get_or_alloc(page);
1296            }
1297            self.grow_window(page);
1298        }
1299        self.window.get_or_alloc(page)
1300    }
1301
1302    fn remove(&mut self, page: usize) -> Option<Box<[T; PAGE]>> {
1303        if page < self.window.pages.len() {
1304            self.window.remove(page)
1305        } else {
1306            self.tree.remove(page)
1307        }
1308    }
1309
1310    fn clear(&mut self) {
1311        // Empty the store before dropping pages: `T::drop()` may panic, and
1312        // the other half is then still dropped while unwinding.
1313        let window = core::mem::take(&mut self.window);
1314        let tree = core::mem::take(&mut self.tree);
1315        drop(tree);
1316        drop(window);
1317    }
1318
1319    #[inline]
1320    fn allocated(&self) -> usize {
1321        self.window.allocated() + self.tree.allocated()
1322    }
1323
1324    fn shrink_to_fit(&mut self) {
1325        // Trimming the window's empty tail keeps every tree page above it.
1326        self.window.shrink_to_fit();
1327        self.tree.shrink_to_fit();
1328    }
1329
1330    fn pages(&self) -> Self::Pages<'_> {
1331        self.pages_in(0..=usize::MAX)
1332    }
1333
1334    fn pages_mut(&mut self) -> Self::PagesMut<'_> {
1335        self.pages_in_mut(0..=usize::MAX)
1336    }
1337
1338    fn pages_in(&self, numbers: RangeInclusive<usize>) -> Self::Pages<'_> {
1339        self.window
1340            .pages_in(numbers.clone())
1341            .chain(self.tree.pages_in(numbers))
1342    }
1343
1344    fn pages_in_mut(&mut self, numbers: RangeInclusive<usize>) -> Self::PagesMut<'_> {
1345        self.window
1346            .pages_in_mut(numbers.clone())
1347            .chain(self.tree.pages_in_mut(numbers))
1348    }
1349
1350    fn into_pages(self) -> Self::IntoPages {
1351        self.window.into_pages().chain(self.tree.into_pages())
1352    }
1353}
1354
1355#[cfg(test)]
1356impl<T, const PAGE: usize> RadixPages<T, PAGE> {
1357    fn check(&self) {
1358        self.tree.check();
1359        let len = self.window.pages.len();
1360        assert_eq!(
1361            self.window.pages.iter().flatten().count(),
1362            self.window.allocated
1363        );
1364        assert!(self.tree.pages().all(|(n, _)| n >= len));
1365        let numbers: Vec<usize> = self.pages().map(|(n, _)| n).collect();
1366        assert_eq!(numbers.len(), self.allocated());
1367        assert!(numbers.windows(2).all(|pair| pair[0] < pair[1]));
1368    }
1369}
1370
1371#[cfg(test)]
1372impl<T, const PAGE: usize> RadixTree<T, PAGE> {
1373    fn check(&self) {
1374        fn visit<T, const PAGE: usize>(child: &Child<T, PAGE>, numbers: &mut Vec<usize>) {
1375            match child {
1376                Child::Leaf { number, .. } => numbers.push(*number),
1377                Child::Table { group, len, slots } => {
1378                    assert!(*len >= 2);
1379                    assert!(*group <= usize::MAX >> 6, "group keeps only high bits");
1380                    assert_eq!(slots.iter().flatten().count(), *len as usize);
1381                    for (offset, slot) in slots.iter().enumerate() {
1382                        if slot.is_some() {
1383                            numbers.push(group << 6 | offset);
1384                        }
1385                    }
1386                }
1387                Child::Node(node) => {
1388                    assert!(node.children.len() >= 2);
1389                    assert_eq!(node.shift % 6, 0);
1390                    assert!(node.shift >= 6, "tables replace branches on the low bits");
1391                    assert!(node.shift < usize::BITS);
1392                    assert_eq!(node.bitmap.count_ones() as usize, node.children.len());
1393                    let mut chunks = (0..64).filter(|c| node.bitmap & (1_u64 << c) != 0);
1394                    for child in &node.children {
1395                        if let Child::Node(inner) = child {
1396                            assert!(inner.shift < node.shift);
1397                        }
1398                        let start = numbers.len();
1399                        visit(child, numbers);
1400                        let c = chunks.next().expect("one bit per child");
1401                        for &n in &numbers[start..] {
1402                            assert_eq!(prefix(n, node.shift), node.prefix);
1403                            assert_eq!(chunk(n, node.shift), c);
1404                        }
1405                    }
1406                }
1407            }
1408        }
1409        let mut numbers = Vec::new();
1410        if let Some(root) = &self.root {
1411            visit(root, &mut numbers);
1412        }
1413        assert_eq!(numbers.len(), self.allocated);
1414        assert!(numbers.windows(2).all(|pair| pair[0] < pair[1]));
1415        assert_eq!(self.pages().map(|(n, _)| n).collect::<Vec<_>>(), numbers);
1416    }
1417}
1418
1419#[cfg(test)]
1420mod tests {
1421    use super::*;
1422    use alloc::vec::Vec;
1423
1424    fn numbers<S: PageStore<u8, 2>>(store: &mut S, range: RangeInclusive<usize>) -> Vec<usize> {
1425        let shared: Vec<usize> = store.pages_in(range.clone()).map(|(n, _)| n).collect();
1426        let unique: Vec<usize> = store.pages_in_mut(range).map(|(n, _)| n).collect();
1427        assert_eq!(shared, unique);
1428        shared
1429    }
1430
1431    fn ranges<S: PageStore<u8, 2> + Default>() {
1432        let mut store = S::default();
1433        for n in [0, 2, 3] {
1434            store.get_or_alloc(n);
1435        }
1436        assert_eq!(numbers(&mut store, 0..=usize::MAX), [0, 2, 3]);
1437        assert_eq!(numbers(&mut store, 1..=2), [2]);
1438        #[allow(clippy::reversed_empty_ranges)]
1439        let inverted = 3..=1;
1440        assert_eq!(numbers(&mut store, inverted), [0; 0]);
1441        assert_eq!(numbers(&mut store, 4..=usize::MAX), [0; 0]);
1442        assert_eq!(numbers(&mut store, usize::MAX..=usize::MAX), [0; 0]);
1443        // An exhausted range keeps its endpoints but is empty.
1444        let mut exhausted = 0..=3;
1445        exhausted.by_ref().for_each(drop);
1446        assert_eq!((*exhausted.start(), *exhausted.end()), (3, 3));
1447        assert_eq!(numbers(&mut store, exhausted), [0; 0]);
1448        let mut back = 0..=0;
1449        back.next_back();
1450        assert_eq!(numbers(&mut store, back), [0; 0]);
1451    }
1452
1453    #[test]
1454    fn pages_in_honours_empty_and_exhausted_ranges() {
1455        ranges::<FlatPages<u8, 2>>();
1456        ranges::<TreePages<u8, 2>>();
1457        ranges::<RadixPages<u8, 2>>();
1458    }
1459
1460    #[test]
1461    fn radix_compresses_and_collapses_every_level() {
1462        let mut store = RadixPages::<u8, 2>::default();
1463        let keys: Vec<_> = (0..usize::BITS)
1464            .step_by(6)
1465            .flat_map(|shift| {
1466                let n = 1_usize << shift;
1467                [n - 1, n, n + 1]
1468            })
1469            .chain([usize::MAX - 1, usize::MAX])
1470            .collect();
1471        store.check();
1472        for &n in &keys {
1473            store.get_or_alloc(n)[0] = n as u8;
1474            store.check();
1475        }
1476        store.shrink_to_fit();
1477        store.check();
1478        let mut clone = store.clone();
1479        clone.check();
1480        for &n in keys.iter().rev() {
1481            clone.remove(n);
1482            clone.check();
1483        }
1484        assert_eq!(clone.allocated(), 0);
1485        for &n in &keys {
1486            store.remove(n);
1487            store.check();
1488        }
1489        assert!(store.tree.root.is_none());
1490        assert_eq!(store.window.allocated(), 0);
1491    }
1492
1493    #[test]
1494    fn radix_window_absorbs_tree_pages() {
1495        let mut store = RadixPages::<u8, 2>::default();
1496        store.get_or_alloc(100)[0] = 7;
1497        store.get_or_alloc(usize::MAX);
1498        assert_eq!(store.tree.allocated(), 2);
1499        for n in 0..10 {
1500            store.get_or_alloc(n);
1501            store.check();
1502        }
1503        assert_eq!(store.window.pages.len(), 10);
1504        store.get_or_alloc(101);
1505        store.check();
1506        assert_eq!(store.window.pages.len(), 102);
1507        assert_eq!(store.tree.allocated(), 1);
1508        assert_eq!(store.get(100).map(|p| p[0]), Some(7));
1509        store.remove(101);
1510        store.shrink_to_fit();
1511        store.check();
1512        assert_eq!(store.window.pages.len(), 101);
1513        let all: Vec<usize> = store.pages().map(|(n, _)| n).collect();
1514        let mut expected: Vec<usize> = (0..10).collect();
1515        expected.extend([100, usize::MAX]);
1516        assert_eq!(all, expected);
1517    }
1518
1519    #[test]
1520    fn radix_shared_iterator_clone_needs_no_slot_clone() {
1521        #[derive(Default)]
1522        struct NotClone;
1523        let mut store = RadixPages::<NotClone, 1>::default();
1524        store.get_or_alloc(usize::MAX);
1525        let iter = store.pages();
1526        assert_eq!(iter.clone().next().map(|(n, _)| n), Some(usize::MAX));
1527        store.check();
1528    }
1529
1530    #[test]
1531    fn radix_invariants_after_every_operation() {
1532        let config = proptest::test_runner::Config {
1533            cases: if cfg!(miri) { 4 } else { 256 },
1534            failure_persistence: None,
1535            ..proptest::test_runner::Config::default()
1536        };
1537        let ops = proptest::collection::vec(
1538            (
1539                0_u8..12,
1540                proptest::prelude::any::<usize>(),
1541                0_u8..4,
1542                0_u8..11,
1543            ),
1544            1..if cfg!(miri) { 16 } else { 200 },
1545        );
1546        proptest::test_runner::TestRunner::new(config)
1547            .run(&ops, |ops| {
1548                let mut store = RadixPages::<u8, 2>::default();
1549                let mut oracle = alloc::collections::BTreeSet::new();
1550                for (op, value, region, level) in ops {
1551                    let shift = (u32::from(level) * 6).min((usize::BITS - 1) / 6 * 6);
1552                    let boundary = 1_usize << shift;
1553                    let n = match region {
1554                        0 => value % 300,
1555                        1 => usize::MAX - value % 300,
1556                        2 => boundary.saturating_add(value % 3).saturating_sub(1),
1557                        _ => value,
1558                    };
1559                    match op {
1560                        0..=3 => {
1561                            store.get_or_alloc(n);
1562                            oracle.insert(n);
1563                        }
1564                        4 => {
1565                            assert_eq!(store.remove(n).is_some(), oracle.remove(&n));
1566                        }
1567                        5 => {
1568                            store.clear();
1569                            oracle.clear();
1570                        }
1571                        6 => store.shrink_to_fit(),
1572                        7 => {
1573                            store.clone().check();
1574                        }
1575                        8 => {
1576                            assert_eq!(store.get(n).is_some(), oracle.contains(&n));
1577                            // A bounded range around `n`, walked from both
1578                            // ends alternately, against the oracle.
1579                            let hi = n.saturating_add(value % 200);
1580                            let mut walk = store.pages_in(n.saturating_sub(value % 150)..=hi);
1581                            let expected: Vec<_> = oracle
1582                                .range(n.saturating_sub(value % 150)..=hi)
1583                                .copied()
1584                                .collect();
1585                            let (mut front, mut back) = (Vec::new(), Vec::new());
1586                            let mut from_back = value % 2 == 0;
1587                            loop {
1588                                let next = if from_back {
1589                                    walk.next_back()
1590                                } else {
1591                                    walk.next()
1592                                };
1593                                let Some((number, _)) = next else { break };
1594                                if from_back {
1595                                    back.push(number)
1596                                } else {
1597                                    front.push(number)
1598                                }
1599                                from_back = !from_back;
1600                            }
1601                            back.reverse();
1602                            front.extend(back);
1603                            assert_eq!(front, expected);
1604                        }
1605                        9 => {
1606                            if let Some(page) = store.get_mut(n) {
1607                                page[0] ^= 1;
1608                            }
1609                        }
1610                        10 => {
1611                            for (_, page) in store.pages_in_mut(n..=usize::MAX) {
1612                                page[1] ^= 1;
1613                            }
1614                        }
1615                        _ => {
1616                            store.clone().into_pages().for_each(drop);
1617                        }
1618                    }
1619                    store.check();
1620                }
1621                Ok(())
1622            })
1623            .unwrap();
1624    }
1625}