o3 0.62.0

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

use crate::buffer::{
    self, resident,
    storage::{self, alloc},
    write::consume,
};

#[repr(C)]
#[derive(Debug)]
pub(in crate::buffer) struct Header<P: buffer::raw::Policy> {
    pub(super) prefix: storage::raw::Prefix<num::NonZero<u32>>,
    pub(super) policy: P,
}

// SAFETY: this initialized header retains its exact embedded reference domain.
unsafe impl<P: buffer::raw::Policy> crate::mem::raw::Edge for Header<P> {
    fn count(&self) -> &crate::mem::raw::Count {
        crate::mem::raw::Edge::count(&self.prefix)
    }
}

// SAFETY: every counted edge retains this allocation and its initialized policy.
unsafe impl<P: buffer::raw::Policy> crate::mem::raw::Target for Header<P> {
    unsafe fn destroy(pointer: ptr::NonNull<Self>) {
        // SAFETY: the last counted edge transfers this exact initialized allocation.
        unsafe { Self::destroy(pointer) };
    }
}

impl<P: buffer::raw::Policy> Header<P> {
    pub(in crate::buffer) const DATA_OFFSET: usize = size_of::<Self>();
    const VALID: () = assert!(
        crate::alloc::raw::Layout::<u8>::try_extend(Layout::new::<Self>(), u32::MAX as usize)
            .is_ok()
    );

    pub(in crate::buffer) fn layout(capacity: num::NonZero<u32>) -> Layout {
        let () = Self::VALID;
        // SAFETY: VALID admits this exact header followed by any u32 byte count;
        // the byte tail starts at DATA_OFFSET and preserves the header alignment.
        unsafe {
            crate::alloc::raw::Layout::<u8>::extend(Layout::new::<Self>(), capacity.get() as usize)
                .0
        }
    }

    /// # Safety
    /// Transfer the full debit, or transfer a sole owner's existing credit
    /// with its exact same-policy delta and free its old region on success.
    pub(super) unsafe fn try_new(
        capacity: num::NonZero<u32>,
        debit: P::Debit,
    ) -> Result<ptr::NonNull<Self>, crate::alloc::Exhausted> {
        // SAFETY: this layout includes an aligned header and the nonzero byte tail.
        let pointer = unsafe { crate::alloc::raw::try_new::<Self>(Self::layout(capacity), false)? };
        // SAFETY: this fresh region receives its initialized header before publication.
        unsafe {
            pointer.write(Self {
                prefix: storage::raw::Prefix::one(capacity),
                policy: debit.into(),
            });
        }
        Ok(pointer)
    }

    /// # Safety
    /// Transfer the live header after `Last`, or from its sole static owner.
    pub(in crate::buffer) unsafe fn destroy(pointer: ptr::NonNull<Self>) {
        // SAFETY: the transferred owner keeps this initialized header live.
        let header = unsafe { pointer.as_ref() };
        let capacity = header.capacity();
        // SAFETY: terminal ownership transfers the complete charge and its exact allocation once.
        unsafe { header.policy.deallocate(pointer.cast(), capacity) };
    }

    pub(in crate::buffer) unsafe fn free(pointer: ptr::NonNull<Self>, capacity: num::NonZero<u32>) {
        // SAFETY: the caller transfers this exact region and has released or
        // transferred any initialized policy's charge; no destructors remain.
        unsafe { crate::alloc::raw::dealloc(Self::layout(capacity), pointer) };
    }

    pub(in crate::buffer) fn capacity(&self) -> num::NonZero<u32> {
        self.prefix.word()
    }

    /// # Safety
    /// Exclusively own this header with the matching allocation layout, and
    /// settle its exact policy charge for the new capacity before publication.
    pub(in crate::buffer) unsafe fn set_capacity(&mut self, capacity: num::NonZero<u32>) {
        // SAFETY: the caller retains this header exclusively.
        unsafe { self.prefix.write(capacity) };
    }

    pub(in crate::buffer) fn data(pointer: ptr::NonNull<Self>) -> ptr::NonNull<u8> {
        // SAFETY: every live header allocation has its byte region directly
        // after the fixed header offset.
        unsafe { pointer.cast::<u8>().add(Self::DATA_OFFSET) }
    }

    /// # Safety
    /// `pointer` names a live allocation whose complete byte region is
    /// initialized for the duration of the returned raw slice use.
    pub(in crate::buffer) unsafe fn slice(pointer: ptr::NonNull<Self>) -> ptr::NonNull<[u8]> {
        // SAFETY: the caller proves the initialized allocation header is live.
        let capacity = unsafe { pointer.as_ref() }.capacity().get() as usize;
        // SAFETY: data begins a live initialized capacity-byte allocation region.
        ptr::NonNull::slice_from_raw_parts(Self::data(pointer), capacity)
    }
}

