Skip to main content

paged_collections/
hive.rs

1//! [`Hive`]: an unordered container with stable addresses, reusable slots
2//! and generational handles.
3//!
4//! Elements live in slots, in pages of `PAGE` slots. Inserting returns an
5//! [`Id`]: the slot index plus a generation. Removing an element frees its
6//! slot for reuse; the next element there gets the next generation, so a
7//! stale id of a removed element is never mistaken for a live one.
8//!
9//! - **Stable addresses.** An element does not move while it is in the hive:
10//!   inserts, removals of other elements, [`reserve`](Hive::reserve) and
11//!   [`shrink_to_fit`](Hive::shrink_to_fit) leave its address unchanged.
12//!   Only [`sort`](Hive::sort) and its variants move elements between
13//!   slots; ids name slots, so after a sort an id names whatever element
14//!   moved into its slot.
15//!   Pages are allocated once with room for `PAGE` slots and never
16//!   reallocated.
17//! - **Slot reuse.** Inserts fill one page with room at a time: a page that
18//!   was full and gains a free slot is used next, and within a page the
19//!   last freed slot is reused first. A page that has room is used before a
20//!   new page is created, so memory follows the peak number of elements, not
21//!   the number of inserts. Which page with room goes first is otherwise
22//!   unspecified.
23//! - **Memory return.** [`shrink_to_fit`](Hive::shrink_to_fit) frees every
24//!   empty page. The page keeps a small record of its highest generation,
25//!   so ids issued before stay dead when the page is used again.
26//!
27//! [`Id`] implements [`Key`](crate::key::Key), so ids index the other
28//! collections directly: a [`PagedSparseMap<Id, V>`](crate::sparse_map) or
29//! [`PagedDirectMap<Id, V>`](crate::direct_map) makes a side table for hive
30//! elements. As there, all generations of a slot share one key slot.
31//!
32//! Comparable in purpose to C++26 `std::hive`. Iteration is in slot order
33//! (page by page), not insertion order.
34//!
35//! | Operation | Cost |
36//! |---|---|
37//! | [`insert`](Hive::insert), [`remove`](Hive::remove) | amortized O(1): a page allocation every `PAGE` new slots, rare directory growth |
38//! | [`get`](Hive::get), [`contains`](Hive::contains), [`occupant`](Hive::occupant) | O(1) |
39//! | [`iter`](Hive::iter) and friends | O(len) on full pages; skips empty pages, scans the free slots of the others |
40//! | [`retain`](Hive::retain), [`clear`](Hive::clear), [`drain`](Hive::drain), [`extract_if`](Hive::extract_if) | O(pages + len) plus the scan, as for iteration |
41//! | [`reserve`](Hive::reserve), [`shrink_to_fit`](Hive::shrink_to_fit) | O(pages) bookkeeping; `shrink_to_fit` also scans the slots of empty pages |
42//!
43//! # Limits and stale ids
44//!
45//! Slot indices are `u32`, below [`MAX_INDICES`]. Each slot issues at most
46//! [`MAX_GENERATION`](crate::id_alloc::MAX_GENERATION) ids; after the last
47//! one is removed the slot is *retired* and never reused, so generations
48//! never wrap. A page with a retired slot is never freed.
49//!
50//! As with [`IdAllocator`](crate::id_alloc::IdAllocator), the stale-id
51//! guarantee holds within one history of a hive. Ids carry no hive
52//! identity, so another hive (or a clone) accepts them, and restoring an
53//! older state (an older clone, or an older serialized snapshot) revives the
54//! ids removed since.
55//!
56//! The module exists only on 32- and 64-bit targets, like
57//! [`id_alloc`](crate::id_alloc).
58//!
59//! ```
60//! use paged_collections::hive::Hive;
61//!
62//! let mut hive: Hive<&str, 4> = Hive::new();
63//! let a = hive.insert("a");
64//! let b = hive.insert("b");
65//! let addr: *const &str = &hive[b];
66//!
67//! assert_eq!(hive.remove(a), Some("a"));
68//! assert_eq!(hive.get(a), None);
69//!
70//! // The slot is reused with a new generation; the stale id stays dead.
71//! let c = hive.insert("c");
72//! assert_eq!(c.index(), a.index());
73//! assert_ne!(c, a);
74//! assert_eq!(hive.get(a), None);
75//!
76//! // Other elements never moved.
77//! hive.extend(["d", "e", "f", "g"]);
78//! assert!(core::ptr::eq(addr, &hive[b]));
79//! assert_eq!(hive.values().copied().collect::<Vec<_>>(), ["c", "b", "d", "e", "f", "g"]);
80//! ```
81//!
82//! With the `rayon` feature, borrowed parallel iterators are unindexed and
83//! visit occupied slots page by page. Collecting into a `Vec` preserves slot
84//! order. The order of `for_each` is unspecified.
85//!
86//! ```rust
87//! # #[cfg(feature = "rayon")] {
88//! use paged_collections::hive::Hive;
89//! use rayon::prelude::*;
90//!
91//! let mut hive: Hive<_, 2> = Hive::new();
92//! let a = hive.insert(10);
93//! let b = hive.insert(20);
94//! hive.par_iter_mut().for_each(|(_, value)| *value += 1);
95//! assert_eq!(hive.par_iter().map(|(id, &v)| (id, v)).collect::<Vec<_>>(), [(a, 11), (b, 21)]);
96//! # }
97//! ```
98
99use alloc::collections::TryReserveError;
100use alloc::vec::Vec;
101use core::cmp::Ordering;
102use core::fmt;
103use core::hash::{Hash, Hasher};
104use core::iter::{Enumerate, FusedIterator};
105use core::ops::{Index, IndexMut};
106
107use crate::id_alloc::{Id, MAX_INDICES, generation_of, live_version};
108use crate::page::{DEFAULT_PAGE, split};
109use crate::paged_vec::capacity_overflow;
110
111/// End of a page's free list.
112const NONE: u32 = u32::MAX;
113
114/// One slot of a [`RawPage`], with versions as in
115/// [`IdAllocator::raw_parts`](crate::id_alloc::IdAllocator::raw_parts).
116#[derive(Clone, Debug, PartialEq, Eq)]
117pub enum RawSlot<T> {
118    /// An occupied slot: an odd version (`2g - 1`) and its element.
119    Occupied {
120        /// The odd version, for generation `g = version / 2 + 1`.
121        version: u32,
122        /// The element in the slot.
123        value: T,
124    },
125    /// A vacant slot: an even non-zero version (`2g`), or `0` if retired.
126    Vacant {
127        /// The even version, or `0` if the slot can never be reused.
128        version: u32,
129    },
130}
131
132/// A page's raw state: its even generation floor and its slots in offset order.
133#[derive(Clone, Debug, PartialEq, Eq)]
134pub struct RawPage<T> {
135    /// The even generation floor; new slots start at `floor + 1`.
136    pub floor: u32,
137    /// The slots in offset order, including vacant and retired slots.
138    pub slots: Vec<RawSlot<T>>,
139}
140
141/// Why [`Hive::try_from_raw_pages`] rejected its input.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143#[non_exhaustive]
144pub enum RawPagesError {
145    /// More pages than the slot indices below [`MAX_INDICES`] can cover.
146    TooManyPages,
147    /// A page exceeds `PAGE`, or the last page exceeds its usable slot indices.
148    PageTooLong,
149    /// A page's generation floor is odd.
150    OddFloor,
151    /// An occupied slot has an even version, or a vacant slot an odd version.
152    VersionParity,
153}
154
155impl fmt::Display for RawPagesError {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        f.write_str(match self {
158            RawPagesError::TooManyPages => "more pages than slot indices",
159            RawPagesError::PageTooLong => "page holds too many slots",
160            RawPagesError::OddFloor => "odd page floor",
161            RawPagesError::VersionParity => "slot version parity mismatch",
162        })
163    }
164}
165
166impl core::error::Error for RawPagesError {}
167
168/// One slot. Versions follow [`IdAllocator`](crate::id_alloc::IdAllocator):
169/// odd while occupied (generation `version / 2 + 1`), even and non-zero
170/// while vacant and in the page's free list, 0 once retired.
171enum Slot<T> {
172    Occupied {
173        version: u32,
174        value: T,
175    },
176    /// `next` is the next free offset in the page, or [`NONE`]; unused when
177    /// retired.
178    Vacant {
179        version: u32,
180        next: u32,
181    },
182}
183
184impl<T> Slot<T> {
185    #[inline]
186    fn version(&self) -> u32 {
187        match *self {
188            Slot::Occupied { version, .. } | Slot::Vacant { version, .. } => version,
189        }
190    }
191}
192
193/// One page of slots.
194///
195/// Invariants, for page number `p` and `limit = limit(p)`:
196///
197/// - `slots.capacity()` is 0 (the page is *unallocated*: `slots` is empty)
198///   or at least `PAGE` (*allocated*); `slots.len() <= limit <= PAGE`, so an
199///   allocated page never reallocates;
200/// - `free_head` starts a list, linked through `Vacant::next`, holding each
201///   vacant non-retired slot of the page exactly once;
202/// - `len` counts the occupied slots and `retired` the retired ones;
203/// - `floor` is even and at least the version every slot at an offset
204///   `>= slots.len()` ever had; a slot created there starts at `floor + 1`.
205struct Page<T> {
206    slots: Vec<Slot<T>>,
207    free_head: u32,
208    len: u32,
209    retired: u32,
210    floor: u32,
211}
212
213impl<T> Page<T> {
214    #[inline]
215    const fn unallocated(floor: u32) -> Self {
216        Self {
217            slots: Vec::new(),
218            free_head: NONE,
219            len: 0,
220            retired: 0,
221            floor,
222        }
223    }
224
225    #[inline]
226    fn allocated(&self) -> bool {
227        self.slots.capacity() != 0
228    }
229
230    /// Whether an insert can use this page.
231    #[inline]
232    fn has_room(&self, limit: usize) -> bool {
233        self.free_head != NONE || self.slots.len() < limit
234    }
235
236    /// Number of inserts the page takes, once allocated.
237    #[inline]
238    fn room(&self, limit: usize) -> usize {
239        limit - self.len as usize - self.retired as usize
240    }
241}
242
243/// An unordered container with stable addresses and generational [`Id`]s.
244///
245/// `PAGE` is the number of slots per page; it must be non-zero and fit in a
246/// `u32`. See the [module docs](crate::hive).
247///
248/// Invariants, besides those of each page:
249///
250/// - page `p` exists only if `p * PAGE < MAX_INDICES`;
251/// - `open` holds each page that has room (`Page::has_room`) exactly once,
252///   and nothing else; inserts use its last entry;
253/// - `len` is the total number of occupied slots.
254pub struct Hive<T, const PAGE: usize = DEFAULT_PAGE> {
255    pages: Vec<Page<T>>,
256    open: Vec<usize>,
257    len: usize,
258}
259
260impl<T, const PAGE: usize> Hive<T, PAGE> {
261    /// Number of slots per page.
262    pub const PAGE: usize = PAGE;
263
264    /// An empty hive. Does not allocate.
265    #[inline]
266    pub const fn new() -> Self {
267        const {
268            assert!(PAGE > 0, "page size must be non-zero");
269            assert!(PAGE <= u32::MAX as usize, "page size must fit in a u32");
270        };
271        Self {
272            pages: Vec::new(),
273            open: Vec::new(),
274            len: 0,
275        }
276    }
277
278    /// An empty hive with pages allocated for `capacity` elements.
279    pub fn with_capacity(capacity: usize) -> Self {
280        let mut hive = Self::new();
281        hive.reserve(capacity);
282        hive
283    }
284
285    /// Number of usable slots in page `p`: `PAGE`, except for a last page
286    /// cut short by [`MAX_INDICES`].
287    #[inline]
288    fn limit(p: usize) -> usize {
289        // Pages exist only for `p * PAGE < MAX_INDICES`.
290        (MAX_INDICES as usize - p * PAGE).min(PAGE)
291    }
292
293    /// Number of elements.
294    #[inline]
295    pub fn len(&self) -> usize {
296        self.len
297    }
298
299    /// Whether there are no elements.
300    #[inline]
301    pub fn is_empty(&self) -> bool {
302        self.len == 0
303    }
304
305    /// Number of usable slots in allocated pages, occupied or not (a last
306    /// page cut short by [`MAX_INDICES`] counts only its usable slots).
307    /// Takes O(pages) time: it scans the page directory.
308    pub fn capacity(&self) -> usize {
309        self.pages
310            .iter()
311            .enumerate()
312            .filter(|(_, page)| page.allocated())
313            .map(|(p, _)| Self::limit(p))
314            .sum()
315    }
316
317    /// Number of allocated pages. Takes O(pages) time: it scans the page
318    /// directory.
319    pub fn allocated_pages(&self) -> usize {
320        self.pages.iter().filter(|page| page.allocated()).count()
321    }
322
323    /// One past the largest slot index the hive can have used: every id it
324    /// issued has a smaller index. Use it to size a side table.
325    #[inline]
326    pub fn index_bound(&self) -> usize {
327        self.pages
328            .len()
329            .saturating_mul(PAGE)
330            .min(MAX_INDICES as usize)
331    }
332
333    /// The raw state: every page in order, including unallocated pages,
334    /// with elements borrowed. Together with
335    /// [`try_from_raw_pages`](Hive::try_from_raw_pages) this round-trips a
336    /// hive for formats other than serde.
337    ///
338    /// A round trip keeps every id, generation, value, floor and retired
339    /// slot. It need not keep allocations or free-list and page reuse
340    /// order, so the next insert may use a different slot.
341    pub fn raw_pages(&self) -> impl ExactSizeIterator<Item = RawPage<&T>> + '_ {
342        self.pages.iter().map(|page| RawPage {
343            floor: page.floor,
344            slots: page
345                .slots
346                .iter()
347                .map(|slot| match slot {
348                    Slot::Occupied { version, value } => RawSlot::Occupied {
349                        version: *version,
350                        value,
351                    },
352                    Slot::Vacant { version, .. } => RawSlot::Vacant { version: *version },
353                })
354                .collect(),
355        })
356    }
357
358    /// Rebuilds a hive from [`raw_pages`](Hive::raw_pages), validating
359    /// them: pages must fit below [`MAX_INDICES`], each page must fit its
360    /// usable slot limit (at most `PAGE`), floors must be even, occupied
361    /// versions odd, and vacant versions even (including `0` for retired).
362    ///
363    /// Free lists are rebuilt lowest offset first. Allocated pages with
364    /// room are reused before unallocated pages, lowest page first within
365    /// each group. Every non-empty page is allocated with room for `PAGE`
366    /// slots; empty pages remain unallocated. Memory can therefore reach
367    /// `PAGE` slots per page read.
368    pub fn try_from_raw_pages(
369        pages: impl IntoIterator<Item = RawPage<T>>,
370    ) -> Result<Self, RawPagesError> {
371        let mut hive = Self::new();
372        let pages: Vec<_> = pages.into_iter().collect();
373        if pages.len() > (MAX_INDICES as usize).div_ceil(PAGE) {
374            return Err(RawPagesError::TooManyPages);
375        }
376        // Validate everything before allocating pages, so that bad input is
377        // rejected without allocating `PAGE` slots per page read.
378        for (p, raw) in pages.iter().enumerate() {
379            if raw.slots.len() > Self::limit(p) {
380                return Err(RawPagesError::PageTooLong);
381            }
382            if raw.floor % 2 == 1 {
383                return Err(RawPagesError::OddFloor);
384            }
385            let parity_ok = raw.slots.iter().all(|slot| match slot {
386                RawSlot::Occupied { version, .. } => version % 2 == 1,
387                RawSlot::Vacant { version } => version % 2 == 0,
388            });
389            if !parity_ok {
390                return Err(RawPagesError::VersionParity);
391            }
392        }
393        hive.pages.reserve_exact(pages.len());
394        for raw in pages {
395            let mut page = Page::unallocated(raw.floor);
396            if !raw.slots.is_empty() {
397                page.slots.reserve_exact(PAGE);
398            }
399            for slot in raw.slots {
400                page.slots.push(match slot {
401                    RawSlot::Occupied { version, value } if version % 2 == 1 => {
402                        page.len += 1;
403                        Slot::Occupied { version, value }
404                    }
405                    RawSlot::Vacant { version } if version % 2 == 0 => {
406                        if version == 0 {
407                            page.retired += 1;
408                        }
409                        Slot::Vacant {
410                            version,
411                            next: NONE,
412                        }
413                    }
414                    _ => unreachable!("slot parity was validated"),
415                });
416            }
417            for (offset, slot) in page.slots.iter_mut().enumerate().rev() {
418                if let Slot::Vacant { version, next } = slot {
419                    if *version != 0 {
420                        *next = page.free_head;
421                        // `offset < PAGE <= u32::MAX`.
422                        page.free_head = offset as u32;
423                    }
424                }
425            }
426            hive.len += page.len as usize;
427            hive.pages.push(page);
428        }
429        hive.rebuild_open();
430        Ok(hive)
431    }
432
433    /// Appends an unallocated page to the directory, with room reserved in
434    /// `open` to list it. `None` if no more slot indices exist.
435    fn push_page(&mut self) -> Option<usize> {
436        let p = self.pages.len();
437        if p.checked_mul(PAGE)
438            .is_none_or(|base| base >= MAX_INDICES as usize)
439        {
440            return None;
441        }
442        self.open.reserve(1);
443        self.pages.push(Page::unallocated(0));
444        Some(p)
445    }
446
447    /// Allocates pages so that the next `additional` inserts allocate
448    /// nothing. Allocates the free pages first, then appends new ones,
449    /// which inserts use after the pages that already have room.
450    ///
451    /// # Panics
452    ///
453    /// Panics if `additional` more elements exceed the slot indices left, or
454    /// an allocation size overflows `isize::MAX` bytes.
455    pub fn reserve(&mut self, additional: usize) {
456        if let Err(e) = self.reserve_with(additional, || Ok(Vec::with_capacity(PAGE))) {
457            panic!("Hive::reserve: {e}");
458        }
459    }
460
461    /// Like [`reserve`](Hive::reserve), but returns an error instead of
462    /// panicking or aborting. On error, pages allocated so far are kept and
463    /// usable.
464    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
465        self.reserve_with(additional, || {
466            let mut slots = Vec::new();
467            slots.try_reserve_exact(PAGE)?;
468            Ok(slots)
469        })
470    }
471
472    fn reserve_with(
473        &mut self,
474        additional: usize,
475        mut alloc_page: impl FnMut() -> Result<Vec<Slot<T>>, TryReserveError>,
476    ) -> Result<(), TryReserveError> {
477        let mut room: usize = (0..self.pages.len())
478            .filter(|&p| self.pages[p].allocated())
479            .map(|p| self.pages[p].room(Self::limit(p)))
480            .sum();
481        // Fail before allocating if the slot indices cannot cover it.
482        let free_pages: usize = (0..self.pages.len())
483            .filter(|&p| !self.pages[p].allocated())
484            .map(Self::limit)
485            .sum();
486        let new_slots =
487            (MAX_INDICES as usize).saturating_sub(self.pages.len().saturating_mul(PAGE));
488        if additional > room.saturating_add(free_pages).saturating_add(new_slots) {
489            return Err(capacity_overflow());
490        }
491        // Free pages are already listed in `open`.
492        for p in 0..self.pages.len() {
493            if room >= additional {
494                return Ok(());
495            }
496            if !self.pages[p].allocated() {
497                self.pages[p].slots = alloc_page()?;
498                room += Self::limit(p);
499            }
500        }
501        if room >= additional {
502            return Ok(());
503        }
504        // `room < additional <= room + free_pages + new_slots` and every free
505        // page is allocated now, so the new slots suffice. Only the last
506        // possible page is shorter than `PAGE`, so this many pages do.
507        let count = (additional - room).div_ceil(PAGE);
508        // Reserve all metadata first, so the pushes below cannot allocate.
509        self.pages.try_reserve(count)?;
510        self.open.try_reserve(count)?;
511        let mut result = Ok(());
512        let mut pushed = 0;
513        while pushed < count {
514            // Allocate before touching the directory: if this fails or
515            // panics, every page pushed so far is allocated and listed.
516            let slots = match alloc_page() {
517                Ok(slots) => slots,
518                Err(e) => {
519                    result = Err(e);
520                    break;
521                }
522            };
523            let p = self.pages.len();
524            debug_assert!(p * PAGE < MAX_INDICES as usize);
525            self.pages.push(Page {
526                slots,
527                ..Page::unallocated(0)
528            });
529            self.open.push(p);
530            pushed += 1;
531        }
532        // Move the new pages below the listed ones, lowest on top, so inserts
533        // fill the pages that already had room first, then the new pages in
534        // order.
535        let n = self.open.len();
536        self.open[n - pushed..].reverse();
537        self.open.rotate_right(pushed);
538        result
539    }
540
541    /// Frees every empty page, except pages with a retired slot. Elements
542    /// never move. Ids issued before stay dead: a freed page remembers its
543    /// highest generation and starts there when used again.
544    pub fn shrink_to_fit(&mut self) {
545        for page in &mut self.pages {
546            if page.allocated() && page.len == 0 && page.retired == 0 {
547                // All slots are vacant, so all versions are even.
548                let floor = page
549                    .slots
550                    .iter()
551                    .map(Slot::version)
552                    .fold(page.floor, u32::max);
553                *page = Page::unallocated(floor);
554            }
555        }
556        // Trailing pages that never issued an id can go entirely.
557        while self
558            .pages
559            .last()
560            .is_some_and(|page| !page.allocated() && page.floor == 0)
561        {
562            self.pages.pop();
563        }
564        self.pages.shrink_to_fit();
565        self.rebuild_open();
566        self.open.shrink_to_fit();
567    }
568
569    /// Lists every page with room in `open`: unallocated pages at the
570    /// bottom, then allocated ones, each group lowest page on top.
571    fn rebuild_open(&mut self) {
572        self.open.clear();
573        for allocated in [false, true] {
574            for p in (0..self.pages.len()).rev() {
575                let page = &self.pages[p];
576                if page.allocated() == allocated && page.has_room(Self::limit(p)) {
577                    self.open.push(p);
578                }
579            }
580        }
581    }
582
583    /// Inserts `value` and returns its id.
584    ///
585    /// # Panics
586    ///
587    /// Panics if every slot index is occupied or retired. See
588    /// [`try_insert`](Hive::try_insert).
589    #[inline]
590    pub fn insert(&mut self, value: T) -> Id {
591        self.insert_with(|_| value)
592    }
593
594    /// Like [`insert`](Hive::insert), but returns `value` back if every slot
595    /// index is occupied or retired. Still panics or aborts if a page cannot
596    /// be allocated; [`try_reserve`](Hive::try_reserve) first to avoid that.
597    #[inline]
598    pub fn try_insert(&mut self, value: T) -> Result<Id, T> {
599        match self.next_page() {
600            Some(p) => Ok(self.insert_in(p, |_| value)),
601            None => Err(value),
602        }
603    }
604
605    /// Inserts the value `f` makes from its id, and returns the id. If `f`
606    /// panics, the hive is unchanged (apart from capacity).
607    ///
608    /// # Panics
609    ///
610    /// Panics if every slot index is occupied or retired. See
611    /// [`try_insert_with`](Hive::try_insert_with).
612    pub fn insert_with(&mut self, f: impl FnOnce(Id) -> T) -> Id {
613        match self.next_page() {
614            Some(p) => self.insert_in(p, f),
615            None => panic!("Hive: all {MAX_INDICES} slot indices are occupied or retired"),
616        }
617    }
618
619    /// Like [`insert_with`](Hive::insert_with), but returns `None`, without
620    /// calling `f`, if every slot index is occupied or retired.
621    pub fn try_insert_with(&mut self, f: impl FnOnce(Id) -> T) -> Option<Id> {
622        let p = self.next_page()?;
623        Some(self.insert_in(p, f))
624    }
625
626    /// Whether no insert is possible: every slot index is occupied or
627    /// retired. Only a hive holding [`MAX_INDICES`] slots can be exhausted.
628    pub fn is_exhausted(&self) -> bool {
629        self.open.is_empty()
630            && self
631                .pages
632                .len()
633                .checked_mul(PAGE)
634                .is_none_or(|slots| slots >= MAX_INDICES as usize)
635    }
636
637    /// The page the next insert uses: the top of `open`, or a new page,
638    /// which it lists there. `None` if no slot index is left.
639    fn next_page(&mut self) -> Option<usize> {
640        if let Some(&p) = self.open.last() {
641            return Some(p);
642        }
643        let p = self.push_page()?;
644        // `push_page` reserved room for this entry.
645        self.open.push(p);
646        Some(p)
647    }
648
649    /// Inserts into page `p`, which must be the top of `open`.
650    fn insert_in(&mut self, p: usize, f: impl FnOnce(Id) -> T) -> Id {
651        let limit = Self::limit(p);
652        let page = &mut self.pages[p];
653        if !page.allocated() {
654            page.slots = Vec::with_capacity(PAGE);
655        }
656        let (offset, version) = match page.free_head {
657            NONE => (page.slots.len(), page.floor + 1),
658            head => (head as usize, page.slots[head as usize].version() + 1),
659        };
660        debug_assert!(offset < limit && version % 2 == 1);
661        // `p * PAGE + offset < MAX_INDICES`, so it fits.
662        let id = Id::new((p * PAGE + offset) as u32, generation_of(version));
663        // User code: nothing has changed yet if it panics.
664        let value = f(id);
665        let occupied = Slot::Occupied { version, value };
666        if offset == page.slots.len() {
667            debug_assert!(page.slots.len() < page.slots.capacity());
668            page.slots.push(occupied);
669        } else {
670            match core::mem::replace(&mut page.slots[offset], occupied) {
671                Slot::Vacant { next, .. } => page.free_head = next,
672                Slot::Occupied { .. } => unreachable!(),
673            }
674        }
675        page.len += 1;
676        self.len += 1;
677        if !page.has_room(limit) {
678            debug_assert_eq!(self.open.last(), Some(&p));
679            self.open.pop();
680        }
681        id
682    }
683
684    /// The `(page, offset)` of the slot `id` occupies, if it is live.
685    #[inline]
686    fn locate(&self, id: Id) -> Option<(usize, usize)> {
687        let version = live_version(id.generation())?;
688        let (p, offset) = split::<PAGE>(id.index() as usize);
689        match self.pages.get(p)?.slots.get(offset)? {
690            Slot::Occupied { version: v, .. } if *v == version => Some((p, offset)),
691            _ => None,
692        }
693    }
694
695    /// Whether `id` is live: returned by an insert and not removed since.
696    #[inline]
697    pub fn contains(&self, id: Id) -> bool {
698        self.locate(id).is_some()
699    }
700
701    /// The element of `id`, if it is live.
702    #[inline]
703    pub fn get(&self, id: Id) -> Option<&T> {
704        let (p, offset) = self.locate(id)?;
705        match &self.pages[p].slots[offset] {
706            Slot::Occupied { value, .. } => Some(value),
707            Slot::Vacant { .. } => None,
708        }
709    }
710
711    /// The element of `id`, mutably, if it is live.
712    #[inline]
713    pub fn get_mut(&mut self, id: Id) -> Option<&mut T> {
714        let (p, offset) = self.locate(id)?;
715        match &mut self.pages[p].slots[offset] {
716            Slot::Occupied { value, .. } => Some(value),
717            Slot::Vacant { .. } => None,
718        }
719    }
720
721    /// The elements of several ids at once, mutably: `None` for each id
722    /// that is not live. O(N log N) for N ids.
723    ///
724    /// ```
725    /// use paged_collections::hive::Hive;
726    ///
727    /// let mut hive: Hive<u32> = Hive::new();
728    /// let (a, b) = (hive.insert(1), hive.insert(2));
729    /// if let [Some(x), Some(y)] = hive.get_disjoint_mut([a, b]) {
730    ///     core::mem::swap(x, y);
731    /// }
732    /// assert_eq!((hive[a], hive[b]), (2, 1));
733    /// ```
734    ///
735    /// # Panics
736    ///
737    /// Panics if a live id is given twice.
738    pub fn get_disjoint_mut<const N: usize>(&mut self, ids: [Id; N]) -> [Option<&mut T>; N] {
739        // The live ids as (page, offset, position in `ids`), in slot order.
740        let mut order = [(0, 0, 0); N];
741        let mut n = 0;
742        for (i, &id) in ids.iter().enumerate() {
743            if let Some((p, offset)) = self.locate(id) {
744                order[n] = (p, offset, i);
745                n += 1;
746            }
747        }
748        let order = &mut order[..n];
749        order.sort_unstable();
750        for pair in order.windows(2) {
751            assert!(
752                (pair[0].0, pair[0].1) != (pair[1].0, pair[1].1),
753                "Hive::get_disjoint_mut: {:?} given twice",
754                ids[pair[1].2]
755            );
756        }
757        // Walk the slots in order, splitting each one off the front of what
758        // is left: the borrows are disjoint by construction.
759        let mut out = [const { None }; N];
760        let mut pages: &mut [Page<T>] = &mut self.pages;
761        let mut pages_base = 0;
762        let mut k = 0;
763        while k < n {
764            let p = order[k].0;
765            let rest = core::mem::take(&mut pages);
766            let Some((page, rest)) = rest[p - pages_base..].split_first_mut() else {
767                unreachable!("located ids name existing pages")
768            };
769            pages = rest;
770            pages_base = p + 1;
771            let mut slots: &mut [Slot<T>] = &mut page.slots;
772            let mut slots_base = 0;
773            while k < n && order[k].0 == p {
774                let (_, offset, i) = order[k];
775                let rest = core::mem::take(&mut slots);
776                let Some((slot, rest)) = rest[offset - slots_base..].split_first_mut() else {
777                    unreachable!("located ids name existing slots")
778                };
779                slots = rest;
780                slots_base = offset + 1;
781                if let Slot::Occupied { value, .. } = slot {
782                    out[i] = Some(value);
783                }
784                k += 1;
785            }
786        }
787        out
788    }
789
790    /// The live id at slot `index`, if the slot is occupied.
791    #[inline]
792    pub fn occupant(&self, index: u32) -> Option<Id> {
793        let (p, offset) = split::<PAGE>(index as usize);
794        match self.pages.get(p)?.slots.get(offset)? {
795            Slot::Occupied { version, .. } => Some(Id::new(index, generation_of(*version))),
796            Slot::Vacant { .. } => None,
797        }
798    }
799
800    /// The id of the element at `value`'s address, if `value` is an element
801    /// of this hive: the inverse of [`get`](Self::get).
802    ///
803    /// Takes O(pages) time: it compares the address with each allocated
804    /// page's slot range, then checks that the slot found is occupied and
805    /// holds exactly that element. A reference to anything else, including
806    /// a field inside an element or an element of another hive, gives
807    /// `None`. Uses address comparison only; no pointer is dereferenced.
808    ///
809    /// ```
810    /// use paged_collections::hive::Hive;
811    ///
812    /// let mut hive: Hive<String> = Hive::new();
813    /// let id = hive.insert("x".to_owned());
814    /// let element: &String = hive.values().next().unwrap();
815    /// assert_eq!(hive.id_of(element), Some(id));
816    /// assert_eq!(hive.id_of(&"x".to_owned()), None);
817    /// ```
818    pub fn id_of(&self, value: &T) -> Option<Id> {
819        let address = core::ptr::from_ref(value).addr();
820        let size = core::mem::size_of::<Slot<T>>();
821        for (p, page) in self.pages.iter().enumerate() {
822            let start = page.slots.as_ptr().addr();
823            let Some(offset) = address.checked_sub(start).map(|bytes| bytes / size) else {
824                continue;
825            };
826            let Some(slot) = page.slots.get(offset) else {
827                continue;
828            };
829            return match slot {
830                Slot::Occupied { version, value: v } if core::ptr::eq(v, value) => {
831                    Some(Id::new((p * PAGE + offset) as u32, generation_of(*version)))
832                }
833                _ => None,
834            };
835        }
836        None
837    }
838
839    /// The live ids, ordered by their elements with `compare` (a stable
840    /// sort: equal elements keep slot order). Moves no element; see
841    /// [`sort_by`](Self::sort_by) to reorder the elements themselves.
842    pub fn sorted_ids_by(&self, mut compare: impl FnMut(&T, &T) -> Ordering) -> Vec<Id> {
843        let mut pairs: Vec<(Id, &T)> = self.iter().collect();
844        pairs.sort_by(|a, b| compare(a.1, b.1));
845        pairs.into_iter().map(|(id, _)| id).collect()
846    }
847
848    /// The live ids, ordered by their elements' keys (a stable sort).
849    pub fn sorted_ids_by_key<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Vec<Id> {
850        self.sorted_ids_by(|a, b| key(a).cmp(&key(b)))
851    }
852
853    /// The live ids, ordered by their elements (a stable sort).
854    ///
855    /// ```
856    /// use paged_collections::hive::Hive;
857    ///
858    /// let mut hive: Hive<u32> = Hive::new();
859    /// let (a, b, c) = (hive.insert(3), hive.insert(1), hive.insert(2));
860    /// assert_eq!(hive.sorted_ids(), [b, c, a]);
861    /// ```
862    pub fn sorted_ids(&self) -> Vec<Id>
863    where
864        T: Ord,
865    {
866        self.sorted_ids_by(T::cmp)
867    }
868
869    /// Sorts the elements in place with `compare`, so iteration (slot
870    /// order) yields them sorted. A stable sort; O(n log n) comparisons,
871    /// O(n) swaps and O(n) extra memory.
872    ///
873    /// **Ids name slots, not elements:** after sorting, each live id names
874    /// whatever element moved into its slot. No id becomes stale and no
875    /// generation changes, so the hive cannot detect ids held across a sort.
876    /// Use [`sorted_ids_by`](Self::sorted_ids_by) to keep ids attached to
877    /// their elements. Elements move, so their addresses change too (the
878    /// set of occupied slots does not). If `compare` panics, no element has
879    /// moved yet.
880    ///
881    /// ```
882    /// use paged_collections::hive::Hive;
883    ///
884    /// let mut hive: Hive<u32> = [3, 1, 2].into_iter().collect();
885    /// let first = hive.ids().next().unwrap();
886    /// hive.sort();
887    /// assert_eq!(hive.values().copied().collect::<Vec<_>>(), [1, 2, 3]);
888    /// assert_eq!(hive[first], 1); // the id now names the smallest element
889    /// ```
890    pub fn sort_by(&mut self, mut compare: impl FnMut(&T, &T) -> Ordering) {
891        self.permute_by(|values, order| order.sort_by(|&a, &b| compare(values[a], values[b])));
892    }
893
894    /// Sorts the elements in place with `compare`, without preserving the
895    /// order of equal elements. Otherwise as [`sort_by`](Self::sort_by)
896    /// (same id and address semantics; O(n) extra memory).
897    pub fn sort_unstable_by(&mut self, mut compare: impl FnMut(&T, &T) -> Ordering) {
898        self.permute_by(|values, order| {
899            order.sort_unstable_by(|&a, &b| compare(values[a], values[b]));
900        });
901    }
902
903    /// Sorts the elements in place by key, without preserving the order of
904    /// equal elements; see [`sort_unstable_by`](Self::sort_unstable_by).
905    pub fn sort_unstable_by_key<K: Ord>(&mut self, mut key: impl FnMut(&T) -> K) {
906        self.sort_unstable_by(|a, b| key(a).cmp(&key(b)));
907    }
908
909    /// Sorts the elements in place, without preserving the order of equal
910    /// elements; see [`sort_unstable_by`](Self::sort_unstable_by).
911    pub fn sort_unstable(&mut self)
912    where
913        T: Ord,
914    {
915        self.sort_unstable_by(T::cmp);
916    }
917
918    /// Sorts the elements in place by key, calling `key` once per element
919    /// (a stable sort); see [`sort_by`](Self::sort_by).
920    pub fn sort_by_cached_key<K: Ord>(&mut self, mut key: impl FnMut(&T) -> K) {
921        self.permute_by(|values, order| {
922            let keys: Vec<K> = values.iter().map(|v| key(v)).collect();
923            order.sort_by(|&a, &b| keys[a].cmp(&keys[b]));
924        });
925    }
926
927    /// Computes a permutation of the live elements with `arrange` (given
928    /// the elements in slot order and the identity permutation to reorder),
929    /// then moves the elements to match. If `arrange` panics, nothing moves.
930    fn permute_by(&mut self, arrange: impl FnOnce(&[&T], &mut [usize])) {
931        let mut values: Vec<&mut T> = self.values_mut().collect();
932        // `order[k]` is the position of the element that belongs at `k`.
933        let mut order: Vec<usize> = (0..values.len()).collect();
934        {
935            let shared: Vec<&T> = values.iter().map(|v| &**v).collect();
936            arrange(&shared, &mut order);
937        }
938        // Apply the permutation one cycle at a time: the element for
939        // position `k` sits at `order[k]`; follow the cycle with swaps.
940        for start in 0..order.len() {
941            let mut k = start;
942            while order[k] != start {
943                let from = order[k];
944                let (low, high) = (k.min(from), k.max(from));
945                let (left, right) = values.split_at_mut(high);
946                core::mem::swap(&mut *left[low], &mut *right[0]);
947                order[k] = k;
948                k = from;
949            }
950            order[k] = k;
951        }
952    }
953
954    /// Sorts the elements in place by key; see [`sort_by`](Self::sort_by).
955    pub fn sort_by_key<K: Ord>(&mut self, mut key: impl FnMut(&T) -> K) {
956        self.sort_by(|a, b| key(a).cmp(&key(b)));
957    }
958
959    /// Sorts the elements in place; see [`sort_by`](Self::sort_by).
960    pub fn sort(&mut self)
961    where
962        T: Ord,
963    {
964        self.sort_by(T::cmp);
965    }
966
967    /// Removes and returns the element of `id`; `None`, and nothing changes,
968    /// if `id` is not live.
969    pub fn remove(&mut self, id: Id) -> Option<T> {
970        let (p, offset) = self.locate(id)?;
971        Some(self.vacate(p, offset))
972    }
973
974    /// Empties the occupied slot `(p, offset)`: it joins the page's free
975    /// list with the next version, or retires after the last generation.
976    fn vacate(&mut self, p: usize, offset: usize) -> T {
977        // Make the `open.push` below infallible before changing anything.
978        self.open.reserve(1);
979        let limit = Self::limit(p);
980        let page = &mut self.pages[p];
981        let had_room = page.has_room(limit);
982        let version = page.slots[offset].version();
983        debug_assert!(version % 2 == 1);
984        let vacant = match version.checked_add(1) {
985            Some(version) => Slot::Vacant {
986                version,
987                next: page.free_head,
988            },
989            None => Slot::Vacant {
990                version: 0,
991                next: NONE,
992            },
993        };
994        let retires = vacant.version() == 0;
995        let Slot::Occupied { value, .. } = core::mem::replace(&mut page.slots[offset], vacant)
996        else {
997            unreachable!()
998        };
999        if retires {
1000            page.retired += 1;
1001        } else {
1002            // `offset < PAGE <= u32::MAX`, and `NONE` is never an offset.
1003            page.free_head = offset as u32;
1004        }
1005        page.len -= 1;
1006        self.len -= 1;
1007        if !had_room && page.has_room(limit) {
1008            self.open.push(p);
1009        }
1010        value
1011    }
1012
1013    /// Removes every element for which `keep` returns `false`, visiting
1014    /// them in slot order. If `keep` or a dropped element panics, the
1015    /// elements already visited stay removed or kept and the hive stays
1016    /// consistent.
1017    pub fn retain(&mut self, mut keep: impl FnMut(Id, &mut T) -> bool) {
1018        for p in 0..self.pages.len() {
1019            let mut left = self.pages[p].len;
1020            let mut offset = 0;
1021            while left > 0 {
1022                let kept = match &mut self.pages[p].slots[offset] {
1023                    Slot::Occupied { version, value } => {
1024                        left -= 1;
1025                        // `p * PAGE + offset < MAX_INDICES`, so it fits.
1026                        let id = Id::new((p * PAGE + offset) as u32, generation_of(*version));
1027                        keep(id, value)
1028                    }
1029                    Slot::Vacant { .. } => true,
1030                };
1031                if !kept {
1032                    drop(self.vacate(p, offset));
1033                }
1034                offset += 1;
1035            }
1036        }
1037    }
1038
1039    /// Removes every element. Pages are kept, and slots keep their
1040    /// generations, so ids issued before stay dead.
1041    pub fn clear(&mut self) {
1042        self.retain(|_, _| false);
1043    }
1044
1045    /// Removes every element and returns them with their ids, in slot
1046    /// order. Slots are freed as [`clear`](Hive::clear) frees them.
1047    ///
1048    /// Elements are removed as the iterator yields them; dropping it removes
1049    /// the rest. If it is leaked instead (`mem::forget`), the elements not
1050    /// yet yielded stay in the hive.
1051    pub fn drain(&mut self) -> Drain<'_, T, PAGE> {
1052        Drain(Visit::new(self))
1053    }
1054
1055    /// Removes the elements for which `pred` returns `true` and returns them
1056    /// with their ids, visiting the elements in slot order.
1057    ///
1058    /// Elements are tested and removed as the iterator advances: those it
1059    /// has not reached when it is dropped stay in the hive. Use
1060    /// [`retain`](Hive::retain) if the removed elements are not needed.
1061    pub fn extract_if<F: FnMut(Id, &mut T) -> bool>(
1062        &mut self,
1063        pred: F,
1064    ) -> ExtractIf<'_, T, F, PAGE> {
1065        ExtractIf {
1066            visit: Visit::new(self),
1067            pred,
1068        }
1069    }
1070
1071    /// Iterates over the ids and elements, in slot order.
1072    pub fn iter(&self) -> Iter<'_, T> {
1073        Iter {
1074            pages: self.pages.iter().enumerate(),
1075            front: PageSlots::default(),
1076            back: PageSlots::default(),
1077            page_size: PAGE,
1078            remaining: self.len,
1079        }
1080    }
1081
1082    /// Iterates over the ids and mutable elements, in slot order.
1083    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1084        IterMut {
1085            pages: self.pages.iter_mut().enumerate(),
1086            front: PageSlots::default(),
1087            back: PageSlots::default(),
1088            page_size: PAGE,
1089            remaining: self.len,
1090        }
1091    }
1092
1093    /// Iterates over the ids, in slot order.
1094    pub fn ids(&self) -> Ids<'_, T> {
1095        Ids(self.iter())
1096    }
1097
1098    /// Iterates over the elements, in slot order.
1099    pub fn values(&self) -> Values<'_, T> {
1100        Values(self.iter())
1101    }
1102
1103    /// Iterates over the elements mutably, in slot order.
1104    pub fn values_mut(&mut self) -> ValuesMut<'_, T> {
1105        ValuesMut(self.iter_mut())
1106    }
1107}
1108
1109impl<T, const PAGE: usize> Default for Hive<T, PAGE> {
1110    #[inline]
1111    fn default() -> Self {
1112        Self::new()
1113    }
1114}
1115
1116/// Clones page by page, with the same ids, free lists and free pages. Each
1117/// allocated page of the clone gets the full capacity `PAGE`, so the clone
1118/// keeps the stable-address guarantee. The clone accepts the original's ids
1119/// (see the [module docs](crate::hive) on stale ids).
1120impl<T: Clone, const PAGE: usize> Clone for Hive<T, PAGE> {
1121    fn clone(&self) -> Self {
1122        let mut pages = Vec::with_capacity(self.pages.len());
1123        for page in &self.pages {
1124            let slots = if page.allocated() {
1125                let mut slots = Vec::with_capacity(PAGE);
1126                slots.extend(page.slots.iter().map(|slot| match slot {
1127                    Slot::Occupied { version, value } => Slot::Occupied {
1128                        version: *version,
1129                        value: value.clone(),
1130                    },
1131                    Slot::Vacant { version, next } => Slot::Vacant {
1132                        version: *version,
1133                        next: *next,
1134                    },
1135                }));
1136                slots
1137            } else {
1138                Vec::new()
1139            };
1140            pages.push(Page {
1141                slots,
1142                free_head: page.free_head,
1143                len: page.len,
1144                retired: page.retired,
1145                floor: page.floor,
1146            });
1147        }
1148        Self {
1149            pages,
1150            open: self.open.clone(),
1151            len: self.len,
1152        }
1153    }
1154}
1155
1156impl<T: fmt::Debug, const PAGE: usize> fmt::Debug for Hive<T, PAGE> {
1157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1158        f.debug_map().entries(self.iter()).finish()
1159    }
1160}
1161
1162/// Equal if both hold the same ids with equal elements, regardless of page
1163/// size. Free slots, generations of vacant slots and capacity are not
1164/// compared, so equal hives may issue different ids from then on.
1165impl<T: PartialEq<U>, U, const PAGE: usize, const PAGE2: usize> PartialEq<Hive<U, PAGE2>>
1166    for Hive<T, PAGE>
1167{
1168    fn eq(&self, other: &Hive<U, PAGE2>) -> bool {
1169        self.len == other.len
1170            && self
1171                .iter()
1172                .zip(other.iter())
1173                .all(|((a, x), (b, y))| a == b && x == y)
1174    }
1175}
1176
1177/// Hive [`PartialEq`] is an equivalence relation when elements implement [`Eq`].
1178impl<T: Eq, const PAGE: usize> Eq for Hive<T, PAGE> {}
1179
1180/// Hashes the length, then the id-element pairs in slot order, consistent
1181/// with [`PartialEq`].
1182impl<T: Hash, const PAGE: usize> Hash for Hive<T, PAGE> {
1183    fn hash<H: Hasher>(&self, state: &mut H) {
1184        state.write_usize(self.len);
1185        for entry in self {
1186            entry.hash(state);
1187        }
1188    }
1189}
1190
1191impl<T, const PAGE: usize> Index<Id> for Hive<T, PAGE> {
1192    type Output = T;
1193
1194    /// # Panics
1195    ///
1196    /// Panics if `id` is not live.
1197    #[inline]
1198    fn index(&self, id: Id) -> &T {
1199        match self.get(id) {
1200            Some(value) => value,
1201            None => panic!("Hive: {id:?} is not live"),
1202        }
1203    }
1204}
1205
1206impl<T, const PAGE: usize> IndexMut<Id> for Hive<T, PAGE> {
1207    /// # Panics
1208    ///
1209    /// Panics if `id` is not live.
1210    #[inline]
1211    fn index_mut(&mut self, id: Id) -> &mut T {
1212        match self.get_mut(id) {
1213            Some(value) => value,
1214            None => panic!("Hive: {id:?} is not live"),
1215        }
1216    }
1217}
1218
1219/// Inserts each element; the ids are discarded.
1220impl<T, const PAGE: usize> Extend<T> for Hive<T, PAGE> {
1221    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1222        for value in iter {
1223            self.insert(value);
1224        }
1225    }
1226}
1227
1228impl<T, const PAGE: usize> FromIterator<T> for Hive<T, PAGE> {
1229    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1230        let mut hive = Self::new();
1231        hive.extend(iter);
1232        hive
1233    }
1234}
1235
1236impl<'a, T, const PAGE: usize> IntoIterator for &'a Hive<T, PAGE> {
1237    type Item = (Id, &'a T);
1238    type IntoIter = Iter<'a, T>;
1239
1240    fn into_iter(self) -> Iter<'a, T> {
1241        self.iter()
1242    }
1243}
1244
1245impl<'a, T, const PAGE: usize> IntoIterator for &'a mut Hive<T, PAGE> {
1246    type Item = (Id, &'a mut T);
1247    type IntoIter = IterMut<'a, T>;
1248
1249    fn into_iter(self) -> IterMut<'a, T> {
1250        self.iter_mut()
1251    }
1252}
1253
1254impl<T, const PAGE: usize> IntoIterator for Hive<T, PAGE> {
1255    type Item = (Id, T);
1256    type IntoIter = IntoIter<T>;
1257
1258    fn into_iter(self) -> IntoIter<T> {
1259        IntoIter {
1260            pages: self.pages.into_iter().enumerate(),
1261            front: PageSlots::default(),
1262            back: PageSlots::default(),
1263            page_size: PAGE,
1264            remaining: self.len,
1265        }
1266    }
1267}
1268
1269/// The occupied slots of one page: `left` of them remain in `slots`, whose
1270/// offsets start at slot index `base`.
1271#[derive(Clone)]
1272struct PageSlots<I> {
1273    base: usize,
1274    slots: Enumerate<I>,
1275    left: u32,
1276}
1277
1278impl<I: Default + Iterator> Default for PageSlots<I> {
1279    fn default() -> Self {
1280        Self {
1281            base: 0,
1282            slots: I::default().enumerate(),
1283            left: 0,
1284        }
1285    }
1286}
1287
1288impl<I: DoubleEndedIterator + ExactSizeIterator> PageSlots<I> {
1289    #[inline]
1290    fn new(base: usize, slots: I, left: u32) -> Self {
1291        Self {
1292            base,
1293            slots: slots.enumerate(),
1294            left,
1295        }
1296    }
1297
1298    #[inline]
1299    fn next<R>(&mut self, take: fn(usize, I::Item) -> Option<R>) -> Option<R> {
1300        if self.left == 0 {
1301            return None;
1302        }
1303        let base = self.base;
1304        let item = self
1305            .slots
1306            .find_map(|(offset, slot)| take(base + offset, slot));
1307        debug_assert!(item.is_some());
1308        self.left -= 1;
1309        item
1310    }
1311
1312    #[inline]
1313    fn next_back<R>(&mut self, take: fn(usize, I::Item) -> Option<R>) -> Option<R> {
1314        if self.left == 0 {
1315            return None;
1316        }
1317        let base = self.base;
1318        let item = self
1319            .slots
1320            .by_ref()
1321            .rev()
1322            .find_map(|(offset, slot)| take(base + offset, slot));
1323        debug_assert!(item.is_some());
1324        self.left -= 1;
1325        item
1326    }
1327}
1328
1329/// The id of the occupied slot at `index` with `version`.
1330#[inline]
1331fn id_at(index: usize, version: u32) -> Id {
1332    // Slot indices are below `MAX_INDICES`, so they fit.
1333    Id::new(index as u32, generation_of(version))
1334}
1335
1336fn take_ref<T>(index: usize, slot: &Slot<T>) -> Option<(Id, &T)> {
1337    match slot {
1338        Slot::Occupied { version, value } => Some((id_at(index, *version), value)),
1339        Slot::Vacant { .. } => None,
1340    }
1341}
1342
1343fn take_mut<T>(index: usize, slot: &mut Slot<T>) -> Option<(Id, &mut T)> {
1344    match slot {
1345        Slot::Occupied { version, value } => Some((id_at(index, *version), value)),
1346        Slot::Vacant { .. } => None,
1347    }
1348}
1349
1350fn take_owned<T>(index: usize, slot: Slot<T>) -> Option<(Id, T)> {
1351    match slot {
1352        Slot::Occupied { version, value } => Some((id_at(index, version), value)),
1353        Slot::Vacant { .. } => None,
1354    }
1355}
1356
1357/// Defines an iterator over the occupied slots, page by page. `$open(base,
1358/// page)` makes the [`PageSlots`] of one page and `$take` extracts an item
1359/// from an occupied slot; `front` and `back` hold the partly consumed pages
1360/// at either end.
1361macro_rules! hive_iter {
1362    (
1363        $(#[$m:meta])* $name:ident<$($lt:lifetime,)? $t:ident>, $item:ty,
1364        $pages:ty, $slots:ty, $open:expr, $take:expr
1365    ) => {
1366        $(#[$m])*
1367        pub struct $name<$($lt,)? $t> {
1368            pages: Enumerate<$pages>,
1369            front: PageSlots<$slots>,
1370            back: PageSlots<$slots>,
1371            page_size: usize,
1372            remaining: usize,
1373        }
1374
1375        impl<$($lt,)? $t> Iterator for $name<$($lt,)? $t> {
1376            type Item = $item;
1377
1378            fn next(&mut self) -> Option<$item> {
1379                if self.remaining == 0 {
1380                    return None;
1381                }
1382                loop {
1383                    if let Some(x) = self.front.next($take) {
1384                        self.remaining -= 1;
1385                        return Some(x);
1386                    }
1387                    match self.pages.next() {
1388                        Some((p, page)) => self.front = $open(p * self.page_size, page),
1389                        None => {
1390                            let x = self.back.next($take)?;
1391                            self.remaining -= 1;
1392                            return Some(x);
1393                        }
1394                    }
1395                }
1396            }
1397
1398            fn size_hint(&self) -> (usize, Option<usize>) {
1399                (self.remaining, Some(self.remaining))
1400            }
1401        }
1402
1403        impl<$($lt,)? $t> DoubleEndedIterator for $name<$($lt,)? $t> {
1404            fn next_back(&mut self) -> Option<$item> {
1405                if self.remaining == 0 {
1406                    return None;
1407                }
1408                loop {
1409                    if let Some(x) = self.back.next_back($take) {
1410                        self.remaining -= 1;
1411                        return Some(x);
1412                    }
1413                    match self.pages.next_back() {
1414                        Some((p, page)) => self.back = $open(p * self.page_size, page),
1415                        None => {
1416                            let x = self.front.next_back($take)?;
1417                            self.remaining -= 1;
1418                            return Some(x);
1419                        }
1420                    }
1421                }
1422            }
1423        }
1424
1425        impl<$($lt,)? $t> ExactSizeIterator for $name<$($lt,)? $t> {}
1426        impl<$($lt,)? $t> FusedIterator for $name<$($lt,)? $t> {}
1427    };
1428}
1429
1430hive_iter!(
1431    /// Iterator over the ids and elements of a [`Hive`], in slot order.
1432    Iter<'a, T>, (Id, &'a T), core::slice::Iter<'a, Page<T>>, core::slice::Iter<'a, Slot<T>>,
1433    |base, page: &'a Page<T>| PageSlots::new(base, page.slots.iter(), page.len),
1434    take_ref
1435);
1436
1437hive_iter!(
1438    /// Iterator over the ids and mutable elements of a [`Hive`], in slot
1439    /// order.
1440    IterMut<'a, T>, (Id, &'a mut T), core::slice::IterMut<'a, Page<T>>,
1441    core::slice::IterMut<'a, Slot<T>>,
1442    |base, page: &'a mut Page<T>| PageSlots::new(base, page.slots.iter_mut(), page.len),
1443    take_mut
1444);
1445
1446hive_iter!(
1447    /// Owning iterator over the ids and elements of a [`Hive`], in slot
1448    /// order.
1449    IntoIter<T>, (Id, T), alloc::vec::IntoIter<Page<T>>, alloc::vec::IntoIter<Slot<T>>,
1450    |base, page: Page<T>| PageSlots::new(base, page.slots.into_iter(), page.len),
1451    take_owned
1452);
1453
1454impl<T> Clone for Iter<'_, T> {
1455    fn clone(&self) -> Self {
1456        Self {
1457            pages: self.pages.clone(),
1458            front: self.front.clone(),
1459            back: self.back.clone(),
1460            page_size: self.page_size,
1461            remaining: self.remaining,
1462        }
1463    }
1464}
1465
1466impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
1467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1468        f.debug_list().entries(self.clone()).finish()
1469    }
1470}
1471
1472/// A walk over the occupied slots in slot order that may remove the slot it
1473/// is at. Removing keeps the walk valid: a vacated slot stays in place.
1474struct Visit<'a, T, const PAGE: usize> {
1475    hive: &'a mut Hive<T, PAGE>,
1476    /// The page being walked, the next offset in it, and the number of its
1477    /// occupied slots not yet visited.
1478    page: usize,
1479    offset: usize,
1480    left: u32,
1481    /// The next page to walk.
1482    next_page: usize,
1483}
1484
1485impl<'a, T, const PAGE: usize> Visit<'a, T, PAGE> {
1486    fn new(hive: &'a mut Hive<T, PAGE>) -> Self {
1487        Self {
1488            hive,
1489            page: 0,
1490            offset: 0,
1491            left: 0,
1492            next_page: 0,
1493        }
1494    }
1495
1496    /// Visits the next occupied slot and removes its element if `remove`
1497    /// says so; returns the first element removed. `None` once every slot
1498    /// has been visited. If `remove` panics, its element stays and the walk
1499    /// goes on after it.
1500    fn next(&mut self, mut remove: impl FnMut(Id, &mut T) -> bool) -> Option<(Id, T)> {
1501        loop {
1502            while self.left == 0 {
1503                let page = self.hive.pages.get(self.next_page)?;
1504                self.page = self.next_page;
1505                self.next_page += 1;
1506                self.offset = 0;
1507                self.left = page.len;
1508            }
1509            let (p, offset) = (self.page, self.offset);
1510            self.offset += 1;
1511            if let Slot::Occupied { version, value } = &mut self.hive.pages[p].slots[offset] {
1512                self.left -= 1;
1513                let id = id_at(p * PAGE + offset, *version);
1514                if remove(id, value) {
1515                    return Some((id, self.hive.vacate(p, offset)));
1516                }
1517            }
1518        }
1519    }
1520}
1521
1522/// Draining iterator over the ids and elements of a [`Hive`], from
1523/// [`drain`](Hive::drain).
1524pub struct Drain<'a, T, const PAGE: usize = DEFAULT_PAGE>(Visit<'a, T, PAGE>);
1525
1526impl<T, const PAGE: usize> Iterator for Drain<'_, T, PAGE> {
1527    type Item = (Id, T);
1528
1529    #[inline]
1530    fn next(&mut self) -> Option<(Id, T)> {
1531        self.0.next(|_, _| true)
1532    }
1533
1534    fn size_hint(&self) -> (usize, Option<usize>) {
1535        // Every element still in the hive is yet to be yielded.
1536        (self.0.hive.len, Some(self.0.hive.len))
1537    }
1538}
1539
1540impl<T, const PAGE: usize> ExactSizeIterator for Drain<'_, T, PAGE> {}
1541impl<T, const PAGE: usize> FusedIterator for Drain<'_, T, PAGE> {}
1542
1543impl<T, const PAGE: usize> Drop for Drain<'_, T, PAGE> {
1544    fn drop(&mut self) {
1545        self.0.hive.clear();
1546    }
1547}
1548
1549impl<T, const PAGE: usize> fmt::Debug for Drain<'_, T, PAGE> {
1550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1551        f.debug_struct("Drain")
1552            .field("remaining", &self.0.hive.len)
1553            .finish_non_exhaustive()
1554    }
1555}
1556
1557/// Iterator that removes and yields the elements of a [`Hive`] matching a
1558/// predicate, from [`extract_if`](Hive::extract_if).
1559pub struct ExtractIf<'a, T, F, const PAGE: usize = DEFAULT_PAGE> {
1560    visit: Visit<'a, T, PAGE>,
1561    pred: F,
1562}
1563
1564impl<T, F: FnMut(Id, &mut T) -> bool, const PAGE: usize> Iterator for ExtractIf<'_, T, F, PAGE> {
1565    type Item = (Id, T);
1566
1567    #[inline]
1568    fn next(&mut self) -> Option<(Id, T)> {
1569        self.visit.next(&mut self.pred)
1570    }
1571
1572    fn size_hint(&self) -> (usize, Option<usize>) {
1573        (0, Some(self.visit.hive.len))
1574    }
1575}
1576
1577impl<T, F: FnMut(Id, &mut T) -> bool, const PAGE: usize> FusedIterator
1578    for ExtractIf<'_, T, F, PAGE>
1579{
1580}
1581
1582impl<T, F, const PAGE: usize> fmt::Debug for ExtractIf<'_, T, F, PAGE> {
1583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1584        f.debug_struct("ExtractIf").finish_non_exhaustive()
1585    }
1586}
1587
1588/// Defines an iterator that maps each item of `$inner` with `$f`.
1589macro_rules! mapped_iter {
1590    ($(#[$m:meta])* $name:ident<$lt:lifetime, $t:ident>, $inner:ident, $item:ty, $f:expr) => {
1591        $(#[$m])*
1592        pub struct $name<$lt, $t>($inner<$lt, $t>);
1593
1594        impl<$lt, $t> Iterator for $name<$lt, $t> {
1595            type Item = $item;
1596
1597            #[inline]
1598            fn next(&mut self) -> Option<$item> {
1599                self.0.next().map($f)
1600            }
1601
1602            fn size_hint(&self) -> (usize, Option<usize>) {
1603                self.0.size_hint()
1604            }
1605        }
1606
1607        impl<$lt, $t> DoubleEndedIterator for $name<$lt, $t> {
1608            #[inline]
1609            fn next_back(&mut self) -> Option<$item> {
1610                self.0.next_back().map($f)
1611            }
1612        }
1613
1614        impl<$t> ExactSizeIterator for $name<'_, $t> {}
1615        impl<$t> FusedIterator for $name<'_, $t> {}
1616    };
1617}
1618
1619mapped_iter!(
1620    /// Iterator over the ids of a [`Hive`], in slot order.
1621    Ids<'a, T>, Iter, Id, |(id, _)| id
1622);
1623
1624mapped_iter!(
1625    /// Iterator over the elements of a [`Hive`], in slot order.
1626    Values<'a, T>, Iter, &'a T, |(_, value)| value
1627);
1628
1629mapped_iter!(
1630    /// Iterator over the mutable elements of a [`Hive`], in slot order.
1631    ValuesMut<'a, T>, IterMut, &'a mut T, |(_, value)| value
1632);
1633
1634impl<T> Clone for Ids<'_, T> {
1635    fn clone(&self) -> Self {
1636        Self(self.0.clone())
1637    }
1638}
1639
1640impl<T> Clone for Values<'_, T> {
1641    fn clone(&self) -> Self {
1642        Self(self.0.clone())
1643    }
1644}
1645
1646#[cfg(feature = "rayon")]
1647pub use rayon_impl::{ParIter, ParIterMut};
1648
1649#[cfg(feature = "rayon")]
1650mod rayon_impl {
1651    use super::*;
1652    use core::iter::from_fn;
1653    use rayon::iter::plumbing::UnindexedConsumer;
1654    use rayon::prelude::*;
1655
1656    /// Unindexed parallel iterator over the ids and elements of a [`Hive`].
1657    pub struct ParIter<'a, T, const PAGE: usize = DEFAULT_PAGE>(&'a [Page<T>]);
1658
1659    /// Unindexed parallel iterator over the ids and mutable elements of a [`Hive`].
1660    pub struct ParIterMut<'a, T, const PAGE: usize = DEFAULT_PAGE>(&'a mut [Page<T>]);
1661
1662    impl<'a, T: Sync, const PAGE: usize> IntoParallelIterator for &'a Hive<T, PAGE> {
1663        type Item = (Id, &'a T);
1664        type Iter = ParIter<'a, T, PAGE>;
1665
1666        fn into_par_iter(self) -> Self::Iter {
1667            ParIter(&self.pages)
1668        }
1669    }
1670
1671    impl<'a, T: Send, const PAGE: usize> IntoParallelIterator for &'a mut Hive<T, PAGE> {
1672        type Item = (Id, &'a mut T);
1673        type Iter = ParIterMut<'a, T, PAGE>;
1674
1675        fn into_par_iter(self) -> Self::Iter {
1676            ParIterMut(&mut self.pages)
1677        }
1678    }
1679
1680    impl<'a, T: Sync, const PAGE: usize> ParallelIterator for ParIter<'a, T, PAGE> {
1681        type Item = (Id, &'a T);
1682
1683        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
1684            self.0
1685                .par_iter()
1686                .enumerate()
1687                .flat_map_iter(|(number, page)| {
1688                    let mut slots = PageSlots::new(number * PAGE, page.slots.iter(), page.len);
1689                    from_fn(move || slots.next(take_ref))
1690                })
1691                .drive_unindexed(consumer)
1692        }
1693    }
1694
1695    impl<'a, T: Send, const PAGE: usize> ParallelIterator for ParIterMut<'a, T, PAGE> {
1696        type Item = (Id, &'a mut T);
1697
1698        fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
1699            self.0
1700                .par_iter_mut()
1701                .enumerate()
1702                .flat_map_iter(|(number, page)| {
1703                    let mut slots = PageSlots::new(number * PAGE, page.slots.iter_mut(), page.len);
1704                    from_fn(move || slots.next(take_mut))
1705                })
1706                .drive_unindexed(consumer)
1707        }
1708    }
1709}
1710
1711#[cfg(feature = "serde")]
1712pub(crate) mod serde_impl {
1713    use super::*;
1714    use serde::de::{Deserialize, Deserializer, Error};
1715    use serde::ser::{Serialize, Serializer};
1716
1717    /// A slot as serialized: its version, and its element if occupied.
1718    #[derive(serde::Serialize, serde::Deserialize)]
1719    enum SlotRepr<V> {
1720        Occupied(u32, V),
1721        Vacant(u32),
1722    }
1723
1724    struct SlotsRef<'a, T>(&'a [Slot<T>]);
1725
1726    impl<T: Serialize> Serialize for SlotsRef<'_, T> {
1727        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1728            serializer.collect_seq(self.0.iter().map(|slot| match slot {
1729                Slot::Occupied { version, value } => SlotRepr::Occupied(*version, value),
1730                Slot::Vacant { version, .. } => SlotRepr::Vacant(*version),
1731            }))
1732        }
1733    }
1734
1735    #[derive(serde::Serialize)]
1736    struct PageRef<Slots: Serialize> {
1737        floor: u32,
1738        slots: Slots,
1739    }
1740
1741    #[cfg(all(
1742        feature = "concurrent",
1743        target_has_atomic = "ptr",
1744        target_has_atomic = "64",
1745        any(target_pointer_width = "32", target_pointer_width = "64")
1746    ))]
1747    pub(crate) mod raw_pages {
1748        use super::*;
1749        use core::ops::{Deref, Range};
1750        use serde::ser::SerializeSeq;
1751
1752        struct SlotsRef<'a, F> {
1753            indices: Range<u32>,
1754            scan: &'a F,
1755        }
1756
1757        impl<V: Deref, F: Fn(u32) -> RawSlot<V>> Serialize for SlotsRef<'_, F>
1758        where
1759            V::Target: Serialize,
1760        {
1761            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1762                let mut seq = serializer.serialize_seq(Some(self.indices.len()))?;
1763                // Each occupied value stays borrowed or guarded only for
1764                // its own serialize call.
1765                for index in self.indices.clone() {
1766                    match (self.scan)(index) {
1767                        RawSlot::Occupied { version, value } => {
1768                            seq.serialize_element(&SlotRepr::Occupied(version, &*value))?;
1769                        }
1770                        RawSlot::Vacant { version } => {
1771                            seq.serialize_element(&SlotRepr::<&V::Target>::Vacant(version))?;
1772                        }
1773                    }
1774                }
1775                seq.end()
1776            }
1777        }
1778
1779        /// Streams raw pages and their guarded or borrowed slot values.
1780        pub(crate) fn serialize<S: Serializer, V: Deref>(
1781            pages: impl Iterator<Item = (u32, Range<u32>)>,
1782            scan: impl Fn(u32) -> RawSlot<V>,
1783            serializer: S,
1784        ) -> Result<S::Ok, S::Error>
1785        where
1786            V::Target: Serialize,
1787        {
1788            serializer.collect_seq(pages.map(|(floor, indices)| PageRef {
1789                floor,
1790                slots: SlotsRef {
1791                    indices,
1792                    scan: &scan,
1793                },
1794            }))
1795        }
1796    }
1797
1798    #[derive(serde::Deserialize)]
1799    struct PageRepr<T> {
1800        floor: u32,
1801        slots: Vec<SlotRepr<T>>,
1802    }
1803
1804    /// Serializes the pages in order, each as its generation floor and its
1805    /// slots (version, and element if occupied). Free lists and capacity
1806    /// are not stored; a round trip keeps every id and generation.
1807    impl<T: Serialize, const PAGE: usize> Serialize for Hive<T, PAGE> {
1808        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1809            serializer.collect_seq(self.pages.iter().map(|page| PageRef {
1810                floor: page.floor,
1811                slots: SlotsRef(&page.slots),
1812            }))
1813        }
1814    }
1815
1816    /// Deserializes and validates the pages: rejects pages beyond the slot
1817    /// indices, a page with more than `PAGE` slots, an odd floor, and
1818    /// versions whose parity does not match the slot state. Free lists are
1819    /// rebuilt, lowest offset first. Every page that holds a slot is
1820    /// allocated with room for `PAGE` slots, so memory can reach `PAGE`
1821    /// slots per page read.
1822    impl<'de, T: Deserialize<'de>, const PAGE: usize> Deserialize<'de> for Hive<T, PAGE> {
1823        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1824            let reprs = Vec::<PageRepr<T>>::deserialize(deserializer)?;
1825            Hive::try_from_raw_pages(reprs.into_iter().map(|repr| {
1826                RawPage {
1827                    floor: repr.floor,
1828                    slots: repr
1829                        .slots
1830                        .into_iter()
1831                        .map(|slot| match slot {
1832                            SlotRepr::Occupied(version, value) => {
1833                                RawSlot::Occupied { version, value }
1834                            }
1835                            SlotRepr::Vacant(version) => RawSlot::Vacant { version },
1836                        })
1837                        .collect(),
1838                }
1839            }))
1840            .map_err(De::Error::custom)
1841        }
1842    }
1843}
1844
1845#[cfg(test)]
1846mod tests {
1847    use super::*;
1848    use core::num::NonZeroU32;
1849
1850    fn g(n: u32) -> NonZeroU32 {
1851        NonZeroU32::new(n).unwrap()
1852    }
1853
1854    /// Checks every invariant documented on `Hive` and `Page`.
1855    fn check<T, const PAGE: usize>(hive: &Hive<T, PAGE>) {
1856        let mut len = 0;
1857        for (p, page) in hive.pages.iter().enumerate() {
1858            assert!(p * PAGE < MAX_INDICES as usize);
1859            let limit = Hive::<T, PAGE>::limit(p);
1860            let cap = page.slots.capacity();
1861            assert!(cap == 0 || cap >= PAGE);
1862            assert!(page.slots.len() <= limit);
1863            assert!(page.floor % 2 == 0);
1864            let mut free = alloc::vec![false; page.slots.len()];
1865            let mut at = page.free_head;
1866            while at != NONE {
1867                assert!(!core::mem::replace(&mut free[at as usize], true));
1868                match page.slots[at as usize] {
1869                    Slot::Vacant { version, next } => {
1870                        assert!(version != 0 && version % 2 == 0);
1871                        at = next;
1872                    }
1873                    Slot::Occupied { .. } => panic!("occupied slot in free list"),
1874                }
1875            }
1876            let (mut occupied, mut retired) = (0, 0);
1877            for (o, slot) in page.slots.iter().enumerate() {
1878                match *slot {
1879                    Slot::Occupied { version, .. } => {
1880                        assert!(version % 2 == 1);
1881                        occupied += 1;
1882                    }
1883                    Slot::Vacant { version: 0, .. } => retired += 1,
1884                    Slot::Vacant { version, .. } => {
1885                        assert!(version % 2 == 0);
1886                        assert!(free[o], "vacant slot missing from free list");
1887                    }
1888                }
1889            }
1890            assert_eq!(page.len, occupied);
1891            assert_eq!(page.retired, retired);
1892            len += occupied as usize;
1893            let listed = hive.open.iter().filter(|&&q| q == p).count();
1894            assert_eq!(listed, usize::from(page.has_room(limit)));
1895        }
1896        assert!(hive.open.iter().all(|&p| p < hive.pages.len()));
1897        assert_eq!(hive.len, len);
1898    }
1899
1900    #[test]
1901    fn raw_rebuild_preserves_page_and_hive_invariants() {
1902        let mut original = Hive::<u32, 4>::with_capacity(20);
1903        let ids: Vec<_> = (0..9).map(|value| original.insert(value)).collect();
1904        for &id in &ids[..5] {
1905            original.remove(id);
1906        }
1907        original.shrink_to_fit();
1908        check(&original);
1909        let snapshot = |hive: &Hive<u32, 4>| {
1910            hive.raw_pages()
1911                .map(|raw| RawPage {
1912                    floor: raw.floor,
1913                    slots: raw
1914                        .slots
1915                        .into_iter()
1916                        .map(|slot| match slot {
1917                            RawSlot::Occupied { version, value } => RawSlot::Occupied {
1918                                version,
1919                                value: *value,
1920                            },
1921                            RawSlot::Vacant { version } => RawSlot::Vacant { version },
1922                        })
1923                        .collect(),
1924                })
1925                .collect::<Vec<_>>()
1926        };
1927        let rebuilt = Hive::try_from_raw_pages(snapshot(&original)).unwrap();
1928        check(&rebuilt);
1929        assert_eq!(original, rebuilt);
1930        assert_eq!(snapshot(&original), snapshot(&rebuilt));
1931        check(&Hive::<u32, 4>::try_from_raw_pages([]).unwrap());
1932
1933        // Retired slots pin their page; empty pages keep their floors and
1934        // directory positions, including never-used trailing pages.
1935        let raw = alloc::vec![
1936            RawPage {
1937                floor: 2,
1938                slots: alloc::vec![
1939                    RawSlot::Vacant { version: 0 },
1940                    RawSlot::Vacant { version: 4 },
1941                    RawSlot::Occupied {
1942                        version: u32::MAX,
1943                        value: 7,
1944                    },
1945                    RawSlot::Vacant { version: 2 },
1946                ],
1947            },
1948            RawPage {
1949                floor: 8,
1950                slots: Vec::new(),
1951            },
1952            RawPage {
1953                floor: 0,
1954                slots: alloc::vec![RawSlot::Occupied {
1955                    version: 1,
1956                    value: 9,
1957                }],
1958            },
1959            RawPage {
1960                floor: u32::MAX - 1,
1961                slots: Vec::new(),
1962            },
1963            RawPage {
1964                floor: 0,
1965                slots: Vec::new(),
1966            },
1967        ];
1968        let mut rebuilt = Hive::<u32, 4>::try_from_raw_pages(raw.clone()).unwrap();
1969        check(&rebuilt);
1970        assert_eq!(snapshot(&rebuilt), raw);
1971        assert_eq!(rebuilt.allocated_pages(), 2);
1972        assert_eq!(rebuilt.index_bound(), 20);
1973        let last = Id::new(2, g(crate::id_alloc::MAX_GENERATION));
1974        assert_eq!(rebuilt.remove(last), Some(7));
1975        check(&rebuilt);
1976        for expected in [1, 3, 9, 10, 11, 4, 5, 6, 7, 12, 13, 14, 15, 16] {
1977            assert_eq!(rebuilt.insert(10).index(), expected);
1978            assert!(!rebuilt.contains(last));
1979            check(&rebuilt);
1980        }
1981        rebuilt.clear();
1982        check(&rebuilt);
1983        rebuilt.shrink_to_fit();
1984        check(&rebuilt);
1985        let rebuilt = Hive::<u32, 4>::try_from_raw_pages(snapshot(&rebuilt)).unwrap();
1986        check(&rebuilt);
1987    }
1988
1989    #[test]
1990    fn insert_remove_reuse() {
1991        let mut hive: Hive<u32, 4> = Hive::new();
1992        let ids: Vec<Id> = (0..6).map(|i| hive.insert(i)).collect();
1993        check(&hive);
1994        assert_eq!(
1995            ids.iter().map(|id| id.index()).collect::<Vec<_>>(),
1996            [0, 1, 2, 3, 4, 5]
1997        );
1998        assert_eq!(hive.remove(ids[1]), Some(1));
1999        assert_eq!(hive.remove(ids[1]), None);
2000        assert_eq!(hive.remove(ids[2]), Some(2));
2001        check(&hive);
2002        // Page 0 gained room last, so it is used first, last freed first.
2003        assert_eq!(hive.insert(10), Id::new(2, g(2)));
2004        assert_eq!(hive.insert(11), Id::new(1, g(2)));
2005        assert_eq!(hive.insert(12), Id::new(6, g(1)));
2006        check(&hive);
2007        assert_eq!(hive.get(ids[1]), None);
2008        assert_eq!(hive[Id::new(1, g(2))], 11);
2009        assert_eq!(hive.occupant(2), Some(Id::new(2, g(2))));
2010        assert_eq!(hive.occupant(7), None);
2011        assert_eq!(hive.occupant(99), None);
2012        assert_eq!(hive.len(), 7);
2013        assert_eq!(
2014            hive.values().copied().collect::<Vec<_>>(),
2015            [0, 11, 10, 3, 4, 5, 12]
2016        );
2017        assert_eq!(
2018            hive.values().rev().copied().collect::<Vec<_>>(),
2019            [12, 5, 4, 3, 10, 11, 0]
2020        );
2021    }
2022
2023    #[test]
2024    fn insert_with_sees_its_id_and_panics_cleanly() {
2025        let mut hive: Hive<Id, 2> = Hive::new();
2026        let a = hive.insert_with(|id| id);
2027        assert_eq!(hive[a], a);
2028        #[cfg(feature = "std")]
2029        {
2030            let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2031                hive.insert_with(|_| panic!("boom"))
2032            }));
2033            assert!(r.is_err());
2034            check(&hive);
2035            assert_eq!(hive.len(), 1);
2036            assert_eq!(hive.insert_with(|id| id).index(), 1);
2037        }
2038    }
2039
2040    #[test]
2041    fn try_insert_reports_exhaustion() {
2042        let mut hive: Hive<u8, 2> = Hive::new();
2043        assert!(!hive.is_exhausted());
2044        assert_eq!(hive.try_insert(1), Ok(Id::new(0, g(1))));
2045        assert_eq!(
2046            hive.try_insert_with(|id| id.index() as u8 + 10),
2047            Some(Id::new(1, g(1)))
2048        );
2049        assert_eq!(hive[Id::new(1, g(1))], 11);
2050        check(&hive);
2051        // Pretend the directory is full: no page has room, and no page
2052        // number is left.
2053        let mut full: Hive<u8, { 1 << 31 }> = Hive::new();
2054        full.pages.push(Page::unallocated(0));
2055        full.pages.push(Page::unallocated(0));
2056        assert!(full.is_exhausted());
2057        assert_eq!(full.try_insert(7), Err(7));
2058        assert_eq!(full.try_insert_with(|_| unreachable!()), None);
2059        assert_eq!(full.len(), 0);
2060    }
2061
2062    #[test]
2063    fn drain_and_extract_if_remove_what_they_yield() {
2064        let mut hive: Hive<u32, 3> = (0..8).collect();
2065        let ids: Vec<Id> = hive.ids().collect();
2066        hive.remove(ids[4]);
2067        let odd: Vec<(Id, u32)> = hive
2068            .extract_if(|_, v| {
2069                *v += 10;
2070                *v % 2 == 1
2071            })
2072            .collect();
2073        check(&hive);
2074        assert_eq!(
2075            odd,
2076            [(ids[1], 11), (ids[3], 13), (ids[5], 15), (ids[7], 17)]
2077        );
2078        assert_eq!(hive.values().copied().collect::<Vec<_>>(), [10, 12, 16]);
2079        // Dropped early: the elements not reached are kept, untested.
2080        assert_eq!(hive.extract_if(|_, _| true).next(), Some((ids[0], 10)));
2081        check(&hive);
2082        assert_eq!(hive.values().copied().collect::<Vec<_>>(), [12, 16]);
2083
2084        hive.extend([20, 21]);
2085        check(&hive);
2086        let mut drain = hive.drain();
2087        assert_eq!(drain.len(), 4);
2088        let first = drain.next().unwrap();
2089        assert_eq!(drain.len(), 3);
2090        drop(drain);
2091        check(&hive);
2092        assert!(hive.is_empty());
2093        assert!(!hive.contains(first.0));
2094        // Slots are reused with new generations after a drain.
2095        let again = hive.insert(1);
2096        assert!(again.generation().get() > 1);
2097        assert_eq!(hive.drain().collect::<Vec<_>>(), [(again, 1)]);
2098        assert_eq!(hive.drain().next(), None);
2099        check(&hive);
2100    }
2101
2102    #[test]
2103    fn get_disjoint_mut_borrows_each_live_id() {
2104        let mut hive: Hive<u32, 2> = (0..5).collect();
2105        let ids: Vec<Id> = hive.ids().collect();
2106        hive.remove(ids[2]);
2107        // Out of slot order, two in one page, one stale, one unknown.
2108        let unknown = Id::new(99, g(1));
2109        let got = hive.get_disjoint_mut([ids[4], ids[1], ids[2], ids[0], unknown]);
2110        let values: Vec<Option<u32>> = got.iter().map(|v| v.as_deref().copied()).collect();
2111        assert_eq!(values, [Some(4), Some(1), None, Some(0), None]);
2112        let [Some(e), Some(b), None, Some(a), None] = got else {
2113            panic!()
2114        };
2115        *e += 100;
2116        *b += 10;
2117        core::mem::swap(a, b);
2118        assert_eq!(hive.values().copied().collect::<Vec<_>>(), [11, 0, 3, 104]);
2119        assert!(hive.get_disjoint_mut([]).is_empty());
2120        // The same stale id twice is fine: neither is live.
2121        assert!(
2122            hive.get_disjoint_mut([ids[2], ids[2]])
2123                .iter()
2124                .all(Option::is_none)
2125        );
2126        check(&hive);
2127    }
2128
2129    #[cfg(feature = "std")]
2130    #[test]
2131    #[should_panic(expected = "given twice")]
2132    fn get_disjoint_mut_rejects_a_repeated_live_id() {
2133        let mut hive: Hive<u32, 2> = (0..3).collect();
2134        let id = hive.ids().nth(1).unwrap();
2135        let _ = hive.get_disjoint_mut([id, id]);
2136    }
2137
2138    #[test]
2139    fn retire_after_last_generation() {
2140        let mut hive: Hive<u8, 2> = Hive::new();
2141        let a = hive.insert(1);
2142        let b = hive.insert(2);
2143        // Jump slot 0 to its last generation.
2144        let Slot::Occupied { version, .. } = &mut hive.pages[0].slots[0] else {
2145            unreachable!()
2146        };
2147        *version = u32::MAX;
2148        let last = Id::new(0, g(crate::id_alloc::MAX_GENERATION));
2149        assert!(!hive.contains(a));
2150        assert_eq!(hive.remove(last), Some(1));
2151        check(&hive);
2152        assert_eq!(hive.pages[0].retired, 1);
2153        // Page 0 has no room: the retired slot is never reused.
2154        assert_eq!(hive.insert(3).index(), 2);
2155        hive.remove(b);
2156        hive.shrink_to_fit();
2157        check(&hive);
2158        // A page with a retired slot is never freed.
2159        assert!(hive.pages[0].allocated());
2160        assert_eq!(hive.insert(4), Id::new(1, g(2)));
2161    }
2162
2163    #[test]
2164    fn shrink_frees_empty_pages_and_keeps_generations() {
2165        let mut hive: Hive<u32, 2> = Hive::new();
2166        let ids: Vec<Id> = (0..6).map(|i| hive.insert(i)).collect();
2167        let addr: *const u32 = &hive[ids[4]];
2168        for &id in &ids[..4] {
2169            hive.remove(id);
2170        }
2171        // Reuse slot 3 a few times to raise its generation.
2172        for _ in 0..3 {
2173            let id = hive.insert(9);
2174            hive.remove(id);
2175        }
2176        hive.shrink_to_fit();
2177        check(&hive);
2178        assert_eq!(hive.allocated_pages(), 1);
2179        assert_eq!(hive.capacity(), 2);
2180        assert!(core::ptr::eq(addr, &hive[ids[4]]));
2181        assert_eq!(hive.pages[0].floor, 2);
2182        assert_eq!(hive.pages[1].floor, 8);
2183        // Freed pages are used again, lowest first, above every old generation.
2184        let a = hive.insert(20);
2185        assert_eq!(a, Id::new(0, g(2)));
2186        assert!(
2187            ids.iter()
2188                .all(|&id| id == ids[4] || id == ids[5] || !hive.contains(id))
2189        );
2190        hive.clear();
2191        hive.shrink_to_fit();
2192        check(&hive);
2193        assert_eq!(hive.allocated_pages(), 0);
2194        assert_eq!(hive.pages.len(), 3);
2195        assert!(ids.iter().all(|&id| !hive.contains(id)));
2196        // Trailing pages that never issued ids are dropped.
2197        let mut fresh: Hive<u32, 2> = Hive::with_capacity(10);
2198        assert_eq!(fresh.allocated_pages(), 5);
2199        fresh.insert(1);
2200        fresh.shrink_to_fit();
2201        check(&fresh);
2202        assert_eq!(fresh.pages.len(), 1);
2203    }
2204
2205    #[test]
2206    fn reserve_fills_open_pages_first() {
2207        let mut hive: Hive<u32, 4> = Hive::new();
2208        let ids: Vec<Id> = (0..4).map(|i| hive.insert(i)).collect();
2209        hive.remove(ids[2]);
2210        hive.reserve(9);
2211        check(&hive);
2212        assert_eq!(hive.allocated_pages(), 3);
2213        let next: Vec<u32> = (0..9).map(|i| hive.insert(i).index()).collect();
2214        assert_eq!(next, [2, 4, 5, 6, 7, 8, 9, 10, 11]);
2215        assert_eq!(hive.allocated_pages(), 3);
2216        check(&hive);
2217        assert!(hive.try_reserve(usize::MAX).is_err());
2218        check(&hive);
2219    }
2220
2221    #[test]
2222    fn retain_iter_and_eq() {
2223        let mut hive: Hive<u32, 3> = (0..10).collect();
2224        hive.retain(|id, v| {
2225            *v += 100;
2226            id.index() % 3 != 1
2227        });
2228        check(&hive);
2229        assert_eq!(
2230            hive.ids().map(Id::index).collect::<Vec<_>>(),
2231            [0, 2, 3, 5, 6, 8, 9]
2232        );
2233        let mut it = hive.iter();
2234        assert_eq!(it.len(), 7);
2235        assert_eq!(it.next().map(|(_, v)| *v), Some(100));
2236        assert_eq!(it.next_back().map(|(_, v)| *v), Some(109));
2237        assert_eq!(it.len(), 5);
2238        for v in hive.values_mut() {
2239            *v -= 100;
2240        }
2241        let clone = hive.clone();
2242        check(&clone);
2243        assert_eq!(clone, hive);
2244        let other: Hive<u32, 16> = hive.iter().map(|(_, v)| *v).collect();
2245        assert_ne!(other, hive);
2246        let owned: Vec<(Id, u32)> = hive.into_iter().rev().collect();
2247        assert_eq!(owned.len(), 7);
2248        assert_eq!(owned[0].1, 9);
2249        assert_eq!(
2250            alloc::format!("{:?}", clone.iter().next()),
2251            "Some((Id(0v1), 0))"
2252        );
2253    }
2254
2255    #[cfg(feature = "serde")]
2256    #[test]
2257    fn serde_round_trip_and_validation() {
2258        let mut hive: Hive<u8, 2> = Hive::new();
2259        let ids: Vec<Id> = (0..3).map(|i| hive.insert(i)).collect();
2260        hive.remove(ids[0]);
2261        let json = serde_json::to_string(&hive).unwrap();
2262        assert_eq!(
2263            json,
2264            r#"[{"floor":0,"slots":[{"Vacant":2},{"Occupied":[1,1]}]},{"floor":0,"slots":[{"Occupied":[1,2]}]}]"#
2265        );
2266        let mut back: Hive<u8, 2> = serde_json::from_str(&json).unwrap();
2267        check(&back);
2268        assert_eq!(back, hive);
2269        assert_eq!(back.insert(7), Id::new(0, g(2)));
2270
2271        for bad in [
2272            r#"[{"floor":1,"slots":[]}]"#,
2273            r#"[{"floor":0,"slots":[{"Vacant":1}]}]"#,
2274            r#"[{"floor":0,"slots":[{"Occupied":[2,0]}]}]"#,
2275            r#"[{"floor":0,"slots":[{"Vacant":2},{"Vacant":2},{"Vacant":2}]}]"#,
2276        ] {
2277            assert!(serde_json::from_str::<Hive<u8, 2>>(bad).is_err(), "{bad}");
2278        }
2279    }
2280}