o3 0.59.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(in crate::depot) 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
    /// `index` is exclusively held outside all chains in this exact store.
    pub(in crate::depot) unsafe fn link_back<H: crate::depot::raw::Hooks + ?Sized>(
        &self,
        hooks: &H,
        index: links::Index,
    ) {
        // SAFETY: the caller retains this vacant hook and the same reciprocal chain.
        let vacant = unsafe { links::Detached::new(hooks.hook_raw(index), index) };
        unsafe { self.push(hooks, vacant) };
    }

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

    /// # Safety
    /// This chain's current tail is reciprocal in the retained store.
    unsafe fn tail_edge<'a, H: raw::Hooks + ?Sized>(
        &'a self,
        hooks: &'a H,
    ) -> (u32, &'a cell::Cell<u32>) {
        let last = self.tail.get();
        let edge = links::Index::decode(last)
            .map_or(&self.head, |index| &unsafe { hooks.hook_raw(index) }.next);
        (last, edge)
    }

    /// # 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, H: crate::depot::raw::Hooks + ?Sized>(
        &'a self,
        hooks: &'a H,
        index: links::Index,
    ) -> links::Detached<'a> {
        let hook = unsafe { hooks.hook_raw(index) };
        unsafe { self.detach_hook::<false, _>(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, H: raw::Hooks + ?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, _>(hooks, index, hook) }
    }

    /// # Safety
    /// The hook is linked here at this index; FRONT also proves it is the head.
    #[inline]
    pub(in crate::depot) unsafe fn detach_hook<'a, const FRONT: bool, H: raw::Hooks + ?Sized>(
        &'a self,
        hooks: &'a H,
        index: links::Index,
        hook: &'a links::Hook,
    ) -> (links::Detached<'a>, bool) {
        let before = if FRONT {
            links::Index::END
        } else {
            hook.previous.get()
        };
        let after = hook.next.get();
        let (left, right) = unsafe { self.neighbors(hooks, before, after) };
        let count = C::storage(&self.count);
        left.set(after);
        right.set(before);
        if let Some(count) = count {
            count.set(count.get() - 1);
        }
        // SAFETY: the two reciprocal neighbors now bypass this exact hook.
        (
            unsafe { links::Detached::new(hook, index) },
            after == links::Index::END,
        )
    }

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

    /// # Safety
    /// The index identifies this nonempty chain's front in the same reciprocal store.
    pub(in crate::depot) unsafe fn rotate_front<H: raw::Hooks + ?Sized>(
        &self,
        hooks: &H,
        index: links::Index,
    ) {
        let hook = unsafe { hooks.hook_raw(index) };
        let Some(next) = hook.next_index() else {
            return;
        };
        let successor = unsafe { hooks.hook_raw(next) };
        // 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;
        self.head.set(next.raw());
        successor.previous.set(links::Index::END);
        // SAFETY: only this front was detached; the same chain retains its cardinality.
        unsafe { self.attach(links::Detached::new(hook, index), (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(in crate::depot) 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);
    }

    /// # Safety
    /// The occupied slot and both of its original neighbors still bound the withdrawn gap.
    pub(in crate::depot) unsafe fn restore<H: raw::Hooks + ?Sized>(
        &self,
        hooks: &H,
        index: links::Index,
    ) {
        let hook = unsafe { hooks.hook_raw(index) };
        let (left, right) = unsafe { self.neighbors(hooks, hook.previous.get(), hook.next.get()) };
        left.set(index.raw());
        right.set(index.raw());
    }

    /// # Safety
    /// `index` is not the target tail and every involved edge is reciprocal.
    pub(in crate::depot) unsafe fn move_back<H: crate::depot::raw::Hooks + ?Sized>(
        &self,
        target: &Self,
        hooks: &H,
        index: links::Index,
    ) {
        // SAFETY: removing this member preserves the target tail, even in the same chain.
        let end = unsafe { target.tail_edge(hooks) };
        let vacant = unsafe { self.unlink(hooks, index) };
        unsafe { target.attach(vacant, 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>());