o3 0.61.0

shared-nothing primitives
Documentation
use std::{marker, mem, ptr};

use crate::depot::{
    self,
    arena::linked::{self, fifo, fifo::ends, slots},
    capacity,
};

/// Sole return entitlement, retaining the allocation's original owner.
pub type Vacant<T, H, Tag = ()> = Slot<T, H, Tag, 0>;
/// An initialized detached slot and the owner that may publish it.
pub type Live<T, H, Tag = ()> = Slot<T, H, Tag, 1>;
/// One reserved credit, optionally owning its initialized unpublished node.
pub type Reserved<T, H, Tag = ()> = Slot<T, H, Tag, 2>;

#[must_use = "a detached slot retains its sole return entitlement"]
pub struct Slot<T, H: linked::Source<T>, Tag, const PHASE: u8> {
    owner: H,
    index: slots::Index<Tag>,
    value: marker::PhantomData<T>,
}

impl<T, H: linked::Source<T>, Tag, const PHASE: u8> Slot<T, H, Tag, PHASE> {
    /// # Safety
    /// The owner retains one debit without other loans. Phases 0 and 1 own the
    /// selected node, initialized only for 1. Phase 2 either owns a live node
    /// or keeps its unclaimed credit at Index::NONE.
    pub(crate) unsafe fn detached(owner: H, index: slots::Index<Tag>) -> Self {
        Self {
            owner,
            index,
            value: marker::PhantomData,
        }
    }

    /// # Safety
    /// Transfer the slot, its initialization state and its sole return right to
    /// the original topology or reservation before exposing it to another caller.
    pub(crate) unsafe fn into_raw_parts(self) -> (H, slots::Index<Tag>) {
        let slot = mem::ManuallyDrop::new(self);
        (unsafe { ptr::read(&slot.owner) }, slot.index)
    }
}

impl<T, H: linked::Source<T>, Tag, const PHASE: u8> Drop for Slot<T, H, Tag, PHASE> {
    fn drop(&mut self) {
        let store = self.owner.store();
        if PHASE == 2 && self.index.get().is_none() {
            if H::TRACK {
                store.refund(1);
            }
            return;
        }
        let index = self.index.raw();
        let node = unsafe { store.slot(index) };
        if PHASE != 0 {
            // SAFETY: this slot retains the value and its address throughout destruction.
            unsafe { (&mut *node.value.get()).assume_init_drop() };
        }
        store.recycle(index, node, H::TRACK);
    }
}

impl<T, H: linked::Source<T>, Tag> Vacant<T, H, Tag> {
    /// # Safety
    /// This owner's store counts all available slots and the owner refunds each claim.
    pub(in crate::depot) unsafe fn try_reserve(owner: H) -> Option<Self> {
        if owner.store().available() == 0 {
            return None;
        }
        Some(unsafe { Self::reserve(owner) })
    }

    fn debit(owner: &H) {
        if H::TRACK {
            owner.store().debit(capacity::Count::new(1));
        }
    }

    /// # Safety
    /// This exact owner has one available slot.
    pub unsafe fn reserve(owner: H) -> Self {
        Self::debit(&owner);
        unsafe { Self::claim(owner) }
    }

    /// # Safety
    /// One already debited reservation is consumed from this exact store.
    pub(in crate::depot::arena::linked) unsafe fn claim(owner: H) -> Self {
        let (index, _) = unsafe { owner.store().claim(None) };
        unsafe { Self::detached(owner, index) }
    }

    /// # Safety
    /// This exact owner has one available slot.
    pub(crate) unsafe fn insert_one(owner: H, value: T) -> Live<T, H, Tag> {
        Self::debit(&owner);
        unsafe { Live::claim(owner, value) }
    }

    pub fn get_mut(&mut self) -> &mut mem::MaybeUninit<T> {
        let node = unsafe { self.owner.store().slot(self.index.raw()) };
        // SAFETY: this vacancy solely owns the exact uninitialized field.
        unsafe { &mut *node.value.get() }
    }

    /// # Safety
    /// This exact field contains an initialized T and retains no value loans.
    pub unsafe fn assume_init(self) -> Live<T, H, Tag> {
        let (owner, index) = unsafe { self.into_raw_parts() };
        let node = unsafe { owner.store().slot(index.raw()) };
        node.next.set(slots::Store::<T>::END);
        unsafe { Live::detached(owner, index) }
    }

    pub fn insert(self, value: T) -> Live<T, H, Tag> {
        let (owner, index) = unsafe { self.into_raw_parts() };
        let node = unsafe { owner.store().slot(index.raw()) };
        unsafe { node.value.get().cast::<T>().write(value) };
        node.next.set(slots::Store::<T>::END);
        unsafe { Live::detached(owner, index) }
    }
}

pub struct Write<'a, T, H: linked::Source<T>, Tag = ()> {
    slot: &'a mut Reserved<T, H, Tag>,
}

impl<T, H: linked::Source<T>, Tag> Reserved<T, H, Tag> {
    /// # Safety
    /// This tracked owner counts and returns every admitted slot credit.
    pub(in crate::depot) unsafe fn try_reserve(owner: H) -> Option<Self> {
        if owner.store().available() == 0 {
            return None;
        }
        Vacant::<T, H, Tag>::debit(&owner);
        Some(unsafe { Self::detached(owner, slots::Index::NONE) })
    }

