o3 0.60.0

shared-nothing primitives
Documentation
use std::{
    cell, marker,
    mem::{self, MaybeUninit},
    num, ptr, slice,
};

use crate::buffer::storage::{
    provided,
    provided::arena::{
        self, Header, Scope,
        entry::{Counter, Data},
    },
    provided::fixed,
};

/// Borrowed access to the exact active header and slot layout.
#[repr(transparent)]
pub struct Root<'d, T, C = (), L: arena::Layout = cell::Cell<u32>> {
    header: &'d Header<C, L, State<'d, L>>,
    slots: SlotDomain<'d, T, L>,
}

impl<T, C, L: arena::Layout> arena::Arena<T, C, L> {
    /// # Safety
    /// The arena is inactive with every prior scope reclaimed. End all issued access,
    /// then finish the returned scope before releasing its exclusive generation borrow.
    /// For fixed storage, `resident` is initialized to this context's admitted ceiling.
    pub(in crate::buffer::storage::provided) unsafe fn enter<'d>(
        &'d mut self,
        limit: u32,
        resident: L::Shared,
    ) -> (Root<'d, T, C, L>, Scope<'d, T, L>) {
        const {
            assert!(size_of::<Header<C, L>>() == size_of::<Header<C, L, State<'_, L>>>());
            assert!(align_of::<Header<C, L>>() == align_of::<Header<C, L, State<'_, L>>>());
            assert!(
                mem::offset_of!(Header<C, L>, context)
                    == mem::offset_of!(Header<C, L, State<'_, L>>, context)
            );
        }
        let capacity = self.entries.extent();
        let (header, values) = self.entries.parts_mut();
        let header = ptr::from_mut(header).cast::<Header<C, L, State<'d, L>>>();
        // SAFETY: both header layouts place the live context at the same offset.
        // The exclusive arena borrow initializes state before lending the header.
        let header = unsafe {
            (&raw mut (*header).state).write(State {
                domain: Domain::new(resident, limit.min(capacity.get())),
                free: cell::Cell::new(None),
            });
            &*header
        };
        let mut free = None;
        for slot in values.iter_mut() {
            let entry = ptr::NonNull::from(slot).cast::<arena::Entry<'d, L>>();
            // SAFETY: this generation exclusively initializes each complete slot;
            // its item remains in UnsafeCell<MaybeUninit<T>> until insertion.
            unsafe {
                entry.as_ptr().write(arena::Entry::new(
                    &header.state.domain,
                    L::empty(),
                    MaybeUninit::new(Data { free }),
                ))
            };
            free = Some(entry);
        }
        header.state.free.set(free);
        // SAFETY: every Entry is initialized; the remaining Slot fields are
        // PhantomData and UnsafeCell<MaybeUninit<T>>, which admit uninitialized bytes.
        let slots = unsafe {
            slice::from_raw_parts(
                values.as_ptr().cast::<arena::Slot<'d, T, L>>(),
                values.len(),
            )
        };
        (
            Root {
                header,
                slots: marker::PhantomData,
            },
            Scope {
                slots: slots.iter(),
            },
        )
    }
}

impl<'d, T, C, L: arena::Layout> Root<'d, T, C, L> {
    pub const fn context(&self) -> &'d C {
        &self.header.context
    }
    pub fn capacity(&self) -> num::NonZero<u32> {
        // SAFETY: enter retains this exact initialized header and original tail extent.
        let view = unsafe {
            crate::alloc::tail::View::<
                Header<C, L, State<'d, L>>,
                arena::Slot<'d, T, L>,
                num::NonZero<u32>,
            >::from_raw(ptr::NonNull::from(self.header).cast())
        };
        view.len_proof().extent()
    }
    fn next_free<X: Copy>(&self, context: X) -> Option<provided::Vacant<'d, T, L, X>> {
        let state = &self.header.state;
        let entry = state.free.get()?;
        // SAFETY: the free head is the complete slot from this typed arena.
        let slot = unsafe { entry.cast::<arena::Slot<'d, T, L>>().as_ref() };
        // SAFETY: a free slot contains its original free successor.
        state
            .free
            .set(unsafe { slot.entry.data.get().assume_init().free });
        Some(provided::Vacant { slot, context })
    }
    pub fn pop_returned(&self) -> Option<T> {
        let state = &self.header.state;
        let head = state.domain.pop_returned()?;
        // SAFETY: this domain contains only complete slots of this arena.
        let slot = unsafe { head.cast::<arena::Slot<'d, T, L>>().as_ref() };
        // SAFETY: the detached slot owns its item after every external and account edge ended.
        let value = unsafe { slot.take_returned() };
        state.push_free(arena::Empty { entry: head });
        Some(value)
    }
    pub fn has_returned(&self) -> bool {
        self.header.state.domain.tail.get().is_some()
    }
}

impl<T, C, L: arena::Layout> Clone for Root<'_, T, C, L> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T, C, L: arena::Layout> Copy for Root<'_, T, C, L> {}

impl<'d, T, C> Root<'d, T, C> {
    pub fn vacant(&self) -> Option<provided::Vacant<'d, T>> {
        self.next_free(())
    }
}

impl<'d, T, C> Root<'d, T, C, ()> {
    pub fn try_vacant(&self) -> Result<provided::Vacant<'d, T, (), &'d C>, fixed::Full> {
        self.next_free(self.context()).ok_or(fixed::Full {
            capacity: self.capacity(),
        })
    }
}

/// Free slots and fixed extent belong to the inactive-item arena.
#[repr(C)]
pub(in crate::buffer::storage::provided) struct State<'d, L: arena::Layout> {
    pub(super) domain: Domain<'d, L>,
    free: cell::Cell<Option<arena::Link<'d, L>>>,
}

