o3 0.61.0

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

use crate::{
    alloc,
    depot::{heap, index::Position, raw::Address},
};

/// # Safety
/// Given a caller-admitted initialized prefix, reverse map and ordering domain, each
/// primitive preserves the stated transition. This trait does not initialize a heap.
/// Comparisons preserve storage and membership. Mutations never expose or reenter a hole.
pub unsafe trait Source {
    type Value;

    fn len(&self) -> u32;

    /// # Safety
    /// Restore the initialized prefix and reverse map before releasing this loan.
    unsafe fn len_mut(&mut self) -> &mut u32;

    /// # Safety
    /// The position is initialized and value belongs to this same ordering domain.
    unsafe fn compare(&self, position: usize, value: &Self::Value) -> cmp::Ordering;

    /// # Safety
    /// The position is initialized and value preserves its encoded identity.
    unsafe fn direction(&self, position: usize, value: &Self::Value) -> cmp::Ordering {
        unsafe { self.compare(position, value) }
    }

    /// # Safety
    /// Both positions are initialized in this unchanged owner.
    unsafe fn compare_at(&self, left: usize, right: usize) -> cmp::Ordering;

    /// # Safety
    /// This initialized position is transferred once; REMOVE ends its membership.
    unsafe fn read<const REMOVE: bool>(&mut self, position: usize) -> Self::Value;

    /// # Safety
    /// Source is initialized, target is the distinct hole, and both belong to this owner.
    unsafe fn shift(&mut self, source: usize, target: usize);

    /// # Safety
    /// The target is this owner's final hole. Without PLACE its identity is unchanged.
    unsafe fn write<const PLACE: bool>(&mut self, position: usize, value: Self::Value);
}

impl<E, I: Position, R, C: alloc::raw::Extent, const INDEXED: bool>
    heap::Capacity<E, I, R, C, INDEXED>
{
    pub(in crate::depot::heap) fn uninit(self) -> Result<alloc::raw::Uninit<Self>, heap::Error<C>> {
        let mut memory =
            alloc::raw::Uninit::try_new(self).map_err(move |error| heap::Error::Allocation {
                capacity: self.count(),
                layout: alloc::raw::Shape::layout(&self),
                error,
            })?;
        memory.planes_mut().1.fill(mem::MaybeUninit::new(I::NONE));
        Ok(memory)
    }

    pub fn allocate(self) -> Result<alloc::raw::Block<Self, u32>, heap::Error<C>> {
        let memory = self.uninit()?;
        // SAFETY: the reverse plane is initialized; the dense prefix is empty.
        Ok(unsafe { memory.finish(0, ()) })
    }

    pub fn allocate_repeat(
        self,
        resident: R,
    ) -> Result<alloc::raw::Block<Self, u32, ptr::NonNull<R>>, heap::Error<C>>
    where
        R: Copy,
    {
        let mut memory = self.uninit()?;
        let residents = memory.planes_mut().2;
        residents.fill(mem::MaybeUninit::new(resident));
        let residents = ptr::NonNull::from(residents).cast();
        // SAFETY: both complete planes are initialized; Copy residents require no Drop.
        Ok(unsafe { memory.finish(0, residents) })
    }
}

impl<K: Address, P, R, C: alloc::raw::Extent, X, const INDEXED: bool>
    alloc::raw::Block<heap::Capacity<(K, P), u32, R, C, INDEXED>, u32, X>
{
    /// # Safety
    /// State retains this block's admitted initialized heap prefix.
    pub unsafe fn heap_first(&self) -> Option<&(K, P)> {
        if self.state == 0 {
            None
        } else {
            Some(unsafe { self.heap_value(0) })
        }
    }

    /// # Safety
    /// The reverse plane is initialized and key belongs to its admitted index domain.
    pub unsafe fn heap_position(&self, key: K) -> u32 {
        unsafe { *self.tail().get_unchecked(key.index()) }
    }

    /// # Safety
    /// Position belongs to this block's initialized heap prefix.
    pub unsafe fn heap_value(&self, position: usize) -> &(K, P) {
        unsafe { self.as_ref().get_unchecked(position).assume_init_ref() }
    }
}

impl<K: Address, P, R, C: alloc::raw::Extent, const INDEXED: bool>
    alloc::raw::Block<heap::Capacity<(K, P), u32, R, C, INDEXED>, u32, ptr::NonNull<R>>
{
    /// # Safety
    /// Key belongs to this block's admitted, initialized resident plane.
    pub unsafe fn resident(&self, key: K) -> &R {
        unsafe { self.values().get_unchecked(key.index()) }
    }

    /// # Safety
    /// Key belongs to this block's admitted, initialized resident plane.
    pub unsafe fn resident_mut(&mut self, key: K) -> &mut R {
        unsafe { self.values_mut().get_unchecked_mut(key.index()) }
    }
}

// The final owner's admitted dense entries and reverse positions share this block.
unsafe impl<K: Address, P: Ord, R, C: alloc::raw::Extent, X, const INDEXED: bool> Source
    for alloc::raw::Block<heap::Capacity<(K, P), u32, R, C, INDEXED>, u32, X>
{
    type Value = (K, P);

    fn len(&self) -> u32 {
        self.state
    }

    unsafe fn len_mut(&mut self) -> &mut u32 {
        &mut self.state
    }

    unsafe fn compare(&self, position: usize, value: &Self::Value) -> cmp::Ordering {
        let other = unsafe { self.heap_value(position) };
        match value.1.cmp(&other.1) {
            cmp::Ordering::Equal if INDEXED => value.0.index().cmp(&other.0.index()),
            order => order,
        }
    }

    unsafe fn direction(&self, position: usize, value: &Self::Value) -> cmp::Ordering {
        let other = unsafe { self.heap_value(position) };
        value.1.cmp(&other.1)
    }

    unsafe fn compare_at(&self, left: usize, right: usize) -> cmp::Ordering {
        let left = unsafe { self.heap_value(left) };
        unsafe { self.compare(right, left) }
    }

    unsafe fn read<const REMOVE: bool>(&mut self, position: usize) -> Self::Value {
        let (_, values, positions) = self.parts_mut();
        let value = unsafe { values.get_unchecked_mut(position) };
        if REMOVE {
            let index = unsafe { value.assume_init_ref() }.0;
            unsafe { *positions.get_unchecked_mut(index.index()) = u32::MAX };
        }
        unsafe { value.assume_init_read() }
    }

    unsafe fn shift(&mut self, source: usize, target: usize) {
        let (_, values, positions) = self.parts_mut();
        let [to, from] = unsafe { values.get_disjoint_unchecked_mut([target, source]) };
        let value = unsafe { from.assume_init_ref() };
        unsafe {
            *positions.get_unchecked_mut(value.0.index()) = target as u32;
            ptr::copy_nonoverlapping(value, to.as_mut_ptr(), 1);
        }
    }

    unsafe fn write<const PLACE: bool>(&mut self, position: usize, value: Self::Value) {
        let (_, values, positions) = self.parts_mut();
        if PLACE {
            unsafe { *positions.get_unchecked_mut(value.0.index()) = position as u32 };
        }
        unsafe { values.get_unchecked_mut(position) }.write(value);
    }
}