o3 0.59.0

shared-nothing primitives
Documentation
use std::{convert, iter, marker, pin::Pin};

pub use cell::Cell;
use cycle::Policy;
use storage::Plane as _;

use crate::depot::{
    arena::slab::{self, key::cycle},
    capacity,
    capacity::Physical,
    index::Initialized,
    queue::links,
};

pub mod entries;
pub mod external;
pub mod key;
pub mod lookup;
pub mod storage;

mod cell;
mod entry;
mod slots;
pub use entry::{anchor::Anchor, anchored::Anchored};
pub type Occupied<B, Tag = (), const ROOT: bool = true> = entry::Slot<B, Tag, ROOT>;
pub use Occupied as Borrowed;
pub use Occupied as Staged;
pub use Occupied as Vacant;
pub use Occupied as Withdrawn;

/// One issued identity retaining its reserved slot until installation or retirement.
pub type Reserved<'a, T, Tag = (), const MAX: u32 = { u32::MAX }, const RECYCLE: bool = false> =
    Vacant<entries::Issued<'a, T, MAX, entries::Interior<RECYCLE>>, Tag>;

/// Why no identity can currently be reserved from a slab.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Vacancy {
    /// Usable slots are occupied or reserved, or the physical capacity is zero.
    Full,
    /// The admitted non-wrapping identity domain is permanently exhausted.
    IdentityExhausted,
}

impl<T, Tag, const MAX: u32, const PARTITIONS: usize> Store<T, Tag, MAX, false, PARTITIONS> {
    /// Reserves every slot and dense index entry transactionally.
    pub fn try_new(cap: capacity::Count) -> Result<Self, crate::alloc::Error> {
        Ok(Self {
            core: entries::Core::try_new(cap)?,
            tag: marker::PhantomData,
        })
    }
}

/// Slot storage whose initialized values remain pinned at their original addresses.
pub struct Pinned<
    T,
    Tag = (),
    const MAX: u32 = { u32::MAX },
    const RECYCLE: bool = false,
    const PARTITIONS: usize = 1,
    S = storage::Heap,
> where
    cycle::Mode<RECYCLE>: Policy,
    S: storage::Storage,
{
    pub(in crate::depot) core: entries::Core<T, MAX, entries::Exclusive<RECYCLE>, PARTITIONS, S>,
    _pin: marker::PhantomPinned,
    tag: marker::PhantomData<fn() -> Tag>,
}

impl<T, Tag, const MAX: u32, const RECYCLE: bool, const PARTITIONS: usize, S>
    Pinned<T, Tag, MAX, RECYCLE, PARTITIONS, S>
where
    cycle::Mode<RECYCLE>: Policy,
    S: storage::Storage,
    S::Plane<T, MAX, entries::Exclusive<RECYCLE>>:
        storage::HeapPlane<T, MAX, entries::Exclusive<RECYCLE>>,
{
    /// Allocates one pinned heap extent under its slot initialization policy.
    pub fn try_new(cap: capacity::Count) -> Result<Self, crate::alloc::Error> {
        Ok(Self {
            core: entries::Core::try_new(cap)?,
            _pin: marker::PhantomPinned,
            tag: marker::PhantomData,
        })
    }
}

impl<T, Tag, const MAX: u32, const PARTITIONS: usize, const N: usize> Default
    for Pinned<T, Tag, MAX, false, PARTITIONS, storage::Inline<N>>
{
    /// Builds the complete inline slot plane without allocating.
    fn default() -> Self {
        Self {
            core: entries::Core::new(),
            _pin: marker::PhantomPinned,
            tag: marker::PhantomData,
        }
    }
}

impl<T, Tag, const MAX: u32, const RECYCLE: bool, const PARTITIONS: usize, S>
    Pinned<T, Tag, MAX, RECYCLE, PARTITIONS, S>
where
    cycle::Mode<RECYCLE>: Policy,
    S: storage::Storage,
{
    pub fn capacity(&self) -> usize {
        self.core.slots.capacity()
    }

    pub fn is_full(&self) -> bool {
        self.core.is_full()
    }

    pub fn vacant(
        self: Pin<&mut Self>,
    ) -> Option<slab::Anchor<'_, T, Tag, MAX, RECYCLE, PARTITIONS, S>> {
        let store = self.into_ref().get_ref();
        // SAFETY: the retained store came from this exclusive pinned loan.
        Some(unsafe { slab::Anchor::pinned(store.core.free()?) })
    }

    pub fn anchor(
        self: Pin<&mut Self>,
        parts: key::Parts<MAX>,
    ) -> Option<slab::Anchored<'_, T, Tag, MAX, RECYCLE, PARTITIONS, S>> {
        let store = self.into_ref().get_ref();
        let entry = entries::Occupied::key(&store.core, parts.index(), parts.generation())?;
        // SAFETY: this live slot is borrowed from the original pinned store.
        Some(unsafe { slab::Anchored::pinned(entry.take()) })
    }
}

