o3 0.61.0

shared-nothing primitives
Documentation
use std::{
    cell, marker,
    mem::{MaybeUninit, size_of},
    num::NonZero,
    ops, ptr,
};

use provided::account;

use crate::{
    buffer::{
        raw::{Policy as _, Projection},
        resident, storage,
        storage::{provided, provided::arena},
    },
    mem::raw::{self, Edge},
    mem::slot,
};

/// Only admitted registrations can change this arena's outstanding count.
#[repr(transparent)]
#[derive(Default)]
pub(super) struct Counter(pub(super) cell::Cell<u32>);

/// A live edge retains the slot and its paying budget.
#[derive(Debug)]
#[repr(transparent)]
pub struct Registration<'d, L: Layout = cell::Cell<u32>> {
    count: raw::Count,
    scope: marker::PhantomData<fn(&'d L) -> &'d L>,
}

/// The hidden scope's authority to reclaim an initialized item.
#[derive(Clone, Copy)]
pub(super) enum State {
    Empty,
    ReturnOnLastAccount,
    Occupied,
}

/// An account can only exist while the slot is detached from both lists.
pub(super) union Data<'d, L: Layout> {
    pub(super) free: Option<arena::Link<'d, L>>,
    pub(super) returned: arena::Link<'d, L>,
    budget: resident::Budget<'d>,
}

#[repr(C, align(8))]
pub(in crate::buffer::storage::provided) struct Entry<'d, L: Layout = cell::Cell<u32>> {
    registration: Registration<'d, L>,
    pub(super) state: cell::Cell<State>,
    pub(super) resident: L::Slot,
    pub(super) data: cell::Cell<MaybeUninit<Data<'d, L>>>,
    pub(super) domain: &'d arena::root::Domain<'d, L>,
}

impl<'d, L: Layout> provided::Account<'d, L> {
    pub(in crate::buffer) fn payer(&self) -> resident::Budget<'d> {
        // SAFETY: this live edge retains the initialized budget arm.
        unsafe {
            self.as_ptr()
                .cast::<Entry<'d, L>>()
                .as_ref()
                .data
                .get()
                .assume_init()
                .budget
        }
    }
}

impl<L: Layout> Registration<'_, L> {
    pub(in crate::buffer) fn resident(&self) -> usize {
        // SAFETY: a borrowed live registration retains its original admitted entry.
        unsafe {
            ptr::NonNull::from(self)
                .cast::<Entry<'_, L>>()
                .as_ref()
                .capacity() as usize
        }
    }
}

