o3 0.62.0

shared-nothing primitives
Documentation
use std::{
    marker,
    mem::{MaybeUninit, needs_drop, size_of},
    num::NonZero,
    ptr, slice,
};

use runtime::entry;

type Index = bounded::raw::U32<0, { u32::MAX - 1 }>;

use crate::{
    alloc,
    base::{marker::ThreadBound, num::bounded},
    depot::{
        arena::{
            hash::{self, errors, runtime},
            slab::key,
        },
        map,
        queue::links,
    },
};

pub struct Core<T, Tag = ()> {
    pub(super) directory: map::raw::Table<Index>,
    thread: marker::PhantomData<ThreadBound>,
    meta: ptr::NonNull<Meta>,
    pub(super) dense: ptr::NonNull<Index>,
    pub(super) values: ptr::NonNull<MaybeUninit<T>>,
    plan: hash::Plan,
    pub(in crate::depot::arena::hash) len: u32,
    pub(super) free: Option<links::Index>,
    tag: marker::PhantomData<fn(Tag) -> Tag>,
}

impl<T, Tag> Core<T, Tag> {
    pub(in crate::depot::arena::hash) fn try_new(
        plan: hash::Plan,
    ) -> Result<Self, crate::alloc::Error> {
        let capacity = plan.capacity().get();
        let table = plan.table.layout();
        let buckets = table.buckets();
        let bundle = alloc::raw::Recipe::try_build(Self::recipe(table))?;
        let fields = bundle.try_allocate()?;
        // SAFETY: the freshly allocated bundle carries exactly the directory planes
        // admitted by `buckets`, which one `Layout` proved for this recipe.
        let dir = unsafe { map::raw::Table::from_fields(fields.prior().prior().prior(), buckets) };
        let meta = fields.prior().prior().tail();
        let dense = fields.prior().tail();
        let values = fields.tail();
        for index in 0..capacity {
            let next = if index + 1 == capacity {
                None
            } else {
                // SAFETY: `index + 1 < capacity <= Index::END` names one slot in this core's domain.
                Some(unsafe { links::Index::new_usize(index + 1) })
            };
            // SAFETY: `index < capacity` addresses one metadata slot of this allocation,
            // which is uninitialized until this write and never read before it.
            unsafe { meta.as_ptr().add(index).write(Meta::vacant(next)) };
        }
        Ok(Self {
            directory: dir,
            thread: marker::PhantomData,
            meta,
            dense,
            values,
            plan,
            len: 0,
            free: (capacity != 0).then_some(NonZero::<u32>::MIN.into()),
            tag: marker::PhantomData,
        })
    }

    pub(in crate::depot::arena::hash) const fn capacity(&self) -> usize {
        self.plan.capacity().get()
    }

    fn position(&self, index: usize) -> Option<(Index, &Meta)> {
        if index >= self.capacity() {
            return None;
        }
        // SAFETY: the admitted index is below capacity and therefore Index::END.
        let index = unsafe { Index::from_proven(index as u32) };
        Some((index, unsafe { self.meta(index) }))
    }

    pub(super) fn lookup(
        &self,
        key: key::Handle<runtime::Domain<Tag>>,
    ) -> Result<Index, errors::Lookup<Tag>> {
        let Some((index, meta)) = self.position(key.index() as usize) else {
            return Err(errors::Lookup::Index {
                key,
                capacity: self.capacity(),
            });
        };
        if !meta.is_live() {
            return Err(errors::Lookup::Vacant {
                key,
                actual: meta.generation,
            });
        }
        if meta.generation != key.generation() {
            return Err(errors::Lookup::Generation {
                key,
                actual: meta.generation,
            });
        }
        Ok(index)
    }

    pub(in crate::depot::arena::hash) fn live_at(
        &self,
        index: usize,
    ) -> Option<(Index, key::Generation)> {
        let (index, meta) = self.position(index)?;
        meta.is_live().then_some((index, meta.generation))
    }

    pub(super) unsafe fn meta(&self, index: Index) -> &Meta {
        // SAFETY: the caller bounds `index` by capacity; this core initialized every such slot in `try_new`.
        unsafe { &*self.meta.as_ptr().add(index.into_usize()) }
    }

    pub(super) unsafe fn meta_mut(&mut self, index: Index) -> &mut Meta {
        // SAFETY: the caller bounds `index` by capacity, and the exclusive borrow keeps the slot unique.
        unsafe { &mut *self.meta.as_ptr().add(index.into_usize()) }
    }

    /// # Safety
    /// `index` must be below this core's capacity and name a live, initialized value.
    pub(super) unsafe fn value(&self, index: Index) -> &T {
        // SAFETY: the caller bounds `index` by capacity and proves the slot initialized.
        unsafe { (&*self.values.as_ptr().add(index.into_usize())).assume_init_ref() }
    }

