o3 0.62.0

shared-nothing primitives
Documentation
use std::{alloc::Layout, marker::PhantomData, mem, ptr};

use crate::alloc::{self, tail::Plan};

#[repr(C)]
pub(super) struct Prefix<H, T, N: alloc::raw::TailExtent> {
    header: H,
    plan: Plan<H, T, N>,
}

/// Allocation with no initialized header or tail.
#[must_use = "initialize the allocation or release it"]
pub struct Uninit<H, T, N: alloc::raw::TailExtent = usize> {
    pub(super) memory: ptr::NonNull<Prefix<H, T, N>>,
    pub(super) layout: Plan<H, T, N>,
}

/// Sole ownership of the initialized header and tail.
#[repr(transparent)]
pub struct Block<H, T, N: alloc::raw::TailExtent = usize> {
    pointer: ptr::NonNull<Prefix<H, T, N>>,
}

/// Pointer-sized borrow retaining provenance over the entire allocation.
#[repr(transparent)]
pub struct View<'a, H, T, N: alloc::raw::TailExtent = usize> {
    pointer: ptr::NonNull<Prefix<H, T, N>>,
    borrow: PhantomData<&'a Block<H, T, N>>,
}

impl<H, T, N: alloc::raw::TailExtent> Prefix<H, T, N> {
    pub(super) fn layout(plan: Plan<H, T, N>) -> Layout {
        // SAFETY: the original layout extension admitted the padded size at this alignment.
        unsafe {
            Layout::from_size_align_unchecked(
                Plan::<H, T, N>::padded(plan.value.len()),
                Plan::<H, T, N>::ALIGN,
            )
        }
    }
}

impl<H, T, N: alloc::raw::TailExtent> Uninit<H, T, N> {
    pub fn init(self, header: H) -> Block<H, mem::MaybeUninit<T>, N> {
        let owner = mem::ManuallyDrop::new(self);
        // SAFETY: the exact allocation has an aligned, exclusively owned vacant prefix.
        unsafe {
            owner.memory.write(Prefix {
                header,
                plan: owner.layout,
            })
        };
        Block {
            pointer: owner.memory.cast(),
        }
    }

    pub fn fill(self, header: H, mut init: impl FnMut(&H, N::Index) -> T) -> Block<H, T, N> {
        let indices = self.layout.value.indices();
        let block = self.init(header);
        let view = View::new(&block);
        let slots = view.data().cast::<T>();
        let header = view.header();
        for index in indices {
            // SAFETY: alloc::raw::TailExtent issues each ordinal exactly once, in the disjoint tail.
            unsafe {
                slots
                    .add(alloc::raw::TailIndex::get(index))
                    .write(init(header, index))
            };
        }
        // SAFETY: the entire issued extent now contains initialized values.
        unsafe { block.assume_init() }
    }

    pub fn repeat(self, header: H, value: T) -> Block<H, T, N>
    where
        T: Copy,
    {
        let mut block = self.init(header);
        block.as_mut_slice().fill(mem::MaybeUninit::new(value));
        // SAFETY: the entire admitted slice was initialized by fill.
        unsafe { block.assume_init() }
    }
}

impl<H, T, N: alloc::raw::TailExtent> Drop for Uninit<H, T, N> {
    fn drop(&mut self) {
        // SAFETY: the allocation has this exact layout and contains no live values.
        unsafe { alloc::raw::LayoutExt::deallocate(self.layout.layout(), self.memory) };
    }
}

impl<H, T, N: alloc::raw::TailExtent> Block<H, mem::MaybeUninit<T>, N> {
    /// # Safety
    /// Every tail slot contains an initialized T.
    pub(crate) unsafe fn assume_init(self) -> Block<H, T, N> {
        Block {
            pointer: mem::ManuallyDrop::new(self).pointer.cast(),
        }
    }

    pub(crate) fn into_header(self) -> H {
        let owner = mem::ManuallyDrop::new(self);
        let layout = View::new(&owner).len_proof();
        // SAFETY: the sole initialized header moves once. The tail has no drop obligations.
        let header = unsafe { (&raw const (*owner.pointer.as_ptr()).header).read() };
        drop(Uninit {
            memory: owner.pointer,
            layout,
        });
        header
    }
}

impl<H, T, N: alloc::raw::TailExtent> Block<H, T, N> {
    pub(crate) fn extent(&self) -> N {
        View::new(self).len_proof().extent()
    }

    pub fn header_mut(&mut self) -> &mut H {
        // SAFETY: exclusive ownership covers the initialized header.
        unsafe { &mut (*self.pointer.as_ptr()).header }
    }

    pub fn parts_mut(&mut self) -> (&mut H, &mut [T]) {
        let (_, tail) = View::new(self).parts();
        // SAFETY: the header and initialized tail are disjoint in this exclusive allocation.
        unsafe { (&mut (*self.pointer.as_ptr()).header, &mut *tail) }
    }