impl<T, Tag, const MAX: u32, const RECYCLE: bool, const PARTITIONS: usize>
    slab::Store<T, Tag, MAX, RECYCLE, PARTITIONS>
where
    cycle::Mode<RECYCLE>: Policy,
{
    pub fn capacity(&self) -> usize {
        self.core.slots.capacity()
    }

    /// Nonretired slots, including occupied slots and unpublished reservations.
    pub fn remaining(&self) -> capacity::Count {
        self.core.remaining()
    }

    pub fn len(&self) -> capacity::Count {
        self.core.len()
    }

    pub fn is_full(&self) -> bool {
        self.core.is_full()
    }

    /// Checks temporary or permanent admission without reserving a slot.
    pub fn try_ready(&self) -> Result<(), Vacancy> {
        if self.core.is_full() {
            Err(self.core.refusal())
        } else {
            Ok(())
        }
    }

    pub fn insert(&mut self, value: T) -> Result<key::Handle<Tag, MAX>, T> {
        let Some(pending) = self.core.free() else {
            return Err(value);
        };
        Ok(slab::Vacant::<_, Tag>::new(pending).insert(value))
    }

    /// Reserves a slot or preserves the exact temporary or permanent refusal.
    pub fn try_vacant(
        &mut self,
    ) -> Result<
        slab::Vacant<entries::Pending<'_, T, MAX, entries::Exclusive<RECYCLE>, PARTITIONS>, Tag>,
        Vacancy,
    > {
        Ok(slab::Vacant::new(
            self.core.free().ok_or_else(|| self.core.refusal())?,
        ))
    }

    /// Reserves free slots under one exclusive owner loan.
    /// Each yielded reservation owns only its distinct slot.
    pub fn vacancies(
        &mut self,
    ) -> impl Iterator<
        Item = slab::Vacant<
            entries::Pending<'_, T, MAX, entries::Exclusive<RECYCLE>, PARTITIONS>,
            Tag,
            false,
        >,
    > {
        let core = &self.core;
        iter::from_fn(move || core.free().map(slab::Vacant::new))
    }

    /// Borrows occupied values in physical slot order from this exact shared owner.
    pub fn values(&self) -> impl Iterator<Item = &T> {
        (0..self.capacity()).filter_map(|index| {
            entries::Occupied::at(&self.core, index as u32).map(entries::Occupied::read)
        })
    }

    pub fn try_get(
        &self,
        key: key::Handle<Tag, MAX>,
    ) -> Result<
        &T,
        key::Error<Tag, MAX, convert::Infallible, <cycle::Mode<RECYCLE> as Policy>::Retired>,
    > {
        Ok(entries::Occupied::try_key(&self.core, key)?.read())
    }

    pub fn get_mut(&mut self, key: key::Handle<Tag, MAX>) -> Option<&mut T> {
        let entry = entries::Occupied::key(&self.core, key.index(), key.generation())?;
        Some(entry.take().into_mut())
    }

    pub fn remove(&mut self, key: key::Handle<Tag, MAX>) -> Option<T> {
        let entry = entries::Occupied::key(&self.core, key.index(), key.generation())?;
        Some(entry.take().remove())
    }

    pub fn clear(&mut self) {
        self.core.clear();
    }

    pub fn try_entry(
        &mut self,
        key: key::Handle<Tag, MAX>,
    ) -> Lookup<'_, T, Tag, MAX, RECYCLE, PARTITIONS> {
        let entry = entries::Occupied::try_key(&self.core, key)?;
        Ok(slab::Occupied::new(entry.take()))
    }
}

