o3 0.59.0

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

use crate::{
    alloc,
    base::marker::ThreadBound,
    depot::{
        self,
        queue::{
            links,
            resident::{
                self, Bounds, Capacity, Draining, Error, Extent, GrantIndex,
                handoff::Cancel,
                raw::{Entry, Node, View},
            },
            round,
        },
    },
};

/// One resident entry keyed by its exact index and current lane.
#[derive(Clone, Copy)]
pub(super) struct Key {
    index: links::Index,
    pub(super) lane: Position,
}

/// One lane admitted by its owner's immutable extent.
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(transparent)]
pub(super) struct Position(links::Index);

impl Position {
    pub(super) fn new<const N: usize, const I: usize>() -> Self {
        const { assert!(I < N && N <= u32::MAX as usize) };
        Self(links::Index::from(
            num::NonZero::<u32>::MIN.saturating_add(I as u32),
        ))
    }

    pub(super) const fn index(self) -> links::Index {
        self.0
    }

    pub(super) const fn from_pos(position: num::NonZero<u32>) -> Self {
        Self(links::Index::from_pos(position))
    }
}

/// A lane borrowed from the store that admitted its position.
pub struct Lane<'a, T> {
    pub(super) owner: &'a T,
    pub(super) position: Position,
}

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

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

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

/// Stable resident values partitioned among runtime FIFO lanes and an active ring.
pub struct Lanes<W, G, P, L = num::NonZero<usize>> {
    storage: Storage<Entry<W, G>, L>,
    thread: marker::PhantomData<(ThreadBound, P)>,
    round: links::Cycle,
    free: links::Free,
    draining: Draining,
}

impl<W, G, P, L> Lanes<W, G, P, L> {
    pub fn try_new(capacity: usize, lanes: L) -> Result<Self, Error>
    where
        L: Extent,
    {
        let extent = Capacity::new(capacity, lanes)?;
        let capacity = alloc::raw::Shape::len(&extent);
        let storage = alloc::raw::Block::try_from_fn(
            extent,
            (),
            |index| {
                let next = index + 1;
                let next = if capacity > next {
                    next as u32
                } else {
                    u32::MAX
                };
                Node::vacant(Entry::default(), index as u32, next)
            },
            |index| Node::vacant(links::Chain::new(), index as u32, u32::MAX),
        )
        .map_err(Error::Exhausted)?;
        Ok(Self {
            storage,
            thread: marker::PhantomData,
            round: links::Cycle::new(),
            free: links::Free::seeded(capacity),
            draining: Draining::default(),
        })
    }

    pub(super) fn at(&self, position: Position) -> Lane<'_, Self> {
        Lane {
            owner: self,
            position,
        }
    }

    pub(super) fn try_at(&self, index: usize) -> Result<Position, Bounds<num::NonZero<u32>>> {
        let lanes = self.storage.extent().lanes();
        if index >= lanes.get() as usize {
            return Err(Bounds::new(index, lanes));
        }
        // SAFETY: this original u32 lane extent proves the tail bound and excludes END.
        Ok(Position(unsafe { links::Index::new_usize(index) }))
    }

    pub(super) fn pop<const PARK: bool>(&self, lane: Position) -> Option<&Entry<W, G>> {
        let entries = self.storage.as_ref();
        // SAFETY: the admitted lane retains its reciprocal FIFO and exact active ring.
        let vacant = round::Join::pop(unsafe { depot::raw::Proof::new(self.join(lane, entries)) })?;
        let entry = Self::view(entries, vacant.index()).into_ref();
        if PARK {
            vacant.park();
        } else {
            vacant.idle();
        }
        Some(entry)
    }

    pub(super) fn take<const ROTATE: bool>(&self) -> Option<W> {
        let lane = Position(self.round.first()?);
        let entries = self.storage.as_ref();
        // SAFETY: this exact active front proves a reciprocal nonempty lane.
        let vacant = round::Join::active::<ROTATE>(unsafe {
            depot::raw::Proof::new(self.join(lane, entries))
        });
        let entry = Self::view(entries, vacant.index());
        vacant.idle();
        // SAFETY: removing the front transfers its initialized wake exactly once.
        Some(unsafe { entry.take() })
    }

    pub fn has_waiters(&self) -> bool {
        !self.round.is_empty()
    }

    pub fn begin_drain(&self) {
        self.draining.begin();
    }

    pub fn is_draining(&self) -> bool {
        self.draining.is_active()
    }

    pub(super) fn is_empty(&self, lane: Position) -> bool {
        let lanes = self.storage.tail();
        // SAFETY: the admitted lane belongs to this owner's immutable lane extent.
        unsafe { View::new(lanes, lane.index()) }.is_empty()
    }

    fn join<'a>(
        &'a self,
        position: Position,
        entries: &'a [Node<Entry<W, G>>],
    ) -> round::NodeJoin<'a, Entry<W, G>> {
        let lanes = self.storage.tail();
        // SAFETY: this private position was admitted by this owner's immutable extent.
        let lane = unsafe { View::new(lanes, position.index()) };
        round::Join {
            hooks: entries,
            lanes,
            entries: lane.into_ref(),
            active: &self.round,
            index: *lane.key(),
        }
    }

    fn view(entries: &[Node<Entry<W, G>>], index: links::Index) -> View<'_, Entry<W, G>> {
        // SAFETY: callers retain a key or hook admitted by this exact owned store.
        unsafe { View::new(entries, index) }
    }

    /// Takes the next value in drain order and ends draining at quiescence.
    #[must_use = "a drained item remains caller-owned"]
    pub fn drain_next(&self) -> Option<W> {
        self.draining.drain(|| self.take::<false>())
    }
}

