o3 0.62.0

shared-nothing primitives
Documentation
use crate::depot::{arena::linked, capacity};
use std::{cell, marker, mem, num::NonZero, ptr};

/// Access to one exact linked-slot region without owning its allocation.
#[derive(Debug)]
pub struct Store<T> {
    pub(super) slots: ptr::NonNull<mem::MaybeUninit<linked::raw::Node<T>>>,
    pub(super) capacity: linked::raw::Capacity<T>,
    pub(super) initialized: cell::Cell<u32>,
    pub(super) free: cell::Cell<u32>,
    pub(in crate::depot) available: cell::Cell<u32>,
    pub(super) ownership: marker::PhantomData<T>,
}

/// Moving the descriptor preserves its region pointer and resident addresses.
impl<T> Unpin for Store<T> {}

impl<T> Store<T> {
    pub(crate) const END: u32 = u32::MAX;

    pub const fn capacity(&self) -> linked::raw::Capacity<T> {
        self.capacity
    }

    pub const fn pointer(&self) -> ptr::NonNull<linked::raw::Node<T>> {
        self.slots.cast()
    }

    /// # Safety
    /// `index` is below this region's initialized prefix.
    pub(crate) unsafe fn slot(&self, index: u32) -> &linked::raw::Node<T> {
        unsafe { (&*self.slots.as_ptr().add(index as usize)).assume_init_ref() }
    }

    pub(crate) fn available(&self) -> usize {
        self.available.get() as usize
    }

    /// Returns this store's already-debited slot credits.
    pub(in crate::depot::arena::linked) fn refund(&self, count: u32) {
        self.available.set(self.available.get().wrapping_add(count));
    }

    pub(crate) fn check(&self, count: capacity::Count) -> Result<(), capacity::Shortage> {
        let room = self.available.get();
        if count.raw() > room {
            return Err(capacity::Shortage {
                // SAFETY: demand exceeding the available count is nonzero.
                requested: unsafe { NonZero::new_unchecked(count.get()) },
                available: room as usize,
            });
        }
        Ok(())
    }

    pub(in crate::depot::arena::linked) fn debit(&self, count: capacity::Count) {
        self.available
            .set(self.available.get().wrapping_sub(count.raw()));
    }

    /// # Safety
    /// One slot was debited. A supplied link names the final next in this store
    /// or its end. In that case initialize the returned slot immediately.
    pub(in crate::depot::arena::linked) unsafe fn claim<Tag>(
        &self,
        next: Option<linked::raw::Index<Tag>>,
    ) -> (linked::raw::Index<Tag>, *mut mem::MaybeUninit<T>) {
        let next = next.map(linked::raw::Index::raw);
        let free = self.free.get();
        let (index, node) = if free == Self::END {
            let index = self.initialized.get();
            let node = unsafe { self.slots.as_ptr().add(index as usize) };
            unsafe {
                node.write(mem::MaybeUninit::new(linked::raw::Node::vacant(
                    next.unwrap_or(index),
                )))
            };
            self.initialized.set(index + 1);
            (index, unsafe { (&*node).assume_init_ref() })
        } else {
            let node = unsafe { self.slot(free) };
            self.free.set(node.next.replace(next.unwrap_or(free)));
            (free, node)
        };
        (linked::raw::Index::new(index), node.value.get())
    }

    pub(in crate::depot::arena::linked) fn recycle(
        &self,
        index: u32,
        node: &linked::raw::Node<T>,
        refund: bool,
    ) {
        node.next.set(self.free.replace(index));
        if refund {
            self.refund(1);
        }
    }

    /// # Safety
    /// The caller solely owns this detached live slot with this exact TRACK policy.
    pub(crate) unsafe fn take<Tag, const TRACK: bool>(&self, index: linked::raw::Index<Tag>) -> T {
        let node = unsafe { self.slot(index.raw()) };
        let value = unsafe { (&*node.value.get()).assume_init_read() };
        self.recycle(index.raw(), node, TRACK);
        value
    }

    /// Returns one live slot's next.
    /// # Safety
    /// `index` belongs to the calling topology in this region.
    pub(crate) unsafe fn next<Tag>(
        &self,
        index: linked::raw::Index<Tag>,
    ) -> linked::raw::Index<Tag> {
        unsafe { self.slot(index.raw()) }.next()
    }

