o3 0.62.0

shared-nothing primitives
Documentation
//! Mutations of a resident FIFO and its active lane under a single retained proof.

use std::cell::Cell;

use crate::{
    alloc,
    depot::queue::{
        indexed::shared,
        links, resident,
        round::{self, phase, values},
    },
    depot::{self, index},
};

type Value<T> = depot::raw::Node<Cell<Option<T>>>;
type Track = depot::raw::Node<links::raw::Chain>;
type Place<'a, T, const G: usize, const N: usize> = values::Snapshot<'a, T, G, values::Place, N>;

/// Borrowed projections of one resident lane. Mutation requires a complete source proof.
#[derive(Debug)]
pub struct Join<'a, H: ?Sized, L: ?Sized> {
    pub hooks: &'a H,
    pub lanes: &'a L,
    pub entries: &'a links::raw::Chain,
    pub active: &'a links::raw::Cycle,
    pub index: links::Index,
}

impl<'a, H: depot::raw::Hooks + ?Sized, L: depot::raw::Hooks + ?Sized> Join<'a, H, L> {
    pub fn insert(source: depot::raw::Proof<(Self, links::Index), phase::Vacant>) {
        let (lane, index) = source.into_inner();
        // SAFETY: the source retains the exact exclusively vacant resident hook.
        let vacant = unsafe { links::Detached::new(lane.hooks.hook_raw(index), index) };
        // SAFETY: the same source retains its detached resident and reciprocal destination.
        unsafe { lane.push(vacant) };
    }

    /// # Safety
    /// The detached resident belongs to this store and its destination is reciprocal.
    pub(in crate::depot::queue) unsafe fn push(self, vacant: links::Detached<'a>) {
        if let links::raw::Insertion::First = unsafe { self.entries.push(self.hooks, vacant) } {
            // SAFETY: the empty lane was absent from its active ring.
            unsafe { self.active.push(self.lanes, self.index) };
        }
    }

    pub fn remove(
        source: depot::raw::Proof<(Self, links::Index), phase::Linked>,
    ) -> links::Detached<'a> {
        let (lane, index) = source.into_inner();
        // SAFETY: the source retains this resident's exact reciprocal membership.
        let hook = unsafe { lane.hooks.hook_raw(index) };
        unsafe { lane.detach::<false, false, false>(index, hook) }
    }

    pub fn active<const ROTATE: bool>(
        source: depot::raw::Proof<Self, phase::Active>,
    ) -> links::Detached<'a> {
        let lane = source.into_inner();
        // SAFETY: active-front membership proves this exact lane remains nonempty.
        let index = unsafe { lane.entries.front_key() };
        let hook = unsafe { lane.hooks.hook_raw(index) };
        unsafe { lane.detach::<true, true, ROTATE>(index, hook) }
    }

    pub fn head<const ROTATE: bool>(
        source: depot::raw::Proof<(Self, links::Index), phase::Head>,
    ) -> links::Detached<'a> {
        let (lane, index) = source.into_inner();
        // SAFETY: Head retains the exact FIFO front through this consuming commit.
        let hook = unsafe { lane.hooks.hook_raw(index) };
        unsafe { lane.detach::<true, false, ROTATE>(index, hook) }
    }

    /// # Safety
    /// The hook belongs to this index in this reciprocal FIFO and the lane is active.
    /// FRONT and ACTIVE additionally assert the respective heads until this mutation.
    pub(in crate::depot::queue) unsafe fn detach<
        const FRONT: bool,
        const ACTIVE: bool,
        const ROTATE: bool,
    >(
        self,
        index: links::Index,
        hook: &'a links::Hook,
    ) -> links::Detached<'a> {
        let (vacant, last) = unsafe {
            self.entries
                .detach_hook::<FRONT, 0, _>(self.hooks, index, hook)
        };
        if last && (FRONT || self.entries.is_empty()) {
            unsafe { self.active.unlink::<ACTIVE, 0>(self.lanes, self.index) };
        } else if ROTATE {
            unsafe { self.active.requeue::<ACTIVE, 0>(self.lanes, self.index) };
        }
        vacant
    }
}

impl<'a, T: Copy> Join<'a, [Value<T>], [Track]> {
    /// # Safety
    /// The lane is admitted against this owner's original extent.
    unsafe fn values<const G: usize, const N: usize>(
        owner: &'a values::Values<T, G, N>,
        index: links::Index,
    ) -> Self {
        let lanes = owner.block.tail();
        Self {
            hooks: owner.block.as_ref(),
            lanes,
            entries: unsafe { resident::raw::View::new(lanes, index) }.into_ref(),
            active: &owner.groups[index.get() % G],
            index,
        }
    }
}

/// An initialized resident retained only until the immediate placement commits.
pub(super) struct Entry<'p, 'a, T: Copy, const G: usize, const N: usize> {
    place: &'p Place<'a, T, G, N>,
    node: &'a Value<T>,
}

impl<'p, 'a, T: Copy, const G: usize, const N: usize> Entry<'p, 'a, T, G, N> {
    pub(super) fn try_index<const LANE: bool>(
        owner: &values::Values<T, G, N>,
        index: usize,
    ) -> Result<links::Index, shared::Bounds> {
        let extent = owner.block.extent();
        let capacity = if LANE {
            alloc::raw::Shape::tail_len(extent)
        } else {
            alloc::raw::Shape::len(extent)
        };
        if index >= capacity {
            return Err(shared::Bounds { index, capacity });
        }
        // SAFETY: both extents were admitted as u32 counts before allocation.
        Ok(unsafe { links::Index::new_usize(index) })
    }

