o3 0.62.0

shared-nothing primitives
Documentation
//! Unsafe boundary for borrowed resident nodes and their stable hooks.

use std::{cell, convert::Infallible, marker::PhantomData, mem, num, ops, ptr};

use crate::{
    alloc,
    depot::{
        self, capacity,
        queue::{
            links,
            resident::{Bounds, Capacity, Grant, Lane, Lanes, Reject, handoff},
            round,
        },
    },
};

// SAFETY: `try_layout` admits both extents against this exact Bundle layout once;
// the retained count and lane count remain unchanged through allocation.
unsafe impl<T, L, E> alloc::raw::Shape for Capacity<T, L, E> {
    type Root = depot::raw::Node<T>;
    type Tail = depot::raw::Node<links::raw::Chain>;
    type Extra = E;
    type Last = ();

    fn len(&self) -> usize {
        self.count.get()
    }

    fn tail_len(&self) -> usize {
        self.lanes.get() as usize
    }
}

/// One resident entry borrowed together with its exact compact identity.
pub struct View<'a, T> {
    item: &'a depot::raw::Node<T>,
    key: links::Index,
}

impl<T> ops::Deref for View<'_, T> {
    type Target = depot::raw::Node<T>;

    fn deref(&self) -> &Self::Target {
        self.item
    }
}

impl<'a, T> View<'a, T> {
    /// # Safety
    /// `key` resolves a node in this exact slice.
    pub unsafe fn new(entries: &'a [depot::raw::Node<T>], key: links::Index) -> Self {
        let item = unsafe { entries.get_unchecked(key.get()) };
        Self { item, key }
    }

    /// # Safety
    /// The free chain belongs to these entries. Publish the returned hook directly
    /// to a list that overwrites both links before either is observed.
    pub unsafe fn reserve_back(
        free: &links::Free,
        entries: &'a [depot::raw::Node<T>],
    ) -> Option<Self> {
        let view = unsafe { Self::new(entries, free.front()?) };
        unsafe { free.acquire_hook(view.hook()) };
        Some(view)
    }

    pub fn key(&self) -> &links::Index {
        &self.key
    }

    pub fn into_ref(self) -> &'a depot::raw::Node<T> {
        self.item
    }

    /// An active lease points to itself only while its grant is parked.
    fn is_parked(&self) -> bool {
        self.item.hook().next.get() == self.key.raw()
    }

    /// # Safety
    /// This view owns its exact detached hook outside every list.
    pub(super) unsafe fn detached(&self) -> links::Detached<'a> {
        unsafe { links::Detached::new(self.item.hook(), self.key) }
    }
}