    pub fn is_empty(&self) -> bool {
        self.index.get().is_none()
    }

    pub fn vacant(&mut self) -> Option<Write<'_, T, H, Tag>> {
        if self.is_empty() {
            Some(Write { slot: self })
        } else {
            None
        }
    }

    pub fn clear(&mut self) {
        if let Some(index) = self.index.get() {
            let store = self.owner.store();
            let node = unsafe { store.slot(index) };
            // SAFETY: this sole unpublished owner retains the initialized value.
            unsafe { (&mut *node.value.get()).assume_init_drop() };
            store.recycle(index, node, false);
            self.index = slots::Index::NONE;
        }
    }

    pub fn finish(self) -> Option<Live<T, H, Tag>> {
        let (owner, index) = unsafe { self.into_raw_parts() };
        if index.get().is_none() {
            if H::TRACK {
                owner.store().refund(1);
            }
            None
        } else {
            Some(unsafe { Live::detached(owner, index) })
        }
    }
}

impl<T, H: linked::Source<T>, Tag> Write<'_, T, H, Tag> {
    pub fn insert(self, value: T) {
        // SAFETY: this short loan retains the unchanged unclaimed credit.
        let (index, target) = unsafe { self.slot.owner.store().claim(Some(slots::Index::NONE)) };
        unsafe { (*target).write(value) };
        self.slot.index = index;
    }
}

impl<T, H: linked::Source<T>, Tag> Live<T, H, Tag> {
    /// # Safety
    /// The exact store has one debited slot ready for immediate initialization.
    pub(super) unsafe fn claim(owner: H, value: T) -> Self {
        let (index, slot) = unsafe { owner.store().claim(Some(slots::Index::NONE)) };
        unsafe { (*slot).write(value) };
        unsafe { Self::detached(owner, index) }
    }

    pub fn get(&self) -> &T {
        unsafe { self.owner.store().value(self.index) }
    }

    pub(crate) fn take(self) -> (T, Vacant<T, H, Tag>) {
        let (owner, index) = unsafe { self.into_raw_parts() };
        let node = unsafe { owner.store().slot(index.raw()) };
        let value = unsafe { (&*node.value.get()).assume_init_read() };
        node.next.set(index.raw());
        (value, unsafe { Vacant::detached(owner, index) })
    }

    pub fn append_ends(
        proof: depot::raw::Proof<(Self, &mut ends::Exclusive<slots::Index<Tag>>), fifo::Append>,
    ) {
        let (node, ends) = proof.into_inner();
        let (owner, index) = unsafe { node.into_raw_parts() };
        unsafe { ends.append_end(owner.store(), index) };
    }

    /// # Safety
    /// The queue belongs to this exact store and the claim has no successor.
    pub(in crate::depot) unsafe fn append_to(self, queue: &mut fifo::Fifo<Tag>) {
        let (owner, index) = unsafe { self.into_raw_parts() };
        unsafe { queue.link::<_, false>(owner.store(), index) };
    }
}

impl<T, M: Copy, Tag, const TRACK: bool> Live<(T, M), slots::Borrow<'_, (T, M), TRACK>, Tag> {
    /// Moves the payload to its final storage and returns this slot.
    pub fn take_into(self, place: &mut mem::MaybeUninit<T>) {
        let (slots::Borrow(store), index) = unsafe { self.into_raw_parts() };
        let node = unsafe { store.slot(index.raw()) };
        // SAFETY: this detached pair owns T; Copy metadata needs no destruction.
        unsafe {
            place
                .as_mut_ptr()
                .write(ptr::addr_of!((*node.value_ptr()).0).read());
        }
        store.recycle(index.raw(), node, TRACK);
    }
}

impl<T, Tag, const TRACK: bool> Live<T, slots::Borrow<'_, T, TRACK>, Tag> {
    /// # Safety
    /// All owning fields have been consumed. No value loans or destruction or
    /// pin obligations remain.
    pub unsafe fn recycle(self) {
        let (slots::Borrow(store), index) = unsafe { self.into_raw_parts() };
        let index = index.raw();
        store.recycle(index, unsafe { store.slot(index) }, TRACK);
    }

    pub fn into_inner(self) -> T {
        let (slots::Borrow(store), index) = unsafe { self.into_raw_parts() };
        unsafe { store.take::<_, TRACK>(index) }
    }
}

impl<T, Tag> Live<T, &slots::Store<T>, Tag> {
    /// # Safety
    /// Transfer this initialized slot into a topology retaining the original store.
    pub(crate) unsafe fn into_index(self) -> slots::Index<Tag> {
        unsafe { self.into_raw_parts() }.1
    }

    /// Publishes the initialized claim into the FIFO proved to retain its exact store.
    pub fn push_back(proof: depot::raw::Proof<(Self, &mut fifo::Fifo<Tag>), linked::Same>) {
        let (claim, queue) = proof.into_inner();
        unsafe { claim.append_to(queue) };
    }
}

impl<T, Tag, const TRACK: bool> crate::mem::Return
    for Vacant<T, slots::Bound<'_, T, Tag, TRACK>, Tag>
{
    type Item = T;

    fn return_item(self, item: T) {
        self.insert(item).publish::<true>();
    }
}