impl<'d, L: Layout> provided::Prefix<'_, 'd, &[u8], L> {
    #[inline]
    pub(in crate::buffer) fn try_account_with<A, F, T>(
        &self,
        budget: resident::Budget<'d>,
        admission: A,
        place: &mut MaybeUninit<T>,
    ) -> Result<ops::ControlFlow<A::Declined>, account::Cause>
    where
        A: resident::Admission,
        F: From<storage::Shared<Option<provided::Account<'d, L>>>>,
        T: From<F>,
    {
        if self.bytes.is_empty() {
            place.write(T::from(F::from(storage::Shared::<
                Option<provided::Account<'d, L>>,
            >::new())));
            return Ok(ops::ControlFlow::Continue(()));
        }
        let pointer = self.owner.entry;
        // SAFETY: the owner retains this scope's stable slot. Occupied
        // registrations remain shared; admission invokes no user callbacks.
        let entry: &'d Entry<'d, L> = unsafe { pointer.as_ref() };
        let registration = &entry.registration;
        if !registration.is_empty() {
            // SAFETY: the live account keeps this slot detached with its original paying budget.
            let paying = unsafe { entry.data.get().assume_init().budget };
            if !ptr::eq(paying.core(), budget.core()) {
                return Err(account::Cause::Foreign);
            }
            if let ops::ControlFlow::Break(declined) = admission.check(budget, 0) {
                return Ok(ops::ControlFlow::Break(declined));
            }
            // SAFETY: the slot owner retains this proved live registration;
            // no callbacks or edge releases intervene before the increment.
            unsafe { registration.try_retain() }.map_err(account::Cause::Retain)?;
        } else {
            let domain = entry.domain;
            let count = domain.accounted.0.get();
            let limit = domain.limit;
            if count >= limit {
                return Err(account::Cause::Exhausted { count, limit });
            }
            // SAFETY: the admitted projection fits this slot's initialized ceiling,
            // and the nonempty prefix retains at least one byte of that projection.
            let resident = unsafe { NonZero::new_unchecked(entry.capacity()) };
            if let ops::ControlFlow::Break(declined) =
                admission.check(budget, resident.get() as usize)
            {
                return Ok(ops::ControlFlow::Break(declined));
            }
            budget
                .try_acquire(resident)
                .map_err(account::Cause::Budget)?;
            domain.accounted.0.set(count + 1);
            entry.data.set(MaybeUninit::new(Data { budget }));
            // SAFETY: the detached slot owns the debit and its count is still empty.
            unsafe { registration.activate() };
        }
        // SAFETY: admission transfers one edge to the first field of this repr(C) entry.
        let owner = unsafe { provided::Account::from_raw(pointer.cast()) };
        // SAFETY: the counted edge retains the same slot as these admitted prefix bytes.
        let extent = unsafe { storage::Shared::assume(self.bytes, Some(owner)) };
        place.write(T::from(F::from(extent)));
        Ok(ops::ControlFlow::Continue(()))
    }
}

impl<'d, L: Layout> Entry<'d, L> {
    pub(super) fn new(
        domain: &'d arena::root::Domain<'d, L>,
        resident: L::Slot,
        data: MaybeUninit<Data<'d, L>>,
    ) -> Self {
        Self {
            registration: Registration {
                count: raw::Count::empty(),
                scope: marker::PhantomData,
            },
            state: cell::Cell::new(State::Empty),
            resident,
            data: cell::Cell::new(data),
            domain,
        }
    }

    /// # Safety
    /// Admission initialized this u32 ceiling and the slot cannot be reused during the borrow.
    pub(in crate::buffer::storage::provided) unsafe fn capacity(&self) -> u32 {
        unsafe { L::resident(&self.resident, &self.domain.resident) }
    }

    /// # Safety
    /// The borrowed domain is this entry's original owning domain.
    /// The registration is initialized and all its issued access has ended.
    /// Consume it once before returning the slot or initializing another charge.
    unsafe fn refund(&self, domain: &arena::root::Domain<'d, L>) {
        // SAFETY: the registration still holds its budget and the same ceiling it debited.
        unsafe {
            self.data
                .get()
                .assume_init()
                .budget
                .release(L::resident(&self.resident, &domain.resident) as usize)
        };
    }

    /// # Safety
    /// The native terminal ended every projection and account in this generation.
    pub(super) unsafe fn refund_ended(&self) {
        if !matches!(self.state.get(), State::Empty) && !self.registration.is_empty() {
            // SAFETY: the terminal owns all remaining charged edges, including forgotten ones.
            unsafe { self.refund(self.domain) };
        }
    }

    /// # Safety
    /// The owner must retain the sole live external edge, consumed exactly once here.
    pub(super) unsafe fn release(owner: &mut provided::Owner<'d, L>) {
        // SAFETY: the owner retains the sole external edge to the live slot.
        let entry = unsafe { owner.entry.as_ref() };
        if entry.registration.is_empty() {
            entry.domain.finish(arena::Ready { entry: owner.entry });
        } else {
            entry.state.set(State::ReturnOnLastAccount);
        }
    }

