o3 0.62.0

shared-nothing primitives
Documentation
use std::convert::Infallible;

use crate::{
    base::num::Step,
    depot::{
        arena::slab::{
            self, Plane, entries, external,
            external::errors,
            key::{self, cycle, cycle::Policy},
            lookup,
        },
        queue::links,
    },
    mem::Rejected,
};

/// One initialized physical position in its original slab and phase.
pub(in crate::depot) struct Position<
    'a,
    T,
    const MAX: u32,
    M: entries::Mode,
    const N: usize,
    S: slab::Storage = slab::Heap,
    const LIVE: bool = true,
> {
    core: &'a slab::raw::Core<T, MAX, M, N, S>,
    index: links::Index,
}

impl<'a, T, const MAX: u32, M: entries::Mode, const N: usize, S: slab::Storage, const LIVE: bool>
    Position<'a, T, MAX, M, N, S, LIVE>
{
    /// # Safety
    /// The index selects an initialized slot in this core, in the specified phase.
    pub(in crate::depot::arena::slab) unsafe fn new(
        core: &'a slab::raw::Core<T, MAX, M, N, S>,
        index: links::Index,
    ) -> Self {
        Self { core, index }
    }

    pub(in crate::depot) fn core(&self) -> &'a slab::raw::Core<T, MAX, M, N, S> {
        self.core
    }

    pub(in crate::depot) fn index(&self) -> links::Index {
        self.index
    }

    pub(in crate::depot::arena::slab) fn slot(&self) -> &'a slab::Slot<T, MAX, M> {
        // SAFETY: this initialized position belongs to the retained nonmoving plane.
        unsafe { self.core.slots.as_ref().get_unchecked(self.index.get()) }
    }

    pub(in crate::depot) fn generation(&self) -> key::Generation<MAX> {
        <M::Cycle as Policy>::generation(self.slot().metadata.generation.get())
    }
}

impl<'a, T, const MAX: u32, M: entries::Mode, const N: usize, S: slab::Storage>
    Position<'a, T, MAX, M, N, S>
{
    pub(in crate::depot::arena::slab) fn take(
        self,
    ) -> slab::raw::Entry<'a, T, MAX, M, N, S, true, false> {
        if M::REENTRANT {
            self.slot().metadata.state.set(M::TAKEN);
        }
        slab::raw::Entry { position: self }
    }

    pub(in crate::depot) fn try_at(
        core: &'a slab::raw::Core<T, MAX, M, N, S>,
        index: u32,
    ) -> Result<Self, lookup::Error<M::Busy, <M::Cycle as Policy>::Retired>> {
        let slots = &core.slots;
        if index >= slots.built() {
            return Err(if index as usize >= slots.capacity() {
                lookup::Error::Index {
                    index,
                    capacity: slots.count(),
                }
            } else {
                lookup::Error::Free { index }
            });
        }
        // SAFETY: this index is in the initialized backing prefix.
        unsafe { Self::allocated(core, index) }
    }

    /// # Safety
    /// Index names an initialized backing slot in this retained owner.
    pub(in crate::depot) unsafe fn allocated(
        core: &'a slab::raw::Core<T, MAX, M, N, S>,
        index: u32,
    ) -> Result<Self, lookup::Error<M::Busy, <M::Cycle as Policy>::Retired>> {
        let slot = unsafe { core.slots.as_ref().get_unchecked(index as usize) };
        match slot.metadata.state.get() {
            slab::State::Occupied => Ok(unsafe { Self::new(core, links::Index::new_raw(index)) }),
            slab::State::Free => Err(lookup::Error::Free { index }),
            slab::State::Reserved => Err(lookup::Error::Reserved { index }),
            slab::State::Busy(borrow) => Err(lookup::Error::Busy { index, borrow }),
            slab::State::Retired(retired) => Err(lookup::Error::Retired { index, retired }),
        }
    }

    pub(in crate::depot) fn at(
        core: &'a slab::raw::Core<T, MAX, M, N, S>,
        index: u32,
    ) -> Option<Self> {
        let slot = core.slots.get(index)?;
        if slot.metadata.state.get() != slab::State::Occupied {
            return None;
        }
        // SAFETY: the original plane and state admitted this physical index.
        Some(unsafe { Self::new(core, links::Index::new_raw(index)) })
    }

    pub(in crate::depot) fn key(
        core: &'a slab::raw::Core<T, MAX, M, N, S>,
        index: u32,
        epoch: key::Generation<MAX>,
    ) -> Option<Self> {
        let live = Self::at(core, index)?;
        (live.generation() == epoch).then_some(live)
    }

    pub(in crate::depot) fn try_key<Tag>(
        core: &'a slab::raw::Core<T, MAX, M, N, S>,
        key: key::Handle<Tag, MAX>,
    ) -> Lookup<Self, Tag, MAX, M> {
        if key.index() >= core.slots.built() {
            return Err(Rejected::new(
                key,
                key::Observation::Index {
                    capacity: core.slots.count(),
                },
            ));
        }
        // SAFETY: this lookup retained the exact key's initialized physical header.
        unsafe { Self::try_bound(core, key) }.map_err(|(key, seen)| Rejected::new(key, seen))
    }

    /// # Safety
    /// The key's physical position belongs to this core's initialized backing.
    pub(in crate::depot) unsafe fn try_bound<Tag, C>(
        core: &'a slab::raw::Core<T, MAX, M, N, S>,
        key: key::Handle<Tag, MAX>,
    ) -> Result<Self, BoundError<Tag, MAX, M, C>> {
        let index = key.index();
        let slot = unsafe { core.slots.as_ref().get_unchecked(index as usize) };
        let actual = <M::Cycle as Policy>::generation(slot.metadata.generation.get());
        slot.metadata
            .state
            .get()
            .classify(actual, key.generation())
            .map_err(|seen| (key, seen))?;
        Ok(unsafe { Self::new(core, links::Index::new_raw(index)) })
    }
}

