o3 0.59.0

shared-nothing primitives
Documentation
//! Fixed-capacity arrays specialized for [`Copy`] elements.

use std::{mem, num, ops, slice};

use crate::depot::array::{self, Len, Vacancy};

/// An inline vector without drop glue.
#[repr(C)]
#[derive(Copy, Debug)]
pub struct Vec<T, const N: usize> {
    pub(super) len: Len<N>,
    pub(super) entries: [mem::MaybeUninit<T>; N],
}

impl<T, const N: usize> Vec<T, N> {
    pub(super) const fn empty() -> Self {
        Self {
            entries: [const { mem::MaybeUninit::uninit() }; N],
            len: Len::ZERO,
        }
    }

    pub(super) fn single(value: T) -> Self {
        let len = Len::ONE;
        let mut entries = [const { mem::MaybeUninit::uninit() }; N];
        // SAFETY: Len::ONE proves N is nonzero at monomorphization.
        entries[0].write(value);
        Self { entries, len }
    }

    pub(super) fn init(&mut self, len: Len<N>, mut f: impl FnMut(Vacancy<N>) -> T) {
        for (index, entry) in len.prefix_mut(&mut self.entries).iter_mut().enumerate() {
            // SAFETY: this position is below the bounded nonempty prefix end.
            let next = unsafe { num::NonZero::new_unchecked(index as u32 + 1) };
            entry.write(f(Vacancy(next)));
        }
        self.len = len;
    }

    /// Maps one bounded source into this destination while retaining its borrow.
    pub fn map_from<'a, U: Copy>(
        &mut self,
        source: &'a Vec<U, N>,
        mut make: impl FnMut(Vacancy<N>, &'a U) -> T,
    ) {
        drop(array::init::IntoIter::drain(self));
        let values = source.as_slice();
        self.init(source.extent(), |slot| {
            // SAFETY: init issues exactly the positions in this initialized source prefix.
            let value = unsafe { values.get_unchecked(slot.index()) };
            make(slot, value)
        });
    }

    pub fn vacancy(&mut self) -> Option<array::Vacant<'_, T, N>> {
        let slot = self.len.vacancy()?;
        Some(array::Vacant { raw: self, slot })
    }

    /// Returns the initialized-prefix length with its fixed capacity attached.
    pub const fn extent(&self) -> Len<N> {
        self.len
    }

    pub fn as_slice(&self) -> &[T] {
        unsafe { self.len.prefix(&self.entries).assume_init_ref() }
    }

    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { self.len.prefix_mut(&mut self.entries).assume_init_mut() }
    }

    pub(super) fn from_array(values: [T; N]) -> Self {
        Self {
            entries: values.map(mem::MaybeUninit::new),
            len: Len::MAX,
        }
    }
}

impl<T: Copy, const N: usize> Clone for Vec<T, N> {
    fn clone(&self) -> Self {
        *self
    }
}

/// A consuming iterator without drop glue.
#[derive(Debug)]
#[repr(C)]
pub struct IntoIter<T, const N: usize> {
    pub(in crate::depot::array) entries: [mem::MaybeUninit<T>; N],
    pub(in crate::depot::array) front: Len<N>,
    pub(in crate::depot::array) back: Len<N>,
}

const _: () = {
    assert!(mem::size_of::<IntoIter<u8, 4>>() == 12);
    assert!(mem::size_of::<IntoIter<u64, 4>>() == 40);
    assert!(mem::align_of::<IntoIter<u64, 4>>() == 8);
};

impl<T: Copy, const N: usize> Default for Vec<T, N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Copy, const N: usize> Vec<T, N> {
    pub const fn new() -> Self {
        Self::empty()
    }

    pub fn from_one(value: T) -> Self {
        Self::single(value)
    }

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

    pub fn pop(&mut self) -> Option<T> {
        let last = num::NonZero::new(self.len.0)?;
        let len = Len(last.get() - 1);
        self.len = len;
        Some(unsafe { self.entries.as_ptr().add(len.get()).read().assume_init() })
    }
}

impl<T: Copy, const N: usize> From<[T; N]> for Vec<T, N> {
    fn from(values: [T; N]) -> Self {
        Self::from_array(values)
    }
}

impl<T: Copy, const N: usize> AsRef<[T]> for Vec<T, N> {
    fn as_ref(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T: Copy, const N: usize> ops::Deref for Vec<T, N> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<T: Copy, const N: usize> ops::DerefMut for Vec<T, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_slice()
    }
}

impl<'a, T: Copy, const N: usize> IntoIterator for &'a Vec<T, N> {
    type IntoIter = slice::Iter<'a, T>;
    type Item = &'a T;

    fn into_iter(self) -> Self::IntoIter {
        self.as_slice().iter()
    }
}

impl<T: Copy, const N: usize> IntoIterator for Vec<T, N> {
    type IntoIter = IntoIter<T, N>;
    type Item = T;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter::new(self)
    }
}

impl<T, const N: usize> IntoIter<T, N> {
    pub(super) fn new(prefix: Vec<T, N>) -> Self {
        Self {
            entries: prefix.entries,
            front: Len::ZERO,
            back: prefix.len,
        }
    }
}

impl<T, const N: usize> Iterator for IntoIter<T, N> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        if self.front == self.back {
            return None;
        }
        let index = self.front.get();
        self.front = Len(self.front.0.wrapping_add(1));
        Some(unsafe { self.entries.get_unchecked(index).assume_init_read() })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.back.get() - self.front.get();
        (len, Some(len))
    }
}

impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {}