o3 0.62.0

shared-nothing primitives
Documentation
use std::mem;

use crate::depot::{
    map,
    queue::{
        indexed::fifo::store::{Membership, Node, Selected, Store},
        links,
    },
};

/// A persistent physical slot in its original fixed allocation.
pub struct Entry<'a, T, P = (), const N: usize = 1, C: crate::depot::raw::ChainCount = u32> {
    pub(in crate::depot::queue::indexed::fifo::store) store: &'a Store<T, P, N, C>,
    pub(in crate::depot::queue::indexed::fifo::store) index: usize,
}

impl<'a, T, P, const N: usize, C: crate::depot::raw::ChainCount> Entry<'a, T, P, N, C> {
    fn row(&self) -> *const Node<T, P, N> {
        self.store.block.as_ptr().wrapping_add(self.index)
    }

    pub fn state(&self) -> &'a P {
        // SAFETY: this persistent slot retains its resident for the shared store loan.
        unsafe { &(*self.row()).state }
    }

    pub(in crate::depot::queue::indexed) fn position(&self) -> links::Index {
        // SAFETY: the retained physical index is below this counted allocation’s end sentinel.
        unsafe { links::Index::new_usize(self.index) }
    }

    pub(in crate::depot::queue::indexed) fn hooks(&self) -> &'a [links::Hook; N] {
        // SAFETY: borrow only the initialized hooks, disjoint from outstanding resident loans.
        unsafe { &(*self.row()).hooks }
    }

    pub(in crate::depot::queue::indexed) fn is_linked<const Q: usize>(&self) -> bool {
        const { assert!(Q < N) };
        self.position().is_linked(&self.hooks()[Q])
    }

    pub(in crate::depot::queue::indexed) fn value<const Q: usize>(
        &self,
    ) -> *mut mem::MaybeUninit<T> {
        const { assert!(Q < N) };
        // SAFETY: the selected cell is initialized independently of its payload and resident.
        (unsafe { &(*self.row()).values })[Q].as_ptr()
    }

    /// # Safety
    /// This slot's selected payload is live; FRONT also retains this exact head.
    pub(in crate::depot::queue) unsafe fn take<const Q: usize, const FRONT: bool>(&self) -> T {
        unsafe { self.unlink::<Q, FRONT>() };
        unsafe { (*self.value::<Q>()).assume_init_read() }
    }

    /// # Safety
    /// This exact slot is linked in plane Q; FRONT also retains its current head.
    pub(in crate::depot::queue::indexed) unsafe fn unlink<const Q: usize, const FRONT: bool>(
        &self,
    ) {
        let lane = self.store.queue::<Q>();
        unsafe {
            lane.chain()
                .detach_hook::<FRONT, 0, _>(&lane, self.position(), &self.hooks()[Q])
        }
        .0
        .idle();
    }

    /// # Safety
    /// This vacant slot owns its publication, or LINKED retains a replaceable Copy payload.
    /// No user code may intervene between membership admission and this write.
    pub(in crate::depot::queue::indexed) unsafe fn write_back<
        const Q: usize,
        const LINKED: bool,
    >(
        &self,
        value: T,
    ) {
        let lane = self.store.queue::<Q>();
        let hook = &self.hooks()[Q];
        unsafe { self.value::<Q>().write(mem::MaybeUninit::new(value)) };
        if LINKED {
            unsafe {
                lane.chain()
                    .rotate::<0, _>(&lane, self.position(), hook, false)
            };
        } else {
            unsafe { lane.chain().link_back::<0, _>(&lane, self.position(), hook) };
        }
    }
}

impl<T: Copy, P, const N: usize> Entry<'_, T, P, N, ()> {
    pub fn index(&self) -> usize {
        self.index
    }

    /// Returns a snapshot while its plane remains linked.
    pub fn get<const Q: usize>(&self) -> Option<T> {
        self.is_linked::<Q>()
            .then(|| unsafe { (*self.value::<Q>()).assume_init_read() })
    }

    pub fn push<const Q: usize>(&self, value: T) {
        // SAFETY: membership cannot change before publication and T is Copy.
        if self.is_linked::<Q>() {
            unsafe { self.write_back::<Q, true>(value) };
        } else {
            unsafe { self.write_back::<Q, false>(value) };
        }
    }

    pub fn clear<const Q: usize>(&self) {
        if self.is_linked::<Q>() {
            // SAFETY: no caller runs before removal of this same copied payload.
            unsafe { self.unlink::<Q, false>() };
        }
    }
}