impl<'a, T, const MAX: u32, const RECYCLE: bool, const N: usize, S: slab::Storage>
    Position<'a, T, MAX, entries::Exclusive<RECYCLE>, N, S>
where
    cycle::Mode<RECYCLE>: Policy,
{
    pub(in crate::depot) fn read(self) -> &'a T {
        // SAFETY: the observed slot retains its exclusive owner's shared loan.
        unsafe { self.slot().value() }
    }

    pub(in crate::depot::arena::slab) fn as_mut_ptr(&self) -> *mut T {
        // SAFETY: only a pointer to the admitted live UnsafeCell escapes.
        unsafe { self.slot().value_ptr() }
    }
}

impl<'a, T, G: Step, M: entries::Mode<Cycle = cycle::Mode<true>>, const N: usize, S: slab::Storage>
    Position<'a, external::Stamped<T, G>, 1, M, N, S>
{
    pub(in crate::depot::arena::slab) fn stamped<Tag>(
        key: external::Key<G, Tag>,
        result: Result<Self, lookup::Error<M::Busy, Infallible>>,
    ) -> Result<Self, errors::Lookup<G, Tag, M::Busy>> {
        let live = result.map_err(|cause| errors::Lookup::Physical { key, cause })?;
        // SAFETY: this occupied observation precedes the sealed, non-reentrant comparison.
        let actual = unsafe { live.slot().value() }.generation;
        if key.generation() == actual {
            Ok(live)
        } else {
            Err(errors::Lookup::Generation { key, actual })
        }
    }
}

type Observed<const MAX: u32, M, C> = key::Observation<
    MAX,
    <M as entries::Mode>::Busy,
    <<M as entries::Mode>::Cycle as Policy>::Retired,
    C,
>;
type BoundError<Tag, const MAX: u32, M, C> = (key::Handle<Tag, MAX>, Observed<MAX, M, C>);
pub(super) type Lookup<S, Tag, const MAX: u32, M> =
    Result<S, Rejected<key::Handle<Tag, MAX>, Observed<MAX, M, crate::depot::capacity::Count>>>;