o3 0.62.0

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

use crate::depot::arena::linked;
use crate::depot::queue::pool::fair::{Lanes, State};
use crate::{
    base::cell::region,
    depot::{capacity, queue::pool},
    mem::credit::fair,
};

/// One fair lane retaining its exact owner and exclusive region brand.
pub struct Binding<'a, 'd, T, S = ()> {
    owner: &'a Lanes<'d, T, S>,
    slot: &'a cell::UnsafeCell<crate::depot::raw::QueueSlot<State<S>>>,
}

/// The original lane loan retaining one initialized head through admission.
pub struct Front<'loan, 'source: 'loan, 'd, T, S = ()> {
    binding: Binding<'source, 'd, T, S>,
    index: linked::raw::Index,
    loan: marker::PhantomData<&'loan mut region::Token<region::Identity<'d>>>,
}

impl<'a, 'd, T, S> Binding<'a, 'd, T, S> {
    /// Projects an admitted lane while retaining its exact owner and region.
    pub fn from_source(
        source: crate::depot::raw::Proof<(&'a Lanes<'d, T, S>, usize), capacity::Physical>,
    ) -> Self {
        let (owner, index) = source.into_inner();
        // SAFETY: the retained physical proof bounds this index in the original
        // owner, whose fixed lanes stay initialized for its complete borrow.
        let slot = unsafe { &*owner.inner.slots.as_ptr().add(index).cast() };
        Self { owner, slot }
    }

    pub const fn index(self) -> usize {
        // SAFETY: bind retains this initialized slot's immutable original index.
        unsafe { (*self.slot.get()).state.index.get() }
    }

    pub fn view<'t>(
        self,
        _: &'t region::Token<region::Identity<'d>>,
    ) -> pool::View<'t, T, State<S>, false>
    where
        'a: 't,
    {
        // SAFETY: the matching shared token excludes exclusive lane loans for 't.
        unsafe { pool::View::new(&self.owner.inner.store, &*self.slot.get()) }
    }

    fn lane_mut<'t>(
        self,
        _: &'t mut region::Token<region::Identity<'d>>,
    ) -> pool::raw::Lane<'t, T, State<S>, false>
    where
        'a: 't,
    {
        // SAFETY: the matching exclusive token excludes every competing lane
        // loan; only fair transitions may consume slots or access the ledger.
        unsafe { pool::raw::Lane::new(&self.owner.inner.store, &mut *self.slot.get()) }
    }

    fn held(self) -> &'a cell::Cell<capacity::Count> {
        // SAFETY: this field is disjoint from value loans protected by the
        // matching region token; no shared borrow of the whole state is formed.
        unsafe { &(*self.slot.get()).state.held }
    }

    /// The original slot capacity excludes u32::MAX and bounds the held count.
    pub fn reserve(self) -> Result<Permit<'a, 'd, T, S>, fair::Cause<usize>> {
        let held = self.held();
        let count = held.get().raw();
        if count != 0 {
            let shared = &self.owner.inner.store.available;
            let Some(rest) = shared.get().checked_sub(1) else {
                let [axis] = fair::Axis::ALL;
                return Err(fair::Cause::Exhausted {
                    axis,
                    required: 1,
                    available: 0,
                });
            };
            shared.set(rest);
        }
        held.set(capacity::Count::new(count + 1));
        Ok(Permit { binding: self })
    }

    pub fn take_front(
        self,
        token: &mut region::Token<region::Identity<'d>>,
    ) -> Option<(T, Permit<'a, 'd, T, S>)> {
        Some(self.front_entry(token)?.take())
    }

    /// Retains this exact head until consumed; dropping it leaves the lane unchanged.
    pub fn front_entry<'t>(
        self,
        token: &'t mut region::Token<region::Identity<'d>>,
    ) -> Option<Front<'t, 'a, 'd, T, S>>
    where
        'a: 't,
    {
        // SAFETY: the matching exclusive token retains this exact lane loan.
        unsafe { self.front_mut(token) }
    }
    /// # Safety
    /// Matching region authority keeps this queue and its values exclusive until the front ends.
    /// Other token uses cannot access them or invalidate the head or allocation; only the disjoint held count and immutable index remain accessible.
    pub unsafe fn front_mut(
        self,
        _: &mut region::Token<region::Identity<'d>>,
    ) -> Option<Front<'a, 'a, 'd, T, S>> {
        // SAFETY: the original token admits this initialized queue; the
        // caller preserves its exclusive loan without borrowing fair state.
        let index = unsafe { (*self.slot.get()).queue.links.head() }?;
        Some(Front {
            binding: self,
            index,
            loan: marker::PhantomData,
        })
    }
}

impl<'loan, 'source: 'loan, 'd, T, S> Front<'loan, 'source, 'd, T, S> {
    pub fn get(&self) -> &T {
        // SAFETY: the original exclusive queue retains this initialized head.
        unsafe { self.binding.owner.inner.store.value(self.index) }
    }

    pub fn take(self) -> (T, Permit<'source, 'd, T, S>) {
        // SAFETY: the retained loan excludes this queue and its live values;
        // the disjoint fair state remains accessible without the token.
        let queue = unsafe { &mut *ptr::addr_of_mut!((*self.binding.slot.get()).queue) };
        let value = unsafe {
            self.index
                .pop::<_, false>(queue, &self.binding.owner.inner.store)
        };
        (
            value,
            Permit {
                binding: self.binding,
            },
        )
    }

    /// Moves the value to its final place before returning the original slot.
    pub fn take_into<U, const BRANCH: u8>(
        self,
        place: &mut mem::MaybeUninit<U>,
    ) -> Permit<'source, 'd, T, S>
    where
        T: crate::mem::raw::Convert<U, BRANCH>,
    {
        let store = &self.binding.owner.inner.store;
        // SAFETY: the retained loan excludes this queue and its live values.
        let queue = unsafe { &mut *ptr::addr_of_mut!((*self.binding.slot.get()).queue) };
        unsafe { self.index.unlink(queue, store) };
        // SAFETY: conversion consumes this exact value once into disjoint storage.
        unsafe { T::take_into(store.value_ptr(self.index), place) };
        // SAFETY: ownership left the payload; return its physical slot before
        // exposing the fair entitlement whose Drop refunds the ledger.
        drop(unsafe {
            linked::raw::Vacant::detached(linked::raw::Borrow::<_, false>(store), self.index)
        });
        Permit {
            binding: self.binding,
        }
    }
}

impl<T, S> Copy for Binding<'_, '_, T, S> {}

impl<T, S> Clone for Binding<'_, '_, T, S> {
    fn clone(&self) -> Self {
        *self
    }
}

/// One unused queue slot entitlement bound to its original fair lane.
#[must_use = "a fair queue reservation must be published or returned"]
pub struct Permit<'a, 'd, T, S = ()> {
    binding: Binding<'a, 'd, T, S>,
}

impl<'a, 'd, T, S> Permit<'a, 'd, T, S> {
    pub fn state_mut<'b>(
        &'b self,
        token: &'b mut region::Token<region::Identity<'d>>,
    ) -> &'b mut S {
        &mut self.binding.lane_mut(token).into_state().value
    }

    pub fn insert<const FRONT: bool, const BRANCH: u8>(
        self,
        token: &mut region::Token<region::Identity<'d>>,
        value: impl crate::mem::raw::Convert<T, BRANCH>,
    ) {
        let binding = mem::ManuallyDrop::new(self).binding;
        // SAFETY: the consumed permit transfers its unit to this lane's ready value.
        unsafe { binding.lane_mut(token).insert_at::<FRONT, BRANCH>(value) };
    }
}

impl<T, S> Drop for Permit<'_, '_, T, S> {
    fn drop(&mut self) {
        let binding = self.binding;
        let held = binding.held();
        let count = held.get().raw();
        held.set(capacity::Count::new(count - 1));
        if count > 1 {
            let shared = &binding.owner.inner.store.available;
            shared.set(shared.get() + 1);
        }
    }
}

const _: () = {
    const WORD: usize = mem::size_of::<usize>();

    let _: [(); 2 * WORD] = [(); mem::size_of::<State<u64>>()];
    let _: [(); 2 * WORD] = [(); mem::size_of::<Binding<'_, '_, u64>>()];
    let _: [(); 2 * WORD] = [(); mem::size_of::<Permit<'_, '_, u64>>()];
    let _: [(); 2 * WORD] = [(); mem::size_of::<Option<Permit<'_, '_, u64>>>()];
};