const _: () = {
    assert!(size_of::<Header<()>>() == size_of::<storage::raw::Prefix>());
    assert!(
        size_of::<storage::raw::Prefix<num::NonZero<u32>>>() == size_of::<storage::raw::Prefix>()
    );
    assert!(
        align_of::<storage::raw::Prefix<num::NonZero<u32>>>() == align_of::<storage::raw::Prefix>()
    );
};
const _: () = assert!(align_of::<Header<()>>() >= 8);
const _: () = assert!(size_of::<Header<resident::Budget<'static>>>() == size_of::<usize>() * 2);

#[repr(transparent)]
#[derive(Debug)]
pub(in crate::buffer) struct Heap<P: buffer::raw::Policy = ()> {
    pointer: ptr::NonNull<buffer::raw::Header<P>>,
}

impl<P: buffer::raw::Policy> Heap<P> {
    pub(in crate::buffer) fn try_new(
        seed: P,
        capacity: num::NonZero<u32>,
    ) -> Result<Self, alloc::Error<P::Failure>> {
        let debit = seed.try_acquire(capacity).map_err(alloc::Error::Budget)?;
        Self::try_charged(capacity, debit).map_err(alloc::Error::Allocation)
    }

    fn try_charged(
        capacity: num::NonZero<u32>,
        debit: P::Debit,
    ) -> Result<Self, crate::alloc::Exhausted> {
        // SAFETY: the debit covers the entire new allocation's capacity.
        let pointer = unsafe { buffer::raw::Header::try_new(capacity, debit)? };
        Ok(Self { pointer })
    }

    fn header(&self) -> &buffer::raw::Header<P> {
        // SAFETY: this owner retains its initialized header for the borrow.
        unsafe { self.pointer.as_ref() }
    }

    pub(in crate::buffer) fn capacity(&self) -> num::NonZero<u32> {
        self.header().capacity()
    }

    pub(in crate::buffer) fn seed(&self) -> P {
        self.header().policy
    }

    pub(in crate::buffer) fn try_reserve(
        &mut self,
        target: num::NonZero<u32>,
    ) -> Result<(), alloc::Error<P::Failure>> {
        let Some(amount) = num::NonZero::new(target.get().saturating_sub(self.capacity().get()))
        else {
            return Ok(());
        };
        // SAFETY: the exact increase preserves the whole allocation and appends no bytes.
        unsafe { self.try_grow(target, amount, 0..0, &[][..]) }
    }

    /// # Safety
    /// `amount` is the exact increase to `target`. The initialized live range
    /// and disjoint appended source fit together in the target.
    pub(in crate::buffer) unsafe fn try_grow<I: buffer::raw::Transfer + ?Sized>(
        &mut self,
        target: num::NonZero<u32>,
        amount: num::NonZero<u32>,
        live: ops::Range<u32>,
        src: &I,
    ) -> Result<(), alloc::Error<P::Failure>> {
        let debit = self
            .seed()
            .try_acquire(amount)
            .map_err(alloc::Error::Budget)?;
        if live.start == 0 {
            // SAFETY: the positive delta is held until the resize succeeds.
            unsafe { self.resize(target) }.map_err(alloc::Error::Allocation)?;
            mem::forget(debit);
            // SAFETY: realloc preserved the prefix and the admitted suffix fits after it.
            unsafe { src.copy_to(self.as_mut_ptr().cast::<u8>().add(live.end as usize)) };
        } else {
            // SAFETY: the old credit and exact delta fund this fresh header together.
            let next = unsafe { buffer::raw::Header::try_new(target, debit) }
                .map_err(alloc::Error::Allocation)?;
            let len = (live.end - live.start) as usize;
            // SAFETY: this sole owner retains the initialized range until the copy finishes.
            let bytes =
                unsafe { buffer::raw::range(self.as_ptr().cast(), live.start as usize, len) };
            let current = self.capacity();
            // SAFETY: the disjoint destination fits both sources. Its header owns
            // the full charge, so the replaced region is freed without a refund.
            unsafe {
                buffer::raw::Transfer::copy_to(
                    &(bytes, src),
                    buffer::raw::Header::data(next).as_ptr(),
                );
                buffer::raw::Header::free(mem::replace(&mut self.pointer, next), current);
            }
        }
        Ok(())
    }

    /// # Safety
    /// Preserve the live extent and settle the exact policy delta on success.
    unsafe fn resize(&mut self, target: num::NonZero<u32>) -> Result<(), crate::alloc::Exhausted> {
        let old = buffer::raw::Header::<P>::layout(self.capacity());
        let new = buffer::raw::Header::<P>::layout(target);
        // SAFETY: these matching layouts belong to this sole owner. Failure
        // preserves the original allocation. Its caller settles the charge on success.
        unsafe {
            self.pointer = crate::alloc::raw::resize(old, self.pointer.cast(), new)?.cast();
            self.pointer.as_mut().set_capacity(target);
        }
        Ok(())
    }

    pub(in crate::buffer) fn as_ptr(&self) -> *const mem::MaybeUninit<u8> {
        buffer::raw::Header::data(self.pointer).cast().as_ptr()
    }

    pub(in crate::buffer) fn as_mut_ptr(&mut self) -> *mut mem::MaybeUninit<u8> {
        buffer::raw::Header::data(self.pointer).cast().as_ptr()
    }

    pub(in crate::buffer) fn into_shared(self) -> crate::mem::raw::Owner<Header<P>> {
        let this = mem::ManuallyDrop::new(self);
        // SAFETY: this unique initialized header transfers its initial counted edge.
        unsafe { crate::mem::raw::Owner::from_raw(this.pointer) }
    }
}

impl<P: buffer::raw::Policy> Drop for Heap<P> {
    fn drop(&mut self) {
        // SAFETY: Drop transfers this sole allocation owner once; its pointer
        // field has no remaining destruction obligation.
        unsafe { buffer::raw::Header::destroy(self.pointer) };
    }
}

const _: () = assert!(size_of::<Heap<()>>() == size_of::<ptr::NonNull<()>>());
const _: () = assert!(size_of::<Option<Heap<()>>>() == size_of::<ptr::NonNull<()>>());
impl<'d> Heap<resident::Budget<'d>> {
    pub(in crate::buffer) fn try_charge(
        charge: resident::Charge<'d>,
    ) -> Result<Option<Self>, storage::AllocError> {
        consume::Error::check(charge.capacity(), u32::MAX as usize)
            .map_err(storage::AllocError::Capacity)?;
        let charge = mem::ManuallyDrop::new(charge);
        match num::NonZero::new(charge.capacity() as u32) {
            Some(capacity) => Self::try_charged(capacity, mem::ManuallyDrop::into_inner(charge))
                .map(Some)
                .map_err(storage::AllocError::Exhausted),
            None => Ok(None),
        }
    }

    pub(in crate::buffer) fn try_compact(
        &mut self,
        capacity: num::NonZero<u32>,
    ) -> Result<(), crate::alloc::Exhausted> {
        let current = self.capacity();
        if capacity == current {
            return Ok(());
        }
        // SAFETY: the retained nonzero prefix and unequal capacity prove a
        // strict shrink. This owner transfers only the released capacity.
        unsafe {
            self.resize(capacity)?;
            self.seed()
                .release((current.get() - capacity.get()) as usize);
        }
        Ok(())
    }
}

impl<P: buffer::raw::Policy> Header<P> {
    pub(in crate::buffer) fn seed(&self) -> P {
        self.policy
    }

    /// Transfers this edge and its initialized allocation range.
    /// # Safety
    /// `start..start + len` is initialized and within this unchanged allocation.
    pub(in crate::buffer) unsafe fn into_range(
        owner: crate::mem::raw::Owner<Self>,
        start: u32,
        len: u32,
    ) -> storage::Shared<crate::mem::raw::Owner<Self>> {
        // SAFETY: the caller retains the initialized range in this exact allocation.
        let pointer = unsafe { Self::data(owner.as_ptr()).add(start as usize) };
        unsafe { storage::raw::Extent::new(pointer, len as usize).bind(owner) }
    }
}

impl Header<resident::Budget<'_>> {
    pub(in crate::buffer) fn try_own(
        owner: crate::mem::raw::Owner<Self>,
    ) -> Result<crate::mem::raw::Owner<Header<()>>, crate::mem::raw::Owner<Self>> {
        const EXTRA: u32 = {
            assert!(size_of::<Header<resident::Budget<'_>>>() >= size_of::<Header<()>>());
            let extra = size_of::<Header<resident::Budget<'_>>>() - size_of::<Header<()>>();
            assert!(extra <= u32::MAX as usize);
            extra as u32
        };
        let original = owner.get().capacity();
        let Some(capacity) = original.checked_add(EXTRA) else {
            return Err(owner);
        };
        if !crate::mem::raw::Edge::is_unique(owner.get())
            || align_of::<Self>() != align_of::<Header<()>>()
        {
            return Err(owner);
        }
        let pointer = owner.into_raw();
        // SAFETY: the sole edge transfers this policy's exact original charge.
        unsafe { pointer.as_ref().policy.release(original.get() as usize) };
        let mut pointer = pointer.cast::<Header<()>>();
        // SAFETY: admission preserves total allocation size and alignment. The
        // common prefix retains its sole edge; former policy bytes become spare.
        unsafe {
            pointer.as_mut().set_capacity(capacity);
            Ok(crate::mem::raw::Owner::from_raw(pointer))
        }
    }
}

impl<P: buffer::raw::Policy> Heap<P> {
    pub(in crate::buffer) fn try_borrow(
        owner: &mut crate::mem::raw::Owner<Header<P>>,
    ) -> Option<&mut Self> {
        if !crate::mem::raw::Edge::is_unique(owner.get()) {
            return None;
        }
        // SAFETY: both transparent owners store the same live header pointer.
        // This exclusive sole-edge loan prevents retain; replacement leaves one edge.
        Some(unsafe { &mut *ptr::from_mut(owner).cast::<Self>() })
    }
}

const _: () = {
    assert!(size_of::<crate::mem::raw::Owner<Header<()>>>() == size_of::<ptr::NonNull<()>>());
    assert!(
        size_of::<Option<crate::mem::raw::Owner<Header<()>>>>() == size_of::<ptr::NonNull<()>>()
    );
};

mod headers;
mod loans;