o3 0.62.0

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

use crate::alloc;

pub mod raw;

/// Checked extent of a header followed by its aligned tail.
#[repr(transparent)]
pub struct Plan<H, T, N: alloc::raw::TailExtent = usize> {
    value: N,
    types: PhantomData<fn() -> (H, T)>,
}

impl<H, T, N: alloc::raw::TailExtent> Plan<H, T, N> {
    const ALIGN: usize = {
        let prefix = mem::align_of::<raw::Prefix<H, T, N>>();
        let element = mem::align_of::<T>();
        if prefix > element { prefix } else { element }
    };

    pub fn try_new(extent: N) -> Result<Self, alloc::Overflow> {
        if !Self::fits(extent.len()) {
            return Err(alloc::Overflow);
        }
        Ok(Self {
            value: extent,
            types: PhantomData,
        })
    }

    const fn fits(len: usize) -> bool {
        alloc::raw::Layout::<T>::try_extend(Layout::new::<raw::Prefix<H, T, N>>(), len).is_ok()
    }

    const fn tail_offset() -> usize {
        mem::size_of::<raw::Prefix<H, T, N>>().next_multiple_of(mem::align_of::<T>())
    }

    const fn padded(len: usize) -> usize {
        (Self::tail_offset() + len * mem::size_of::<T>()).next_multiple_of(Self::ALIGN)
    }

    pub fn layout(&self) -> Layout {
        raw::Prefix::layout(*self)
    }

    pub(crate) const fn extent(self) -> N {
        self.value
    }

    pub fn try_allocate(self) -> Result<raw::Uninit<H, T, N>, alloc::Exhausted> {
        Ok(raw::Uninit {
            memory: alloc::raw::LayoutExt::try_allocate(self.layout())?,
            layout: self,
        })
    }
}

impl<H, T> Plan<H, T> {
    pub const fn size(self) -> usize {
        Self::padded(self.value)
    }

    #[must_use]
    pub const fn fixed<const LEN: usize>() -> Self {
        const {
            assert!(Self::fits(LEN), "layout");
        }
        Self {
            value: LEN,
            types: PhantomData,
        }
    }
}

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

impl<H, T, N: alloc::raw::TailExtent> Copy for Plan<H, T, N> {}

const _: () = {
    assert!(std::mem::size_of::<raw::Block<usize, usize>>() == std::mem::size_of::<usize>());
    assert!(
        std::mem::size_of::<Option<raw::Block<usize, usize>>>() == std::mem::size_of::<usize>()
    );
    assert!(
        std::mem::size_of::<raw::View<'static, usize, usize>>() == std::mem::size_of::<usize>()
    );
    assert!(std::mem::size_of::<raw::Uninit<usize, usize>>() == 2 * std::mem::size_of::<usize>());
    assert!(
        std::mem::size_of::<Option<raw::Uninit<usize, usize>>>()
            == 2 * std::mem::size_of::<usize>()
    );
    assert!(
        std::mem::size_of::<Result<Plan<usize, usize>, crate::alloc::Overflow>>()
            == 2 * std::mem::size_of::<usize>()
    );
};