o3 0.62.0

shared-nothing primitives
Documentation
//! Fixed-domain resident values scheduled through an insertion-ordered round-robin
//! lane ring.

use std::{convert::Infallible, marker, mem, num};

use crate::{
    alloc,
    depot::{self, capacity, queue::links},
};
pub(super) use grant::Grant;
pub use lanes::Lanes;

pub mod fifo;
mod grant;
pub mod handoff;
mod lanes;
pub mod raw;

/// The destination lane and exact cause of a rejected registration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[must_use = "a rejected registration must be handled"]
pub enum Reject<P = Infallible> {
    Active { index: usize },
    Draining { index: usize },
    Full { index: usize },
    GrantPending { index: P },
}

/// A lane extent fixed by the storage constructor.
#[derive(Clone, Copy)]
pub struct Fixed<const N: usize>;

/// The immutable lane extent retained by its storage type.
pub trait Extent {
    fn count(self) -> num::NonZero<usize>;
}

impl Extent for num::NonZero<usize> {
    fn count(self) -> num::NonZero<usize> {
        self
    }
}

impl<const N: usize> Extent for Fixed<N> {
    fn count(self) -> num::NonZero<usize> {
        const { assert!(N > 0 && N <= u32::MAX as usize) };
        num::NonZero::<usize>::MIN.saturating_add(N - 1)
    }
}

/// Exact failed indexed lookup against one resident extent.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Bounds<N> {
    pub index: usize,
    pub len: N,
}

impl<N> Bounds<N> {
    pub const fn new(index: usize, len: N) -> Self {
        Self { index, len }
    }
}

/// Exact failure to build one resident lane store.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Error {
    Capacity(capacity::Error),
    Exhausted(alloc::Exhausted),
    Overflow(alloc::Overflow),
}

impl From<alloc::Error> for Error {
    fn from(error: alloc::Error) -> Self {
        match error {
            alloc::Error::Exhausted => Self::Exhausted(alloc::Exhausted),
            alloc::Error::Overflow => Self::Overflow(alloc::Overflow),
        }
    }
}

#[derive(Debug)]
#[repr(C)]
pub(in crate::depot::queue) struct Capacity<T, L = num::NonZero<usize>, E = ()> {
    count: capacity::Count,
    lanes: num::NonZero<u32>,
    ownership: marker::PhantomData<(
        depot::raw::Node<T>,
        depot::raw::Node<links::raw::Chain>,
        L,
        E,
    )>,
}

impl<T, L> Capacity<T, L> {
    fn new(capacity: usize, lanes: L) -> Result<Self, Error>
    where
        L: Extent,
    {
        let count = capacity::Count::try_from(capacity).map_err(Error::Capacity)?;
        let lanes = capacity::Count::try_nonzero(lanes.count()).map_err(Error::Capacity)?;
        Self::try_layout(count, lanes).map_err(Error::Overflow)
    }
}

impl<T, L, E> Capacity<T, L, E> {
    pub(in crate::depot::queue) fn try_layout(
        count: capacity::Count,
        lanes: num::NonZero<u32>,
    ) -> Result<Self, alloc::Overflow> {
        alloc::raw::Bundle::try_layout::<Self>(count.get(), lanes.get() as usize)?;
        Ok(Self {
            count,
            lanes,
            ownership: marker::PhantomData,
        })
    }
}

type Storage<T, L> = alloc::raw::Block<Capacity<T, L>, (), (), depot::raw::Node<T>>;

/// A lane borrowed from the store that admitted its position.
pub struct Lane<'a, T> {
    owner: &'a T,
    index: links::Index,
}

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

impl<T> Copy for Lane<'_, T> {}

impl<'a, T> Lane<'a, T> {
    fn new(owner: &'a T, index: links::Index) -> Self {
        Self { owner, index }
    }
}

impl<W, L, G, P> Lane<'_, Lanes<W, L, G, P>> {
    #[must_use = "a taken item remains caller-owned"]
    pub fn take_one(self) -> Option<W> {
        raw::Entry::take_front(self)
    }
}

