o3 0.62.0

shared-nothing primitives
Documentation
use std::{cell::Cell, mem, pin::Pin, ptr::NonNull};

use crate::depot::{
    self,
    queue::{links, tagged},
};

type Pointer<T> = Option<NonNull<depot::raw::Entry<T>>>;

/// The reciprocal links of an intrusive FIFO, without length tracking.
#[repr(C)]
pub struct Links<T> {
    previous: Cell<Pointer<T>>,
    next: Cell<Pointer<T>>,
}

impl<T> Default for Links<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Links<T> {
    pub const fn new() -> Self {
        Self {
            previous: Cell::new(None),
            next: Cell::new(None),
        }
    }

    pub fn front(&self) -> Option<Pin<&depot::raw::Entry<T>>> {
        // SAFETY: linked entries remain pinned and live through removal.
        Some(unsafe { Pin::new_unchecked(self.next.get()?.as_ref()) })
    }

    pub fn is_empty(&self) -> bool {
        self.next.get().is_none()
    }

    unsafe fn neighbor(&self, item: Pointer<T>) -> &Self {
        match item {
            Some(node) => &unsafe { node.as_ref() }.links,
            None => self,
        }
    }

    /// Links one pinned entry at the back.
    /// # Safety
    /// The entry is unlinked and remains pinned and live through removal and outstanding loans.
    pub unsafe fn push_back(&self, entry: Pin<&depot::raw::Entry<T>>) {
        let node = entry.get_ref();
        let item = Some(NonNull::from(node));
        let previous = self.previous.get();
        node.links.previous.set(previous);
        node.links.next.set(None);
        unsafe { self.neighbor(previous) }.next.set(item);
        self.previous.set(item);
    }

    /// Unlinks without moving the value; insertion overwrites the detached links.
    /// # Safety
    /// The pinned entry is currently linked in this exact list.
    pub unsafe fn remove(&self, entry: Pin<&depot::raw::Entry<T>>) {
        let previous = entry.links.previous.get();
        let next = entry.links.next.get();
        unsafe { self.neighbor(previous) }.next.set(next);
        unsafe { self.neighbor(next) }.previous.set(previous);
    }
}

const _: () = assert!(mem::size_of::<Links<usize>>() == 2 * mem::size_of::<usize>());

/// Borrowed hook cells retain their source's word representation.
pub(in crate::depot) struct EndpointHook<'a> {
    pub(in crate::depot) previous: &'a Cell<u32>,
    pub(in crate::depot) next: &'a Cell<u32>,
}

impl<'a> From<&'a links::Hook> for EndpointHook<'a> {
    fn from(hook: &'a links::Hook) -> Self {
        Self {
            previous: &hook.previous,
            next: &hook.next,
        }
    }
}

impl<'a> EndpointHook<'a> {
    /// # Safety
    /// The hook is exclusively linked in this head's reciprocal lane.
    /// Only `Index::END` is an endpoint; other words resolve live nodes without topology changes.
    pub(in crate::depot) unsafe fn unlink<
        const PLANE: usize,
        H: tagged::raw::Head,
        S: crate::depot::raw::Hooks<PLANE> + ?Sized,
    >(
        self,
        head: &'a H,
        hooks: &S,
    ) {
        let before = self.previous.get();
        let after = self.next.get();
        let neighbor = |word| match links::Index::decode(word) {
            Some(index) => Neighbor::node(word, unsafe { hooks.hook_raw(index) }.into()),
            None => Neighbor::head(word, head),
        };
        // SAFETY: both original neighbors remain live through reciprocal repair.
        unsafe { Self::detach(neighbor(before), neighbor(after)) };
    }
}

/// One observed link and its resolved neighbor under the original owner loan.
pub(in crate::depot) struct Neighbor<'a, H> {
    link: u32,
    target: Target<'a, H>,
}

enum Target<'a, H> {
    Node(EndpointHook<'a>),
    Head(&'a H),
}

impl<'a, H> Neighbor<'a, H> {
    pub(in crate::depot) fn node(link: u32, hook: EndpointHook<'a>) -> Self {
        Self {
            link,
            target: Target::Node(hook),
        }
    }

    pub(in crate::depot) fn head(link: u32, head: &'a H) -> Self {
        Self {
            link,
            target: Target::Head(head),
        }
    }
}

impl EndpointHook<'_> {
    /// # Safety
    /// The hook is exclusively vacant at `index`; head, endpoint and the
    /// optional adjacent node retain the same reciprocal lane and owner.
    pub(in crate::depot) unsafe fn push<const FRONT: bool, H: tagged::raw::Head>(
        self,
        head: &H,
        index: links::Index,
        endpoint: u32,
        adjacent: Option<(links::Index, EndpointHook<'_>)>,
    ) {
        const { assert!(FRONT || H::TAIL) };
        let adjacent = adjacent.map(|(adjacent, hook)| {
            let neighbor = if FRONT { hook.previous } else { hook.next };
            neighbor.set(index.raw());
            adjacent.raw()
        });
        let word = adjacent.unwrap_or(endpoint);
        self.previous.set(if FRONT { endpoint } else { word });
        self.next.set(if FRONT { word } else { endpoint });
        if adjacent.is_none() {
            // SAFETY: the empty lane receives this exact first and last node.
            if FRONT {
                if let Some(tail) = head.tail() {
                    tail.set_last(Some(index));
                }
            } else {
                unsafe { head.set_first(Some(index)) };
            }
        }
        // SAFETY: the retained lane's adjacent edge was repaired above.
        if FRONT {
            unsafe { head.set_first(Some(index)) };
        } else if let Some(tail) = head.tail() {
            tail.set_last(Some(index));
        }
    }

    /// # Safety
    /// Both neighbors resolve one exclusive member's unchanged reciprocal
    /// links in the same owner and lane.
    pub(in crate::depot) unsafe fn detach<H: tagged::raw::Head>(
        previous: Neighbor<'_, H>,
        next: Neighbor<'_, H>,
    ) {
        let before = previous.link;
        let after = next.link;
        match previous.target {
            Target::Node(hook) => hook.next.set(after),
            // SAFETY: after the head is a live node or the same endpoint.
            Target::Head(head) => unsafe {
                head.set_first((after != before).then(|| links::Index::new_raw(after)))
            },
        }
        match next.target {
            Target::Node(hook) => hook.previous.set(before),
            // SAFETY: before the tail is a live node or the same endpoint.
            Target::Head(head) => {
                if let Some(tail) = head.tail() {
                    tail.set_last(
                        (before != after).then(|| unsafe { links::Index::new_raw(before) }),
                    );
                }
            }
        }
    }

    /// # Safety
    /// The hook at `index` is exclusively detached from its original lane.
    pub(in crate::depot) unsafe fn clear(self, index: links::Index) {
        self.previous.set(index.raw());
        self.next.set(links::Index::END);
    }
}