    /// # Safety
    /// `index` must be below this core's capacity and name a live, initialized value.
    pub(super) unsafe fn value_mut(&mut self, index: Index) -> &mut T {
        // SAFETY: the caller bounds `index` by capacity, proves the slot initialized,
        // and the exclusive borrow keeps the value unique.
        unsafe { (&mut *self.values.as_ptr().add(index.into_usize())).assume_init_mut() }
    }

    /// # Safety
    /// `index` must be below this core's capacity, so it addresses one initialized
    /// metadata slot whose generation names this key's exact slot.
    pub(super) unsafe fn key_for(&self, index: Index) -> key::Handle<runtime::Domain<Tag>> {
        // SAFETY: the caller bounds `index` by capacity; `meta` reads that initialized slot.
        key::Handle::new(index.get(), unsafe { self.meta(index) }.generation)
    }
}

impl<T, Tag> Core<T, Tag> {
    pub(in crate::depot::arena::hash) fn vacant(&mut self) -> Option<hash::Vacant<'_, T, Tag>> {
        let index = Index::from_one(self.free?.position());
        Some(hash::Vacant { core: self, index })
    }

    /// # Safety
    /// This slot is initialized in this owner and has membership phase `P`.
    pub(super) unsafe fn live<P>(&mut self, index: Index) -> entry::Live<'_, T, Tag, P> {
        entry::Live {
            core: self,
            index,
            phase: marker::PhantomData,
        }
    }

    pub(super) fn dense(&self) -> &[Index] {
        // SAFETY: this owner initializes each element of its dense live prefix once.
        unsafe { slice::from_raw_parts(self.dense.as_ptr(), self.len as usize) }
    }
}

impl<T, Tag> Core<T, Tag> {
    /// # Safety
    /// The map owns the live indexed slot; its field borrows must permit this exclusive loan.
    pub unsafe fn bind(
        map: &mut runtime::Map<T, Tag>,
        index: links::Index,
    ) -> entry::Live<'_, T, Tag> {
        unsafe { map.core.live(Index::from_one(index.position())) }
    }

    /// # Safety
    /// The slot is live in this map; pointer accesses must respect its field loans and lifetime.
    pub unsafe fn project(entry: &entry::Live<'_, T, Tag>, index: links::Index) -> *mut T {
        unsafe { entry.core.values.add(index.get()).cast::<T>().as_ptr() }
    }
}

impl<T, Tag> Drop for Core<T, Tag> {
    fn drop(&mut self) {
        let recipe = Self::recipe(self.plan.table.layout());
        // SAFETY: this exclusive owner reconstructs the recipe-bound bundle.
        let layout = unsafe { alloc::raw::Recipe::build(recipe) };
        let pointer = self.directory.base();
        if needs_drop::<T>() {
            for &index in self.dense().iter().rev() {
                // SAFETY: each dense position owns one distinct live value.
                unsafe {
                    self.values
                        .add(index.into_usize())
                        .as_mut()
                        .assume_init_drop()
                };
            }
        }
        // SAFETY: this exclusive owner reconstructs the recipe-bound bundle and
        // releases the allocation once, after every initialized value is cleared.
        unsafe { layout.deallocate(pointer) };
    }
}

const _: () = assert!(size_of::<Core<u64>>() == 9 * size_of::<usize>());

impl<T, Tag> Core<T, Tag> {
    fn recipe(table: map::raw::Layout<Index>) -> impl alloc::raw::Recipe<Fields = Fields<T>> {
        use alloc::raw::Recipe as _;

        let capacity = table.shape().capacity().get();
        alloc::raw::Recipe::tail::<Meta>(table, capacity)
            .tail::<Index>(capacity)
            .tail::<MaybeUninit<T>>(capacity)
    }
}

type Fields<T> = alloc::raw::Tail<
    alloc::raw::Tail<
        alloc::raw::Tail<<map::raw::Layout<Index> as alloc::raw::Recipe>::Fields, Meta>,
        Index,
    >,
    MaybeUninit<T>,
>;

pub(super) const VACANT: u32 = 1 << 31;

#[derive(Clone, Copy)]
#[repr(C)]
pub(super) struct Meta {
    pub(super) generation: key::Generation,
    pub(super) slot: u32,
    pub(super) bucket: Option<map::raw::Occupied>,
}

impl Meta {
    pub(super) const FREE: u32 = (1 << 31) - 1;

    fn vacant(next: Option<links::Index>) -> Self {
        Self {
            generation: key::Generation::MIN,
            slot: VACANT | next.map_or(Self::FREE, links::Index::raw),
            bucket: None,
        }
    }