const _: () = {
    assert!(size_of::<slab::Occupied<entries::Busy<'static, u64>>>() == 2 * size_of::<usize>());
    assert!(
        size_of::<Option<slab::Occupied<entries::Busy<'static, u64>>>>() == 2 * size_of::<usize>()
    );
    assert!(
        size_of::<Option<slab::Vacant<entries::Pending<'static, u64>>>>() == 2 * size_of::<usize>()
    );
    assert!(
        size_of::<
            Option<
                slab::Staged<
                    crate::mem::Lease<entries::Busy<'static, u64>, crate::mem::lease::Open>,
                >,
            >,
        >() == 2 * size_of::<usize>()
    );
    assert!(
        size_of::<slab::Occupied<entries::Busy<'static, u64>, (), false>>()
            == size_of::<slab::Occupied<entries::Busy<'static, u64>>>()
    );
    assert!(
        size_of::<
            slab::Occupied<entries::Busy<'static, u64, { u32::MAX }, entries::Exclusive, 1, u8>>,
        >() == size_of::<slab::Occupied<entries::Busy<'static, u64>>>()
    );
    assert!(
        size_of::<
            Option<
                slab::Occupied<
                    entries::Busy<'static, u64, { u32::MAX }, entries::Exclusive, 1, u8>,
                >,
            >,
        >() == size_of::<slab::Occupied<entries::Busy<'static, u64>>>()
    );
};

impl<'a, 'h, T, Tag, const MAX: u32>
    TryFrom<
        crate::depot::raw::Proof<
            (
                &'a mut slab::Store<T, Tag, MAX>,
                capacity::Key<'h, key::Handle<Tag, MAX>>,
            ),
            Physical,
        >,
    > for slab::Occupied<entries::Busy<'a, T, MAX>, Tag>
{
    type Error = key::Stale<'h, Tag, MAX>;

    fn try_from(
        proof: crate::depot::raw::Proof<
            (
                &'a mut slab::Store<T, Tag, MAX>,
                capacity::Key<'h, key::Handle<Tag, MAX>>,
            ),
            Physical,
        >,
    ) -> Result<Self, Self::Error> {
        let entry = entries::Occupied::try_bound(unsafe {
            proof.map(|(source, key)| (&source.core, key))
        })?;
        Ok(Self::new(entry.take()))
    }
}

/// A branded exclusive slab owner with an explicit generation policy.
pub struct Store<
    T,
    Tag = (),
    const MAX: u32 = { u32::MAX },
    const RECYCLE: bool = false,
    const PARTITIONS: usize = 1,
> where
    cycle::Mode<RECYCLE>: Policy,
{
    pub(in crate::depot::arena::slab) core:
        entries::Core<T, MAX, entries::Exclusive<RECYCLE>, PARTITIONS>,
    pub(in crate::depot::arena::slab) tag: marker::PhantomData<fn() -> Tag>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum State<B, R> {
    Free,
    Reserved,
    Occupied,
    Busy(B),
    Retired(R),
}

impl<B, R> State<B, R> {
    /// Classifies one admitted slot, retaining the live-borrow witness for its caller.
    fn classify<const MAX: u32, C>(
        self,
        actual: key::Generation<MAX>,
        expected: key::Generation<MAX>,
    ) -> Result<(), key::Observation<MAX, B, R, C>> {
        use key::Observation;

        match self {
            Self::Free => Err(Observation::Free { actual }),
            Self::Reserved => Err(Observation::Reserved { actual }),
            Self::Retired(retired) => Err(Observation::Retired { actual, retired }),
            Self::Busy(borrow) => Err(Observation::Busy { actual, borrow }),
            Self::Occupied if actual != expected => Err(Observation::Generation { actual }),
            Self::Occupied => Ok(()),
        }
    }
}

impl<'a, T, Tag, const MAX: u32, const RECYCLE: bool, const PARTITIONS: usize>
    slab::Store<T, Tag, MAX, RECYCLE, PARTITIONS>
where
    cycle::Mode<RECYCLE>: Policy,
{
    /// Consumes an initialized-slot proof without repeating its lookup.
    pub fn value<P>(
        live: crate::depot::raw::Proof<
            (
                &'a slab::Store<T, Tag, MAX, RECYCLE, PARTITIONS>,
                links::Index,
            ),
            Initialized<P>,
        >,
    ) -> crate::depot::raw::Proof<(&'a T, links::Index), Initialized<P>> {
        // SAFETY: the native core retains the complete shared slab loan.
        entries::Core::read(unsafe { live.map(|(slab, index)| (&slab.core, index)) })
    }
}

/// One distinct physical slot retained by exclusive iteration.
pub enum Entry<'a, T, Tag = (), const MAX: u32 = { u32::MAX }> {
    Vacant(slab::Vacant<entries::Pending<'a, T, MAX>, Tag, false>),
    Occupied(slab::Occupied<entries::Busy<'a, T, MAX>, Tag, false>),
}

/// The retained (owner, index, projector) selects a valid field of that initialized slot.
/// The field remains disjoint from mutable payloads for the owner's full returned loan.
pub enum Field {}

impl crate::depot::raw::Sealed for Field {}

type Lookup<'a, T, Tag, const MAX: u32, const RECYCLE: bool, const PARTITIONS: usize> = Result<
    slab::Occupied<entries::Busy<'a, T, MAX, entries::Exclusive<RECYCLE>, PARTITIONS>, Tag>,
    key::Error<Tag, MAX, convert::Infallible, <cycle::Mode<RECYCLE> as Policy>::Retired>,
>;