    /// Replaces one live slot's next.
    /// # Safety
    /// `index` is live and `next` is empty or live in the same topology domain.
    pub(crate) unsafe fn set_next<Tag>(
        &self,
        index: linked::raw::Index<Tag>,
        next: linked::raw::Index<Tag>,
    ) {
        unsafe { self.slot(index.raw()) }.next.set(next.raw());
    }

    /// Borrows one live value.
    /// # Safety
    /// The owner borrow prevents mutation or release of `index`.
    pub(crate) unsafe fn value<Tag>(&self, index: linked::raw::Index<Tag>) -> &T {
        unsafe { &*self.value_ptr(index) }
    }

    /// Projects the address of one live value without creating a reference.
    /// # Safety
    /// `index` is live; reference aliases must derive from its exact owner.
    pub(crate) unsafe fn value_ptr<Tag>(&self, index: linked::raw::Index<Tag>) -> *mut T {
        unsafe { self.slot(index.raw()) }.value_ptr()
    }

    /// # Safety
    /// Every live value is solely owned and every region loan has ended.
    /// Do not access any value through this store after this terminal operation.
    pub unsafe fn drop_values(&mut self) {
        if !mem::needs_drop::<T>() {
            return;
        }
        let mut free = self.free.get();
        while free != Self::END {
            let slot = unsafe { self.slot(free) };
            free = slot.next.replace(free);
        }
        for offset in 0..self.initialized.get() {
            let slot =
                unsafe { (&mut *self.slots.as_ptr().add(offset as usize)).assume_init_mut() };
            if slot.next.get() != offset {
                unsafe { (&mut *slot.value.get()).assume_init_drop() };
            }
        }
    }
}

impl<T> linked::Sealed<T> for &Store<T> {}

impl<T> Store<T> {
    /// # Safety
    /// The distinct source owns exactly count live slots. The target admits the run and next; PRIVATE retains fresh and publishes the prefix, otherwise the reservation debited it.
    /// Conversion returns normally without observing or changing either store.
    pub(crate) unsafe fn move_run<const PRIVATE: bool, Tag>(
        &self,
        source: &Store<impl Into<T>>,
        (head, stop): (linked::raw::Index<Tag>, linked::raw::Index<Tag>),
        after: u32,
        count: u32,
        fresh: u32,
    ) -> (linked::raw::Index<Tag>, linked::raw::Index<Tag>) {
        let end = Self::END;
        let input = source.slots.as_ptr();
        let output = self.slots.as_ptr().cast::<linked::raw::Node<T>>();
        let mut free = if PRIVATE { end } else { self.free.get() };
        let first = if free == end { fresh } else { free };
        let head = head.raw();
        let stop = stop.raw();
        let mut read = head;
        let (last, tail) = 'moved: {
            if free != end {
                loop {
                    // SAFETY: these distinct live and free partitions own the two slots.
                    let from = unsafe { (&*input.add(read as usize)).assume_init_ref() };
                    let to = unsafe { &*output.add(free as usize) };
                    unsafe { to.value_ptr().write(from.value_ptr().read().into()) };
                    let next = to.next.get();
                    if read == stop {
                        if next != after {
                            to.next.set(after);
                        }
                        self.free.set(next);
                        break 'moved (free, &from.next);
                    }
                    read = from.next.get();
                    if next == end {
                        to.next.set(fresh);
                        self.free.set(end);
                        break;
                    }
                    free = next;
                }
            }
            let mut index = fresh;
            loop {
                // SAFETY: each remaining source slot owns one value and the reservation
                // covers the same number of uninitialized destination slots.
                let from = unsafe { (&*input.add(read as usize)).assume_init_ref() };
                let next = index + 1;
                unsafe {
                    linked::raw::Node::write(
                        output.add(index as usize),
                        from.value_ptr().read().into(),
                        if read == stop { after } else { next },
                    )
                };
                if read == stop {
                    if !PRIVATE {
                        self.initialized.set(next);
                    }
                    break 'moved (index, &from.next);
                }
                read = from.next.get();
                index = next;
            }
        };
        tail.set(source.free.replace(head));
        source.refund(count);
        (
            linked::raw::Index::new(first),
            linked::raw::Index::new(last),
        )
    }
}

impl<T> linked::Source<T> for &Store<T> {
    fn store(&self) -> &Store<T> {
        self
    }
}

const _: () = assert!(mem::size_of::<Store<u64>>() == 3 * mem::size_of::<usize>());