o3 0.62.0

shared-nothing primitives
Documentation
use crate::{buffer, mem::credit};
use std::{mem, num, ops};

use storage::alloc;

use crate::buffer::{bytes::bounded, resident, storage, write::consume};

pub(super) mod exact;
pub(super) mod nonempty;

/// Construction and ownership transitions for one initialized byte allocation.
#[derive(Debug)]
#[repr(C)]
pub struct Owned<P: buffer::raw::Policy = ()> {
    pub(in crate::buffer::storage) allocation: Option<buffer::raw::Heap<P>>,
    pub(in crate::buffer::storage) len: u32,
}

impl Owned {
    pub fn try_with(capacity: usize) -> Result<Self, storage::AllocError> {
        match admit(capacity).map_err(storage::AllocError::Capacity)? {
            Some(capacity) => Self::try_nonzero(capacity),
            None => Ok(Self::EMPTY),
        }
    }

    pub(in crate::buffer) fn try_nonzero(
        capacity: num::NonZero<u32>,
    ) -> Result<Self, storage::AllocError> {
        let heap = buffer::raw::Heap::try_new((), capacity)?;
        Ok(Self {
            allocation: Some(heap),
            len: 0,
        })
    }

    /// Reserves a total capacity while preserving the initialized bytes.
    /// Smaller targets leave the allocation unchanged.
    pub fn try_reserve(
        &mut self,
        target: num::NonZero<u32>,
    ) -> Result<(), crate::alloc::Exhausted> {
        grow(&mut self.allocation, (), target).map_err(alloc::Error::into_alloc)
    }
}

impl Owned {
    #[must_use]
    pub fn freeze(self) -> storage::Shared {
        storage::raw::share(self)
            .map(Into::into)
            .unwrap_or_default()
    }
}

impl<P: buffer::raw::Policy> AsRef<[u8]> for Owned<P> {
    fn as_ref(&self) -> &[u8] {
        buffer::raw::Prefix::as_slice(self)
    }
}

impl<P: buffer::raw::Policy> AsMut<[u8]> for Owned<P> {
    fn as_mut(&mut self) -> &mut [u8] {
        buffer::raw::Exclusive::as_mut_slice(self)
    }
}

impl<P: buffer::raw::Policy> Owned<P> {
    pub(in crate::buffer) const EMPTY: Self = Self {
        allocation: None,
        len: 0,
    };
}

impl<'d> Owned<resident::Budget<'d>> {
    pub fn try_compact(&mut self) -> Result<(), crate::alloc::Exhausted> {
        let Some(heap) = &mut self.allocation else {
            return Ok(());
        };
        let Some(capacity) = num::NonZero::new(self.len) else {
            *self = Self::EMPTY;
            return Ok(());
        };
        heap.try_compact(capacity)
    }
}

const _: () = assert!(size_of::<Owned<()>>() == 2 * size_of::<usize>());

/// Unique bytes charged to one resident domain.
impl<'d> Owned<resident::Budget<'d>> {
    pub fn try_copy<T: From<Self>>(
        source: &impl bounded::Source,
        budget: &resident::Budget<'d>,
        place: &mut mem::MaybeUninit<T>,
    ) -> Result<(), alloc::Error<credit::Error>> {
        let owner = match buffer::raw::Slices::from_source(source) {
            Some(source) => source.try_init(*budget)?.into_owned(),
            None => Self::EMPTY,
        };
        place.write(T::from(owner));
        Ok(())
    }

    pub fn try_slice<T: From<Self>>(
        budget: &resident::Budget<'d>,
        bytes: &[u8],
        place: &mut mem::MaybeUninit<T>,
    ) -> Result<(), resident::AllocError> {
        let owner =
            match buffer::raw::Slices::try_new([bytes]).map_err(resident::AllocError::Capacity)? {
                Some(source) => source.try_init(*budget)?.into_owned(),
                None => Self::EMPTY,
            };
        place.write(T::from(owner));
        Ok(())
    }

    /// Allocates against an existing debit without acquiring resident capacity again.
    /// Failure releases the consumed charge; a zero charge needs no allocation.
    pub fn try_charge(charge: resident::Charge<'d>) -> Result<Self, storage::AllocError> {
        Ok(Self {
            allocation: buffer::raw::Heap::try_charge(charge)?,
            len: 0,
        })
    }

    pub fn try_allocate(
        budget: &resident::Budget<'d>,
        capacity: usize,
    ) -> Result<Self, storage::AllocError<credit::Error>> {
        let heap = admit(capacity)
            .map_err(storage::AllocError::Capacity)?
            .map(|capacity| buffer::raw::Heap::try_new(*budget, capacity))
            .transpose()?;
        Ok(Self {
            allocation: heap,
            len: 0,
        })
    }

    /// Reserves a total capacity while preserving the initialized bytes.
    /// `seed` is used only without an allocation; growth retains the original domain.
    pub fn try_reserve(
        &mut self,
        seed: &resident::Budget<'d>,
        target: usize,
    ) -> Result<(), storage::AllocError<credit::Error>> {
        if let Some(target) = admit(target).map_err(storage::AllocError::Capacity)? {
            grow(&mut self.allocation, *seed, target)?;
        }
        Ok(())
    }
}

const _: () =
    assert!(size_of::<storage::Owned<resident::Budget<'static>>>() == size_of::<usize>() * 2);

impl<P: buffer::raw::Policy> Default for Owned<P> {
    fn default() -> Self {
        Self::EMPTY
    }
}

impl<P: buffer::raw::Policy> ops::Deref for Owned<P> {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        buffer::raw::Prefix::as_slice(self)
    }
}

impl<P: buffer::raw::Policy> ops::DerefMut for Owned<P> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        buffer::raw::Exclusive::as_mut_slice(self)
    }
}

impl<P: buffer::raw::Policy> Owned<P> {
    pub fn capacity(&self) -> usize {
        match &self.allocation {
            None => 0,
            Some(heap) => heap.capacity().get() as usize,
        }
    }
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn len(&self) -> usize {
        self.len as usize
    }

    /// Returns the allocation pointer without borrowing its initialized prefix.
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
        buffer::raw::Exclusive::as_mut_ptr(self).cast()
    }
}

fn admit(capacity: usize) -> Result<Option<num::NonZero<u32>>, consume::Error> {
    consume::Error::check(capacity, u32::MAX as usize)?;
    Ok(num::NonZero::new(capacity as u32))
}

fn grow<P: buffer::raw::Policy>(
    current: &mut Option<buffer::raw::Heap<P>>,
    seed: P,
    target: num::NonZero<u32>,
) -> Result<(), alloc::Error<P::Failure>> {
    match current {
        Some(heap) => heap.try_reserve(target),
        None => {
            *current = Some(buffer::raw::Heap::try_new(seed, target)?);
            Ok(())
        }
    }
}