o3 0.59.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, raw::Balance},
};

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 _: () = assert!(std::mem::size_of::<Plan>() == 2 * std::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 }
    }

    fn balance(self) -> Balance<1, usize> {
        Balance::new(
            [self.held().get().get()],
            [self.owner.inner.store.available()],
        )
    }

    fn set_balance(self, balance: Balance<1, usize>) {
        let ([held], [shared]) = balance.into_parts();
        // Both admitted counts are bounded by this allocation's u32 capacity.
        self.held().set(capacity::Count::new(held as u32));
        self.owner.inner.store.available.set(shared as u32);
    }

    pub fn reserve(self) -> Result<Permit<'a, 'd, T, S>, fair::Cause<usize>> {
        self.set_balance(self.balance().try_acquire([1], [1])?);
        Ok(Permit { binding: self })
    }

    pub fn take_front(
        self,
        token: &mut region::Token<region::Identity<'d>>,
    ) -> Option<(T, Permit<'a, 'd, T, S>)> {
        self.front_entry(token).map(|take| 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<impl FnOnce() -> (T, Permit<'a, 'd, T, S>) + 't>
    where
        'a: 't,
    {
        let index = self.lane_mut(token).slot.queue.links.head()?;
        Some(move || {
            let lane = self.lane_mut(token);
            // SAFETY: the exclusive token retained this unchanged head. No lane
            // reference survived admission, so independent ledger changes remain valid.
            let value = unsafe { lane.slot.queue.pop::<_, false>(lane.store, index) };
            (value, Permit { binding: self })
        })
    }
}

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;
        // SAFETY: the unpublished permit owns one held unit in its issuing lane.
        binding.set_balance(unsafe { binding.balance().release_raw([1], [1]) });
    }
}

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

    assert!(mem::size_of::<State<u64>>() == 2 * WORD);
    assert!(mem::size_of::<Binding<'static, 'static, u64>>() == 2 * WORD);
    assert!(mem::size_of::<Permit<'static, 'static, u64>>() == 2 * WORD);
    assert!(mem::size_of::<Option<Permit<'static, 'static, u64>>>() == 2 * WORD);
};