impl<'a, T, P, const N: usize> Entry<'a, T, P, N> {
    /// # Safety
    /// The original exclusive root loan keeps this membership stable until the plane is consumed.
    pub(in crate::depot::queue::indexed) unsafe fn classify<const Q: usize>(
        self,
    ) -> Membership<'a, T, P, N, Q> {
        if self.is_linked::<Q>() {
            map::Entry::Occupied(Plane(self))
        } else {
            map::Entry::Vacant(Plane(self))
        }
    }
}

impl<P, const N: usize> Entry<'_, (), P, N> {
    /// # Safety
    /// Plane zero is live and, when Q < N, this slot retains the exact front of Q.
    pub(in crate::depot::queue::indexed) unsafe fn release<const Q: usize>(&self) {
        for (plane, (chain, hook)) in self
            .store
            .block
            .state()
            .iter()
            .zip(self.hooks())
            .enumerate()
        {
            let lane = Selected {
                store: self.store,
                plane,
            };
            let detached = if plane == Q {
                unsafe { chain.detach_hook::<true, 0, _>(&lane, self.position(), hook) }
            } else if plane == 0 || self.position().is_linked(hook) {
                unsafe { chain.detach_hook::<false, 0, _>(&lane, self.position(), hook) }
            } else {
                continue;
            };
            detached.0.idle();
        }
    }
}

/// One admitted resident under its original exclusive root loan.
pub struct Resident<'a, P, const N: usize> {
    pub(in crate::depot::queue::indexed::fifo::store) store: &'a mut Store<(), P, N>,
    pub(in crate::depot::queue::indexed::fifo::store) index: usize,
}

/// One plane loan; the resident field cannot be reached through it.
pub struct Plane<
    'a,
    T,
    P,
    const N: usize,
    const Q: usize,
    const LINKED: bool,
    const FRONT: bool = false,
>(pub(in crate::depot::queue::indexed::fifo::store) Entry<'a, T, P, N>);

impl<'a, P, const N: usize, const Q: usize, const FRONT: bool> Plane<'a, (), P, N, Q, true, FRONT> {
    pub fn unlink(self) -> Plane<'a, (), P, N, Q, false> {
        // SAFETY: this loan retains the exact membership and, when set, its head.
        unsafe { self.0.unlink::<Q, FRONT>() };
        Plane(self.0)
    }

    pub fn move_to_back(self) {
        let lane = self.0.store.queue::<Q>();
        // SAFETY: membership cannot change during this exclusive plane loan.
        unsafe {
            lane.chain()
                .rotate::<0, _>(&lane, self.0.position(), &self.0.hooks()[Q], FRONT)
        };
    }
}

impl<P, const N: usize, const Q: usize> Plane<'_, (), P, N, Q, false> {
    pub fn link_back(self) {
        // SAFETY: this exact plane is vacant; unit publication has no user effect.
        self.push_back(());
    }
}

impl<P, const N: usize> Resident<'_, P, N> {
    pub fn get_mut(&mut self) -> &mut P {
        // SAFETY: this shorter exclusive loan excludes all plane and resident borrows.
        &mut unsafe { self.store.block.get_unchecked_mut(self.index) }.state
    }

    pub fn plane<const Q: usize>(&mut self) -> Membership<'_, (), P, N, Q> {
        // SAFETY: the same exclusive root retains this slot; no resident loan escapes here.
        unsafe {
            Entry {
                store: self.store,
                index: self.index,
            }
            .classify::<Q>()
        }
    }
}

impl<T, P, const N: usize, const Q: usize> Plane<'_, T, P, N, Q, false> {
    pub fn push_back(self, value: T) {
        // SAFETY: this consuming vacancy owns the write and publication of the payload.
        unsafe { self.0.write_back::<Q, false>(value) };
    }
}

impl<'a, T, P, const N: usize, const Q: usize, const FRONT: bool>
    Plane<'a, T, P, N, Q, true, FRONT>
{
    pub fn get(&self) -> &T {
        // SAFETY: this exclusive plane holds the initialized payload for this borrow.
        unsafe { (*self.0.value::<Q>()).assume_init_ref() }
    }

    pub fn remove(self) -> (Plane<'a, T, P, N, Q, false>, T) {
        // SAFETY: consuming the exclusive plane transfers its initialized payload once.
        let value = unsafe { self.0.take::<Q, FRONT>() };
        (Plane(self.0), value)
    }

    pub fn clear(self) {
        // SAFETY: this plane owns removal and in-place destruction of its payload.
        unsafe {
            self.0.unlink::<Q, FRONT>();
            (*self.0.value::<Q>()).assume_init_drop();
        }
    }
}