o3 0.61.0

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

use crate::depot::{queue::links, raw};
/// Allocation-free indexed FIFO with an optional cardinality policy.
#[repr(C)]
#[derive(Debug)]
pub struct Chain<C: Copy = ()> {
    head: cell::Cell<u32>,
    tail: cell::Cell<u32>,
    count: cell::Cell<C>,
}

impl<C: crate::depot::raw::ChainCount> Default for Chain<C> {
    fn default() -> Self {
        Self::new()
    }
}

impl<C: crate::depot::raw::ChainCount> Chain<C> {
    pub const fn new() -> Self {
        Self {
            head: cell::Cell::new(links::Index::END),
            tail: cell::Cell::new(links::Index::END),
            count: cell::Cell::new(C::EMPTY),
        }
    }

    pub fn first(&self) -> Option<links::Index> {
        links::Index::decode(self.head.get())
    }

    pub fn front(&self) -> Option<usize> {
        self.first().map(links::Index::get)
    }

    pub fn last(&self) -> Option<links::Index> {
        links::Index::decode(self.tail.get())
    }

    /// # Safety
    /// This exact chain is non-empty for the immediate operation.
    pub unsafe fn front_key(&self) -> links::Index {
        unsafe { links::Index::new_raw(self.head.get()) }
    }

    pub fn is_empty(&self) -> bool {
        self.head.get() == links::Index::END
    }

    /// # Safety
    /// `hook` is exclusively held at `index` outside all chains in this exact store.
    pub unsafe fn link_back<const PLANE: usize, H: crate::depot::raw::Hooks<PLANE> + ?Sized>(
        &self,
        hooks: &H,
        index: links::Index,
        hook: &links::Hook,
    ) {
        // SAFETY: the caller retains this exact hook, index and reciprocal chain.
        let vacant = unsafe { links::Detached::new(hook, index) };
        unsafe { self.push::<PLANE, _>(hooks, vacant) };
    }

    /// # Safety
    /// The detached hook and this chain's reciprocal tail belong to the same store.
    pub(in crate::depot) unsafe fn push<const PLANE: usize, H: raw::Hooks<PLANE> + ?Sized>(
        &self,
        hooks: &H,
        vacant: links::Detached<'_>,
    ) -> bool {
        let last = self.last();
        let edge = unsafe { self.next_edge::<PLANE, _>(hooks, last) };
        let count = C::storage(&self.count);
        unsafe { self.attach(vacant, (links::Index::encode(last), edge)) };
        if let Some(count) = count {
            count.set(count.get() + 1);
        }
        last.is_none()
    }