const _: () = {
    assert!(mem::size_of::<View<'static, u64>>() == 2 * mem::size_of::<usize>());
    assert!(mem::size_of::<Option<View<'static, u64>>>() == 2 * mem::size_of::<usize>());
};

union Payload<W, G> {
    value: mem::ManuallyDrop<W>,
    grant: mem::ManuallyDrop<G>,
}

/// Storage for the value or grant selected by the resident node's existing links.
pub struct Entry<W, G = Infallible> {
    payload: cell::Cell<mem::MaybeUninit<Payload<W, G>>>,
}

impl<W, G> Default for Entry<W, G> {
    fn default() -> Self {
        Self {
            payload: cell::Cell::new(mem::MaybeUninit::uninit()),
        }
    }
}

impl<W, G> Entry<W, G> {
    fn payload(&self) -> *mut Payload<W, G> {
        self.payload.as_ptr().cast()
    }

    pub fn initialize(&self, value: W)
    where
        W: Copy,
    {
        // SAFETY: the cell permits writing this field without reading its previous contents.
        unsafe { (&raw mut (*self.payload()).value).write(mem::ManuallyDrop::new(value)) };
    }

    /// # Safety
    /// The caller owns this initialized value and consumes it only once.
    pub unsafe fn take(&self) -> W {
        unsafe { mem::ManuallyDrop::take(&mut (*self.payload()).value) }
    }

    /// # Safety
    /// The caller removed the parked grant and owns its single transfer.
    pub(super) unsafe fn take_grant(&self) -> G {
        unsafe { mem::ManuallyDrop::take(&mut (*self.payload()).grant) }
    }
}

type Joined<'a, W, G> =
    round::raw::Join<'a, [depot::raw::Node<Entry<W, G>>], [depot::raw::Node<links::raw::Chain>]>;

impl<'a> View<'a, links::raw::Chain> {
    pub(super) fn try_index<W, L, G, P>(
        owner: &Lanes<W, L, G, P>,
        index: usize,
    ) -> Result<links::Index, Bounds<num::NonZero<u32>>> {
        let lanes = owner.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(unsafe { links::Index::new_usize(index) })
    }

    /// Borrows a lane in this exact owner's immutable lane extent.
    pub fn lane<W>(
        source: depot::raw::Proof<(&'a Lanes<W>, usize), capacity::Physical>,
    ) -> Lane<'a, Lanes<W>> {
        let (owner, index) = source.into_inner();
        // SAFETY: the physical lane proof retains this owner's admitted u32 extent.
        Lane::new(owner, unsafe { links::Index::new_usize(index) })
    }

    pub(super) fn join<W, L, G, P>(lane: Lane<'a, Lanes<W, L, G, P>>) -> Joined<'a, W, G> {
        let lanes = lane.owner.storage.tail();
        // SAFETY: the private lane belongs to this owner's immutable extent.
        let entries = unsafe { Self::new(lanes, lane.index) }.into_ref();
        round::raw::Join {
            hooks: lane.owner.storage.as_ref(),
            lanes,
            entries,
            active: &lane.owner.round,
            index: lane.index,
        }
    }
}

impl<W, G> Entry<W, G> {
    /// # Safety
    /// The index is the front of this lane. ACTIVE also proves the active ring front.
    unsafe fn detach<const ACTIVE: bool, const ROTATE: bool, const PARK: bool>(
        lane: Joined<'_, W, G>,
        index: links::Index,
    ) -> &Self {
        // SAFETY: the FIFO front owns an initialized wake at this exact node.
        let node = unsafe { View::new(lane.hooks, index) }.into_ref();
        let vacant = unsafe { lane.detach::<true, ACTIVE, ROTATE>(index, node.hook()) };
        if PARK {
            vacant.park();
        } else {
            vacant.idle();
        }
        node
    }

    pub(super) fn take_active<const ROTATE: bool, L, P>(owner: &Lanes<W, L, G, P>) -> Option<W> {
        let lane = View::join(Lane::new(owner, owner.round.first()?));
        // SAFETY: an active lane is nonempty and remains the ring front through removal.
        let index = unsafe { lane.entries.front_key() };
        Some(unsafe { Self::detach::<true, ROTATE, false>(lane, index).take() })
    }

    fn pop<const PARK: bool, L, P>(lane: Lane<'_, Lanes<W, L, G, P>>) -> Option<&Self> {
        let lane = View::join(lane);
        let index = lane.entries.first()?;
        // SAFETY: this exact lane supplied its initialized front.
        Some(unsafe { Self::detach::<false, false, PARK>(lane, index) })
    }

    pub(super) fn take_front<L, P>(lane: Lane<'_, Lanes<W, L, G, P>>) -> Option<W> {
        // SAFETY: removal hands off this wake once.
        Some(unsafe { Self::pop::<false, _, _>(lane)?.take() })
    }

    pub(super) fn offer<L>(
        lane: Lane<'_, Lanes<W, L, G, usize>>,
        grant: G,
    ) -> handoff::Offer<W, G> {
        let Some(entry) = Self::pop::<true, _, _>(lane) else {
            return handoff::Offer::Empty(grant);
        };
        // SAFETY: install the grant into the parked slot before its lease can observe it.
        let value = unsafe { entry.take() };
        unsafe { (&raw mut (*entry.payload()).grant).write(mem::ManuallyDrop::new(grant)) };
        handoff::Offer::Value(value)
    }
}

pub(super) struct Binding<'a, T> {
    owner: &'a T,
    index: links::Index,
    lane: links::Index,
    target: PhantomData<cell::Cell<&'a T>>,
}

impl<'a, W, L, G, P: Grant> Binding<'a, Lanes<W, L, G, P>> {
    pub(super) fn lane(&self) -> Lane<'a, Lanes<W, L, G, P>> {
        Lane::new(self.owner, self.lane)
    }

    fn view(&self) -> View<'a, Entry<W, G>> {
        // SAFETY: the lease holds this resident out of the free list until removal.
        unsafe { View::new(self.owner.storage.as_ref(), self.index) }
    }

    /// # Safety
    /// The selected hook belongs to this binding and is linked in its recorded lane.
    unsafe fn unlink(&self, view: &View<'a, Entry<W, G>>) -> links::Detached<'a> {
        unsafe {
            View::join(self.lane()).detach::<false, false, false>(self.index, view.item.hook())
        }
    }

    pub(super) fn keep(
        active: &mut Option<Self>,
        lane: Lane<'a, Lanes<W, L, G, P>>,
        value: W,
    ) -> Result<(), Reject<P>>
    where
        W: Copy,
    {
        let index = lane.index.get();
        let view = match active {
            Some(binding) => {
                let view = binding.view();
                let same = ptr::eq(binding.owner, lane.owner);
                let linked = same && binding.index.is_linked(view.hook());
                if !linked
                    && let Some(index) = P::from_lane(index)
                    && view.is_parked()
                {
                    return Err(Reject::GrantPending { index });
                }
                if !same {
                    return Err(Reject::Active { index });
                }
                if !linked || binding.lane != lane.index {
                    // SAFETY: this lease owns the selected node in either its linked or idle state.
                    let vacant = if linked {
                        unsafe { binding.unlink(&view) }
                    } else {
                        unsafe { view.detached() }
                    };
                    unsafe { View::join(lane).push(vacant) };
                    binding.lane = lane.index;
                }
                view
            }
            None => {
                // SAFETY: the free list and destination lane belong to this resident store.
                let view =
                    unsafe { View::reserve_back(&lane.owner.free, lane.owner.storage.as_ref()) }
                        .ok_or(Reject::Full { index })?;
                unsafe { View::join(lane).push(view.detached()) };
                *active = Some(Self {
                    owner: lane.owner,
                    index: view.key,
                    lane: lane.index,
                    target: PhantomData,
                });
                view
            }
        };
        view.initialize(value);
        Ok(())
    }

    pub(super) fn remove(&self) -> handoff::Cancel<G> {
        let view = self.view();
        let (vacant, result) = if self.index.is_linked(view.hook()) {
            // SAFETY: this lease owns the selected node in its current lane.
            let vacant = unsafe { self.unlink(&view) };
            (vacant, handoff::Cancel::Wake)
        } else {
            let result = if P::from_lane(self.lane.get()).is_some() && view.is_parked() {
                // SAFETY: the parked slot exclusively holds a grant until recycling.
                handoff::Cancel::Grant(unsafe { view.take_grant() })
            } else {
                handoff::Cancel::Empty
            };
            (unsafe { view.detached() }, result)
        };
        self.owner.free.recycle(vacant);
        result
    }
}

impl<W, L, G> Binding<'_, Lanes<W, L, G, usize>> {
    pub(super) fn take_grant(active: &mut Option<Self>) -> handoff::Grant<G> {
        let Some(binding) = active else {
            return handoff::Grant::Empty;
        };
        let view = binding.view();
        if !view.is_parked() {
            return handoff::Grant::Pending;
        }
        // SAFETY: the parked marker proves this lease owns an initialized, unlinked grant.
        let grant = unsafe { view.take_grant() };
        binding.owner.free.recycle(unsafe { view.detached() });
        *active = None;
        handoff::Grant::Ready(grant)
    }
}