o3 0.62.0

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

use crate::{
    base::num::bounded,
    depot::array::{self, Len, copy, sorted},
};

mod drain;
pub use drain::Drain;

/// Native positions in the fixed domain `0..N`.
/// # Safety
/// Values must identify positions below `N` bijectively; reconstruction is inverse.
pub unsafe trait BitIndex<const N: usize>: Copy {
    fn index(self) -> usize;
    /// # Safety
    /// The position must be below `N`, and `N` must be at most sixteen.
    unsafe fn from_index(index: usize) -> Self;
}

pub(super) fn prefix<T, const N: usize>(len: array::Len<N>, values: &[T; N]) -> &[T] {
    // SAFETY: the bounded length is at most the size of this array.
    unsafe { values.get_unchecked(..len.get()) }
}

pub(super) fn prefix_mut<T, const N: usize>(len: array::Len<N>, values: &mut [T; N]) -> &mut [T] {
    // SAFETY: the exclusive borrow retains the same bounded prefix.
    unsafe { values.get_unchecked_mut(..len.get()) }
}

pub(super) fn at<'a, T, const N: usize>(slot: &array::Vacancy<N>, values: &'a [T; N]) -> &'a T {
    // SAFETY: the vacancy's position is strictly below N.
    unsafe { values.get_unchecked(slot.index()) }
}

pub(super) fn at_mut<'a, T, const N: usize>(
    slot: &array::Vacancy<N>,
    values: &'a mut [T; N],
) -> &'a mut T {
    // SAFETY: the same affine position selects one element of the exclusive array.
    unsafe { values.get_unchecked_mut(slot.index()) }
}

pub(super) fn insert_at<'a, T: Copy, const N: usize, const M: usize>(
    slot: &array::Vacancy<N>,
    values: &[T; M],
    value: T,
    out: &'a mut mem::MaybeUninit<[T; N]>,
) -> &'a mut [T; N] {
    const { assert!(M < N && M + 1 == N) };
    let index = slot.index();
    // SAFETY: index <= M. Two disjoint copies and the gap value initialize all N positions.
    unsafe {
        let target = out.as_mut_ptr().cast::<T>();
        ptr::copy_nonoverlapping(values.as_ptr(), target, index);
        target.add(index).write(value);
        ptr::copy_nonoverlapping(values.as_ptr().add(index), target.add(index + 1), M - index);
        out.assume_init_mut()
    }
}

pub(super) fn bit_at<I: BitIndex<N>, const N: usize>(slot: array::Vacancy<N>) -> I {
    const { assert!(N <= u16::BITS as usize) };
    // SAFETY: the retained position is below N in the native bit domain.
    unsafe { I::from_index(slot.index()) }
}

pub(super) const fn compact_position<const N: usize>(slot: array::Vacancy<N>) -> NonZero<u8> {
    const { assert!(N <= u8::MAX as usize) };
    // SAFETY: committing this vacancy gives its one-based position in 1..=N.
    unsafe { NonZero::new_unchecked(slot.commit().get() as u8) }
}

pub(super) const fn position_u32<const N: usize, const MAX: u32>(
    index: array::Index<N>,
) -> bounded::raw::U32<0, MAX> {
    const { assert!(N <= u8::MAX as usize && N.saturating_sub(1) <= MAX as usize) };
    // SAFETY: the position is below N, so its zero-based value is at most MAX.
    unsafe { bounded::raw::U32::from_proven(index.index() as u32) }
}

pub(super) fn slice<T, const N: usize>(source: &copy::Vec<T, N>) -> &[T] {
    // SAFETY: source.len counts its initialized prefix.
    unsafe { source.len.prefix(&source.entries).assume_init_ref() }
}

pub(super) fn slice_mut<T, const N: usize>(source: &mut copy::Vec<T, N>) -> &mut [T] {
    // SAFETY: the exclusively borrowed vector owns its entire initialized prefix.
    unsafe { source.len.prefix_mut(&mut source.entries).assume_init_mut() }
}

pub(super) fn retain<T: Copy, const N: usize>(
    source: &mut copy::Vec<T, N>,
    mut keep: impl FnMut(&T) -> bool,
) {
    let values: &mut [T] = source;
    let Some(mut written) = values.iter().position(|value| !keep(value)) else {
        return;
    };
    for read in written + 1..values.len() {
        if keep(&values[read]) {
            let value = values[read];
            // SAFETY: the first hole and ordered scan keep written < read < values.len().
            unsafe { *values.get_unchecked_mut(written) = value };
            written += 1;
        }
    }
    source.len = Len(written as u32);
}

pub(super) fn pop<T: Copy, const N: usize>(source: &mut copy::Vec<T, N>) -> Option<T> {
    let last = NonZero::new(source.len.0)?;
    source.len = Len(last.get() - 1);
    // SAFETY: the shortened position held the initialized last value.
    Some(unsafe {
        source
            .entries
            .get_unchecked(source.len.get())
            .assume_init_read()
    })
}

pub(super) fn ordered<T: Copy + Ord, const N: usize>(
    source: &mut copy::Vec<T, N>,
    value: T,
) -> Result<(), sorted::Error<T>> {
    let position = match source.binary_search(&value) {
        Ok(index) => {
            // SAFETY: the search found this index in the initialized prefix.
            let existing = unsafe { *source.get_unchecked(index) };
            return Err(sorted::Error::Duplicate { value, existing });
        }
        Err(index) => index,
    };
    let slot = source
        .len
        .vacancy()
        .ok_or(sorted::Error::Full { value, capacity: N })?;
    // SAFETY: position is in 0..=len; the admitted vacancy fits the shifted suffix.
    unsafe {
        let start = source.entries.as_mut_ptr().add(position);
        ptr::copy(start, start.add(1), source.len.get() - position);
        start.write(mem::MaybeUninit::new(value));
    }
    source.len = slot.commit();
    Ok(())
}

pub(super) fn next<T, const N: usize>(cursor: &mut copy::IntoIter<T, N>) -> Option<T> {
    let front = cursor.front;
    if front == cursor.back {
        return None;
    }
    cursor.front = Len(front.0.wrapping_add(1));
    // SAFETY: the original front lies inside the initialized unread interval.
    Some(unsafe { cursor.entries.get_unchecked(front.get()).assume_init_read() })
}

pub(super) fn restore<T, const N: usize>(slot: array::Withdrawn<'_, T, N>, value: T) {
    let cursor = &mut slot.source.raw;
    let front = Len(cursor.front.0.wrapping_sub(1));
    // SAFETY: the consumed entitlement exclusively retains the preceding vacated slot.
    unsafe { cursor.entries.get_unchecked_mut(front.get()) }.write(value);
    cursor.front = front;
}

pub(super) fn release<T, const N: usize>(cursor: &mut copy::IntoIter<T, N>) {
    let front = mem::replace(&mut cursor.front, cursor.back);
    // SAFETY: taking the remaining interval transfers its initialized values for destruction.
    unsafe {
        cursor
            .entries
            .get_unchecked_mut(front.get()..cursor.back.get())
            .assume_init_drop()
    };
}