    /// # Safety
    /// Any predecessor belongs to this chain in the retained store.
    unsafe fn next_edge<'a, const PLANE: usize, H: raw::Hooks<PLANE> + ?Sized>(
        &'a self,
        hooks: &'a H,
        before: Option<links::Index>,
    ) -> &'a cell::Cell<u32> {
        before.map_or(&self.head, |i| &unsafe { hooks.hook_raw(i) }.next)
    }

    /// # Safety
    /// The detached hook belongs to this store and the retained edge is this chain's tail or empty head.
    unsafe fn attach(&self, vacant: links::Detached<'_>, (last, edge): (u32, &cell::Cell<u32>)) {
        let (hook, index) = vacant.into_parts();
        edge.set(index.raw());
        hook.previous.set(last);
        hook.next.set(links::Index::END);
        self.tail.set(index.raw());
    }

    /// # Safety
    /// `index` is linked in this exact chain and store.
    pub(in crate::depot) unsafe fn unlink<
        'a,
        const PLANE: usize,
        H: crate::depot::raw::Hooks<PLANE> + ?Sized,
    >(
        &'a self,
        hooks: &'a H,
        index: links::Index,
    ) -> links::Detached<'a> {
        let hook = unsafe { hooks.hook_raw(index) };
        unsafe { self.detach_hook::<false, PLANE, _>(hooks, index, hook) }.0
    }

    /// # Safety
    /// The index is this chain's live front in this exact store.
    pub(in crate::depot) unsafe fn pop<'a, const PLANE: usize, H: raw::Hooks<PLANE> + ?Sized>(
        &'a self,
        hooks: &'a H,
        index: links::Index,
    ) -> (links::Detached<'a>, bool) {
        let hook = unsafe { hooks.hook_raw(index) };
        unsafe { self.detach_hook::<true, PLANE, _>(hooks, index, hook) }
    }

    /// # Safety
    /// The hook is linked here at this index; FRONT also proves it is the head.
    #[inline]
    pub unsafe fn detach_hook<
        'a,
        const FRONT: bool,
        const PLANE: usize,
        H: raw::Hooks<PLANE> + ?Sized,
    >(
        &'a self,
        hooks: &'a H,
        index: links::Index,
        hook: &'a links::Hook,
    ) -> (links::Detached<'a>, bool) {
        let after = hook.next_index();
        let vacant = unsafe { self.bypass::<PLANE, _>(hooks, index, hook, FRONT, after) };
        if let Some(count) = C::storage(&self.count) {
            count.set(count.get() - 1);
        }
        (vacant, after.is_none())
    }

    /// # Safety
    /// The linked hook is at `index`, `after` is its successor, and `front` may be true only at the head.
    unsafe fn bypass<'a, const PLANE: usize, H: raw::Hooks<PLANE> + ?Sized>(
        &self,
        hooks: &H,
        index: links::Index,
        hook: &'a links::Hook,
        front: bool,
        after: Option<links::Index>,
    ) -> links::Detached<'a> {
        let before = if front { None } else { hook.prev_index() };
        let (left, right) = unsafe { self.neighbors::<PLANE, _>(hooks, before, after) };
        left.set(links::Index::encode(after));
        right.set(links::Index::encode(before));
        unsafe { links::Detached::new(hook, index) }
    }

    /// # Safety
    /// Both words identify retained neighbors of the same slot, or this chain's endpoints.
    unsafe fn neighbors<'a, const PLANE: usize, H: raw::Hooks<PLANE> + ?Sized>(
        &'a self,
        hooks: &'a H,
        before: Option<links::Index>,
        after: Option<links::Index>,
    ) -> (&'a cell::Cell<u32>, &'a cell::Cell<u32>) {
        let left = unsafe { self.next_edge::<PLANE, _>(hooks, before) };
        let right = after.map_or(&self.tail, |i| &unsafe { hooks.hook_raw(i) }.previous);
        (left, right)
    }

    /// # Safety
    /// This hook is linked at `index` in this chain; `front` may be true only at its head.
    pub unsafe fn rotate<const PLANE: usize, H: raw::Hooks<PLANE> + ?Sized>(
        &self,
        hooks: &H,
        index: links::Index,
        hook: &links::Hook,
        front: bool,
    ) {
        let Some(next) = hook.next_index() else {
            return;
        };
        // SAFETY: the successor proves a distinct live tail in this nonempty chain.
        let last = self.tail.get();
        let edge = &unsafe { hooks.hook_raw(links::Index::new_raw(last)) }.next;
        let vacant = unsafe { self.bypass::<PLANE, _>(hooks, index, hook, front, Some(next)) };
        unsafe { self.attach(vacant, (last, edge)) };
    }
}

impl Chain {
    pub(in crate::depot) fn set_first(&self, index: Option<links::Index>) {
        self.head.set(links::Index::encode(index));
    }

    pub(in crate::depot) fn set_last(&self, index: Option<links::Index>) {
        self.tail.set(links::Index::encode(index));
    }

    /// # Safety
    /// The distinct chains own these endpoints. When the destination is nonempty,
    /// the pair retains the source head hook and the destination tail's index and hook.
    pub unsafe fn splice(
        &self,
        source: &Self,
        head: links::Index,
        join: Option<(&links::Hook, links::Index, &links::Hook)>,
    ) {
        if let Some((first, last, back)) = join {
            back.next.set(head.raw());
            first.previous.set(last.raw());
        } else {
            self.head.set(head.raw());
        }
        self.tail.set(source.tail.get());
        source.head.set(links::Index::END);
        source.tail.set(links::Index::END);
    }
}

impl Chain<u32> {
    pub fn len(&self) -> usize {
        self.count.get() as usize
    }
}

const _: () = assert!(mem::size_of::<Chain>() == 2 * mem::size_of::<u32>());