    pub(super) fn cell<const CLEAR: bool>(slot: &values::Slot<'a, T, G, N>) -> &'a Value<T> {
        let index = slot.index;
        // SAFETY: the slot retains its own immutable resident extent.
        let node = unsafe { resident::raw::View::new(slot.owner.block.as_ref(), index) }.into_ref();
        if CLEAR && index.is_linked(node.hook()) {
            // SAFETY: a linked hook records its actual admitted lane in the paired plane.
            let lane = unsafe { slot.owner.block.values().get_unchecked(index.get()) }.get();
            unsafe {
                Join::values(slot.owner, lane).detach::<false, false, false>(index, node.hook())
            }
            .idle();
        }
        node
    }

    pub(super) fn written(place: &'p Place<'a, T, G, N>, value: T) -> Self {
        let node = Self::cell::<false>(&place.slot());
        node.set(Some(value));
        Self { place, node }
    }

    pub(super) fn initialized(
        source: depot::raw::Proof<
            &'p Place<'a, T, G, N>,
            index::Initialized<values::Values<T, G, N>>,
        >,
    ) -> Self {
        let place = source.into_inner();
        Self {
            place,
            node: Self::cell::<false>(&place.slot()),
        }
    }

    pub(super) fn append<const REQUEUE: bool>(self) {
        let owner = self.place.owner;
        let round::Position { index, lane } = self.place.position;
        let hook = self.node.hook();
        // SAFETY: the admitted resident also indexes its paired lane cell.
        let saved = unsafe { owner.block.values().get_unchecked(index.get()) };
        let vacant = if index.is_linked(hook) {
            let source = saved.get();
            if !REQUEUE && source == lane {
                return;
            }
            // SAFETY: the live hook names this exact resident in its recorded FIFO.
            unsafe { Join::values(owner, source).detach::<false, false, false>(index, hook) }
        } else {
            // SAFETY: this initialized resident is detached from every lane.
            unsafe { links::Detached::new(hook, index) }
        };
        // SAFETY: the placement admits its destination in the same owner as the resident.
        unsafe { Join::values(owner, lane).push(vacant) };
        saved.set(lane);
    }
}

/// The initialized front retained by one lane or active group.
pub struct Head<'a, T: Copy, const G: usize, const N: usize = 0, const ACTIVE: bool = false> {
    pub(super) owner: &'a values::Values<T, G, N>,
    pub(super) position: round::Position,
}

impl<'a, T: Copy, const G: usize, const N: usize, const ACTIVE: bool> Head<'a, T, G, N, ACTIVE> {
    pub(super) fn resolve(
        snapshot: values::Snapshot<'a, T, G, values::Turn<ACTIVE>, N>,
    ) -> Option<Self> {
        let owner = snapshot.owner;
        let position = snapshot.position;
        // SAFETY: the snapshot retains lane admission even when its selected front changes.
        let lane = unsafe { resident::raw::View::new(owner.block.tail(), position.lane) };
        (lane.first() == Some(position.index)
            && (!ACTIVE || owner.groups[position.lane.get() % G].first() == Some(position.lane)))
        .then_some(Self { owner, position })
    }

    pub const fn index(&self) -> usize {
        self.position.index.get()
    }

    fn node(&self) -> &Value<T> {
        // SAFETY: this head retains its physical resident in the original allocation.
        unsafe { resident::raw::View::new(self.owner.block.as_ref(), self.position.index) }
            .into_ref()
    }

    pub fn get(&self) -> T {
        // SAFETY: the live front retains the initialized payload until consumption.
        unsafe { *crate::mem::raw::initialized(&self.node().get()) }
    }

    pub fn pop(self) -> T {
        let node = self.node();
        // SAFETY: this exact resident and its lane remain linked until detach commits.
        let lane = unsafe { Join::values(self.owner, self.position.lane) };
        unsafe { lane.detach::<true, ACTIVE, ACTIVE>(self.position.index, node.hook()) }.idle();
        // SAFETY: detachment changed only links and `Head` owns the initialized value.
        unsafe { *crate::mem::raw::initialized(&node.take()) }
    }
}

impl<'a, T: Copy, const G: usize, const N: usize> Head<'a, T, G, N> {
    pub(super) fn front(source: &values::Lane<'a, T, G, N>) -> Option<Self> {
        let owner = source.owner;
        let lane = source.index;
        // SAFETY: this lane retains its original admitted extent.
        let index = unsafe { resident::raw::View::new(owner.block.tail(), lane) }.first()?;
        Some(Self {
            owner,
            position: round::Position { lane, index },
        })
    }

    pub fn rotate(&mut self) {
        // SAFETY: this retained FIFO front and its lane stay in their original stores.
        let lane = unsafe { Join::values(self.owner, self.position.lane) };
        let next = unsafe {
            lane.entries
                .rotate(lane.hooks, self.position.index, self.node().hook(), true)
        };
        unsafe { lane.active.requeue::<false, 0>(lane.lanes, lane.index) };
        self.position.index = next;
    }
}

impl<'a, T: Copy, const G: usize, const N: usize> Head<'a, T, G, N, true> {
    pub(super) fn active(group: &values::Group<'a, T, G, N>) -> Option<Self> {
        let owner = group.owner;
        let lane = group.ring.first()?;
        // SAFETY: the active ring names an admitted nonempty FIFO until this immediate selection.
        let index = unsafe { resident::raw::View::new(owner.block.tail(), lane).front_key() };
        Some(Self {
            owner,
            position: round::Position { lane, index },
        })
    }
}