Skip to main content

paged_collections/concurrent/
hive.rs

1//! Stable value cells, pinned by guards and claimed by CAS before every reuse.
2//!
3//! The low 32 state bits are the id version. BUSY owns the cell exclusively
4//! while inserting or finalizing; MARKED prevents new guards; TAKE reserves a
5//! removed value for its taker. The remaining 29 bits count guards. Pages do
6//! not drop values: only a BUSY owner, or an exclusive hive scan, may do that.
7
8use alloc::boxed::Box;
9use alloc::vec::Vec;
10use core::fmt;
11use core::iter::FusedIterator;
12use core::marker::PhantomData;
13use core::mem::MaybeUninit;
14use core::ops::Deref;
15use core::ptr;
16
17use super::atomic::{AtomicU32, AtomicU64, Ordering, UnsafeCell, spin_loop};
18use super::count::StripedLen;
19use super::free_stack::{FreeStack, Unissued, block_for};
20use super::recycle::PageStack;
21use super::spine::Spine;
22use crate::hive::{Hive, RawPage, RawSlot};
23use crate::id_alloc::{Id, MAX_INDICES, generation_of, live_version};
24use crate::page::DEFAULT_PAGE;
25
26#[cfg(not(loom))]
27const CHUNKS: usize = 28;
28#[cfg(loom)]
29const CHUNKS: usize = 32;
30
31const VERSION: u64 = u32::MAX as u64;
32const BUSY: u64 = 1 << 32;
33const MARKED: u64 = 1 << 33;
34const TAKE: u64 = 1 << 34;
35const REF: u64 = 1 << 35;
36const REFS: u64 = !(REF - 1);
37
38struct Slot<T> {
39    state: AtomicU64,
40    next: AtomicU32,
41    value: UnsafeCell<MaybeUninit<T>>,
42}
43
44impl<T> Slot<T> {
45    fn new() -> Self {
46        Self::with_state(0)
47    }
48
49    /// A vacant slot at `version` (even), for a recycled page.
50    fn with_state(version: u32) -> Self {
51        Self {
52            state: AtomicU64::new(u64::from(version)),
53            next: AtomicU32::new(0),
54            value: UnsafeCell::new(MaybeUninit::uninit()),
55        }
56    }
57}
58
59struct Page<T> {
60    // MaybeUninit deliberately has no value destructor. The hive scans cells.
61    slots: Box<[Slot<T>]>,
62}
63
64fn vacant(live: u32) -> u64 {
65    u64::from(live.checked_add(1).unwrap_or(0))
66}
67
68fn matches(word: u64, version: u32) -> bool {
69    word & VERSION == u64::from(version) && word & (BUSY | MARKED) == 0
70}
71
72fn retry(spins: &mut u32) {
73    *spins = spins.saturating_add(1);
74    #[cfg(all(feature = "std", not(loom)))]
75    if *spins >= 64 {
76        std::thread::yield_now();
77        return;
78    }
79    spin_loop();
80}
81
82/// A paged container with stable addresses and shared insertion and removal.
83///
84/// [`get`](Self::get) returns a guard instead of a bare reference. Removal
85/// invalidates the id immediately, but existing guards keep the value alive.
86/// Taking a value waits for its guards. A forgotten guard pins its slot until
87/// exclusive access or destruction. There is no mutable access while shared.
88///
89/// Pages stay allocated until [`shrink_to_fit`](Self::shrink_to_fit) frees
90/// the empty ones; shared inserts reuse freed pages later. Shared iteration is weakly
91/// consistent: it may miss concurrent insertions or removals. `len` is
92/// approximate during shared operations and exact when they have finished.
93/// Exclusive scans take O([`index_bound`](Self::index_bound)) time.
94///
95/// Each successful lookup costs two atomic writes (guard acquisition and
96/// release). Prefer [`Hive`](crate::hive::Hive) when shared mutation is not
97/// needed. As with that type, ids carry no container identity, generations
98/// never wrap, and stale ids stay dead within one allocation history.
99///
100/// `PAGE` must be non-zero, fit in a `u32`, and fit a page in `isize::MAX`
101/// bytes. Uses only `core` and `alloc`; `std` enables yielding while waiting.
102pub struct ConcurrentHive<T, const PAGE: usize = DEFAULT_PAGE> {
103    pages: Spine<Page<T>, CHUNKS>,
104    free: FreeStack,
105    /// Pages freed by `shrink_to_fit`, below the reservation bound.
106    recycled: PageStack,
107    len: StripedLen,
108}
109
110// SAFETY: moving the hive transfers its owned cells; no guard outlives its
111// borrow. Exclusive finalization may drop T on the receiving thread.
112unsafe impl<T: Send, const PAGE: usize> Send for ConcurrentHive<T, PAGE> {}
113// SAFETY: BUSY exclusively owns writes/drops; matching counted guards alone
114// share live T. Shared removal/take can also transfer or drop T across threads.
115unsafe impl<T: Send + Sync, const PAGE: usize> Sync for ConcurrentHive<T, PAGE> {}
116
117/// Owns a cell already claimed by CAS (or by an exclusive scan). Releasing it
118/// publishes completion before making it reusable. Also runs during unwinding
119/// after a factory or value destructor panics; value drop glue finishes before
120/// this owner's cleanup runs.
121struct Busy<'a, T, const PAGE: usize> {
122    hive: &'a ConcurrentHive<T, PAGE>,
123    slot: &'a Slot<T>,
124    index: u32,
125    vacant: u64,
126    armed: bool,
127}
128
129impl<T, const PAGE: usize> Drop for Busy<'_, T, PAGE> {
130    fn drop(&mut self) {
131        if self.armed {
132            // Release publishes the end of ALL value access, including drop
133            // glue during unwinding. A claim's Acquire observes this even if
134            // its stack hint did not come from this particular push.
135            self.slot.state.store(self.vacant, Ordering::Release);
136            if self.vacant != 0 {
137                self.hive.free.push(self.index, &self.slot.next);
138            }
139        }
140    }
141}
142
143impl<T, const PAGE: usize> ConcurrentHive<T, PAGE> {
144    /// Number of slots per page.
145    pub const PAGE: usize = PAGE;
146
147    /// An empty hive, without allocating.
148    ///
149    /// # Panics
150    ///
151    /// Panics if the page capacity is invalid; see the type's documentation.
152    pub fn new() -> Self {
153        assert!(
154            PAGE > 0
155                && PAGE <= u32::MAX as usize
156                && PAGE <= isize::MAX as usize / core::mem::size_of::<Slot<T>>(),
157            "ConcurrentHive: invalid page capacity"
158        );
159        Self {
160            pages: Spine::new(),
161            free: FreeStack::new(),
162            recycled: PageStack::new(),
163            len: StripedLen::new(),
164        }
165    }
166
167    fn slot(&self, index: u32) -> Option<&Slot<T>> {
168        if index == MAX_INDICES {
169            return None;
170        }
171        self.pages
172            .get(index as usize / PAGE)
173            .map(|page| &page.slots[index as usize % PAGE])
174    }
175
176    fn ensure_slot(&self, index: u32) -> &Slot<T> {
177        let page = self.pages.get_or_insert_with(index as usize / PAGE, || {
178            Box::new(Page {
179                slots: (0..PAGE).map(|_| Slot::new()).collect(),
180            })
181        });
182        &page.slots[index as usize % PAGE]
183    }
184
185    fn busy<'a>(&'a self, slot: &'a Slot<T>, index: u32, vacant: u64) -> Busy<'a, T, PAGE> {
186        Busy {
187            hive: self,
188            slot,
189            index,
190            vacant,
191            armed: true,
192        }
193    }
194
195    /// Reinstalls a page freed by `shrink_to_fit`, with every usable slot
196    /// vacant at the page's floor. Pushes all its slots but the first to the
197    /// free stack and returns the first, for the caller to claim by CAS.
198    ///
199    /// The popper is the page's only installer: the free stack holds none of
200    /// its indices (it was rebuilt when the page was freed), and fresh
201    /// reservation never hands out an index in a freed page: the counter
202    /// never goes below the bound, and indices reserved in a thread's block
203    /// but not handed out keep state 0, which stops their page from being
204    /// freed (uninstalled pages are never freed). Its slots are unreachable
205    /// until pushed (a guessed id finds a vacant state), so this thread owns
206    /// them while pushing.
207    fn recycle(&self) -> Option<u32> {
208        let (page, floor) = self.recycled.pop()?;
209        let base = page * PAGE;
210        let limit = PAGE.min(MAX_INDICES as usize - base);
211        let installed = self.pages.get_or_insert_with(page, || {
212            Box::new(Page {
213                slots: (0..PAGE)
214                    .map(|offset| Slot::with_state(if offset < limit { floor } else { 0 }))
215                    .collect(),
216            })
217        });
218        for offset in (1..limit).rev() {
219            self.free
220                .push((base + offset) as u32, &installed.slots[offset].next);
221        }
222        Some(base as u32)
223    }
224
225    fn claim(&self) -> Option<(Busy<'_, T, PAGE>, u32)> {
226        loop {
227            let (index, reused) = self.free.next_index(
228                |index| &self.slot(index).expect("free index has a page").next,
229                || self.recycle(),
230                MAX_INDICES,
231                block_for(PAGE),
232            )?;
233            let slot = self.ensure_slot(index);
234            // Acquire observes a completed finalizer, independently of the
235            // free-stack hint. No flags or references may remain at claim.
236            let old = slot.state.load(Ordering::Acquire);
237            if old & !VERSION != 0 || old & 1 != 0 || (reused && old == 0) {
238                continue;
239            }
240            // AcqRel claims sole ownership and observes the preceding vacant
241            // Release. A failed CAS discards the hint, never retries that word.
242            // Fresh 0|BUSY and retiring 0|BUSY overlap harmlessly: both are
243            // owned, unclaimable states; fresh indices are uniquely reserved.
244            if slot
245                .state
246                .compare_exchange(old, old | BUSY, Ordering::AcqRel, Ordering::Acquire)
247                .is_err()
248            {
249                continue;
250            }
251            // If the insertion unwinds (a panicking factory), the id it was
252            // shown is spent: the slot returns as the vacancy after `live`,
253            // so that id can never name a later value.
254            let live = old as u32 + 1;
255            return Some((self.busy(slot, index, vacant(live)), live));
256        }
257    }
258
259    // The caller owns this empty cell through a claim or exclusive conversion.
260    fn write_value(&self, slot: &Slot<T>, index: u32, live: u32, value: T) {
261        slot.value.with_mut(|cell| {
262            // SAFETY: the claim CAS or exclusive construction grants sole
263            // ownership of this uninitialized cell. MaybeUninit<T> has T's
264            // layout/alignment.
265            unsafe { ptr::write(cell.cast::<T>(), value) };
266        });
267        // Relaxed accounting precedes publication, so any removal of this
268        // value, even through a guessed id, is counted after it.
269        self.len.increment(index as usize / PAGE);
270        // Release publishes the initialized value and preceding accounting;
271        // every successful reader/remover CAS acquires that publication.
272        slot.state.store(u64::from(live), Ordering::Release);
273    }
274
275    fn publish(&self, mut owner: Busy<'_, T, PAGE>, live: u32, value: T) -> Id {
276        self.write_value(owner.slot, owner.index, live, value);
277        owner.armed = false;
278        Id::new(owner.index, generation_of(live))
279    }
280
281    /// Inserts `value` and returns its id.
282    ///
283    /// # Panics
284    ///
285    /// Panics if all [`MAX_INDICES`] indices are occupied or retired, or a
286    /// page cannot be allocated. A concurrent finalizer may make room later.
287    pub fn insert(&self, value: T) -> Id {
288        self.try_insert(value).unwrap_or_else(|_| {
289            panic!("ConcurrentHive: all {MAX_INDICES} slot indices are occupied or retired")
290        })
291    }
292
293    /// Like [`insert`](Self::insert), returning the value on index exhaustion.
294    /// Allocation failures may still panic or abort.
295    pub fn try_insert(&self, value: T) -> Result<Id, T> {
296        let Some((owner, live)) = self.claim() else {
297            return Err(value);
298        };
299        Ok(self.publish(owner, live, value))
300    }
301
302    /// Inserts the value `f` makes from its id.
303    ///
304    /// If `f` panics, the slot is returned to the free stack and the
305    /// generation of the id passed to `f` is spent, so that id stays dead.
306    ///
307    /// # Panics
308    ///
309    /// Panics on index exhaustion or if `f` panics; allocation may also fail.
310    pub fn insert_with(&self, f: impl FnOnce(Id) -> T) -> Id {
311        self.try_insert_with(f).unwrap_or_else(|| {
312            panic!("ConcurrentHive: all {MAX_INDICES} slot indices are occupied or retired")
313        })
314    }
315
316    /// Like [`insert_with`](Self::insert_with), returning `None` without
317    /// calling `f` when no index is available.
318    pub fn try_insert_with(&self, f: impl FnOnce(Id) -> T) -> Option<Id> {
319        let (owner, live) = self.claim()?;
320        let value = f(Id::new(owner.index, generation_of(live)));
321        Some(self.publish(owner, live, value))
322    }
323
324    fn acquire(&self, index: u32, expected: Option<u32>) -> Option<Ref<'_, T, PAGE>> {
325        let slot = self.slot(index)?;
326        self.acquire_slot(slot, index, expected).ok()
327    }
328
329    // Returns the word that ruled out a guard, so a scan can map that state
330    // without loading again after a concurrent transition.
331    fn acquire_slot<'a>(
332        &'a self,
333        slot: &'a Slot<T>,
334        index: u32,
335        expected: Option<u32>,
336    ) -> Result<Ref<'a, T, PAGE>, u64> {
337        // Acquire observes publication before inspecting the version/flags.
338        let mut word = slot.state.load(Ordering::Acquire);
339        loop {
340            let live = word as u32;
341            if live & 1 == 0
342                || word & (BUSY | MARKED) != 0
343                || expected.is_some_and(|version| version != live)
344            {
345                return Err(word);
346            }
347            assert!(word & REFS != REFS, "ConcurrentHive: guard count overflow");
348            // Acquire sees the value published by the inserter; Release makes
349            // this guard count visible to removers and subsequent guard drops.
350            match slot.state.compare_exchange_weak(
351                word,
352                word + REF,
353                Ordering::AcqRel,
354                Ordering::Acquire,
355            ) {
356                Ok(_) => {
357                    return Ok(Ref {
358                        hive: self,
359                        slot,
360                        index,
361                        version: live,
362                        #[cfg(loom)]
363                        access: Some(slot.value.read()),
364                    });
365                }
366                Err(actual) => word = actual,
367            }
368        }
369    }
370
371    fn snapshot_slot(&self, index: u32, unissued: &Unissued) -> RawSlot<Ref<'_, T, PAGE>> {
372        let Some(slot) = self.slot(index) else {
373            // A reservation or recycled page may still be uninstalled.
374            return RawSlot::Vacant { version: 0 };
375        };
376        let word = match self.acquire_slot(slot, index, None) {
377            Ok(value) => {
378                return RawSlot::Occupied {
379                    version: value.version,
380                    value,
381                };
382            }
383            Err(word) => word,
384        };
385        let mut version = word as u32;
386        if word & BUSY != 0 {
387            #[cfg(all(test, loom))]
388            super::loom_hive::record_snapshot_busy(index);
389            // A claimer keeps the old vacancy; a finalizer has already
390            // advanced to the next vacancy (or to zero on retirement).
391            debug_assert_eq!(version & 1, 0);
392        } else if word & MARKED != 0 {
393            #[cfg(all(test, loom))]
394            super::loom_hive::record_snapshot_marked();
395            // Logical removal precedes finalization, including for TAKE.
396            version = vacant(version) as u32;
397        } else if version == 0 && unissued.contains_shared(index) {
398            version = 2;
399        }
400        RawSlot::Vacant { version }
401    }
402
403    /// Pins the value of a matching live id until the returned guard drops.
404    ///
405    /// Returns `None` for a stale or removed id. Panics if the slot already
406    /// has the maximum of 2²⁹ − 1 guards. Guards cannot be cloned.
407    pub fn get(&self, id: Id) -> Option<Ref<'_, T, PAGE>> {
408        self.acquire(id.index(), Some(live_version(id.generation())?))
409    }
410
411    /// Whether this id is live at the instant of one state load.
412    /// Does not pin the value against a subsequent removal.
413    pub fn contains(&self, id: Id) -> bool {
414        let Some(live) = live_version(id.generation()) else {
415            return false;
416        };
417        // Acquire observes publication/invalidation, but grants no cell access.
418        self.slot(id.index())
419            .is_some_and(|slot| matches(slot.state.load(Ordering::Acquire), live))
420    }
421
422    /// Logically removes a matching live id. Exactly one remover succeeds.
423    /// Existing guards defer destruction until the last guard drops.
424    ///
425    /// If immediate value destruction panics, the id is still removed and its
426    /// slot is returned after drop glue finishes unwinding.
427    pub fn remove(&self, id: Id) -> bool {
428        let Some(live) = live_version(id.generation()) else {
429            return false;
430        };
431        let Some(slot) = self.slot(id.index()) else {
432            return false;
433        };
434        // Acquire observes publication and competing guard/removal operations.
435        let mut word = slot.state.load(Ordering::Acquire);
436        loop {
437            if !matches(word, live) {
438                return false;
439            }
440            let direct = word & REFS == 0;
441            let new = if direct {
442                vacant(live) | BUSY
443            } else {
444                word | MARKED
445            };
446            // AcqRel acquires value publication and prior guard releases, and
447            // publishes invalidation. Only the winner may finalize or mark.
448            match slot
449                .state
450                .compare_exchange_weak(word, new, Ordering::AcqRel, Ordering::Acquire)
451            {
452                Ok(_) => {
453                    // Relaxed accounting: logically removed now, before any
454                    // user destructor (which may panic or reenter the hive).
455                    self.len.decrement(id.index() as usize / PAGE);
456                    if direct {
457                        let owner = self.busy(slot, id.index(), vacant(live));
458                        self.drop_owned(&owner);
459                    }
460                    return true;
461                }
462                Err(actual) => word = actual,
463            }
464        }
465    }
466
467    fn drop_owned(&self, owner: &Busy<'_, T, PAGE>) {
468        owner.slot.value.with_mut(|cell| {
469            // SAFETY: the finalizing CAS (or exclusive scan) granted this
470            // BUSY owner an initialized value, with no remaining guard holders.
471            unsafe { ptr::drop_in_place(cell.cast::<T>()) };
472        });
473    }
474
475    /// Removes and returns a matching live value, waiting for its guards.
476    ///
477    /// Blocks while any guard on this id lives; **deadlocks if the calling
478    /// thread holds one**. A forgotten guard can block this call forever.
479    /// Competing removes or takes return `false`/`None` once this call marks
480    /// the id. The last guard never drops a value owned by a taker.
481    pub fn take(&self, id: Id) -> Option<T> {
482        let live = live_version(id.generation())?;
483        let slot = self.slot(id.index())?;
484        // Acquire observes the initialized live value and current guard count.
485        let mut word = slot.state.load(Ordering::Acquire);
486        loop {
487            if !matches(word, live) {
488                return None;
489            }
490            // AcqRel reserves the value for this taker, observes publication,
491            // and prevents any new guard from being acquired.
492            match slot.state.compare_exchange_weak(
493                word,
494                word | MARKED | TAKE,
495                Ordering::AcqRel,
496                Ordering::Acquire,
497            ) {
498                Ok(_) => break,
499                Err(actual) => word = actual,
500            }
501        }
502        // Relaxed accounting: the mark is the logical removal point.
503        self.len.decrement(id.index() as usize / PAGE);
504        let mut spins = 0;
505        loop {
506            // Acquire observes guard releases before exclusive extraction.
507            let word = slot.state.load(Ordering::Acquire);
508            // AcqRel transfers the cell from the marked taker to BUSY;
509            // its Acquire sees the last guard's Release, even on retries.
510            if word & REFS == 0
511                && slot
512                    .state
513                    .compare_exchange(
514                        u64::from(live) | MARKED | TAKE,
515                        vacant(live) | BUSY,
516                        Ordering::AcqRel,
517                        Ordering::Acquire,
518                    )
519                    .is_ok()
520            {
521                let owner = self.busy(slot, id.index(), vacant(live));
522                let value = slot.value.with_mut(|cell| {
523                    // SAFETY: the taker's final CAS owns BUSY after all
524                    // guards released; no finalizer can drop this value.
525                    unsafe { ptr::read(cell.cast::<T>()) }
526                });
527                drop(owner);
528                return Some(value);
529            }
530            retry(&mut spins);
531        }
532    }
533
534    /// Number of logically live values; approximate during shared operations.
535    /// Exact when no operation is in flight; this is no publication barrier.
536    ///
537    /// It sums per-thread counters (per page group without `std`). While
538    /// operations are in flight it may combine counters read at different
539    /// moments and differ from every count the hive held; it never
540    /// exceeds the number of insertions.
541    pub fn len(&self) -> usize {
542        self.len.get()
543    }
544
545    /// Whether the hive is empty; approximate during shared operations.
546    pub fn is_empty(&self) -> bool {
547        self.len() == 0
548    }
549
550    /// One past the highest reserved index, including insertions in flight.
551    /// A reserved index's page may not have been installed yet.
552    ///
553    /// Threads that contend for fresh indices reserve them in blocks of
554    /// about one page, so the bound may exceed the indices handed out by up
555    /// to one block per thread.
556    pub fn index_bound(&self) -> u32 {
557        self.free.index_bound()
558    }
559
560    /// Iterates over `(id, guard)` in slot order, weakly consistently.
561    /// Scans only indices below the reservation bound at iterator creation.
562    pub fn iter(&self) -> Iter<'_, T, PAGE> {
563        Iter {
564            hive: self,
565            indices: 0..self.index_bound(),
566        }
567    }
568
569    // &mut self proves every outstanding count belongs to a forgotten Ref.
570    // Such a guard can never run again. MARKED values are already absent from
571    // len; finalize them without decrementing it a second time.
572    fn normalize_slot(&mut self, index: u32) {
573        let Some(slot) = self.slot(index) else {
574            return;
575        };
576        // Acquire is conservative; exclusivity alone rules out concurrent use.
577        let word = slot.state.load(Ordering::Acquire);
578        if word & 1 == 0 {
579            return;
580        }
581        if word & MARKED != 0 {
582            let vacant = vacant(word as u32);
583            // Release records exclusive BUSY ownership before user drop code.
584            slot.state.store(vacant | BUSY, Ordering::Release);
585            let owner = self.busy(slot, index, vacant);
586            self.drop_owned(&owner);
587        } else if word & REFS != 0 {
588            // Release resets forgotten counts; no actual guard can still exist.
589            slot.state.store(word & !REFS, Ordering::Release);
590        }
591    }
592
593    fn normalize(&mut self) {
594        for index in 0..self.index_bound() {
595            self.normalize_slot(index);
596        }
597    }
598
599    /// The matching live value, mutably, under exclusive access.
600    /// Forgotten guard counts at this slot are reset. A marked value is
601    /// finalized and is never returned, even for a different requested id.
602    pub fn get_mut(&mut self, id: Id) -> Option<&mut T> {
603        self.normalize_slot(id.index());
604        let live = live_version(id.generation())?;
605        let slot = self.slot(id.index())?;
606        // Acquire observes the normalized state; exclusivity excludes writers.
607        if !matches(slot.state.load(Ordering::Acquire), live) {
608            return None;
609        }
610        Some(slot.value.with_mut(|cell| {
611            // SAFETY: &mut self excludes all usable guards and other accesses;
612            // normalization removed marked values and reset forgotten counts.
613            unsafe { &mut *cell.cast::<T>() }
614        }))
615    }
616
617    /// Removes and returns a live value without waiting for forgotten guards.
618    /// Finalizes a marked value at this slot without returning it.
619    pub fn take_mut(&mut self, id: Id) -> Option<T> {
620        self.normalize_slot(id.index());
621        self.take(id)
622    }
623
624    /// Iterates over live `(id, &mut value)` pairs in slot order.
625    /// Finalizes all marked values and resets forgotten counts before yielding.
626    pub fn iter_mut(&mut self) -> IterMut<'_, T, PAGE> {
627        self.normalize();
628        IterMut {
629            remaining: self.len(),
630            indices: 0..self.index_bound(),
631            hive: self,
632            exclusive: PhantomData,
633        }
634    }
635
636    /// Removes and drops every value, retaining pages and generation history.
637    /// Forgotten guards do not pin values under exclusive access.
638    pub fn clear(&mut self) {
639        self.retain(|_, _| false);
640    }
641
642    /// Eagerly removes every live value, yielding owned `(id, value)` pairs in
643    /// slot order. Dropping or forgetting the iterator leaves the hive empty.
644    /// Marked values are finalized and not yielded. Pages and generations stay.
645    pub fn drain(&mut self) -> Drain<'_, T, PAGE> {
646        self.normalize();
647        let mut values = Vec::with_capacity(self.len());
648        for index in 0..self.index_bound() {
649            let Some(slot) = self.slot(index) else {
650                continue;
651            };
652            // Acquire observes normalized live state; access is exclusive.
653            let word = slot.state.load(Ordering::Acquire);
654            if word & 1 != 0 {
655                let id = Id::new(index, generation_of(word as u32));
656                values.push((id, self.take(id).expect("normalized live value")));
657            }
658        }
659        Drain {
660            inner: values.into_iter(),
661            exclusive: PhantomData,
662        }
663    }
664
665    /// Keeps values for which `keep(id, value)` returns true, in slot order.
666    /// Finalizes marked values and resets forgotten counts before calling
667    /// `keep`. If the predicate or a destructor panics, prior changes remain
668    /// and `len` stays exact.
669    pub fn retain(&mut self, mut keep: impl FnMut(Id, &mut T) -> bool) {
670        self.normalize();
671        for index in 0..self.index_bound() {
672            let Some(slot) = self.slot(index) else {
673                continue;
674            };
675            // Acquire observes normalized state; exclusivity rules out races.
676            let word = slot.state.load(Ordering::Acquire);
677            if word & 1 == 0 {
678                continue;
679            }
680            let id = Id::new(index, generation_of(word as u32));
681            let keep_value = keep(id, self.get_mut(id).expect("normalized live value"));
682            if !keep_value {
683                drop(self.take(id));
684            }
685        }
686    }
687
688    /// Frees every page that holds no value, under exclusive access. Takes
689    /// O([`index_bound`](Self::index_bound)) time.
690    ///
691    /// Marked values are finalized and forgotten guard counts reset first.
692    /// A page is then freed if it lies wholly below the reservation bound and
693    /// all its slots are vacant and reusable (a page with a retired slot is
694    /// kept). It remembers its highest version, so ids it issued stay dead:
695    /// shared inserts reuse freed pages, lowest first, after the free slots
696    /// of the remaining pages, with generations above every earlier one.
697    /// That order is exact only for one inserter that has not contended
698    /// with others: a thread first uses up a block of fresh indices it
699    /// reserved under contention, and while one insert is relinking a
700    /// reused page, a concurrent insert can take a fresh index
701    /// instead (and fail at the index limit even though slots are about to
702    /// be freed). The free slots are relinked in index order. The page directory's own
703    /// small arrays stay allocated.
704    ///
705    /// ```
706    /// use paged_collections::concurrent::ConcurrentHive;
707    ///
708    /// let mut hive = ConcurrentHive::<u32, 4>::new();
709    /// let ids: Vec<_> = (0..12).map(|v| hive.insert(v)).collect();
710    /// for &id in &ids[..8] {
711    ///     hive.remove(id);
712    /// }
713    /// hive.shrink_to_fit(); // frees the first two pages
714    /// assert_eq!(*hive.get(ids[8]).unwrap(), 8);
715    /// let new = hive.insert(99); // reuses a freed page
716    /// assert!(new.index() < 8 && !ids.contains(&new));
717    /// assert!(hive.get(ids[0]).is_none());
718    /// ```
719    pub fn shrink_to_fit(&mut self) {
720        self.normalize();
721        let bound = self.index_bound() as usize;
722        let mut freed = self.recycled.pending().to_vec();
723        let installed: Vec<usize> = self.pages.iter().map(|(number, _)| number).collect();
724        for number in installed {
725            let base = number * PAGE;
726            let end = (base + PAGE).min(MAX_INDICES as usize);
727            if end > bound {
728                continue;
729            }
730            let page = self.pages.get(number).expect("page was just listed");
731            let mut floor = 0;
732            let empty = page.slots[..end - base].iter().all(|slot| {
733                // Relaxed: exclusive access, and normalization left no flags.
734                let word = slot.state.load(Ordering::Relaxed);
735                debug_assert_eq!(word & !VERSION, 0, "normalized slot has flags");
736                let version = word as u32;
737                floor = floor.max(version);
738                // Live (odd) or retired (zero below the bound) slots stay.
739                version & 1 == 0 && version != 0
740            });
741            if empty {
742                // The page's cells are all vacant: dropping it drops no T.
743                drop(self.pages.remove(number));
744                freed.push((number, floor));
745            }
746        }
747        // The free stack linked through freed slots: relink the rest,
748        // pushed from the top so the lowest index pops first.
749        self.free.reset();
750        for index in (0..bound as u32).rev() {
751            if let Some(slot) = self.slot(index) {
752                // Relaxed: exclusive access rules out concurrent changes.
753                let version = slot.state.load(Ordering::Relaxed) as u32;
754                if version & 1 == 0 && version != 0 {
755                    self.free.push(index, &slot.next);
756                }
757            }
758        }
759        self.recycled.set(freed);
760    }
761
762    /// Clones a weakly consistent snapshot into a plain [`Hive`].
763    /// Insertions that happen-before the call are included if the entry
764    /// stays live throughout it. Ids whose removal happens-before the
765    /// call stay dead. The raw pages always validate. Scans up to
766    /// [`index_bound`](Self::index_bound) with a floor lookup per page.
767    ///
768    /// Each value stays guarded while its `Clone` runs. Taking that id in
769    /// the callback, or waiting there for another thread to take it, deadlocks.
770    pub fn snapshot(&self) -> Hive<T, PAGE>
771    where
772        T: Clone,
773    {
774        let bound = self.index_bound();
775        let unissued = self.free.unissued_shared();
776        let pages = self
777            .recycled
778            .snapshot_pages(bound, PAGE)
779            .map(|(floor, indices)| RawPage {
780                floor,
781                slots: indices
782                    .map(|index| match self.snapshot_slot(index, &unissued) {
783                        RawSlot::Occupied { version, value } => RawSlot::Occupied {
784                            version,
785                            value: (*value).clone(),
786                        },
787                        RawSlot::Vacant { version } => RawSlot::Vacant { version },
788                    })
789                    .collect(),
790            });
791        Hive::try_from_raw_pages(pages).expect("hive snapshot has valid raw pages")
792    }
793
794    /// Moves into a plain [`Hive`], preserving live ids and stale-id history.
795    /// Takes O([`index_bound`](Self::index_bound)) time; pages and reuse order
796    /// may change.
797    ///
798    /// Marked values are finalized and not carried over. Forgotten guards are
799    /// released: their counts are reset before any live value is moved.
800    /// Every slot below the bound is represented explicitly: zero states
801    /// become retired vacancies, even versions become reusable vacancies,
802    /// and odd versions keep their values. Indices reserved for a thread's
803    /// block but never handed out become reusable vacancies at version 2. A page freed by
804    /// [`shrink_to_fit`](Self::shrink_to_fit) becomes an empty raw page with
805    /// its floor; other floors are zero. Offsets beyond the bound have never
806    /// issued ids and need no history.
807    ///
808    /// Raw-page validation cannot fail by construction: all versions have
809    /// the required parity, all pages fit `PAGE`, and indices are below
810    /// [`MAX_INDICES`]. Allocation or a marked value's destructor may panic;
811    /// allocation may also abort. Values already moved are owned by the raw
812    /// pages; this hive's empty cells cannot drop them again, including if
813    /// allocation unwinds.
814    ///
815    /// # Examples
816    ///
817    /// ```
818    /// use paged_collections::concurrent::ConcurrentHive;
819    ///
820    /// let hive = ConcurrentHive::<String, 4>::new();
821    /// let id = hive.insert(String::from("hello"));
822    /// let plain = hive.into_hive();
823    /// assert_eq!(plain.get(id).map(String::as_str), Some("hello"));
824    /// assert_eq!(plain.len(), 1);
825    /// ```
826    pub fn into_hive(mut self) -> Hive<T, PAGE> {
827        self.normalize();
828        let bound = self.index_bound() as usize;
829        let mut unissued = self.free.unissued();
830        let mut pages = Vec::with_capacity(bound.div_ceil(PAGE));
831        for base in (0..bound).step_by(PAGE) {
832            if let Some(floor) = self.recycled.floor_of(base / PAGE) {
833                // A freed page: every slot restarts above its floor.
834                pages.push(RawPage {
835                    floor,
836                    slots: Vec::new(),
837                });
838                continue;
839            }
840            let end = base + PAGE.min(bound - base);
841            let mut slots = Vec::with_capacity(end - base);
842            for index in base..end {
843                let mut version = self.slot(index as u32).map_or(0, |slot| {
844                    // Acquire is conservative: normalization and exclusive
845                    // ownership rule out concurrent flags or guard counts.
846                    let word = slot.state.load(Ordering::Acquire);
847                    debug_assert!(word & !VERSION == 0);
848                    word as u32
849                });
850                if unissued.contains(index as u32) {
851                    // Reserved in a block, never handed out: reusable, with
852                    // generation 1 spent (a zero would read as retired).
853                    debug_assert_eq!(version, 0, "unissued index was used");
854                    version = 2;
855                }
856                slots.push(if version & 1 != 0 {
857                    let id = Id::new(index as u32, generation_of(version));
858                    RawSlot::Occupied {
859                        version,
860                        value: self.take(id).expect("normalized live value"),
861                    }
862                } else {
863                    RawSlot::Vacant { version }
864                });
865            }
866            pages.push(RawPage { floor: 0, slots });
867        }
868        Hive::try_from_raw_pages(pages)
869            .expect("concurrent hive raw pages are valid by construction")
870    }
871
872    #[cfg(all(test, loom))]
873    pub(super) fn inject_busy_hint(&self, index: u32) {
874        let slot = self.slot(index).unwrap();
875        assert_ne!(slot.state.load(Ordering::Acquire) & BUSY, 0);
876        // Models a stale link installed after tag wrap, without 2^32 pops.
877        self.free.push(index, &slot.next);
878    }
879}
880
881/// Clones via [`ConcurrentHive::snapshot`], preserving generations.
882/// Each value stays guarded while its `Clone` runs, so taking that id
883/// or waiting for its taker from the callback deadlocks.
884impl<T: Clone, const PAGE: usize> Clone for ConcurrentHive<T, PAGE> {
885    fn clone(&self) -> Self {
886        Self::from(self.snapshot())
887    }
888}
889
890impl<'a, T, const PAGE: usize> IntoIterator for &'a ConcurrentHive<T, PAGE> {
891    type Item = (Id, Ref<'a, T, PAGE>);
892    type IntoIter = Iter<'a, T, PAGE>;
893
894    fn into_iter(self) -> Self::IntoIter {
895        self.iter()
896    }
897}
898
899impl<'a, T, const PAGE: usize> IntoIterator for &'a mut ConcurrentHive<T, PAGE> {
900    type Item = (Id, &'a mut T);
901    type IntoIter = IterMut<'a, T, PAGE>;
902
903    fn into_iter(self) -> Self::IntoIter {
904        self.iter_mut()
905    }
906}
907
908impl<T, const PAGE: usize> Default for ConcurrentHive<T, PAGE> {
909    fn default() -> Self {
910        Self::new()
911    }
912}
913
914#[cfg(feature = "serde")]
915mod serde_impl {
916    use super::*;
917    use crate::hive::serde_impl::raw_pages;
918    use serde::de::{Deserialize, Deserializer};
919    use serde::ser::{Serialize, Serializer};
920
921    /// Serializes a weakly consistent snapshot in the plain [`Hive`] format.
922    /// Uses the same consistency as [`ConcurrentHive::snapshot`] and scans
923    /// to the initial index bound with one floor lookup per page.
924    /// The resulting pages always pass [`Hive`]'s validation.
925    ///
926    /// Each value stays guarded while its `Serialize` runs. Taking that id
927    /// in the callback, or waiting there for another thread to take it, deadlocks.
928    impl<T: Serialize, const PAGE: usize> Serialize for ConcurrentHive<T, PAGE> {
929        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
930            let bound = self.index_bound();
931            let unissued = self.free.unissued_shared();
932            raw_pages::serialize(
933                self.recycled.snapshot_pages(bound, PAGE),
934                |index| self.snapshot_slot(index, &unissued),
935                serializer,
936            )
937        }
938    }
939
940    /// Validates the plain [`Hive`] format and converts in O(index bound).
941    impl<'de, T: Deserialize<'de>, const PAGE: usize> Deserialize<'de> for ConcurrentHive<T, PAGE> {
942        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
943            Hive::deserialize(deserializer).map(Self::from)
944        }
945    }
946}
947
948/// Moves a plain hive into shared storage without changing live ids.
949/// Takes O(the source hive's index bound) time; pages and reuse order may change.
950///
951/// The new reservation bound ends after the last explicit raw slot or the
952/// last page with a nonzero floor, whichever is later. The untouched suffix
953/// of floor-zero pages is left to fresh reservation. Omitted offsets below
954/// this bound become reusable vacancies at their page floor. For floor-zero
955/// holes only, generation 1 is spent and the vacancy starts at version 2:
956/// a popped zero state must always mean retired. Nonzero floors retain their
957/// exact next generation, `floor / 2 + 1`. Explicit retired zeros are never
958/// pushed. Thus no previously issued dead id can revive.
959///
960/// Versions are copied before draining values, since draining advances the
961/// source versions. Occupied states are published only after their values
962/// have moved; unwinding during allocation cannot expose uninitialized cells
963/// to this hive's destructor.
964impl<T, const PAGE: usize> From<Hive<T, PAGE>> for ConcurrentHive<T, PAGE> {
965    fn from(mut hive: Hive<T, PAGE>) -> Self {
966        let mut out = Self::new();
967        // Copy only floors and versions; no borrowed value escapes raw_pages.
968        let metadata: Vec<(u32, Vec<u32>)> = hive
969            .raw_pages()
970            .map(|raw| {
971                let versions = raw
972                    .slots
973                    .into_iter()
974                    .map(|slot| match slot {
975                        RawSlot::Occupied { version, .. } | RawSlot::Vacant { version } => version,
976                    })
977                    .collect();
978                (raw.floor, versions)
979            })
980            .collect();
981        let mut bound = 0;
982        for (page, (floor, versions)) in metadata.iter().enumerate() {
983            let base = page * PAGE;
984            if *floor != 0 {
985                // Include the entire usable page: omitted offsets inherit
986                // this floor even when no raw slot remains after shrinking.
987                bound = base + PAGE.min(MAX_INDICES as usize - base);
988            } else if !versions.is_empty() {
989                bound = base + versions.len();
990            }
991        }
992        out.free.set_next_fresh(bound as u32);
993        for index in 0..bound {
994            let (floor, versions) = &metadata[index / PAGE];
995            let version = versions
996                .get(index % PAGE)
997                .copied()
998                .unwrap_or((*floor).max(2));
999            let slot = out.ensure_slot(index as u32);
1000            if version & 1 == 0 {
1001                // Relaxed suffices during exclusive construction. Nonzero
1002                // vacancies are reusable; explicit zero states stay retired.
1003                slot.state.store(u64::from(version), Ordering::Relaxed);
1004                if version != 0 {
1005                    out.free.push(index as u32, &slot.next);
1006                }
1007            }
1008            // Occupied metadata stays at empty state zero until its value
1009            // is moved below; no panic can make Drop read uninitialized T.
1010        }
1011        for (id, value) in hive.drain() {
1012            let live = live_version(id.generation()).expect("Hive issues valid generations");
1013            let slot = out.slot(id.index()).expect("copied slot has a page");
1014            out.write_value(slot, id.index(), live, value);
1015        }
1016        out
1017    }
1018}
1019
1020impl<T, const PAGE: usize> fmt::Debug for ConcurrentHive<T, PAGE> {
1021    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1022        f.debug_struct("ConcurrentHive")
1023            .field("len", &self.len())
1024            .field("index_bound", &self.index_bound())
1025            .finish_non_exhaustive()
1026    }
1027}
1028
1029impl<T, const PAGE: usize> Drop for ConcurrentHive<T, PAGE> {
1030    fn drop(&mut self) {
1031        // If a value's destructor panics, keep dropping the remaining values
1032        // while unwinding (a second panic then aborts, as usual).
1033        struct Rest<'a, T, const PAGE: usize>(&'a mut ConcurrentHive<T, PAGE>);
1034        impl<T, const PAGE: usize> Drop for Rest<'_, T, PAGE> {
1035            fn drop(&mut self) {
1036                self.0.clear();
1037            }
1038        }
1039        let rest = Rest(self);
1040        rest.0.clear();
1041        core::mem::forget(rest);
1042    }
1043}
1044
1045/// A guard pinning one live value in a [`ConcurrentHive`].
1046///
1047/// Dereferences to `T`; no mutable access or cloning is provided. The value
1048/// stays alive after logical removal until all its guards are dropped, unless
1049/// a taker owns it. Forgetting a guard pins its slot during shared access.
1050pub struct Ref<'a, T, const PAGE: usize = DEFAULT_PAGE> {
1051    hive: &'a ConcurrentHive<T, PAGE>,
1052    slot: &'a Slot<T>,
1053    index: u32,
1054    version: u32,
1055    #[cfg(loom)]
1056    access: Option<loom::cell::ConstPtr<MaybeUninit<T>>>,
1057}
1058
1059// SAFETY: the counted guard pins a shared T; sending the guard can make this
1060// thread the finalizer, so both sharing and transferring/dropping T are needed.
1061unsafe impl<T: Send + Sync, const PAGE: usize> Send for Ref<'_, T, PAGE> {}
1062// SAFETY: dereferencing shares only a pinned T, and the hive can be shared
1063// because T: Send + Sync; no shared operation yields mutable value access.
1064unsafe impl<T: Send + Sync, const PAGE: usize> Sync for Ref<'_, T, PAGE> {}
1065
1066impl<T, const PAGE: usize> Ref<'_, T, PAGE> {
1067    /// The id whose value this guard pins, even after logical removal.
1068    pub fn id(&self) -> Id {
1069        Id::new(self.index, generation_of(self.version))
1070    }
1071}
1072
1073impl<T, const PAGE: usize> Deref for Ref<'_, T, PAGE> {
1074    type Target = T;
1075
1076    fn deref(&self) -> &T {
1077        self.slot.value.with(|cell| {
1078            // SAFETY: this matching-version guard holds a counted reference;
1079            // no finalizer or taker can access the cell until it is released.
1080            // Under loom, access also tracks this read for the entire guard.
1081            unsafe { &*cell.cast::<T>() }
1082        })
1083    }
1084}
1085
1086impl<T: fmt::Debug, const PAGE: usize> fmt::Debug for Ref<'_, T, PAGE> {
1087    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1088        f.debug_struct("Ref")
1089            .field("id", &self.id())
1090            .field("value", &**self)
1091            .finish()
1092    }
1093}
1094
1095impl<T, const PAGE: usize> Drop for Ref<'_, T, PAGE> {
1096    fn drop(&mut self) {
1097        // End loom's tracked read BEFORE releasing the count or finalizing.
1098        #[cfg(loom)]
1099        drop(self.access.take());
1100        // Acquire sees removal/take marks and prior guard releases.
1101        let mut word = self.slot.state.load(Ordering::Acquire);
1102        loop {
1103            debug_assert!(word & REFS != 0);
1104            let finalize = word & REFS == REF && word & MARKED != 0 && word & TAKE == 0;
1105            let new = if finalize {
1106                vacant(self.version) | BUSY
1107            } else {
1108                word - REF
1109            };
1110            // Release ends this guard's value access. Acquire observes the
1111            // preceding releases if this is the last guard and must finalize.
1112            match self.slot.state.compare_exchange_weak(
1113                word,
1114                new,
1115                Ordering::AcqRel,
1116                Ordering::Acquire,
1117            ) {
1118                Ok(_) => {
1119                    if finalize {
1120                        let owner = self.hive.busy(self.slot, self.index, vacant(self.version));
1121                        self.hive.drop_owned(&owner);
1122                    }
1123                    return;
1124                }
1125                Err(actual) => word = actual,
1126            }
1127        }
1128    }
1129}
1130
1131/// Weakly consistent iterator over `(id, guard)` pairs, in slot order.
1132/// Each slot is visited once, up to the initial reservation bound.
1133pub struct Iter<'a, T, const PAGE: usize = DEFAULT_PAGE> {
1134    hive: &'a ConcurrentHive<T, PAGE>,
1135    indices: core::ops::Range<u32>,
1136}
1137
1138impl<'a, T, const PAGE: usize> Iterator for Iter<'a, T, PAGE> {
1139    type Item = (Id, Ref<'a, T, PAGE>);
1140
1141    fn next(&mut self) -> Option<Self::Item> {
1142        for index in self.indices.by_ref() {
1143            if let Some(value) = self.hive.acquire(index, None) {
1144                return Some((value.id(), value));
1145            }
1146        }
1147        None
1148    }
1149
1150    fn size_hint(&self) -> (usize, Option<usize>) {
1151        (0, Some((self.indices.end - self.indices.start) as usize))
1152    }
1153}
1154
1155impl<T, const PAGE: usize> FusedIterator for Iter<'_, T, PAGE> {}
1156
1157/// Exclusive iterator over `(id, &mut value)` pairs, in slot order.
1158/// Holds the exclusive hive borrow even though traversal reads its metadata.
1159pub struct IterMut<'a, T, const PAGE: usize = DEFAULT_PAGE> {
1160    hive: &'a ConcurrentHive<T, PAGE>,
1161    indices: core::ops::Range<u32>,
1162    remaining: usize,
1163    exclusive: PhantomData<&'a mut ConcurrentHive<T, PAGE>>,
1164}
1165
1166impl<'a, T, const PAGE: usize> Iterator for IterMut<'a, T, PAGE> {
1167    type Item = (Id, &'a mut T);
1168
1169    fn next(&mut self) -> Option<Self::Item> {
1170        for index in self.indices.by_ref() {
1171            let Some(slot) = self.hive.slot(index) else {
1172                continue;
1173            };
1174            // Acquire is conservative: exclusive construction normalized every
1175            // slot and the iterator alone can access this hive until it drops.
1176            let word = slot.state.load(Ordering::Acquire);
1177            if word & 1 == 0 {
1178                continue;
1179            }
1180            self.remaining -= 1;
1181            let value = slot.value.with_mut(|cell| {
1182                // SAFETY: exclusive iterator construction removed marked values
1183                // and reset forgotten refs. Each distinct slot is yielded once;
1184                // metadata traversal never reborrows any yielded value.
1185                unsafe { &mut *cell.cast::<T>() }
1186            });
1187            return Some((Id::new(index, generation_of(word as u32)), value));
1188        }
1189        None
1190    }
1191
1192    fn size_hint(&self) -> (usize, Option<usize>) {
1193        (self.remaining, Some(self.remaining))
1194    }
1195}
1196
1197impl<T, const PAGE: usize> ExactSizeIterator for IterMut<'_, T, PAGE> {}
1198impl<T, const PAGE: usize> FusedIterator for IterMut<'_, T, PAGE> {}
1199
1200/// Eager draining iterator of owned `(id, value)` pairs.
1201/// All values have already been removed from the hive when this is returned.
1202pub struct Drain<'a, T, const PAGE: usize = DEFAULT_PAGE> {
1203    inner: alloc::vec::IntoIter<(Id, T)>,
1204    exclusive: PhantomData<&'a mut ConcurrentHive<T, PAGE>>,
1205}
1206
1207impl<T, const PAGE: usize> Iterator for Drain<'_, T, PAGE> {
1208    type Item = (Id, T);
1209
1210    fn next(&mut self) -> Option<Self::Item> {
1211        self.inner.next()
1212    }
1213
1214    fn size_hint(&self) -> (usize, Option<usize>) {
1215        self.inner.size_hint()
1216    }
1217}
1218
1219impl<T, const PAGE: usize> DoubleEndedIterator for Drain<'_, T, PAGE> {
1220    fn next_back(&mut self) -> Option<Self::Item> {
1221        self.inner.next_back()
1222    }
1223}
1224
1225impl<T, const PAGE: usize> ExactSizeIterator for Drain<'_, T, PAGE> {}
1226impl<T, const PAGE: usize> FusedIterator for Drain<'_, T, PAGE> {}
1227
1228#[cfg(all(test, not(loom), feature = "std"))]
1229mod tests {
1230    use super::*;
1231    use crate::id_alloc::MAX_GENERATION;
1232    use core::num::NonZeroU32;
1233    use std::panic::{AssertUnwindSafe, catch_unwind};
1234
1235    /// Versions of a converted hive's first page-group, slot by slot.
1236    fn raw_versions<T>(plain: &Hive<T, 4>) -> Vec<u32> {
1237        plain
1238            .raw_pages()
1239            .flat_map(|page| page.slots)
1240            .map(|slot| match slot {
1241                RawSlot::Occupied { version, .. } | RawSlot::Vacant { version } => version,
1242            })
1243            .collect()
1244    }
1245
1246    #[test]
1247    fn unissued_block_tail_becomes_reusable_vacancies() {
1248        let mut hive = ConcurrentHive::<u32, 4>::new();
1249        let a = hive.insert(0);
1250        let b = hive.insert(1);
1251        hive.free.force_blocks();
1252        // Block mode reserves [2, 64) (blocks of 64, aligned) and hands out 2.
1253        let c = hive.insert(2);
1254        assert_eq!((a.index(), b.index(), c.index()), (0, 1, 2));
1255        assert_eq!(hive.index_bound(), 64);
1256        assert!(hive.remove(b));
1257        // State-0 tail slots keep their pages: shrinking frees nothing here.
1258        hive.shrink_to_fit();
1259        let versions = raw_versions(&hive.snapshot());
1260        assert_eq!(&versions[..4], &[1, 2, 1, 2]);
1261        // Index 3 is on the installed page. The rest have no page yet.
1262        assert!(versions[4..].iter().all(|&v| v == 0));
1263        #[cfg(feature = "serde")]
1264        {
1265            let json = serde_json::to_string(&hive).unwrap();
1266            let decoded: Hive<u32, 4> = serde_json::from_str(&json).unwrap();
1267            assert_eq!(raw_versions(&decoded), versions);
1268        }
1269        let plain = hive.into_hive();
1270        let versions = raw_versions(&plain);
1271        assert_eq!(versions.len(), 64);
1272        assert_eq!(&versions[..3], &[1, 2, 1]);
1273        assert!(versions[3..].iter().all(|&v| v == 2), "{versions:?}");
1274        assert!(plain.get(b).is_none());
1275        assert_eq!((plain.get(a), plain.get(c)), (Some(&0), Some(&2)));
1276        // Round trip: the holes stay reusable and b stays dead.
1277        let back = ConcurrentHive::from(plain);
1278        let fresh: Vec<Id> = (0..62).map(|v| back.insert(v)).collect();
1279        assert!(fresh.iter().all(|id| id.index() < 64 && *id != b));
1280        assert!(back.get(b).is_none());
1281        assert_eq!(back.index_bound(), 64);
1282    }
1283
1284    #[test]
1285    fn last_generation_retires_to_plain_zero() {
1286        let hive = ConcurrentHive::<u8, 2>::new();
1287        let old = hive.insert(7);
1288        let slot = hive.slot(old.index()).unwrap();
1289        // Single-threaded fixture: jump this initialized value to its final
1290        // live version without waiting for billions of allocation cycles.
1291        slot.state.store(u64::from(u32::MAX), Ordering::Release);
1292        let last = Id::new(old.index(), NonZeroU32::new(MAX_GENERATION).unwrap());
1293        assert!(hive.remove(last));
1294        assert_eq!(slot.state.load(Ordering::Acquire), 0);
1295        // Even a corrupted stack must never resurrect a retired zero slot.
1296        hive.free.push(old.index(), &slot.next);
1297        let new = hive.insert(8);
1298        assert_ne!(old.index(), new.index());
1299        assert!(!hive.contains(last));
1300        assert_eq!(hive.len(), 1);
1301    }
1302
1303    #[test]
1304    fn overflow_panics_without_wrapping_the_count() {
1305        let mut hive = ConcurrentHive::<u8, 2>::new();
1306        let id = hive.insert(7);
1307        let slot = hive.slot(id.index()).unwrap();
1308        // Single-threaded fixture models counts from forgotten guards. No
1309        // actual reference exists, so exclusive recovery may discard them.
1310        slot.state.store(1 | REFS, Ordering::Release);
1311        assert!(catch_unwind(AssertUnwindSafe(|| hive.get(id))).is_err());
1312        assert_eq!(slot.state.load(Ordering::Acquire), 1 | REFS);
1313        assert_eq!(hive.take_mut(id), Some(7));
1314        assert!(hive.is_empty());
1315    }
1316
1317    // Leaks the hive: exclusive cleanup (drop, clear, shrink) walks every
1318    // index below the bound, ~4.3e9 here.
1319    #[cfg_attr(miri, ignore)]
1320    #[test]
1321    fn the_last_slots_below_u32_max_hold_values_and_exhaust_exactly() {
1322        // The last page is [2^32 - 4096, 2^32); its top slot (index
1323        // u32::MAX) is NONE and never usable.
1324        let mut hive = ConcurrentHive::<u64, 4096>::new();
1325        hive.free.set_next_fresh(MAX_INDICES - 2);
1326        let a = hive.insert(1);
1327        let b = hive.insert(2);
1328        assert_eq!((a.index(), b.index()), (MAX_INDICES - 2, MAX_INDICES - 1));
1329        assert_eq!(hive.try_insert(3), Err(3));
1330        assert_eq!(hive.index_bound(), MAX_INDICES);
1331        assert_eq!((*hive.get(a).unwrap(), *hive.get(b).unwrap()), (1, 2));
1332        let top = Id::new(MAX_INDICES, b.generation());
1333        assert!(hive.get(top).is_none() && !hive.remove(top));
1334        assert_eq!(hive.take(top), None);
1335        // The top usable slot is reused with a new generation.
1336        assert_eq!(hive.take(b), Some(2));
1337        let c = hive.insert(4);
1338        assert_eq!(c.index(), MAX_INDICES - 1);
1339        assert!(c != b && hive.get(b).is_none());
1340        assert_eq!(*hive.get(c).unwrap(), 4);
1341        assert_eq!(hive.try_insert(5), Err(5));
1342        assert_eq!(hive.len(), 2);
1343        // u64 values need no drop; the pages are freed with the process.
1344        core::mem::forget(hive);
1345    }
1346
1347    #[test]
1348    fn a_live_stack_hint_is_discarded() {
1349        let hive = ConcurrentHive::<u8, 2>::new();
1350        let a = hive.insert(1);
1351        let slot = hive.slot(a.index()).unwrap();
1352        hive.free.push(a.index(), &slot.next);
1353        let b = hive.insert(2);
1354        assert_ne!(a.index(), b.index());
1355        assert_eq!(*hive.get(a).unwrap(), 1);
1356        assert_eq!(*hive.get(b).unwrap(), 2);
1357        assert_eq!(hive.len(), 2);
1358    }
1359}