Skip to main content

paged_collections/concurrent/
append_hive.rs

1//! Stable value cells with shared insertion and exclusive removal.
2//!
3//! The low 32 state bits are the id version. BUSY, in bit 32, owns the cell
4//! exclusively while inserting. A published live state changes only under
5//! exclusive access, so one Acquire state load permits an ordinary `&T`.
6//! Pages do not drop values: an exclusive hive scan does 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::Index;
15use core::ptr;
16
17use super::atomic::{AtomicU32, AtomicU64, Ordering, UnsafeCell};
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;
33
34struct Slot<T> {
35    state: AtomicU64,
36    next: AtomicU32,
37    value: UnsafeCell<MaybeUninit<T>>,
38}
39
40impl<T> Slot<T> {
41    fn new() -> Self {
42        Self::with_state(0)
43    }
44
45    /// A vacant slot at `version` (even), for a recycled page.
46    fn with_state(version: u32) -> Self {
47        Self {
48            state: AtomicU64::new(u64::from(version)),
49            next: AtomicU32::new(0),
50            value: UnsafeCell::new(MaybeUninit::uninit()),
51        }
52    }
53
54    // Called only under an exclusive hive borrow (including exclusive
55    // iterator construction and traversal). No insertion can be in flight.
56    fn exclusive_version(&self) -> u32 {
57        // Relaxed suffices: exclusivity rules out concurrent publication.
58        let word = self.state.load(Ordering::Relaxed);
59        debug_assert_eq!(word & !VERSION, 0, "exclusive slot is BUSY");
60        word as u32
61    }
62}
63
64struct Page<T> {
65    // MaybeUninit deliberately has no value destructor. The hive scans cells.
66    slots: Box<[Slot<T>]>,
67}
68
69fn vacant(live: u32) -> u64 {
70    u64::from(live.checked_add(1).unwrap_or(0))
71}
72
73/// A paged container with stable addresses and shared insertion.
74///
75/// [`get`](Self::get) returns an ordinary `&T` after one Acquire slot-state
76/// load, with no guard or reference count. Published values can be changed,
77/// removed or moved only under `&mut self`, which excludes every reference
78/// borrowed from shared access. Prefer [`ConcurrentHive`](super::ConcurrentHive)
79/// when removal must also be shared.
80///
81/// Pages stay allocated until [`shrink_to_fit`](Self::shrink_to_fit) frees
82/// the empty ones; shared inserts reuse freed pages later. Shared
83/// iteration is weakly consistent and may miss insertions in flight. `len`
84/// is approximate during insertion and exact when insertions have finished.
85/// Exclusive scans and conversions take O([`index_bound`](Self::index_bound))
86/// time. Conversions to and from [`Hive`] preserve live ids and stale-id
87/// history, but may change allocation and slot reuse order.
88///
89/// As with [`Hive`], ids carry no container identity, generations never wrap,
90/// and stale ids stay dead within one allocation history. A panicking
91/// [`insert_with`](Self::insert_with) spends the id shown to its factory.
92///
93/// `PAGE` must be non-zero, fit in a `u32`, and fit a page in `isize::MAX`
94/// bytes. Uses only `core` and `alloc`.
95///
96/// ```
97/// use paged_collections::concurrent::ConcurrentAppendHive;
98///
99/// let mut hive = ConcurrentAppendHive::<&str, 4>::new();
100/// let first = hive.insert("first");
101/// let value = hive.get(first).unwrap();
102/// let second = hive.insert("second");
103/// assert_eq!(*value, "first");
104/// assert_eq!(hive[second], "second");
105/// assert_eq!(hive.remove(first), Some("first"));
106/// assert!(hive.get(first).is_none());
107/// ```
108///
109/// Sharing requires both `Send` and `Sync` elements:
110///
111/// ```compile_fail
112/// use paged_collections::concurrent::ConcurrentAppendHive;
113/// use std::rc::Rc;
114/// fn assert_sync<T: Sync>() {}
115/// assert_sync::<ConcurrentAppendHive<Rc<()>>>();
116/// ```
117pub struct ConcurrentAppendHive<T, const PAGE: usize = DEFAULT_PAGE> {
118    pages: Spine<Page<T>, CHUNKS>,
119    free: FreeStack,
120    /// Pages freed by `shrink_to_fit`, below the reservation bound.
121    recycled: PageStack,
122    len: StripedLen,
123}
124
125// SAFETY: moving the hive transfers its owned cells; no borrowed reference
126// outlives it. Exclusive removal or destruction may drop T on the receiver.
127unsafe impl<T: Send, const PAGE: usize> Send for ConcurrentAppendHive<T, PAGE> {}
128// SAFETY: the claim CAS grants exclusive cell ownership until publication;
129// published T is shared immutably. Shared insertion also transfers T between
130// threads, so both Send and Sync are required.
131unsafe impl<T: Send + Sync, const PAGE: usize> Sync for ConcurrentAppendHive<T, PAGE> {}
132
133/// Owns an uninitialized cell already claimed by CAS. Unwinding spends the
134/// factory's id and publishes a reusable vacancy, or retires the slot.
135struct Busy<'a, T, const PAGE: usize> {
136    hive: &'a ConcurrentAppendHive<T, PAGE>,
137    slot: &'a Slot<T>,
138    index: u32,
139    vacant: u64,
140    armed: bool,
141}
142
143impl<T, const PAGE: usize> Drop for Busy<'_, T, PAGE> {
144    fn drop(&mut self) {
145        if self.armed {
146            // Release publishes the end of all factory/cell access before
147            // reuse. A claim acquires this even with a stale stack hint.
148            self.slot.state.store(self.vacant, Ordering::Release);
149            if self.vacant != 0 {
150                self.hive.free.push(self.index, &self.slot.next);
151            }
152        }
153    }
154}
155
156impl<T, const PAGE: usize> ConcurrentAppendHive<T, PAGE> {
157    /// Number of slots per page.
158    pub const PAGE: usize = PAGE;
159
160    /// An empty hive, without allocating.
161    ///
162    /// # Panics
163    ///
164    /// Panics if the page capacity is invalid; see the type's documentation.
165    pub fn new() -> Self {
166        assert!(
167            PAGE > 0
168                && PAGE <= u32::MAX as usize
169                && PAGE <= isize::MAX as usize / core::mem::size_of::<Slot<T>>(),
170            "ConcurrentAppendHive: invalid page capacity"
171        );
172        Self {
173            pages: Spine::new(),
174            free: FreeStack::new(),
175            recycled: PageStack::new(),
176            len: StripedLen::new(),
177        }
178    }
179
180    fn slot(&self, index: u32) -> Option<&Slot<T>> {
181        if index == MAX_INDICES {
182            return None;
183        }
184        self.pages
185            .get(index as usize / PAGE)
186            .map(|page| &page.slots[index as usize % PAGE])
187    }
188
189    fn snapshot_slot(&self, index: u32, unissued: &Unissued) -> RawSlot<&T> {
190        let Some(slot) = self.slot(index) else {
191            // A reservation or recycled page may still be uninstalled.
192            return RawSlot::Vacant { version: 0 };
193        };
194        // Acquire observes the value published by the inserter.
195        let word = slot.state.load(Ordering::Acquire);
196        let version = word as u32;
197        if word & BUSY != 0 {
198            debug_assert_eq!(version & 1, 0);
199            return RawSlot::Vacant { version };
200        }
201        if version & 1 != 0 {
202            let value = slot.value.with(|cell| {
203                // SAFETY: the acquired live state publishes the value. Only
204                // exclusive access can remove it, and this borrow keeps it live.
205                unsafe { &*cell.cast::<T>() }
206            });
207            return RawSlot::Occupied { version, value };
208        }
209        let version = if version == 0 && unissued.contains_shared(index) {
210            2
211        } else {
212            version
213        };
214        RawSlot::Vacant { version }
215    }
216
217    fn ensure_slot(&self, index: u32) -> &Slot<T> {
218        let page = self.pages.get_or_insert_with(index as usize / PAGE, || {
219            Box::new(Page {
220                slots: (0..PAGE).map(|_| Slot::new()).collect(),
221            })
222        });
223        &page.slots[index as usize % PAGE]
224    }
225
226    /// Reinstalls a page freed by `shrink_to_fit`, with every usable slot
227    /// vacant at the page's floor. Pushes all its slots but the first to the
228    /// free stack and returns the first, for the caller to claim by CAS.
229    ///
230    /// The popper is the page's only installer: the free stack holds none of
231    /// its indices (it was rebuilt when the page was freed), and fresh
232    /// reservation never hands out an index in a freed page: the counter
233    /// never goes below the bound, and indices reserved in a thread's block
234    /// but not handed out keep state 0, which stops their page from being
235    /// freed (uninstalled pages are never freed). Its slots are unreachable
236    /// until pushed, so this thread owns them while pushing.
237    fn recycle(&self) -> Option<u32> {
238        let (page, floor) = self.recycled.pop()?;
239        let base = page * PAGE;
240        let limit = PAGE.min(MAX_INDICES as usize - base);
241        let installed = self.pages.get_or_insert_with(page, || {
242            Box::new(Page {
243                slots: (0..PAGE)
244                    .map(|offset| Slot::with_state(if offset < limit { floor } else { 0 }))
245                    .collect(),
246            })
247        });
248        for offset in (1..limit).rev() {
249            self.free
250                .push((base + offset) as u32, &installed.slots[offset].next);
251        }
252        Some(base as u32)
253    }
254
255    fn claim(&self) -> Option<(Busy<'_, T, PAGE>, u32)> {
256        loop {
257            let (index, reused) = self.free.next_index(
258                |index| &self.slot(index).expect("free index has a page").next,
259                || self.recycle(),
260                MAX_INDICES,
261                block_for(PAGE),
262            )?;
263            let slot = self.ensure_slot(index);
264            // Acquire observes the completed vacancy, independently of the
265            // free-stack hint. Only even versions without BUSY may be claimed.
266            let old = slot.state.load(Ordering::Acquire);
267            if old & !VERSION != 0 || old & 1 != 0 || (reused && old == 0) {
268                continue;
269            }
270            // AcqRel claims sole ownership and observes the preceding vacant
271            // Release. A failed CAS discards the hint, never retries that word.
272            // Fresh zero is claimable only through its unique reservation;
273            // zero popped from the stack is retired and was rejected above.
274            if slot
275                .state
276                .compare_exchange(old, old | BUSY, Ordering::AcqRel, Ordering::Acquire)
277                .is_err()
278            {
279                continue;
280            }
281            let live = old as u32 + 1;
282            return Some((
283                Busy {
284                    hive: self,
285                    slot,
286                    index,
287                    vacant: vacant(live),
288                    armed: true,
289                },
290                live,
291            ));
292        }
293    }
294
295    // The caller owns this empty cell through a claim or exclusive conversion.
296    fn write_value(&self, slot: &Slot<T>, index: u32, live: u32, value: T) {
297        slot.value.with_mut(|cell| {
298            // SAFETY: the claim CAS or exclusive construction grants sole
299            // ownership of this uninitialized cell. MaybeUninit has T's layout.
300            unsafe { ptr::write(cell.cast::<T>(), value) };
301        });
302        // Relaxed accounting precedes publication; len is exact once no
303        // insertion is in flight, but does not itself grant value access.
304        self.len.increment(index as usize / PAGE);
305        // Release publishes the initialized value to matching Acquire reads.
306        slot.state.store(u64::from(live), Ordering::Release);
307    }
308
309    fn publish(&self, mut owner: Busy<'_, T, PAGE>, live: u32, value: T) -> Id {
310        self.write_value(owner.slot, owner.index, live, value);
311        owner.armed = false;
312        Id::new(owner.index, generation_of(live))
313    }
314
315    /// Inserts `value` and returns its id.
316    ///
317    /// # Panics
318    ///
319    /// Panics if all [`MAX_INDICES`] indices are occupied or retired, or a
320    /// page cannot be allocated. A panicking concurrent factory may make room.
321    pub fn insert(&self, value: T) -> Id {
322        self.try_insert(value).unwrap_or_else(|_| {
323            panic!("ConcurrentAppendHive: all {MAX_INDICES} slot indices are occupied or retired")
324        })
325    }
326
327    /// Like [`insert`](Self::insert), returning the value on index exhaustion.
328    /// Allocation failures may still panic or abort.
329    pub fn try_insert(&self, value: T) -> Result<Id, T> {
330        let Some((owner, live)) = self.claim() else {
331            return Err(value);
332        };
333        Ok(self.publish(owner, live, value))
334    }
335
336    /// Inserts the value `f` makes from its id.
337    ///
338    /// If `f` panics, its id's generation is spent and that id stays dead.
339    /// The slot becomes reusable unless its last generation was spent.
340    ///
341    /// # Panics
342    ///
343    /// Panics on index exhaustion or if `f` panics; allocation may also fail.
344    pub fn insert_with(&self, f: impl FnOnce(Id) -> T) -> Id {
345        self.try_insert_with(f).unwrap_or_else(|| {
346            panic!("ConcurrentAppendHive: all {MAX_INDICES} slot indices are occupied or retired")
347        })
348    }
349
350    /// Like [`insert_with`](Self::insert_with), returning `None` without
351    /// calling `f` when no index is available.
352    pub fn try_insert_with(&self, f: impl FnOnce(Id) -> T) -> Option<Id> {
353        let (owner, live) = self.claim()?;
354        let value = f(Id::new(owner.index, generation_of(live)));
355        Some(self.publish(owner, live, value))
356    }
357
358    /// The value of a matching live id, without a guard or reference count.
359    /// Returns `None` for stale, invalid or unpublished ids.
360    pub fn get(&self, id: Id) -> Option<&T> {
361        let live = live_version(id.generation())?;
362        let slot = self.slot(id.index())?;
363        // Acquire observes the initialized value; exact equality rejects BUSY.
364        if slot.state.load(Ordering::Acquire) != u64::from(live) {
365            return None;
366        }
367        Some(slot.value.with(|cell| {
368            // SAFETY: the matching published live state changes only under
369            // &mut self, which cannot coexist with this shared borrow. The
370            // value remains initialized and immovable for the returned lifetime.
371            unsafe { &*cell.cast::<T>() }
372        }))
373    }
374
375    /// The id of the element at `value`'s address, if `value` is a live
376    /// element of this hive: the inverse of [`get`](Self::get).
377    ///
378    /// Takes time linear in the directory's page cells up to the highest
379    /// installed page (with `Flat`, O(highest page number)): it compares the
380    /// address with each installed page's slot range, then checks that the slot found is published live
381    /// and holds exactly that element. Anything else gives `None`. Uses
382    /// address comparison only; no pointer is dereferenced.
383    ///
384    /// ```
385    /// use paged_collections::concurrent::ConcurrentAppendHive;
386    ///
387    /// let hive = ConcurrentAppendHive::<u32, 4>::new();
388    /// let id = hive.insert(7);
389    /// let element = hive.get(id).unwrap();
390    /// assert_eq!(hive.id_of(element), Some(id));
391    /// assert_eq!(hive.id_of(&7), None);
392    /// ```
393    pub fn id_of(&self, value: &T) -> Option<Id> {
394        let target = ptr::from_ref(value);
395        let size = core::mem::size_of::<Slot<T>>();
396        for (number, page) in self.pages.iter() {
397            let start = page.slots.as_ptr().addr();
398            let Some(offset) = target.addr().checked_sub(start).map(|bytes| bytes / size) else {
399                continue;
400            };
401            let Some(slot) = page.slots.get(offset) else {
402                continue;
403            };
404            if !slot.value.with(|cell| ptr::eq(cell.cast::<T>(), target)) {
405                return None;
406            }
407            // Acquire observes publication; only an exact odd state is live.
408            let word = slot.state.load(Ordering::Acquire);
409            return (word & 1 == 1 && word & !VERSION == 0)
410                .then(|| Id::new((number * PAGE + offset) as u32, generation_of(word as u32)));
411        }
412        None
413    }
414
415    /// Whether this id is live at the instant of one state load.
416    pub fn contains(&self, id: Id) -> bool {
417        let Some(live) = live_version(id.generation()) else {
418            return false;
419        };
420        // Acquire observes publication; exact equality excludes BUSY.
421        self.slot(id.index())
422            .is_some_and(|slot| slot.state.load(Ordering::Acquire) == u64::from(live))
423    }
424
425    /// Number of live values; approximate during shared insertion.
426    /// Exact when no insertion is in flight; this is no publication barrier.
427    ///
428    /// It sums per-thread counters (per page group without `std`), which only
429    /// grow while shared, so it lies between the counts at the start and the
430    /// end of the call.
431    pub fn len(&self) -> usize {
432        self.len.get()
433    }
434
435    /// Whether the hive is empty; approximate during shared insertion.
436    pub fn is_empty(&self) -> bool {
437        self.len() == 0
438    }
439
440    /// One past the highest reserved index, including insertions in flight.
441    /// A reserved index's page may not have been installed yet.
442    ///
443    /// Threads that contend for fresh indices reserve them in blocks of
444    /// about one page, so the bound may exceed the indices handed out by up
445    /// to one block per thread.
446    pub fn index_bound(&self) -> u32 {
447        self.free.index_bound()
448    }
449
450    /// Iterates over `(id, &value)` in slot order, weakly consistently.
451    /// Scans only indices below the reservation bound at iterator creation;
452    /// may miss insertions in flight, but never yields an unpublished value.
453    pub fn iter(&self) -> AppendIter<'_, T, PAGE> {
454        AppendIter {
455            hive: self,
456            indices: 0..self.index_bound(),
457        }
458    }
459
460    /// The matching live value, mutably, under exclusive access.
461    pub fn get_mut(&mut self, id: Id) -> Option<&mut T> {
462        let live = live_version(id.generation())?;
463        let slot = self.slot(id.index())?;
464        if slot.exclusive_version() != live {
465            return None;
466        }
467        Some(slot.value.with_mut(|cell| {
468            // SAFETY: &mut self excludes all other accesses; the matching
469            // live state proves the cell holds an initialized T.
470            unsafe { &mut *cell.cast::<T>() }
471        }))
472    }
473
474    /// Removes and returns a matching live value under exclusive access.
475    /// The id stays dead; its slot is reused with a new generation or retired.
476    pub fn remove(&mut self, id: Id) -> Option<T> {
477        let live = live_version(id.generation())?;
478        let slot = self.slot(id.index())?;
479        if slot.exclusive_version() != live {
480            return None;
481        }
482        let value = slot.value.with_mut(|cell| {
483            // SAFETY: exclusive access excludes all borrowed values and
484            // inserters; this matching live value is moved out exactly once.
485            unsafe { ptr::read(cell.cast::<T>()) }
486        });
487        let vacant = vacant(live);
488        // Release records the empty cell before any future shared claim.
489        slot.state.store(vacant, Ordering::Release);
490        if vacant != 0 {
491            self.free.push(id.index(), &slot.next);
492        }
493        // Relaxed accounting completes before user destruction can run.
494        self.len.decrement(id.index() as usize / PAGE);
495        Some(value)
496    }
497
498    /// Iterates over live `(id, &mut value)` pairs in slot order.
499    pub fn iter_mut(&mut self) -> AppendIterMut<'_, T, PAGE> {
500        AppendIterMut {
501            remaining: self.len(),
502            indices: 0..self.index_bound(),
503            hive: self,
504            exclusive: PhantomData,
505        }
506    }
507
508    /// Eagerly removes every live value, yielding owned `(id, value)` pairs
509    /// in slot order. Dropping or forgetting the iterator leaves the hive
510    /// empty. Pages and generation history stay allocated.
511    pub fn drain(&mut self) -> AppendDrain<'_, T, PAGE> {
512        let mut values = Vec::with_capacity(self.len());
513        for index in 0..self.index_bound() {
514            let Some(slot) = self.slot(index) else {
515                continue;
516            };
517            let version = slot.exclusive_version();
518            if version & 1 != 0 {
519                let id = Id::new(index, generation_of(version));
520                values.push((id, self.remove(id).expect("exclusive live value")));
521            }
522        }
523        AppendDrain {
524            inner: values.into_iter(),
525            exclusive: PhantomData,
526        }
527    }
528
529    /// Keeps values for which `keep(id, value)` returns true, in slot order.
530    /// If the predicate or a destructor panics, prior changes remain and
531    /// `len` stays exact.
532    pub fn retain(&mut self, mut keep: impl FnMut(Id, &mut T) -> bool) {
533        for index in 0..self.index_bound() {
534            let Some(slot) = self.slot(index) else {
535                continue;
536            };
537            let version = slot.exclusive_version();
538            if version & 1 == 0 {
539                continue;
540            }
541            let id = Id::new(index, generation_of(version));
542            if !keep(id, self.get_mut(id).expect("exclusive live value")) {
543                drop(self.remove(id));
544            }
545        }
546    }
547
548    /// Removes and drops every value, retaining pages and generation history.
549    pub fn clear(&mut self) {
550        self.retain(|_, _| false);
551    }
552
553    /// Frees every page that holds no value, under exclusive access. Takes
554    /// O([`index_bound`](Self::index_bound)) time.
555    ///
556    /// A page is freed if it lies wholly below the reservation bound and all
557    /// its slots are vacant and reusable (a page with a retired slot is
558    /// kept). It remembers its highest version, so ids it issued stay dead:
559    /// shared inserts reuse freed pages, lowest first, after the free slots
560    /// of the remaining pages, with generations above every earlier one.
561    /// That order is exact only for one inserter that has not contended
562    /// with others: a thread first uses up a block of fresh indices it
563    /// reserved under contention, and while one insert is relinking a
564    /// reused page, a concurrent insert can take a fresh index
565    /// instead (and fail at the index limit even though slots are about to
566    /// be freed). The free slots are relinked in index order. The page directory's own
567    /// small arrays stay allocated.
568    ///
569    /// ```
570    /// use paged_collections::concurrent::ConcurrentAppendHive;
571    ///
572    /// let mut hive = ConcurrentAppendHive::<u32, 4>::new();
573    /// let ids: Vec<_> = (0..12).map(|v| hive.insert(v)).collect();
574    /// for &id in &ids[..8] {
575    ///     hive.remove(id);
576    /// }
577    /// hive.shrink_to_fit(); // frees the first two pages
578    /// assert_eq!(hive[ids[8]], 8);
579    /// let new = hive.insert(99); // reuses a freed page
580    /// assert!(new.index() < 8 && !ids.contains(&new));
581    /// assert!(hive.get(ids[0]).is_none());
582    /// ```
583    pub fn shrink_to_fit(&mut self) {
584        let bound = self.index_bound() as usize;
585        let mut freed = self.recycled.pending().to_vec();
586        let installed: Vec<usize> = self.pages.iter().map(|(number, _)| number).collect();
587        for number in installed {
588            let base = number * PAGE;
589            let end = (base + PAGE).min(MAX_INDICES as usize);
590            if end > bound {
591                continue;
592            }
593            let page = self.pages.get(number).expect("page was just listed");
594            let mut floor = 0;
595            let empty = page.slots[..end - base].iter().all(|slot| {
596                let version = slot.exclusive_version();
597                floor = floor.max(version);
598                // Live (odd) or retired (zero below the bound) slots stay.
599                version & 1 == 0 && version != 0
600            });
601            if empty {
602                // The page's cells are all vacant: dropping it drops no T.
603                drop(self.pages.remove(number));
604                freed.push((number, floor));
605            }
606        }
607        // The free stack linked through freed slots: relink the rest,
608        // pushed from the top so the lowest index pops first.
609        self.free.reset();
610        for index in (0..bound as u32).rev() {
611            if let Some(slot) = self.slot(index) {
612                let version = slot.exclusive_version();
613                if version & 1 == 0 && version != 0 {
614                    self.free.push(index, &slot.next);
615                }
616            }
617        }
618        self.recycled.set(freed);
619    }
620
621    /// Moves into a plain [`Hive`], preserving live ids and stale-id history.
622    /// Takes O([`index_bound`](Self::index_bound)) time.
623    ///
624    /// Every slot below the bound is represented explicitly: zero states
625    /// become retired vacancies, even versions become reusable vacancies,
626    /// and odd versions keep their values. Indices reserved for a thread's
627    /// block but never handed out become reusable vacancies at version 2. A page freed by
628    /// [`shrink_to_fit`](Self::shrink_to_fit) becomes an empty raw page with
629    /// its floor; other floors are zero. Offsets beyond the bound have never
630    /// issued ids and need no history.
631    ///
632    /// Raw-page validation cannot fail by construction: all versions have
633    /// the required parity, all pages fit `PAGE`, and indices are below
634    /// [`MAX_INDICES`]. Allocation may still panic or abort. Values already
635    /// moved are owned by the raw pages; this hive's empty cells cannot drop
636    /// them again, including if allocation unwinds.
637    pub fn into_hive(mut self) -> Hive<T, PAGE> {
638        let bound = self.index_bound() as usize;
639        let mut unissued = self.free.unissued();
640        let mut pages = Vec::with_capacity(bound.div_ceil(PAGE));
641        for base in (0..bound).step_by(PAGE) {
642            if let Some(floor) = self.recycled.floor_of(base / PAGE) {
643                // A freed page: every slot restarts above its floor.
644                pages.push(RawPage {
645                    floor,
646                    slots: Vec::new(),
647                });
648                continue;
649            }
650            let end = base + PAGE.min(bound - base);
651            let mut slots = Vec::with_capacity(end - base);
652            for index in base..end {
653                let mut version = self.slot(index as u32).map_or(0, Slot::exclusive_version);
654                if unissued.contains(index as u32) {
655                    // Reserved in a block, never handed out: reusable, with
656                    // generation 1 spent (a zero would read as retired).
657                    debug_assert_eq!(version, 0, "unissued index was used");
658                    version = 2;
659                }
660                slots.push(if version & 1 != 0 {
661                    let id = Id::new(index as u32, generation_of(version));
662                    RawSlot::Occupied {
663                        version,
664                        value: self.remove(id).expect("exclusive live value"),
665                    }
666                } else {
667                    RawSlot::Vacant { version }
668                });
669            }
670            pages.push(RawPage { floor: 0, slots });
671        }
672        Hive::try_from_raw_pages(pages).expect("append hive raw pages are valid by construction")
673    }
674
675    /// Clones a weakly consistent snapshot into a plain [`Hive`].
676    /// Insertions that happen-before the call are included. Ids whose removal
677    /// happens-before the call stay dead. The raw pages always validate. Scans
678    /// up to [`index_bound`](Self::index_bound) with a floor lookup per page.
679    pub fn snapshot(&self) -> Hive<T, PAGE>
680    where
681        T: Clone,
682    {
683        let bound = self.index_bound();
684        let unissued = self.free.unissued_shared();
685        let pages = self
686            .recycled
687            .snapshot_pages(bound, PAGE)
688            .map(|(floor, indices)| RawPage {
689                floor,
690                slots: indices
691                    .map(|index| match self.snapshot_slot(index, &unissued) {
692                        RawSlot::Occupied { version, value } => RawSlot::Occupied {
693                            version,
694                            value: value.clone(),
695                        },
696                        RawSlot::Vacant { version } => RawSlot::Vacant { version },
697                    })
698                    .collect(),
699            });
700        Hive::try_from_raw_pages(pages).expect("append hive snapshot has valid raw pages")
701    }
702
703    #[cfg(all(test, loom))]
704    pub(super) fn prepare_fresh_page(&self) {
705        // Install before the publication litmus starts: otherwise the page
706        // directory's Release could hide a missing slot-state Release.
707        self.ensure_slot(0);
708    }
709
710    #[cfg(all(test, loom))]
711    pub(super) fn inject_busy_hint(&self, index: u32) {
712        let slot = self.slot(index).unwrap();
713        assert_ne!(slot.state.load(Ordering::Acquire) & BUSY, 0);
714        // Models a stale link installed after tag wrap, without 2^32 pops.
715        self.free.push(index, &slot.next);
716    }
717}
718
719/// Clones via [`ConcurrentAppendHive::snapshot`], preserving generations.
720impl<T: Clone, const PAGE: usize> Clone for ConcurrentAppendHive<T, PAGE> {
721    fn clone(&self) -> Self {
722        Self::from(self.snapshot())
723    }
724}
725
726impl<'a, T, const PAGE: usize> IntoIterator for &'a ConcurrentAppendHive<T, PAGE> {
727    type Item = (Id, &'a T);
728    type IntoIter = AppendIter<'a, T, PAGE>;
729
730    fn into_iter(self) -> Self::IntoIter {
731        self.iter()
732    }
733}
734
735impl<'a, T, const PAGE: usize> IntoIterator for &'a mut ConcurrentAppendHive<T, PAGE> {
736    type Item = (Id, &'a mut T);
737    type IntoIter = AppendIterMut<'a, T, PAGE>;
738
739    fn into_iter(self) -> Self::IntoIter {
740        self.iter_mut()
741    }
742}
743
744impl<T, const PAGE: usize> Default for ConcurrentAppendHive<T, PAGE> {
745    fn default() -> Self {
746        Self::new()
747    }
748}
749
750#[cfg(feature = "serde")]
751mod serde_impl {
752    use super::*;
753    use crate::hive::serde_impl::raw_pages;
754    use serde::de::{Deserialize, Deserializer};
755    use serde::ser::{Serialize, Serializer};
756
757    /// Serializes a weakly consistent snapshot in the plain [`Hive`] format.
758    /// Uses the same consistency as [`ConcurrentAppendHive::snapshot`] and
759    /// scans to the initial index bound with one floor lookup per page.
760    /// The resulting pages always pass [`Hive`]'s validation.
761    impl<T: Serialize, const PAGE: usize> Serialize for ConcurrentAppendHive<T, PAGE> {
762        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
763            let bound = self.index_bound();
764            let unissued = self.free.unissued_shared();
765            raw_pages::serialize(
766                self.recycled.snapshot_pages(bound, PAGE),
767                |index| self.snapshot_slot(index, &unissued),
768                serializer,
769            )
770        }
771    }
772
773    /// Validates the plain [`Hive`] format and converts in O(index bound).
774    impl<'de, T: Deserialize<'de>, const PAGE: usize> Deserialize<'de>
775        for ConcurrentAppendHive<T, PAGE>
776    {
777        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
778            Hive::deserialize(deserializer).map(Self::from)
779        }
780    }
781}
782
783/// Moves a plain hive into shared append storage without changing live ids.
784/// Takes O(the source hive's index bound) time; pages and reuse order may change.
785///
786/// The new reservation bound ends after the last explicit raw slot or the
787/// last page with a nonzero floor, whichever is later. The untouched suffix
788/// of floor-zero pages is left to fresh reservation. Omitted offsets below
789/// this bound become reusable vacancies at their page floor. For floor-zero
790/// holes only, generation 1 is spent and the vacancy starts at version 2:
791/// a popped zero state must always mean retired. Nonzero floors retain their
792/// exact next generation, `floor / 2 + 1`. Explicit retired zeros are never
793/// pushed. Thus no previously issued dead id can revive.
794///
795/// Versions are copied before draining values, since draining advances the
796/// source versions. Occupied states are published only after their values
797/// have moved; unwinding during allocation cannot expose uninitialized cells
798/// to this hive's destructor.
799impl<T, const PAGE: usize> From<Hive<T, PAGE>> for ConcurrentAppendHive<T, PAGE> {
800    fn from(mut hive: Hive<T, PAGE>) -> Self {
801        let mut out = Self::new();
802        // Copy only floors and versions; no borrowed value escapes raw_pages.
803        let metadata: Vec<(u32, Vec<u32>)> = hive
804            .raw_pages()
805            .map(|raw| {
806                let versions = raw
807                    .slots
808                    .into_iter()
809                    .map(|slot| match slot {
810                        RawSlot::Occupied { version, .. } | RawSlot::Vacant { version } => version,
811                    })
812                    .collect();
813                (raw.floor, versions)
814            })
815            .collect();
816        let mut bound = 0;
817        for (page, (floor, versions)) in metadata.iter().enumerate() {
818            let base = page * PAGE;
819            if *floor != 0 {
820                // Include the entire usable page: omitted offsets inherit
821                // this floor even when no raw slot remains after shrinking.
822                bound = base + PAGE.min(MAX_INDICES as usize - base);
823            } else if !versions.is_empty() {
824                bound = base + versions.len();
825            }
826        }
827        out.free.set_next_fresh(bound as u32);
828        for index in 0..bound {
829            let (floor, versions) = &metadata[index / PAGE];
830            let version = versions
831                .get(index % PAGE)
832                .copied()
833                .unwrap_or((*floor).max(2));
834            let slot = out.ensure_slot(index as u32);
835            if version & 1 == 0 {
836                // Relaxed suffices during exclusive construction. Nonzero
837                // vacancies are reusable; explicit zero states stay retired.
838                slot.state.store(u64::from(version), Ordering::Relaxed);
839                if version != 0 {
840                    out.free.push(index as u32, &slot.next);
841                }
842            }
843            // Occupied metadata stays at empty state zero until its value
844            // is moved below; no panic can make Drop read uninitialized T.
845        }
846        for (id, value) in hive.drain() {
847            let live = live_version(id.generation()).expect("Hive issues valid generations");
848            let slot = out.slot(id.index()).expect("copied slot has a page");
849            out.write_value(slot, id.index(), live, value);
850        }
851        out
852    }
853}
854
855impl<T, const PAGE: usize> fmt::Debug for ConcurrentAppendHive<T, PAGE> {
856    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857        f.debug_struct("ConcurrentAppendHive")
858            .field("len", &self.len())
859            .field("index_bound", &self.index_bound())
860            .finish_non_exhaustive()
861    }
862}
863
864impl<T, const PAGE: usize> Index<Id> for ConcurrentAppendHive<T, PAGE> {
865    type Output = T;
866
867    /// # Panics
868    ///
869    /// Panics if `id` is not live.
870    fn index(&self, id: Id) -> &T {
871        self.get(id)
872            .unwrap_or_else(|| panic!("ConcurrentAppendHive: {id:?} is not live"))
873    }
874}
875
876impl<T, const PAGE: usize> Drop for ConcurrentAppendHive<T, PAGE> {
877    fn drop(&mut self) {
878        // If a value's destructor panics, keep dropping the remaining values
879        // while unwinding (a second panic then aborts, as usual).
880        struct Rest<'a, T, const PAGE: usize>(&'a mut ConcurrentAppendHive<T, PAGE>);
881        impl<T, const PAGE: usize> Drop for Rest<'_, T, PAGE> {
882            fn drop(&mut self) {
883                self.0.clear();
884            }
885        }
886        let rest = Rest(self);
887        rest.0.clear();
888        core::mem::forget(rest);
889    }
890}
891
892/// Weakly consistent iterator over `(id, &value)` pairs, in slot order.
893/// Each slot is visited once, up to the initial reservation bound.
894pub struct AppendIter<'a, T, const PAGE: usize = DEFAULT_PAGE> {
895    hive: &'a ConcurrentAppendHive<T, PAGE>,
896    indices: core::ops::Range<u32>,
897}
898
899impl<'a, T, const PAGE: usize> Iterator for AppendIter<'a, T, PAGE> {
900    type Item = (Id, &'a T);
901
902    fn next(&mut self) -> Option<Self::Item> {
903        for index in self.indices.by_ref() {
904            let Some(slot) = self.hive.slot(index) else {
905                continue;
906            };
907            // Acquire observes value publication; BUSY is never yielded.
908            let word = slot.state.load(Ordering::Acquire);
909            if word & !VERSION != 0 || word & 1 == 0 {
910                continue;
911            }
912            let value = slot.value.with(|cell| {
913                // SAFETY: this published live state changes only under
914                // &mut self; the iterator's shared borrow excludes removal
915                // and keeps the initialized value alive for 'a.
916                unsafe { &*cell.cast::<T>() }
917            });
918            return Some((Id::new(index, generation_of(word as u32)), value));
919        }
920        None
921    }
922
923    fn size_hint(&self) -> (usize, Option<usize>) {
924        (0, Some((self.indices.end - self.indices.start) as usize))
925    }
926}
927
928impl<T, const PAGE: usize> FusedIterator for AppendIter<'_, T, PAGE> {}
929
930/// Exclusive iterator over `(id, &mut value)` pairs, in slot order.
931/// Holds the exclusive hive borrow even though traversal reads its metadata.
932pub struct AppendIterMut<'a, T, const PAGE: usize = DEFAULT_PAGE> {
933    hive: &'a ConcurrentAppendHive<T, PAGE>,
934    indices: core::ops::Range<u32>,
935    remaining: usize,
936    exclusive: PhantomData<&'a mut ConcurrentAppendHive<T, PAGE>>,
937}
938
939impl<'a, T, const PAGE: usize> Iterator for AppendIterMut<'a, T, PAGE> {
940    type Item = (Id, &'a mut T);
941
942    fn next(&mut self) -> Option<Self::Item> {
943        for index in self.indices.by_ref() {
944            let Some(slot) = self.hive.slot(index) else {
945                continue;
946            };
947            let version = slot.exclusive_version();
948            if version & 1 == 0 {
949                continue;
950            }
951            self.remaining -= 1;
952            let value = slot.value.with_mut(|cell| {
953                // SAFETY: exclusive iterator construction excludes every
954                // other hive access. Each distinct slot is yielded once;
955                // metadata traversal never reborrows any yielded value.
956                unsafe { &mut *cell.cast::<T>() }
957            });
958            return Some((Id::new(index, generation_of(version)), value));
959        }
960        None
961    }
962
963    fn size_hint(&self) -> (usize, Option<usize>) {
964        (self.remaining, Some(self.remaining))
965    }
966}
967
968impl<T, const PAGE: usize> ExactSizeIterator for AppendIterMut<'_, T, PAGE> {}
969impl<T, const PAGE: usize> FusedIterator for AppendIterMut<'_, T, PAGE> {}
970
971/// Eager draining iterator of owned `(id, value)` pairs.
972/// All values have already been removed from the hive when this is returned.
973pub struct AppendDrain<'a, T, const PAGE: usize = DEFAULT_PAGE> {
974    inner: alloc::vec::IntoIter<(Id, T)>,
975    exclusive: PhantomData<&'a mut ConcurrentAppendHive<T, PAGE>>,
976}
977
978impl<T, const PAGE: usize> Iterator for AppendDrain<'_, T, PAGE> {
979    type Item = (Id, T);
980
981    fn next(&mut self) -> Option<Self::Item> {
982        self.inner.next()
983    }
984
985    fn size_hint(&self) -> (usize, Option<usize>) {
986        self.inner.size_hint()
987    }
988}
989
990impl<T, const PAGE: usize> DoubleEndedIterator for AppendDrain<'_, T, PAGE> {
991    fn next_back(&mut self) -> Option<Self::Item> {
992        self.inner.next_back()
993    }
994}
995
996impl<T, const PAGE: usize> ExactSizeIterator for AppendDrain<'_, T, PAGE> {}
997impl<T, const PAGE: usize> FusedIterator for AppendDrain<'_, T, PAGE> {}
998
999#[cfg(all(test, not(loom)))]
1000mod tests {
1001    use super::*;
1002    use crate::id_alloc::MAX_GENERATION;
1003    use core::num::NonZeroU32;
1004
1005    /// Versions of a converted hive's first page-group, slot by slot.
1006    fn raw_versions<T>(plain: &Hive<T, 4>) -> Vec<u32> {
1007        plain
1008            .raw_pages()
1009            .flat_map(|page| page.slots)
1010            .map(|slot| match slot {
1011                RawSlot::Occupied { version, .. } | RawSlot::Vacant { version } => version,
1012            })
1013            .collect()
1014    }
1015
1016    #[test]
1017    fn unissued_block_tail_becomes_reusable_vacancies() {
1018        let mut hive = ConcurrentAppendHive::<u32, 4>::new();
1019        let a = hive.insert(0);
1020        let b = hive.insert(1);
1021        hive.free.force_blocks();
1022        let c = hive.insert(2);
1023        assert_eq!((a.index(), b.index(), c.index()), (0, 1, 2));
1024        assert_eq!(hive.index_bound(), 64);
1025        assert_eq!(hive.remove(b), Some(1));
1026        hive.shrink_to_fit();
1027        let versions = raw_versions(&hive.snapshot());
1028        assert_eq!(&versions[..4], &[1, 2, 1, 2]);
1029        // Index 3 is on the installed page. The rest have no page yet.
1030        assert!(versions[4..].iter().all(|&v| v == 0));
1031        #[cfg(feature = "serde")]
1032        {
1033            let json = serde_json::to_string(&hive).unwrap();
1034            let decoded: Hive<u32, 4> = serde_json::from_str(&json).unwrap();
1035            assert_eq!(raw_versions(&decoded), versions);
1036        }
1037        let plain = hive.into_hive();
1038        let versions = raw_versions(&plain);
1039        assert_eq!(versions.len(), 64);
1040        assert_eq!(&versions[..3], &[1, 2, 1]);
1041        assert!(versions[3..].iter().all(|&v| v == 2), "{versions:?}");
1042        assert!(plain.get(b).is_none());
1043        let back = ConcurrentAppendHive::from(plain);
1044        let fresh: Vec<Id> = (0..62).map(|v| back.insert(v)).collect();
1045        assert!(fresh.iter().all(|id| id.index() < 64 && *id != b));
1046        assert!(back.get(b).is_none());
1047    }
1048
1049    #[test]
1050    fn last_live_version_retires_and_even_a_stale_hint_cannot_revive_it() {
1051        let plain = Hive::<u8, 2>::try_from_raw_pages([RawPage {
1052            floor: 0,
1053            slots: alloc::vec![
1054                RawSlot::Occupied {
1055                    version: u32::MAX,
1056                    value: 7,
1057                },
1058                RawSlot::Vacant { version: 0 },
1059            ],
1060        }])
1061        .unwrap();
1062        let mut hive = ConcurrentAppendHive::from(plain);
1063        let last = Id::new(0, NonZeroU32::new(MAX_GENERATION).unwrap());
1064        assert_eq!(hive.get(last), Some(&7));
1065        assert_eq!(hive.iter().next(), Some((last, &7)));
1066        assert_eq!(hive.remove(last), Some(7));
1067        let slot = hive.slot(0).unwrap();
1068        assert_eq!(slot.state.load(Ordering::Acquire), 0);
1069        hive.free.push(0, &slot.next);
1070        let next = hive.insert(8);
1071        assert_eq!(next.index(), 2);
1072        assert!(hive.get(last).is_none());
1073        assert_eq!(hive.len(), 1);
1074    }
1075
1076    #[test]
1077    fn a_live_stack_hint_is_discarded() {
1078        let hive = ConcurrentAppendHive::<u8, 2>::new();
1079        let a = hive.insert(1);
1080        let borrowed = hive.get(a).unwrap();
1081        let slot = hive.slot(a.index()).unwrap();
1082        hive.free.push(a.index(), &slot.next);
1083        let b = hive.insert(2);
1084        assert_ne!(a.index(), b.index());
1085        assert_eq!(*borrowed, 1);
1086        assert_eq!(hive.get(b), Some(&2));
1087        assert_eq!(hive.len(), 2);
1088    }
1089}