o3 0.62.0

shared-nothing primitives
Documentation
use crate::base::num;
use crate::depot::{
    arena::slab::{self, entries, external, external::errors},
    index::Initialized,
    queue::links,
};
use std::{
    marker,
    mem::{ManuallyDrop, MaybeUninit},
    pin::Pin,
    ptr,
};
type Entry<'a, T, G, const LIVE: bool> = slab::raw::Entry<
    'a,
    external::Stamped<T, G>,
    1,
    entries::Exclusive<true>,
    1,
    slab::Lazy,
    LIVE,
    false,
>;

pub struct Anchor<'a, T, G: num::Step, Tag = ()> {
    entry: Entry<'a, T, G, false>,
    next: &'a mut Option<G>,
    generation: G,
    tag: marker::PhantomData<fn() -> Tag>,
}

pub struct Anchored<'a, T, G: num::Step, Tag = ()> {
    entry: Entry<'a, T, G, true>,
    tag: marker::PhantomData<fn() -> Tag>,
}

type Retirement<'a, T, G> = slab::raw::Retirement<
    'a,
    external::Stamped<T, G>,
    1,
    entries::Exclusive<true>,
    1,
    slab::Lazy,
    true,
>;

impl<'a, T, G: num::Step, Tag> Anchor<'a, T, G, Tag> {
    pub(super) fn try_new(
        owner: Pin<&'a mut external::Pinned<T, G, Tag>>,
    ) -> Result<Self, slab::Vacancy> {
        // SAFETY: only next is mutably borrowed; the pinned slot plane stays at its original address.
        let owner = unsafe { owner.get_unchecked_mut() };
        let epoch = owner.next.ok_or(slab::Vacancy::IdentityExhausted)?;
        let entry = owner.core.free().ok_or(slab::Vacancy::Full)?;
        Ok(Self {
            entry,
            next: &mut owner.next,
            generation: epoch,
            tag: marker::PhantomData,
        })
    }

    pub fn index(&self) -> links::Index {
        self.entry.index()
    }

    pub fn uninit(&mut self) -> &mut MaybeUninit<T> {
        let stamp = self.entry.uninit().as_mut_ptr();
        // SAFETY: this exact reservation owns the inactive stamped payload.
        unsafe { &mut *ptr::addr_of_mut!((*stamp).value).cast::<MaybeUninit<T>>() }
    }

    pub fn occupy(mut self, value: T) -> (external::Key<G, Tag>, Anchored<'a, T, G, Tag>) {
        self.uninit().write(value);
        // SAFETY: this exact reserved value is initialized without outstanding loans.
        unsafe { self.publish() }
    }

    /// # Safety
    /// This reserved value is initialized, unborrowed, and was not previously pinned.
    pub unsafe fn publish(mut self) -> (external::Key<G, Tag>, Anchored<'a, T, G, Tag>) {
        let epoch = self.generation;
        let stamp = self.entry.uninit().as_mut_ptr();
        unsafe { ptr::addr_of_mut!((*stamp).generation).write(epoch) };
        let index = self.entry.index();
        let entry = unsafe { self.entry.publish() };
        *self.next = epoch.next();
        (
            external::Key::new(index.raw(), epoch),
            Anchored {
                entry,
                tag: marker::PhantomData,
            },
        )
    }
}

impl<'a, T, G: num::Step, Tag> Anchored<'a, T, G, Tag> {
    pub(super) fn try_new(
        owner: Pin<&'a mut external::Pinned<T, G, Tag>>,
        key: external::Key<G, Tag>,
    ) -> Result<Self, errors::Lookup<G, Tag>> {
        let core = &owner.into_ref().get_ref().core;
        let entry =
            slab::raw::Position::stamped(key, slab::raw::Position::try_at(core, key.index()))?
                .take();
        Ok(Self {
            entry,
            tag: marker::PhantomData,
        })
    }

