o3 0.62.0

shared-nothing primitives
Documentation
use crate::{
    depot::{
        arena::slab::{self, Plane, Vacancy, entries, key},
        capacity,
        capacity::Physical,
        index::{Initialized, Unborrowed},
        queue::links,
    },
    mem::Rejected,
};
use std::{convert, marker};

/// Exclusive slots with bounded, non-wrapping generations.
pub struct Store<T, Tag = (), const MAX: u32 = { u32::MAX }, const PARTITIONS: usize = 1> {
    pub(in crate::depot::arena::slab) core: slab::raw::Core<T, MAX, entries::Exclusive, PARTITIONS>,
    tag: marker::PhantomData<fn() -> Tag>,
}

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

    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.slots.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.slots.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::raw::Vacant::<_, Tag, MAX, _, PARTITIONS>::new(pending).insert(value))
    }

    /// Borrows occupied values in physical slot order from this exact shared owner.
    pub fn values(&self) -> impl Iterator<Item = &T> {
        self.core.slots.as_ref().iter().filter_map(|slot| {
            if slot.metadata.state.get() == slab::State::Occupied {
                // SAFETY: this state and the exclusive owner's shared loan retain the value.
                Some(unsafe { slot.value() })
            } else {
                None
            }
        })
    }

    pub fn try_get_ptr(
        &self,
        key: key::Handle<Tag, MAX>,
    ) -> Result<
        *mut T,
        Rejected<key::Handle<Tag, MAX>, key::Observation<MAX, convert::Infallible, ()>>,
    > {
        let entry = slab::raw::Position::try_key(&self.core, key)?;
        Ok(entry.as_mut_ptr())
    }

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

    /// Consumes an initialized-slot proof without repeating its lookup.
    pub fn value<P>(
        live: crate::depot::raw::Proof<
            (&'a slab::Store<T, Tag, MAX, PARTITIONS>, links::Index),
            Initialized<P>,
        >,
    ) -> &'a T {
        let (owner, index) = live.into_inner();
        // SAFETY: the original initialized proof retains this shared owner loan.
        unsafe { owner.core.read(index) }
    }

    pub fn value_ptr<P>(
        live: crate::depot::raw::Proof<(&Self, links::Index), Initialized<P>>,
    ) -> *mut T {
        let (store, index) = live.into_inner();
        unsafe {
            store
                .core
                .slots
                .as_ref()
                .get_unchecked(index.get())
                .value_ptr()
        }
    }

    pub fn discard<P>(live: crate::depot::raw::Proof<(&Self, links::Index), Unborrowed<P>>) {
        let (store, index) = live.into_inner();
        // SAFETY: the original unborrowed proof retains this initialized slot and plane P.
        unsafe { store.core.project(index) }.issue();
    }

    /// Borrows the current value at a physical slot through the owner's shared loan.
    /// Checks occupancy without matching a generation.
    pub fn value_at(&'a self, index: u32) -> Option<&'a T> {
        Some(slab::raw::Position::at(&self.core, index)?.read())
    }
}

impl<'a, T, Tag, const MAX: u32> Store<T, Tag, MAX> {
    /// Borrows each usable physical slot once, retaining disjoint entry proofs.
    pub fn entries(&'a mut self) -> impl Iterator<Item = slab::Entry<'a, T, Tag, MAX>> {
        let core = &self.core;
        core.slots
            .as_ref()
            .iter()
            .enumerate()
            .filter_map(move |(index, slot)| {
                match slot.metadata.state.get() {
                    slab::State::Occupied => Some(slab::Entry::Occupied(slab::raw::Occupied::new(
                        // SAFETY: this exclusive iteration yields each occupied position once.
                        unsafe { slab::raw::Entry::new(core, links::Index::new_usize(index)) },
                    ))),
                    slab::State::Free => {
                        // SAFETY: this unique visit proved the original slot's free membership.
                        let entry = unsafe {
                            slab::raw::Free::new(core, links::Index::new_usize(index)).unlink(slot)
                        };
                        Some(slab::Entry::Vacant(slab::raw::Vacant::new(entry)))
                    }
                    slab::State::Reserved | slab::State::Retired(()) => None,
                }
            })
    }

    pub(in crate::depot) fn contains(proof: PhysicalSlot<'a, T, Tag, MAX>) -> bool {
        let (source, key) = proof.into_inner();
        let slots = source.core.slots.as_ref();
        // SAFETY: the retained bound selects this eager owner's initialized extent.
        let slot = unsafe { slots.get_unchecked(key.index() as usize) };
        slot.metadata.state.get() == slab::State::Occupied
            && slot.metadata.generation.get() == key.generation()
    }
}

type PhysicalSlot<'a, T, Tag, const MAX: u32> =
    crate::depot::raw::Proof<(&'a slab::Store<T, Tag, MAX>, key::Handle<Tag, MAX>), Physical>;