    pub fn as_mut_slice(&mut self) -> &mut [T] {
        self.parts_mut().1
    }
}

impl<H, T, N: alloc::raw::TailExtent> Drop for Block<H, T, N> {
    fn drop(&mut self) {
        let (layout, tail) = View::new(self).parts();
        // SAFETY: this is the sole destruction right. The header remains live until the
        // last tail element is gone; its destructor runs before deallocation.
        unsafe {
            ptr::drop_in_place(tail);
            ptr::drop_in_place(self.pointer.as_ptr());
        }
        drop(Uninit {
            memory: self.pointer,
            layout,
        });
    }
}

impl<'a, H, T, N: alloc::raw::TailExtent> View<'a, H, T, N> {
    pub fn new(block: &'a Block<H, T, N>) -> Self {
        Self {
            pointer: block.pointer,
            borrow: PhantomData,
        }
    }

    /// # Safety
    /// This pointer retains the entire exact initialized allocation for `'a`.
    pub(crate) unsafe fn from_raw(pointer: ptr::NonNull<u8>) -> Self {
        Self {
            pointer: pointer.cast(),
            borrow: PhantomData,
        }
    }

    pub(crate) const fn as_ptr(&self) -> ptr::NonNull<u8> {
        self.pointer.cast()
    }

    fn prefix(self) -> &'a Prefix<H, T, N> {
        // SAFETY: the view borrows this initialized prefix for its entire lifetime.
        unsafe { self.pointer.as_ref() }
    }

    pub(in crate::alloc) fn data(&self) -> ptr::NonNull<T> {
        // SAFETY: the allocation retains the admitted offset, also when the tail is empty.
        unsafe { self.pointer.byte_add(Plan::<H, T, N>::tail_offset()).cast() }
    }

    fn parts(self) -> (Plan<H, T, N>, *mut [T]) {
        let plan = self.len_proof();
        (
            plan,
            ptr::slice_from_raw_parts_mut(self.data().as_ptr(), plan.value.len()),
        )
    }

    pub(crate) fn len_proof(self) -> Plan<H, T, N> {
        self.prefix().plan
    }

    pub fn header(self) -> &'a H {
        &self.prefix().header
    }

    pub fn len(self) -> usize {
        self.len_proof().value.len()
    }

    pub fn is_empty(self) -> bool {
        self.len() == 0
    }

    pub fn as_slice(&self) -> &'a [T] {
        // SAFETY: the retained extent covers the initialized, immutably borrowed tail.
        unsafe { &*self.parts().1 }
    }
}

impl<H, T, N: alloc::raw::TailExtent> Clone for View<'_, H, T, N> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<H, T, N: alloc::raw::TailExtent> Copy for View<'_, H, T, N> {}

/// A pointer-sized resident borrow retaining its complete allocation provenance.
#[repr(transparent)]
pub struct Resident<'a, H, T, N: alloc::raw::TailExtent = usize> {
    pointer: ptr::NonNull<T>,
    borrow: PhantomData<&'a Block<H, T, N>>,
}

impl<'a, H, T, N: alloc::raw::TailExtent> Resident<'a, H, T, N> {
    /// # Safety
    /// `index` is within this exact initialized view's tail.
    pub unsafe fn new(view: View<'a, H, T, N>, index: N::Index) -> Self {
        // SAFETY: the bounded ordinal is derived from the complete allocation pointer.
        let pointer = unsafe { view.data().add(alloc::raw::TailIndex::get(index)) };
        Self {
            pointer,
            borrow: PhantomData,
        }
    }

    pub fn get(self) -> &'a T {
        // SAFETY: construction retains this initialized element and owner's lifetime.
        unsafe { self.pointer.as_ref() }
    }

    /// Recovers the original whole-allocation view from an immutable resident ordinal.
    /// # Safety
    /// `index` is exactly the ordinal passed when this resident was constructed.
    pub unsafe fn view(self, index: N::Index) -> View<'a, H, T, N> {
        // SAFETY: subtracting the original ordinal and admitted tail offset
        // recovers the same retained allocation pointer without leaving its bounds.
        let pointer = unsafe {
            self.pointer
                .sub(alloc::raw::TailIndex::get(index))
                .cast::<u8>()
                .sub(Plan::<H, T, N>::tail_offset())
                .cast()
        };
        // SAFETY: the exact original ordinal recovers this retained allocation's prefix.
        unsafe { View::from_raw(pointer) }
    }
}

impl<H, T, N: alloc::raw::TailExtent> Clone for Resident<'_, H, T, N> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<H, T, N: alloc::raw::TailExtent> Copy for Resident<'_, H, T, N> {}

const _: () = {
    assert!(std::mem::size_of::<Resident<'static, u8, u8>>() == std::mem::size_of::<usize>());
    assert!(
        std::mem::size_of::<Option<Resident<'static, u8, u8>>>() == std::mem::size_of::<usize>()
    );
};