impl<W, G, P, const N: usize> Lanes<W, G, P, resident::Fixed<N>> {
    pub fn lane<const I: usize>(&self) -> Lane<'_, Self> {
        self.at(Position::new::<N, I>())
    }
}

impl<'a, W, G, P: GrantIndex, L> Lane<'a, Lanes<W, G, P, L>> {
    pub fn try_keep(
        self,
        slot: &mut resident::Lease<'a, W, G, P, L>,
        value: W,
    ) -> Result<(), resident::Reject<P>>
    where
        W: Copy,
    {
        let index = self.position.index().get();
        if self.owner.is_draining() {
            return Err(resident::Reject::Draining { index });
        }
        let view = match slot.active.as_mut() {
            Some((active, key)) => {
                let same_owner = ptr::eq(*active, self.owner);
                let entries = active.storage.as_ref();
                let view = Lanes::<_, _, P, L>::view(entries, key.index);
                let linked = same_owner && key.index.is_linked(view.hook());
                if !linked && let Some(index) = view.grant_index(index) {
                    return Err(resident::Reject::GrantPending { index });
                }
                if !same_owner {
                    return Err(resident::Reject::Active { index });
                }
                let previous = linked.then_some(key.lane);
                if previous != Some(self.position) {
                    self.push(entries, view, previous);
                    key.lane = self.position;
                }
                view
            }
            None => {
                let entries = self.owner.storage.as_ref();
                // SAFETY: the free list and nodes share this owner's immutable extent.
                let view = unsafe { View::acquire(&self.owner.free, entries) }
                    .ok_or(resident::Reject::Full { index })?;
                self.push(entries, view, None);
                slot.active = Some((
                    self.owner,
                    Key {
                        index: *view.key(),
                        lane: self.position,
                    },
                ));
                view
            }
        };
        view.initialize(value);
        Ok(())
    }

    fn push(
        self,
        entries: &[Node<Entry<W, G>>],
        view: View<'_, Entry<W, G>>,
        previous: Option<Position>,
    ) {
        let target = self.owner.join(self.position, entries);
        let vacant = match previous {
            // SAFETY: the lease retained this resident's exact lane membership.
            Some(lane) => round::Join::remove(unsafe {
                depot::raw::Proof::new((self.owner.join(lane, entries), *view.key()))
            }),
            // SAFETY: a new or rearmed lease owns its detached hook outside every list.
            None => unsafe { view.detached() },
        };
        // SAFETY: both the detached hook and destination belong to this lease's owner.
        round::Join::push(unsafe { depot::raw::Proof::new((target, vacant)) });
    }

    #[must_use = "a taken item remains caller-owned"]
    pub fn take_one(self) -> Option<W> {
        let entry = self.owner.pop::<false>(self.position)?;
        // SAFETY: pop detached one initialized wake; its registration retains the slot.
        Some(unsafe { entry.take() })
    }
}

impl<W, G, L> Lanes<W, G, usize, L> {
    pub(super) fn claim(&self, key: Key) -> Option<&Entry<W, G>> {
        let view = Self::view(self.storage.as_ref(), key.index);
        let vacant = view.unpark()?;
        self.free.recycle(vacant);
        Some(view.into_ref())
    }
}

impl<W, G, P: GrantIndex, L> Lanes<W, G, P, L> {
    pub(super) fn remove(&self, key: Key) -> Cancel<&Entry<W, G>> {
        let entries = self.storage.as_ref();
        let view = Self::view(entries, key.index);
        let (vacant, result) = if key.index.is_linked(view.hook()) {
            // SAFETY: the lease retains this exact resident's current lane membership.
            let vacant = round::Join::remove(unsafe {
                depot::raw::Proof::new((self.join(key.lane, entries), key.index))
            });
            (vacant, Cancel::Wake)
        } else {
            let result = if view.grant_index::<P>(key.lane.index().get()).is_some() {
                Cancel::Grant(&**view.into_ref())
            } else {
                Cancel::Empty
            };
            // SAFETY: the unlinked lease owns this hook outside the FIFO and free list.
            (unsafe { view.detached() }, result)
        };
        self.free.recycle(vacant);
        result
    }
}

const _: () = {
    assert!(mem::size_of::<Storage<(), num::NonZero<usize>>>() == 24);
    assert!(mem::size_of::<resident::fifo::Fifo<()>>() == 5 * mem::size_of::<usize>());
    assert!(
        mem::size_of::<Option<resident::fifo::Fifo<()>>>()
            == mem::size_of::<resident::fifo::Fifo<()>>()
    );
};