    const fn is_live(&self) -> bool {
        self.slot & VACANT == 0
    }

    pub(super) fn next(&self) -> Option<links::Index> {
        let next = self.slot & Self::FREE;
        if next == Self::FREE {
            None
        } else {
            // SAFETY: the packed free link retains its original allocation index.
            Some(unsafe { links::Index::new_raw(next) })
        }
    }
}

const _: () = assert!(size_of::<Meta>() == 3 * size_of::<u32>());
const _: () = assert!(size_of::<Option<map::raw::Occupied>>() == size_of::<u32>());

// SAFETY: each directory read keeps the core's allocation, slot domain and live slots unchanged.
unsafe impl<'a, T, Tag> map::raw::Query for &'a mut Core<T, Tag> {
    const SPARE: bool = true;
    type Payload = Index;
    type Value = T;
    type Occupied = entry::Live<'a, T, Tag, entry::Indexed>;

    fn table(&self) -> &map::raw::Table<Self::Payload> {
        &self.directory
    }

    fn value(entry: map::Found<&Self>) -> &T {
        let (owner, payload) = entry.project();
        let index = *payload;
        // SAFETY: the directory retains only live payloads within its domain, so this index is initialized.
        unsafe { Core::value(owner, index) }
    }

    fn occupied(entry: map::Found<Self>) -> Self::Occupied {
        let (owner, index) = entry.copied();
        // SAFETY: the occupied bucket retains one live entry at this bounded index.
        unsafe { owner.live(index) }
    }
}

// SAFETY: the vacancy retains the same core and publishes its exact hash and payload.
unsafe impl<'a, T, Tag> map::raw::Insertion for &'a mut Core<T, Tag> {
    type Vacant = entry::Vacancy<'a, T, Tag>;

    fn vacant(entry: map::Vacancy<Self>, hash: u64) -> Option<Self::Vacant> {
        let (core, bucket, ()) = entry.into_parts();
        let hash::Vacant { core, index } = core.vacant()?;
        Some(entry::Vacancy {
            core,
            index,
            bucket,
            hash,
        })
    }
}

// SAFETY: the exclusive core borrow keeps the directory and reverse indices uniquely owned.
unsafe impl<T, Tag> map::raw::Mutation for &mut Core<T, Tag> {
    /// # Safety
    /// The caller preserves this exact directory and every live payload it holds.
    unsafe fn table_mut(&mut self) -> &mut map::raw::Table<Self::Payload> {
        &mut self.directory
    }

    /// # Safety
    /// Both buckets belong to this core; `next` is live with `hash` and `hole` is vacant.
    unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64) {
        // SAFETY: both buckets belong to this directory; `next` is live with `hash` and `hole` is vacant.
        let (moved, index) = unsafe { self.directory.shift(hole, next, hash) };
        let index = *index;
        // SAFETY: a directory shift reports an index below capacity, so its metadata slot is initialized.
        unsafe { self.meta_mut(index).bucket = Some(moved) };
    }
}

// SAFETY: the shared Map loan preserves its directory and initialized resident slots.
unsafe impl<T, Tag, P> map::raw::Query for &runtime::Map<T, Tag, P> {
    const SPARE: bool = true;
    type Payload = Index;
    type Value = T;
    type Occupied = key::Handle<runtime::Domain<Tag>>;
    fn table(&self) -> &map::raw::Table<Self::Payload> {
        &self.core.directory
    }
    fn value(entry: map::Found<&Self>) -> &T {
        let (owner, payload) = entry.project();
        // SAFETY: the directory contains only live positions in this retained owner.
        unsafe { owner.core.value(*payload) }
    }
    fn occupied(entry: map::Found<Self>) -> Self::Occupied {
        let (owner, index) = entry.copied();
        // SAFETY: the directory proves the exact initialized slot and generation.
        unsafe { owner.core.key_for(index) }
    }
}

// SAFETY: the staged entry retains the exclusive core and its live directory.
unsafe impl<T, Tag> map::raw::Query for entry::Live<'_, T, Tag, entry::Staged> {
    type Payload = Index;
    type Value = T;
    type Occupied = (Self, key::Handle<runtime::Domain<Tag>>);

    fn table(&self) -> &map::raw::Table<Self::Payload> {
        &self.core.directory
    }

    fn value(entry: map::Found<&Self>) -> &T {
        let (owner, index) = entry.project();
        // SAFETY: a directory payload names a live value in this retained core.
        unsafe { owner.core.value(*index) }
    }

    fn occupied(entry: map::Found<Self>) -> Self::Occupied {
        let (owner, index) = entry.copied();
        // SAFETY: the collision retains its initialized slot and exact generation.
        let key = unsafe { owner.core.key_for(index) };
        (owner, key)
    }
}