o3 0.62.0

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

use crate::alloc::{self, Exhausted};

/// An unpublished allocation whose planes can only be borrowed uninitialized.
/// Dropping it releases the backing. Callers retire any initialized values before abandoning it.
pub struct Uninit<E: alloc::raw::Shape> {
    memory: ptr::NonNull<u8>,
    extent: E,
}

impl<E: alloc::raw::Shape> Uninit<E> {
    pub fn try_new(extent: E) -> Result<Self, Exhausted> {
        Ok(Self {
            memory: alloc::raw::LayoutExt::try_allocate(extent.layout())?,
            extent,
        })
    }

    pub fn planes_mut(&mut self) -> Arrays<'_, E::Root, E::Tail, E::Extra, E::Last> {
        let len = self.extent.len();
        // SAFETY: the shape proves four aligned, disjoint planes in this exclusively borrowed allocation.
        unsafe {
            let entries = self.plane(0, len);
            let extra = self.plane(self.extent.extra(), len);
            let last = self.plane(self.extent.last(), len);
            (&mut *entries, self.tail_mut(), &mut *extra, &mut *last)
        }
    }

    /// # Safety
    /// Root has R's exact layout and initialization, Tail is initialized, and
    /// extra retains the auxiliary planes' locations and initialization states.
    pub unsafe fn finish<S, X, R>(self, state: S, extra: X) -> alloc::raw::Block<E, S, X, R> {
        let root = self.memory.cast();
        // SAFETY: the retained shape proves the tail's exact offset and alignment.
        let tail = unsafe { self.memory.add(self.extent.offset()) }.cast();
        let memory = mem::ManuallyDrop::new(self);
        // SAFETY: ownership of the shape and allocation moves once into the initialized block.
        let extent = unsafe { ptr::read(&memory.extent) };
        alloc::raw::Block {
            root,
            tail,
            extent,
            state,
            extra,
        }
    }

    unsafe fn plane<T>(&self, offset: usize, len: usize) -> *mut [mem::MaybeUninit<T>] {
        // SAFETY: the caller supplies the admitted offset and extent for T.
        let entries = unsafe { self.memory.add(offset) }.cast::<mem::MaybeUninit<T>>();
        ptr::slice_from_raw_parts_mut(entries.as_ptr(), len)
    }

    fn tail_mut(&mut self) -> &mut [mem::MaybeUninit<E::Tail>] {
        // SAFETY: the immutable shape supplies the exact tail under this exclusive borrow.
        unsafe { &mut *self.plane(self.extent.offset(), self.extent.tail_len()) }
    }

    unsafe fn write_pair<A, B>(
        &mut self,
        first: usize,
        second: usize,
        make: impl Fn(usize) -> (A, B),
    ) -> (ptr::NonNull<A>, ptr::NonNull<B>) {
        let len = self.extent.len();
        // SAFETY: the caller selects disjoint A/B planes, each with exactly len rows.
        let (first, second) =
            unsafe { (&mut *self.plane(first, len), &mut *self.plane(second, len)) };
        for (index, (left, right)) in first.iter_mut().zip(second.iter_mut()).enumerate() {
            let (a, b) = make(index);
            left.write(a);
            right.write(b);
        }
        (
            ptr::NonNull::from(first).cast(),
            ptr::NonNull::from(second).cast(),
        )
    }
}

type Arrays<'a, A, B, C, D> = (
    &'a mut [mem::MaybeUninit<A>],
    &'a mut [mem::MaybeUninit<B>],
    &'a mut [mem::MaybeUninit<C>],
    &'a mut [mem::MaybeUninit<D>],
);

impl<E: alloc::raw::Rows> Uninit<E> {
    pub(crate) fn try_fill<S>(
        extent: E,
        state: S,
        init: impl Fn(usize) -> (mem::MaybeUninit<E::Root>, E::Tail),
    ) -> Result<alloc::raw::Block<E, S>, Exhausted> {
        const { assert!(!mem::needs_drop::<E::Tail>()) };
        let mut memory = Uninit::try_new(extent)?;
        // SAFETY: Rows gives equal lengths; the first plane accepts MaybeUninit<Root>.
        unsafe { memory.write_pair(0, memory.extent.offset(), init) };
        // SAFETY: Rows gives equal lengths; the loop wrote every tail entry.
        Ok(unsafe { memory.finish(state, ()) })
    }
}

impl<E: alloc::raw::Shape> Uninit<E> {
    pub fn try_from_fn<S>(
        extent: E,
        state: S,
        root: impl Fn(usize) -> E::Root,
        tail: impl Fn(usize) -> E::Tail,
    ) -> Result<alloc::raw::Block<E, S, (), E::Root>, Exhausted> {
        const { assert!(!mem::needs_drop::<E::Tail>()) };
        let mut memory = Uninit::try_new(extent)?;
        // SAFETY: Shape places the complete root plane at zero.
        let entries = unsafe { &mut *memory.plane(0, memory.extent.len()) };
        alloc::raw::init(entries, &root);
        alloc::raw::init(memory.tail_mut(), tail);
        // SAFETY: the separate loops initialized each complete plane, including
        // Shapes whose root and tail lengths differ.
        Ok(unsafe { memory.finish(state, ()) })
    }
}

impl<E: alloc::raw::Shape<Last = ()>> Uninit<E> {
    /// Initializes each root and auxiliary row together, then the separate tail.
    pub fn try_planes<S>(
        extent: E,
        state: S,
        root: impl Fn(usize) -> (E::Root, E::Extra),
        tail: impl Fn(usize) -> E::Tail,
    ) -> Result<alloc::raw::Block<E, S, alloc::raw::Initialized, E::Root>, Exhausted> {
        const {
            assert!(!mem::needs_drop::<E::Tail>());
            assert!(!mem::needs_drop::<E::Extra>());
        };
        let mut memory = Uninit::try_new(extent)?;
        // SAFETY: root and extra are disjoint and both have the shape's root length.
        unsafe { memory.write_pair(0, memory.extent.extra(), &root) };
        alloc::raw::init(memory.tail_mut(), tail);
        // SAFETY: all three complete planes are initialized; the marker retains
        // auxiliary initialization while its location is reconstructed from the shape.
        Ok(unsafe { memory.finish(state, alloc::raw::Initialized) })
    }
}

impl<E: alloc::raw::Rows<Tail = mem::MaybeUninit<T>>, T> Uninit<E> {
    pub fn try_parts<S>(
        extent: E,
        state: S,
        init: impl Fn(usize) -> (E::Extra, E::Last),
    ) -> Result<alloc::raw::Parts<E, S>, Exhausted> {
        const {
            assert!(!mem::needs_drop::<E::Extra>());
            assert!(!mem::needs_drop::<E::Last>());
        };
        let mut memory = Uninit::try_new(extent)?;
        // SAFETY: extra and last are disjoint and both have the shape's root length.
        let extra =
            unsafe { memory.write_pair(memory.extent.extra(), memory.extent.last(), &init) };
        // SAFETY: both equal-length auxiliary planes were fully initialized;
        // root and tail remain MaybeUninit and the pointers retain their owner.
        Ok(unsafe { memory.finish(state, extra) })
    }
}

impl<E: alloc::raw::Shape> Drop for Uninit<E> {
    fn drop(&mut self) {
        // SAFETY: an unfinished owner retains its original allocation and has published no plane.
        unsafe { alloc::raw::LayoutExt::deallocate(self.extent.layout(), self.memory) };
    }
}