o3 0.62.0

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

use crate::{
    depot::{
        array::{copy, init},
        capacity,
    },
    mem::slot::Occupied,
};

/// Exclusive ownership of initialized elements in caller-provided array storage.
#[derive(Debug)]
#[must_use = "dropping the iterator releases its unread values"]
pub struct Drain<'a, T, const REVERSE: bool = false> {
    first: ptr::NonNull<T>,
    len: usize,
    borrow: marker::PhantomData<&'a mut [mem::MaybeUninit<T>]>,
}

impl<'a, T, const REVERSE: bool> Drain<'a, T, REVERSE> {
    pub(in crate::depot) fn empty<U, const N: usize>(
        entries: &'a mut [mem::MaybeUninit<U>; N],
    ) -> Self {
        let entries = crate::mem::raw::cast_uninit::<U, T, N>(entries);
        Self {
            first: ptr::NonNull::from_mut(entries).cast(),
            len: 0,
            borrow: marker::PhantomData,
        }
    }

    pub(in crate::depot) const fn extent(&self) -> usize {
        self.len
    }

    pub(in crate::depot) fn as_slice(&self) -> &[T] {
        // SAFETY: the cursor owns exactly len initialized elements starting at first.
        unsafe { slice::from_raw_parts(self.first.as_ptr(), self.len) }
    }

    pub fn as_mut_slice(&mut self) -> &mut [T] {
        // SAFETY: the same initialized range is exclusively borrowed.
        unsafe { slice::from_raw_parts_mut(self.first.as_ptr(), self.len) }
    }

    pub(in crate::depot) fn at<'b, U, const N: usize>(
        guard: &init::Guard<'_, T, N, REVERSE, init::Vacant>,
        values: &'b [U; N],
    ) -> &'b U {
        // SAFETY: this phase was issued only after checking len < N.
        unsafe { values.get_unchecked(guard.as_slice().len()) }
    }

    pub(in crate::depot) fn paired<'b, 'c, U, const N: usize>(
        guard: &'b init::Guard<'_, T, N, REVERSE, init::Vacant>,
        values: &'c [U; N],
    ) -> iter::Zip<slice::Iter<'b, T>, slice::Iter<'c, U>> {
        let prefix = guard.as_slice();
        // SAFETY: the vacancy retains exactly this initialized prefix in capacity N.
        let other = unsafe { values.get_unchecked(..prefix.len()) };
        prefix.iter().zip(other)
    }

    fn write(&mut self, value: T) {
        // SAFETY: each caller consumes a distinct vacancy before extending this prefix.
        unsafe { self.first.add(self.len).write(value) };
        self.len += 1;
    }

    pub(in crate::depot) fn fill_vacancy<const N: usize>(
        slot: init::Guard<'a, T, N, REVERSE, init::Vacant>,
        value: T,
    ) -> Self {
        let mut storage = slot.into_iter();
        storage.write(value);
        storage
    }

    pub(in crate::depot) fn fill_row<V, const N: usize>(
        row: init::Row<'_, 'a, '_, T, V, N, REVERSE>,
        value: T,
    ) {
        // SAFETY: the consumed row exclusively borrows its guard after one source advance.
        unsafe { row.storage().as_mut() }.write(value);
    }

    pub(in crate::depot) fn take_full<const N: usize>(
        full: init::Guard<'a, T, N, REVERSE, init::Full>,
    ) -> [T; N] {
        let storage = mem::ManuallyDrop::new(full.into_iter());
        // SAFETY: Full transfers all N elements; their former destructor is disarmed.
        unsafe { storage.first.cast::<[T; N]>().read() }
    }
}

impl<'a, T> Drain<'a, T> {
    pub(in crate::depot) fn key<'b, 'id, const N: usize>(
        prefix: &'b init::Prefix<'_, 'id, T, N>,
        key: capacity::Key<'id, u8>,
    ) -> &'b T {
        // SAFETY: only publish issues this invariant brand's keys; positions remain initialized.
        unsafe { prefix.as_slice().get_unchecked(*key.as_inner() as usize) }
    }

    pub(in crate::depot) fn key_mut<'b, 'id, const N: usize>(
        prefix: &'b mut init::Prefix<'_, 'id, T, N>,
        key: capacity::Key<'id, u8>,
    ) -> &'b mut T {
        // SAFETY: this exclusive projection retains the same branded position.
        unsafe {
            prefix
                .as_mut_slice()
                .get_unchecked_mut(*key.as_inner() as usize)
        }
    }

    pub(in crate::depot) fn publish<'id, const N: usize>(
        slot: init::Slot<'_, '_, 'id, T, N>,
        value: T,
    ) -> capacity::Key<'id, u8> {
        let (mut storage, slot) = slot.parts();
        // SAFETY: the consumed slot holds this prefix exclusively for the insertion.
        let storage = unsafe { storage.as_mut() };
        let index = slot.index() as u8;
        // SAFETY: this vacancy retains the exact next position in the same branded array.
        unsafe { storage.first.add(index as usize).write(value) };
        storage.len = slot.commit().get();
        // SAFETY: the branded position is initialized and remains live until the scope ends.
        capacity::Key::new(unsafe { crate::depot::raw::Proof::new(index) })
    }
    pub(in crate::depot) fn take<const N: usize>(source: &'a mut copy::Vec<T, N>) -> Self {
        let entries = source.take_entries();
        let len = entries.len();
        Self {
            first: ptr::NonNull::from_mut(entries).cast(),
            len,
            borrow: marker::PhantomData,
        }
    }
}

impl<T, const REVERSE: bool> Iterator for Drain<'_, T, REVERSE> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        if self.len == 0 {
            return None;
        }
        let first = self.first;
        self.len -= 1;
        // SAFETY: retiring the live first position leaves len elements from its successor.
        unsafe {
            self.first = first.add(1);
            Some(first.read())
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len, Some(self.len))
    }
}

impl<T, const REVERSE: bool> ExactSizeIterator for Drain<'_, T, REVERSE> {}
impl<T, const REVERSE: bool> iter::FusedIterator for Drain<'_, T, REVERSE> {}

impl<'a, T, const N: usize> From<Occupied<'a, [T; N]>> for Drain<'a, T> {
    fn from(owner: Occupied<'a, [T; N]>) -> Self {
        let mut source = owner.into_uninit();
        Self {
            first: ptr::NonNull::from_mut(source.get_mut()).cast(),
            len: N,
            borrow: marker::PhantomData,
        }
    }
}

impl<T, const REVERSE: bool> Drop for Drain<'_, T, REVERSE> {
    fn drop(&mut self) {
        // SAFETY: this terminal cursor owns exactly these unread values.
        unsafe {
            let entries = ptr::slice_from_raw_parts_mut(self.first.as_ptr(), self.len);
            if REVERSE {
                for value in slice::from_raw_parts_mut(self.first.as_ptr(), self.len)
                    .iter_mut()
                    .rev()
                {
                    ptr::drop_in_place(value);
                }
            } else {
                ptr::drop_in_place(entries);
            }
        }
    }
}

const _: () = assert!(size_of::<Drain<'static, u8>>() == 2 * size_of::<usize>());