o3 0.60.0

shared-nothing primitives
Documentation
//! Region-owned FIFO lanes with fair unit admission embedded in their sidecars.

use std::{cell, mem, num};

use credit::fair;
pub use lanes::Lanes;

use crate::{
    base::cell::region,
    depot::{capacity, queue::pool},
    mem::credit,
};

mod lanes;

#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Plan {
    slots: capacity::Count,
    lanes: num::NonZero<u32>,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Error {
    ZeroLanes { capacity: usize },
    CapacityBelowLanes { capacity: usize, lanes: usize },
    Capacity(capacity::Error),
}

const _: [(); mem::size_of::<Plan>()] = [(); 2 * mem::size_of::<u32>()];

impl Plan {
    #[inline]
    pub fn new(capacity: usize, lanes: usize) -> Result<Self, Error> {
        if capacity < lanes {
            return Err(Error::CapacityBelowLanes { capacity, lanes });
        }
        let lanes = num::NonZero::new(lanes).ok_or(Error::ZeroLanes { capacity })?;
        let slots = capacity::Count::try_from(capacity).map_err(Error::Capacity)?;
        Ok(Self {
            slots,
            lanes: capacity::Count::try_nonzero(lanes).map_err(Error::Capacity)?,
        })
    }
}

pub struct State<S> {
    value: S,
    held: cell::Cell<capacity::Count>,
    index: capacity::Count,
}

impl<S> State<S> {
    pub const fn value(&self) -> &S {
        &self.value
    }
}

/// 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>>>,
}

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::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::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 }
    }

    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(remaining) = shared.get().checked_sub(1) else {
                let [axis] = fair::Axis::ALL;
                return Err(fair::Cause::Exhausted {
                    axis,
                    required: 1,
                    available: 0,
                });
            };
            shared.set(remaining);
        }
        // The original slot extent excludes u32::MAX; its capacity bounds held.
        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)?.into())
    }

    /// 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<
        crate::depot::raw::Proof<
            (
                (Self, &'t mut region::Token<region::Identity<'d>>),
                crate::depot::arena::linked::slots::Index,
            ),
            crate::depot::index::Initialized<pool::Head>,
        >,
    >
    where
        'a: 't,
    {
        let index = self.lane_mut(token).slot.queue.links.head()?;
        // SAFETY: the returned exclusive token retains this unchanged head.
        Some(unsafe { crate::depot::raw::Proof::new(((self, token), index)) })
    }
}

mod raw {
    use super::{Binding, Permit, pool, region};
    use crate::depot::arena::linked::slots;

    // SAFETY: the exact head and original exclusive token are consumed once.
    unsafe impl<'lane: 'token, 'token, 'd, T, S>
        crate::depot::raw::Project<slots::Index, pool::Head>
        for (
            Binding<'lane, 'd, T, S>,
            &'token mut region::Token<region::Identity<'d>>,
        )
    {
        type Output = (T, Permit<'lane, 'd, T, S>);

        unsafe fn project(self, index: slots::Index) -> Self::Output {
            let (binding, token) = self;
            let lane = binding.lane_mut(token);
            let value = unsafe { lane.slot.queue.pop::<_, false>(lane.store, index) };
            (value, Permit { 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 push_back(self, token: &mut region::Token<region::Identity<'d>>, value: T) {
        self.publish::<false>(token, value);
    }

    /// Restores a deferred head using its retained fair-lane entitlement.
    pub fn push_front(self, token: &mut region::Token<region::Identity<'d>>, value: T) {
        self.publish::<true>(token, value);
    }

    fn publish<const FRONT: bool>(self, token: &mut region::Token<region::Identity<'d>>, value: T) {
        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>(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<'static, 'static, u64>>()];
    let _: [(); 2 * WORD] = [(); mem::size_of::<Permit<'static, 'static, u64>>()];
    let _: [(); 2 * WORD] = [(); mem::size_of::<Option<Permit<'static, 'static, u64>>>()];
};