/// Last-edge accounting and returned slots share one owning domain.
#[repr(C)]
pub(in crate::buffer::storage::provided) struct Domain<'d, L: arena::Layout> {
    head: cell::Cell<MaybeUninit<arena::Link<'d, L>>>,
    pub(super) tail: cell::Cell<Option<arena::Link<'d, L>>>,
    pub(super) accounted: Counter,
    pub(super) limit: u32,
    pub(super) resident: L::Shared,
    brand: marker::PhantomData<fn(&'d ()) -> &'d ()>,
}

impl<'d, L: arena::Layout> State<'d, L> {
    pub(super) fn push_free(&self, node: arena::Empty<'d, L>) {
        // SAFETY: this affine vacancy retains its exact detached slot.
        unsafe { node.entry.as_ref() }
            .data
            .set(MaybeUninit::new(Data {
                free: self.free.get(),
            }));
        self.free.set(Some(node.entry));
    }

    /// # Safety
    /// This domain is the first field of the original owning item arena.
    pub(super) unsafe fn from_domain(domain: &'d Domain<'d, L>) -> &'d Self {
        // SAFETY: the typed vacancy can only originate in State's repr(C) allocation.
        unsafe { &*ptr::from_ref(domain).cast::<Self>() }
    }
}

impl<'d, L: arena::Layout> Domain<'d, L> {
    pub(super) fn new(resident: L::Shared, limit: u32) -> Self {
        Self {
            head: cell::Cell::new(MaybeUninit::uninit()),
            tail: cell::Cell::new(None),
            accounted: Counter::default(),
            limit,
            resident,
            brand: marker::PhantomData,
        }
    }

    pub(super) fn pop_returned(&self) -> Option<arena::Link<'d, L>> {
        let tail = self.tail.get()?;
        // SAFETY: a tail proves an initialized head in this same domain.
        let head = unsafe { self.head.get().assume_init() };
        if head == tail {
            self.tail.set(None);
        } else {
            // SAFETY: finish initialized the successor of every nontail entry.
            let next = unsafe { head.as_ref().data.get().assume_init().returned };
            self.head.set(MaybeUninit::new(next));
        }
        Some(head)
    }

    pub(super) fn finish(&self, node: arena::Ready<'d, L>) {
        if let Some(last) = self.tail.get() {
            // SAFETY: the old tail gains its first initialized successor.
            unsafe { last.as_ref() }.data.set(MaybeUninit::new(Data {
                returned: node.entry,
            }));
        } else {
            self.head.set(MaybeUninit::new(node.entry));
        }
        self.tail.set(Some(node.entry));
    }
}

type SlotDomain<'d, T, L> =
    marker::PhantomData<fn(&'d arena::Slot<'d, T, L>) -> &'d arena::Slot<'d, T, L>>;