Skip to main content

paged_collections/concurrent/
append.rs

1//! Append ownership, per-slot publication, and a helped, hole-free watermark.
2//!
3//! Every position below committed is initialized and ready. Ready positions
4//! above it are independently readable. With no push in flight, committed ==
5//! reserved. Removal and moving values require exclusive access.
6
7use alloc::boxed::Box;
8use alloc::vec::Vec;
9use core::fmt;
10use core::iter::FusedIterator;
11use core::mem::MaybeUninit;
12use core::ops::Range;
13use core::{ptr, slice};
14
15use super::atomic::{AtomicU64, AtomicUsize, Ordering, UnsafeCell};
16use super::spine::{self, Spine};
17use crate::page::DEFAULT_PAGE;
18use crate::paged_vec::PagedVec;
19
20// Enough directory levels for usize positions on either target and with
21// loom's smaller spine base. Unrepresentable allocations fail before claiming.
22const CHUNKS: usize = usize::BITS as usize;
23
24struct Page<T> {
25    ready: Box<[AtomicU64]>,
26    slots: Box<[UnsafeCell<MaybeUninit<T>>]>,
27}
28
29impl<T> Page<T> {
30    fn new(capacity: usize) -> Self {
31        Self {
32            ready: (0..capacity.div_ceil(64))
33                .map(|_| AtomicU64::new(0))
34                .collect(),
35            slots: (0..capacity)
36                .map(|_| UnsafeCell::new(MaybeUninit::uninit()))
37                .collect(),
38        }
39    }
40
41    fn ready(&self, offset: usize, ordering: Ordering) -> bool {
42        // Callers pass Acquire, which observes the value write published by
43        // the ready RMW.
44        self.ready[offset / 64].load(ordering) & (1 << (offset % 64)) != 0
45    }
46
47    fn drop_ready(&mut self) {
48        // Only called while the page is destroyed: skip the scan entirely
49        // for element types without drop glue.
50        if !core::mem::needs_drop::<T>() {
51            return;
52        }
53        for (offset, slot) in self.slots.iter_mut().enumerate() {
54            let mask = 1 << (offset % 64);
55            // Relaxed: exclusive destruction. Clear before user drop code so
56            // unwinding cleanup cannot drop the same value again.
57            if self.ready[offset / 64].fetch_and(!mask, Ordering::Relaxed) & mask != 0 {
58                slot.with_mut(|cell| {
59                    // SAFETY: the ready bit owns one initialized value;
60                    // exclusive page destruction excludes readers and writers.
61                    unsafe { ptr::drop_in_place(cell.cast::<T>()) };
62                });
63            }
64        }
65    }
66}
67
68impl<T> Drop for Page<T> {
69    fn drop(&mut self) {
70        // Continue through remaining ready values if one destructor panics.
71        struct Rest<'a, T>(&'a mut Page<T>);
72        impl<T> Drop for Rest<'_, T> {
73            fn drop(&mut self) {
74                self.0.drop_ready();
75            }
76        }
77        let rest = Rest(self);
78        rest.0.drop_ready();
79        core::mem::forget(rest);
80    }
81}
82
83/// Stable append storage with independently visible slots and a committed prefix.
84pub(crate) struct AppendLog<T, const PAGE: usize> {
85    pages: Spine<Page<T>, CHUNKS>,
86    reserved: AtomicUsize,
87    committed: AtomicUsize,
88    /// Only its chain of read-modify-writes matters; the value may wrap.
89    sync: AtomicUsize,
90}
91
92// SAFETY: moving the log transfers its owned cells, including their drops;
93// references cannot outlive the borrow from which they were obtained.
94unsafe impl<T: Send, const PAGE: usize> Send for AppendLog<T, PAGE> {}
95// SAFETY: claims uniquely own writes, ready/committed acquire publication,
96// and shared access never moves or drops values. Losing allocations may drop
97// on another thread; sharing initialized values also requires Sync.
98unsafe impl<T: Send + Sync, const PAGE: usize> Sync for AppendLog<T, PAGE> {}
99
100impl<T, const PAGE: usize> AppendLog<T, PAGE> {
101    pub(super) fn valid_page_capacity() -> bool {
102        PAGE > 0
103            && PAGE
104                <= isize::MAX as usize / core::mem::size_of::<UnsafeCell<MaybeUninit<T>>>().max(1)
105            && PAGE.div_ceil(64) <= isize::MAX as usize / core::mem::size_of::<AtomicU64>()
106    }
107
108    pub(crate) fn new() -> Self {
109        assert!(
110            Self::valid_page_capacity(),
111            "AppendLog: invalid page capacity"
112        );
113        Self {
114            pages: Spine::new(),
115            reserved: AtomicUsize::new(0),
116            committed: AtomicUsize::new(0),
117            sync: AtomicUsize::new(0),
118        }
119    }
120
121    #[cfg(feature = "serde")]
122    pub(super) fn can_append_at(pos: usize) -> bool {
123        Spine::<Page<T>, CHUNKS>::can_allocate_page(pos / PAGE)
124    }
125
126    fn claim(&self, limit: usize) -> Option<(usize, &Page<T>)> {
127        // Acquire: a claim only needs the latest count it can observe; the
128        // CAS below decides ownership.
129        let mut pos = self.reserved.load(Ordering::Acquire);
130        loop {
131            if pos >= limit {
132                return None;
133            }
134            // Allocate BEFORE claiming: capacity/allocation panics cannot
135            // strand a hole. No user code runs between a claim and ready;
136            // values are passed in, and all storage is already initialized.
137            let page = self
138                .pages
139                .get_or_insert_with(pos / PAGE, || Box::new(Page::new(PAGE)));
140            // AcqRel: the winner uniquely owns `pos`. Failure acquires the
141            // intervening reservations before trying their next position.
142            match self
143                .reserved
144                .compare_exchange(pos, pos + 1, Ordering::AcqRel, Ordering::Acquire)
145            {
146                Ok(_) => return Some((pos, page)),
147                Err(actual) => pos = actual,
148            }
149        }
150    }
151
152    fn publish(&self, pos: usize, page: &Page<T>, value: T) {
153        let offset = pos % PAGE;
154        page.slots[offset].with_mut(|cell| {
155            // SAFETY: the reservation CAS uniquely owns this uninitialized
156            // slot; shared operations never overwrite an initialized slot.
157            unsafe { ptr::write(cell.cast::<T>(), value) };
158        });
159        // Release publishes the write to anyone who acquires this bit, or
160        // acquires something that follows it (the sync in `help`, a sparse
161        // slot stored after this push).
162        page.ready[offset / 64].fetch_or(1 << (offset % 64), Ordering::Release);
163        self.help();
164    }
165
166    fn help(&self) {
167        // Every publisher does one read-modify-write on `sync` AFTER
168        // setting its ready bit and BEFORE scanning. These RMWs are totally
169        // ordered and each acquires the previous one, so the publisher whose
170        // sync comes last has acquired every other publisher's page install,
171        // write and ready bit. Its scan below therefore cannot stop early:
172        // with no push in flight, committed == reserved.
173        //
174        // This replaces the textbook "set my bit, then read yours" check,
175        // which is a store-buffering pattern that only SeqCst forbids (and
176        // that loom cannot model). The RMW chain needs AcqRel only.
177        //
178        // A separate counter that really changes, not `fetch_add(0)` on the
179        // watermark: compilers may weaken an RMW that leaves its value
180        // unchanged.
181        self.sync.fetch_add(1, Ordering::AcqRel);
182        loop {
183            // Acquire: sees every slot below the returned watermark.
184            let c = self.committed.load(Ordering::Acquire);
185            // Acquire observes the write behind each set bit; a missing page
186            // is not ready. Advancing over the whole ready run at once costs
187            // one contended CAS per run rather than per position.
188            let mut end = c;
189            while self.ready(end, Ordering::Acquire) {
190                end += 1;
191            }
192            if end == c {
193                break;
194            }
195            // AcqRel publishes the extended prefix and carries what this
196            // helper acquired (the bits in c..end) to later readers of
197            // `committed`. On failure another helper advanced: rescan.
198            let _ = self
199                .committed
200                .compare_exchange(c, end, Ordering::AcqRel, Ordering::Acquire);
201        }
202    }
203
204    pub(crate) fn push(&self, value: T, limit: usize) -> Result<usize, T> {
205        let Some((pos, page)) = self.claim(limit) else {
206            return Err(value);
207        };
208        self.publish(pos, page, value);
209        Ok(pos)
210    }
211
212    /// Claims storage before taking a pending value from the caller.
213    pub(super) fn push_from(&self, value: &mut Option<T>, limit: usize) -> Option<usize> {
214        assert!(value.is_some(), "missing pending append");
215        let (pos, page) = self.claim(limit)?;
216        self.publish(pos, page, value.take().expect("pending append"));
217        Some(pos)
218    }
219
220    /// Appends all `values` at consecutive positions with one reservation
221    /// and one helping pass, returning the first position. The caller
222    /// retains the values if storage preparation panics or the limit would
223    /// be exceeded. An empty batch reserves nothing.
224    pub(super) fn push_many_from(&self, values: &mut Vec<T>, limit: usize) -> Option<usize> {
225        let n = values.len();
226        // Acquire: as in `claim`, only the CAS decides ownership.
227        let mut pos = self.reserved.load(Ordering::Acquire);
228        if n == 0 {
229            return Some(pos);
230        }
231        loop {
232            if pos > limit || limit - pos < n {
233                return None;
234            }
235            // Allocate every page of the block BEFORE claiming it: capacity or
236            // allocation panics cannot strand holes. Pages installed for a
237            // lost CAS stay for later claims.
238            for page in pos / PAGE..=(pos + n - 1) / PAGE {
239                self.pages
240                    .get_or_insert_with(page, || Box::new(Page::new(PAGE)));
241            }
242            // AcqRel: the winner uniquely owns pos..pos + n.
243            match self
244                .reserved
245                .compare_exchange(pos, pos + n, Ordering::AcqRel, Ordering::Acquire)
246            {
247                Ok(_) => break,
248                Err(actual) => pos = actual,
249            }
250        }
251        // No user code runs from the claim until every slot is ready: moving
252        // out of a Vec and raw writes cannot panic.
253        for (i, value) in values.drain(..).enumerate() {
254            let at = pos + i;
255            let page = self.pages.get(at / PAGE).expect("claimed page installed");
256            page.slots[at % PAGE].with_mut(|cell| {
257                // SAFETY: the block reservation uniquely owns this
258                // uninitialized slot; shared operations never overwrite an
259                // initialized slot.
260                unsafe { ptr::write(cell.cast::<T>(), value) };
261            });
262        }
263        let (mut at, end) = (pos, pos + n);
264        while at < end {
265            let page = self.pages.get(at / PAGE).expect("claimed page installed");
266            let offset = at % PAGE;
267            let bit = offset % 64;
268            // Bits of this word within both the block and the page.
269            let count = (64 - bit).min(end - at).min(PAGE - offset);
270            let mask = if count == 64 {
271                u64::MAX
272            } else {
273                ((1u64 << count) - 1) << bit
274            };
275            // Release publishes these writes, as the single-bit RMW in
276            // `publish` does for one.
277            page.ready[offset / 64].fetch_or(mask, Ordering::Release);
278            at += count;
279        }
280        self.help();
281        Some(pos)
282    }
283
284    #[cfg(all(test, loom))]
285    pub(super) fn push_many(&self, mut values: Vec<T>, limit: usize) -> Result<usize, Vec<T>> {
286        self.push_many_from(&mut values, limit).ok_or(values)
287    }
288
289    fn ready(&self, pos: usize, ordering: Ordering) -> bool {
290        self.pages
291            .get(pos / PAGE)
292            .is_some_and(|page| page.ready(pos % PAGE, ordering))
293    }
294
295    pub(crate) fn len(&self) -> usize {
296        // Acquire observes every write in the prefix, transitively through
297        // the helpers' acquiring and releasing watermark CASes.
298        self.committed.load(Ordering::Acquire)
299    }
300
301    pub(crate) fn reserved_len(&self) -> usize {
302        // Relaxed: claims only; this does not grant access to any value.
303        self.reserved.load(Ordering::Relaxed)
304    }
305
306    pub(crate) fn get(&self, pos: usize) -> Option<&T> {
307        let prefix = self.len();
308        let page = self.pages.get(pos / PAGE)?;
309        // Acquire independently observes a finished push above the prefix.
310        if pos >= prefix && !page.ready(pos % PAGE, Ordering::Acquire) {
311            return None;
312        }
313        Some(page.slots[pos % PAGE].with(|cell| {
314            // SAFETY: acquiring committed or this slot's ready bit proves
315            // initialization. Shared access cannot remove or modify this T.
316            unsafe { &*cell.cast::<T>() }
317        }))
318    }
319
320    pub(crate) fn iter(&self) -> DenseIter<'_, T, PAGE> {
321        DenseIter::new(self)
322    }
323
324    #[cfg(not(loom))]
325    pub(crate) fn pages(
326        &self,
327    ) -> impl DoubleEndedIterator<Item = &[T]> + ExactSizeIterator + FusedIterator {
328        let len = self.len();
329        (0..len.div_ceil(PAGE)).map(move |p| {
330            let page = self.pages.get(p).expect("committed page exists");
331            let used = PAGE.min(len - p * PAGE);
332            // SAFETY: the acquired prefix initializes exactly these used
333            // slots. The production shim, UnsafeCell and MaybeUninit are
334            // transparent, so the boxed array has T's stride/alignment.
335            // Derive the pointer from the whole allocation, not one cell.
336            unsafe { core::slice::from_raw_parts(page.slots.as_ptr().cast::<T>(), used) }
337        })
338    }
339
340    // Loom's cells contain tracking metadata and are not contiguous T. Visit
341    // the SAME snapshotted prefix as singleton slices, checking every cell's
342    // publication through the shim instead of reinterpreting that metadata.
343    #[cfg(loom)]
344    pub(crate) fn pages(
345        &self,
346    ) -> impl DoubleEndedIterator<Item = &[T]> + ExactSizeIterator + FusedIterator {
347        self.iter().map(core::slice::from_ref)
348    }
349
350    pub(crate) fn get_mut(&mut self, pos: usize) -> Option<&mut T> {
351        if pos >= self.len() {
352            return None;
353        }
354        let page = self.pages.get(pos / PAGE).expect("committed page exists");
355        Some(page.slots[pos % PAGE].with_mut(|cell| {
356            // SAFETY: exclusivity implies quiescence (committed == reserved),
357            // initialization, and no outstanding references to this slot.
358            unsafe { &mut *cell.cast::<T>() }
359        }))
360    }
361
362    pub(crate) fn pages_mut(&mut self) -> PagesMut<'_, T> {
363        let len = self.len();
364        PagesMut {
365            pages: self.pages.iter_mut(),
366            len,
367            capacity: PAGE,
368            #[cfg(loom)]
369            slots: slice::IterMut::default(),
370        }
371    }
372
373    pub(crate) fn pop(&mut self) -> Option<T> {
374        let pos = self.len().checked_sub(1)?;
375        let page = self.pages.get(pos / PAGE).expect("committed page exists");
376        let offset = pos % PAGE;
377        // Relaxed throughout: &mut self excludes all shared operations. Clear
378        // ownership metadata before returning a value whose drop may panic.
379        page.ready[offset / 64].fetch_and(!(1 << (offset % 64)), Ordering::Relaxed);
380        self.committed.store(pos, Ordering::Relaxed);
381        self.reserved.store(pos, Ordering::Relaxed);
382        Some(page.slots[offset].with_mut(|cell| {
383            // SAFETY: this exclusively owned, initialized slot has just been
384            // removed from both counters and ready bits; transfer it once.
385            unsafe { ptr::read(cell.cast::<T>()) }
386        }))
387    }
388
389    pub(crate) fn swap_remove(&mut self, pos: usize) -> T {
390        let last = self.len().checked_sub(1).expect("nonempty append log");
391        assert!(pos <= last, "append log removal out of bounds");
392        if pos == last {
393            return self.pop().expect("last slot exists");
394        }
395        let value = self.pop().expect("last slot exists");
396        core::mem::replace(self.get_mut(pos).expect("remaining slot exists"), value)
397    }
398
399    pub(crate) fn truncate(&mut self, len: usize) {
400        while self.len() > len {
401            drop(self.pop());
402        }
403    }
404
405    pub(crate) fn clear(&mut self) {
406        self.truncate(0);
407    }
408
409    pub(super) fn shrink_to_fit(&mut self) {
410        let first_unused = self.len().div_ceil(PAGE);
411        let removed: Vec<_> = self
412            .pages
413            .iter()
414            .map(|(number, _)| number)
415            .skip_while(|&number| number < first_unused)
416            .collect();
417        for number in removed {
418            // Exclusive access means every initialized slot is in the prefix.
419            drop(self.pages.remove(number));
420        }
421    }
422
423    pub(crate) fn into_inner(mut self) -> PagedVec<T, PAGE> {
424        let mut result = PagedVec::with_capacity(self.len());
425        while let Some(value) = self.pop() {
426            result.push(value);
427        }
428        result.reverse();
429        result
430    }
431
432    #[cfg(all(test, loom))]
433    pub(super) fn reserve_for_test(&self, limit: usize) -> usize {
434        self.claim(limit).expect("test reservation fits").0
435    }
436
437    #[cfg(all(test, loom))]
438    pub(super) fn finish_for_test(&self, pos: usize, value: T) {
439        let page = self.pages.get(pos / PAGE).expect("test claimed this slot");
440        self.publish(pos, page, value);
441    }
442}
443
444/// Iterates over the committed prefix of a [`ConcurrentPagedVec`](super::ConcurrentPagedVec) or
445/// [`ConcurrentSparseSet`](super::ConcurrentSparseSet) in dense order.
446#[must_use = "iterators are lazy and do nothing unless consumed"]
447pub struct DenseIter<'a, T, const PAGE: usize = DEFAULT_PAGE> {
448    log: &'a AppendLog<T, PAGE>,
449    indices: Range<usize>,
450}
451
452impl<'a, T, const PAGE: usize> DenseIter<'a, T, PAGE> {
453    fn new(log: &'a AppendLog<T, PAGE>) -> Self {
454        Self {
455            log,
456            indices: 0..log.len(),
457        }
458    }
459}
460
461impl<'a, T, const PAGE: usize> Iterator for DenseIter<'a, T, PAGE> {
462    type Item = &'a T;
463
464    fn next(&mut self) -> Option<Self::Item> {
465        self.nth(0)
466    }
467
468    fn nth(&mut self, n: usize) -> Option<Self::Item> {
469        let index = self.indices.nth(n)?;
470        Some(self.log.get(index).expect("committed slot is ready"))
471    }
472
473    fn size_hint(&self) -> (usize, Option<usize>) {
474        self.indices.size_hint()
475    }
476}
477
478impl<T, const PAGE: usize> DoubleEndedIterator for DenseIter<'_, T, PAGE> {
479    fn next_back(&mut self) -> Option<Self::Item> {
480        self.nth_back(0)
481    }
482
483    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
484        let index = self.indices.nth_back(n)?;
485        Some(self.log.get(index).expect("committed slot is ready"))
486    }
487}
488
489impl<T, const PAGE: usize> ExactSizeIterator for DenseIter<'_, T, PAGE> {}
490impl<T, const PAGE: usize> FusedIterator for DenseIter<'_, T, PAGE> {}
491
492impl<T, const PAGE: usize> fmt::Debug for DenseIter<'_, T, PAGE> {
493    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494        f.debug_struct("DenseIter")
495            .field("indices", &self.indices)
496            .finish_non_exhaustive()
497    }
498}
499
500/// Exclusive traversal of initialized page slices. Loom yields singleton
501/// slices because its simulated cells contain tracking metadata.
502pub(crate) struct PagesMut<'a, T> {
503    pages: spine::IterMut<'a, Page<T>>,
504    len: usize,
505    capacity: usize,
506    #[cfg(loom)]
507    slots: slice::IterMut<'a, UnsafeCell<MaybeUninit<T>>>,
508}
509
510impl<'a, T> Iterator for PagesMut<'a, T> {
511    type Item = &'a mut [T];
512
513    #[cfg(not(loom))]
514    fn next(&mut self) -> Option<Self::Item> {
515        for (number, page) in self.pages.by_ref() {
516            let used = self
517                .capacity
518                .min(self.len.saturating_sub(number * self.capacity));
519            if used == 0 {
520                continue;
521            }
522            // SAFETY: quiescence initializes the prefix; each page is yielded
523            // once under exclusive access. Transparent production cells give
524            // the array T's layout; no unwritten tail is in the slice.
525            return Some(unsafe {
526                slice::from_raw_parts_mut(page.slots.as_mut_ptr().cast::<T>(), used)
527            });
528        }
529        None
530    }
531
532    #[cfg(loom)]
533    fn next(&mut self) -> Option<Self::Item> {
534        loop {
535            if let Some(slot) = self.slots.next() {
536                return Some(slot.with_mut(|cell| {
537                    // SAFETY: exclusive iteration yields each initialized
538                    // prefix slot once. Singleton slices use the shim without
539                    // assuming its cell metadata has T's layout.
540                    slice::from_mut(unsafe { &mut *cell.cast::<T>() })
541                }));
542            }
543            let (number, page) = self.pages.next()?;
544            let used = self
545                .capacity
546                .min(self.len.saturating_sub(number * self.capacity));
547            self.slots = page.slots[..used].iter_mut();
548        }
549    }
550}
551
552impl<T, const PAGE: usize> Drop for AppendLog<T, PAGE> {
553    fn drop(&mut self) {
554        // Quiescence gives committed == reserved. Empty values in the log's
555        // normal clear order, and finish that order on unwind.
556        // Page::drop remains a fallback for every ready bit, independently of
557        // the counters (also useful for deliberately split loom fixtures).
558        struct Rest<'a, T, const PAGE: usize>(&'a mut AppendLog<T, PAGE>);
559        impl<T, const PAGE: usize> Drop for Rest<'_, T, PAGE> {
560            fn drop(&mut self) {
561                self.0.clear();
562            }
563        }
564        // Nothing to run for element types without drop glue.
565        if !core::mem::needs_drop::<T>() {
566            return;
567        }
568        let rest = Rest(self);
569        rest.0.clear();
570        core::mem::forget(rest);
571    }
572}
573
574#[cfg(all(test, not(loom)))]
575mod tests {
576    use super::AppendLog;
577
578    #[test]
579    fn shrink_removes_only_pages_outside_the_prefix() {
580        let mut log = AppendLog::<usize, 3>::new();
581        for index in 0..9 {
582            assert_eq!(log.push(index, usize::MAX), Ok(index));
583        }
584        log.truncate(4);
585        log.shrink_to_fit();
586        assert_eq!(log.pages.iter().count(), 2);
587        assert!(log.pages.get(2).is_none());
588        let shared = &log;
589        for index in 4..9 {
590            assert_eq!(shared.push(index, usize::MAX), Ok(index));
591        }
592        assert!(shared.pages.get(2).is_some());
593        assert!(shared.iter().copied().eq(0..9));
594        log.clear();
595        log.shrink_to_fit();
596        assert_eq!(log.pages.iter().count(), 0);
597    }
598}