    /// # Safety
    /// The index is live in this exact pinned owner and has no overlapping loan.
    pub(in crate::depot) unsafe fn from_slot(
        owner: Pin<&'a mut external::Pinned<T, G, Tag>>,
        index: links::Index,
    ) -> Self {
        let entry = unsafe { owner.into_ref().get_ref().core.project(index) };
        Self {
            entry,
            tag: marker::PhantomData,
        }
    }

    pub fn index(&self) -> links::Index {
        self.entry.index()
    }

    pub fn value(&mut self) -> Pin<&mut T> {
        // SAFETY: this initialized stamp stays pinned under the original owner loan.
        unsafe { Pin::new_unchecked(&mut self.entry.value_mut().value) }
    }

    pub fn into_value(self) -> Pin<&'a mut T> {
        // SAFETY: the original exclusive pinned owner loan outlives this projection.
        unsafe { Pin::new_unchecked(&mut self.entry.into_mut().value) }
    }

    pub fn as_mut_ptr(&mut self) -> *mut T {
        Retirement::payload(self.entry.slot())
    }

    pub fn retire(self) -> Retirement<'a, T, G> {
        Retirement::new(&self.entry.into_place())
    }

    pub fn project<P>(live: crate::depot::raw::Proof<(&Self, links::Index), Initialized<P>>) -> &T {
        let (owner, index) = live.into_inner();
        // SAFETY: this initialized neighbor stays in the original pinned owner loan.
        &unsafe { owner.entry.core().read(index) }.value
    }

    pub fn discard(self) {
        self.entry.issue();
    }
}

// SAFETY: the initialized proof retains this exact shared stamped payload.
unsafe impl<'a, T, G: num::Step, Tag, const N: usize, P> crate::depot::raw::Project<links::Index, P>
    for &'a external::Exclusive<T, G, Tag, N>
{
    type Output = &'a T;

    unsafe fn project(self, index: links::Index) -> Self::Output {
        &unsafe { self.core.read(index) }.value
    }
}

/// A detached physical reservation whose drop destroys the payload while it is initialized.
pub struct Withdrawn<'a, T, G: num::Step, const N: usize, const INITIALIZED: bool> {
    entry: slab::raw::Entry<
        'a,
        external::Stamped<T, G>,
        1,
        entries::Exclusive<true>,
        N,
        slab::Heap,
        false,
        true,
    >,
}

impl<'a, T, G: num::Step, const N: usize> Withdrawn<'a, T, G, N, true> {
    pub(super) fn new<Tag>(
        owner: external::Occupied<'a, T, G, Tag, entries::Exclusive<true>, N>,
    ) -> Self {
        Self {
            entry: owner.entry.withdraw(),
        }
    }

    pub fn get_mut(&mut self) -> &mut T {
        // SAFETY: the detached value is initialized and exclusively held.
        unsafe { &mut (*self.entry.slot().value_ptr()).value }
    }

    /// Transfers payload destruction while retaining the same reservation.
    pub fn into_uninit(self) -> Withdrawn<'a, T, G, N, false> {
        let this = ManuallyDrop::new(self);
        // SAFETY: the retained entry moves exactly once; the old destruction is disarmed.
        Withdrawn {
            entry: unsafe { ptr::read(&this.entry) },
        }
    }
}

impl<T, G: num::Step, const N: usize> Withdrawn<'_, T, G, N, false> {
    pub fn get_mut(&mut self) -> &mut MaybeUninit<T> {
        // SAFETY: only the possibly uninitialized field is borrowed; the reservation is still held.
        unsafe {
            &mut *ptr::addr_of_mut!((*self.entry.slot().value_ptr()).value).cast::<MaybeUninit<T>>()
        }
    }
}

impl<T, G: num::Step, const N: usize, const INITIALIZED: bool> Drop
    for Withdrawn<'_, T, G, N, INITIALIZED>
{
    fn drop(&mut self) {
        if INITIALIZED {
            // SAFETY: this phase owns the initialized stamp's destruction before physical reuse.
            unsafe { self.entry.slot().drop_value() };
        }
    }
}