    /// # Safety
    /// The hidden scope has ended every issued access to the complete slot.
    pub(super) unsafe fn revoke<T>(
        slot: &'d arena::Slot<'d, T, L>,
    ) -> Option<slot::Occupied<'d, T>> {
        let entry = &slot.entry;
        match entry.state.get() {
            State::Empty => None,
            State::ReturnOnLastAccount | State::Occupied => {
                if !entry.registration.is_empty() {
                    // SAFETY: the ended scope owns even forgotten account edges.
                    // No issued access or count operation survives reclamation;
                    // the next generation initializes this slot before reuse.
                    unsafe { entry.refund(entry.domain) };
                }
                // SAFETY: this ended generation owns the initialized item until its release.
                Some(unsafe { slot.occupied() })
            }
        }
    }
}

impl<T, L: Layout> arena::Slot<'_, T, L> {
    /// # Safety
    /// The caller detached this returned slot and exclusively owns its initialized item.
    pub(super) unsafe fn take_returned(&self) -> T {
        // SAFETY: the detached slot owns the item until this move.
        let value = unsafe { self.occupied() }.into_inner();
        self.entry.state.set(State::Empty);
        value
    }
}

impl<'d, L: Layout> arena::Ready<'d, L> {
    pub(super) fn publish(self, view: Projection<'d, '_>) -> provided::Unique<'d, L> {
        // SAFETY: publication consumes the detached initialized slot for this projection.
        unsafe { self.entry.as_ref() }.state.set(State::Occupied);
        provided::Unique::new(view, provided::Owner { entry: self.entry })
    }
}

// SAFETY: every account edge retains this exact slot and embedded count.
unsafe impl<L: Layout> raw::Edge for Registration<'_, L> {
    fn count(&self) -> &raw::Count {
        &self.count
    }
}

// SAFETY: account edges retain the initialized debit; its finalizer owns both
// refunds before returning the slot, without callbacks or premature reuse.
unsafe impl<'d, L: Layout> raw::Target for Registration<'d, L> {
    unsafe fn destroy(pointer: ptr::NonNull<Self>) {
        // Activation issued the first field's address from the complete repr(C) slot.
        let pointer = pointer.cast::<Entry<'d, L>>();
        // SAFETY: the last counted edge ended and set this registration's count to zero.
        let entry = unsafe { pointer.as_ref() };
        let domain = entry.domain;
        domain.accounted.0.set(domain.accounted.0.get() - 1);
        // SAFETY: this last live edge owns the registration's remaining debit.
        unsafe { entry.refund(domain) };
        if matches!(entry.state.get(), State::ReturnOnLastAccount) {
            domain.finish(arena::Ready { entry: pointer });
        }
    }
}

const _: () = {
    assert!(size_of::<Entry<'_>>() == 4 * size_of::<usize>());
    assert!(size_of::<Entry<'_, ()>>() == 3 * size_of::<usize>());
    assert!(align_of::<Entry<'_>>() == 8);
};

/// Static storage layout for a provided registration.
pub trait Layout: capacity::Sealed + std::fmt::Debug + Unpin + 'static {
    type Slot;
    type Shared;
    fn empty() -> Self::Slot;
    /// # Safety
    /// This slot holds its admitted live projection.
    unsafe fn resident(slot: &Self::Slot, shared: &Self::Shared) -> u32;
}

mod capacity {
    pub trait Sealed {}
    impl Sealed for () {}
    impl Sealed for std::cell::Cell<u32> {}
}

impl Layout for () {
    type Slot = ();
    type Shared = NonZero<u32>;
    fn empty() {}
    unsafe fn resident(_: &(), shared: &Self::Shared) -> u32 {
        shared.get()
    }
}

impl Layout for cell::Cell<u32> {
    type Slot = cell::Cell<MaybeUninit<u32>>;
    type Shared = ();
    fn empty() -> Self::Slot {
        cell::Cell::new(MaybeUninit::uninit())
    }
    unsafe fn resident(slot: &Self::Slot, _: &()) -> u32 {
        // SAFETY: publication initialized this exact slot's admitted capacity.
        unsafe { slot.get().assume_init() }
    }
}

impl<L: Layout> Clone for Data<'_, L> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<L: Layout> Copy for Data<'_, L> {}