impl<'a, W, L, G, P: Grant> Lane<'a, Lanes<W, L, G, P>> {
    pub fn try_keep(self, slot: &mut Lease<'a, W, L, G, P>, value: W) -> Result<(), Reject<P>>
    where
        W: Copy,
    {
        let index = self.index.get();
        if self.owner.is_draining() {
            return Err(Reject::Draining { index });
        }
        raw::Binding::keep(&mut slot.active, self, value)
    }
}

impl<W, L, G> Lane<'_, Lanes<W, L, G, usize>> {
    pub fn offer_one(self, grant: G) -> handoff::Offer<W, G> {
        if self.owner.is_draining() {
            return handoff::Offer::Draining(grant);
        }
        raw::Entry::offer(self, grant)
    }

    pub fn is_empty(self) -> bool {
        raw::View::join(self).entries.is_empty()
    }
}

/// Two-word ownership of one slot in an exactly borrowed target.
/// The invariant reference retains the original registration lifetime and !Sync.
#[repr(transparent)]
pub struct Lease<'a, W, L = num::NonZero<usize>, G = Infallible, P: Grant = Infallible> {
    active: Option<raw::Binding<'a, Lanes<W, L, G, P>>>,
}

impl<'a, W, L, G, P: Grant> Lease<'a, W, L, G, P> {
    pub const fn new() -> Self {
        Self { active: None }
    }
}

impl<W, L, G, P: Grant> Default for Lease<'_, W, L, G, P> {
    fn default() -> Self {
        Self::new()
    }
}

impl<W, L, G, P: Grant> Drop for Lease<'_, W, L, G, P> {
    fn drop(&mut self) {
        if let Some(binding) = &self.active {
            drop(binding.remove());
        }
    }
}

impl<W, L> Lease<'_, W, L> {
    pub fn is_active(&self) -> bool {
        self.active.is_some()
    }

    /// Retires this slot; a taken value hands off to the next value in its lane.
    /// Draining retires without taking a successor.
    pub fn cancel(&mut self) -> Option<W> {
        let binding = self.active.take()?;
        let lane = binding.lane();
        if matches!(binding.remove(), handoff::Cancel::Empty) && !lane.owner.is_draining() {
            return lane.take_one();
        }
        None
    }
}

impl<W, L, G> Lease<'_, W, L, G, usize> {
    /// Cancels this registration and returns any delivered grant.
    pub fn cancel(&mut self) -> handoff::Cancel<G> {
        let Some(binding) = self.active.take() else {
            return handoff::Cancel::Empty;
        };
        binding.remove()
    }

    pub fn take_grant(&mut self) -> handoff::Grant<G> {
        raw::Binding::take_grant(&mut self.active)
    }
}

const _: () = {
    assert!(mem::size_of::<Bounds<usize>>() == 2 * mem::size_of::<usize>());
    assert!(mem::size_of::<Error>() == 2 * mem::size_of::<usize>());
    assert!(mem::size_of::<Storage<(), num::NonZero<usize>>>() == 24);
    assert!(mem::size_of::<Lanes<()>>() == 5 * mem::size_of::<usize>());
    assert!(mem::size_of::<Option<Lanes<()>>>() == mem::size_of::<Lanes<()>>());
    assert!(mem::size_of::<Lease<'static, usize>>() == 2 * mem::size_of::<usize>());
    assert!(mem::align_of::<Lease<'static, usize>>() == mem::align_of::<usize>());
    assert!(mem::size_of::<Lanes<usize, fifo::Scope<'static>>>() == mem::size_of::<Lanes<usize>>());
    assert!(
        mem::size_of::<Lease<'static, usize, Fixed<2>, usize, usize>>()
            == 2 * mem::size_of::<usize>()
    );
    assert!(
        mem::align_of::<Lease<'static, usize, Fixed<2>, usize, usize>>()
            == mem::align_of::<usize>()
    );
};