o3 0.61.0

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

use storage::alloc;

use crate::buffer::{raw, raw::Policy as _, resident, storage};

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

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

    #[inline]
    pub(in crate::buffer) fn try_charged(
        debit: raw::Debit<P>,
    ) -> Result<Self, crate::alloc::Exhausted> {
        // SAFETY: the debit covers the entire new allocation's capacity.
        let pointer = unsafe { raw::Header::try_new(*debit.item(), debit)? };
        Ok(Self { pointer })
    }

    fn header(&self) -> &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: raw::SliceExt + ?Sized>(
        &mut self,
        target: num::NonZero<u32>,
        amount: num::NonZero<u32>,
        live: ops::Range<u32>,
        src: &I,
    ) -> Result<(), alloc::Error<P::Failure>> {
        use raw::SliceExt as _;

        let debit = raw::Debit::try_new(self.seed(), 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)?;
            debit.commit();
            // 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 { 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 { 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 {
                (bytes, src).copy_to(raw::Header::data(next).as_ptr());
                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 = raw::Header::<P>::layout(self.capacity());
        let new = 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> {
        raw::Header::data(self.pointer).cast().as_ptr()
    }

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

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

impl<P: 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 { 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_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().refund(crate::mem::raw::Counter::nonzero(
                current.get() - capacity.get(),
            ));
        }
        Ok(())
    }
}