o3 0.61.0

shared-nothing primitives
Documentation
//! Owner-preserving storage for resources returned by an external subsystem.
//! Fixed and exact capacity owners over one private intrusive state machine.

use std::{cell, mem, num::NonZero, ops};

pub use arena::{Arena, Layout, account::Account, owner::Owner, root::Root, vacant::Vacant};

use crate::{
    buffer,
    buffer::{
        resident, storage,
        storage::provided,
        write::{consume, consume::Consume},
    },
};

pub mod account;
mod arena;
pub mod fixed;
pub use arena::native;
pub mod view;

/// Mutable provided storage preserving its owner through splitting and freezing.
pub trait Mutable<'d>: buffer::raw::Split + buffer::raw::Freeze<Output = Self::Frozen> {
    type Account: AsRef<[u8]> + buffer::Residency;
    type Frozen: Frozen<'d, Account = Self::Account>;
    type Prefix<'a>: Mutable<'d, Account = Self::Account>
    where
        Self: 'a;

    fn try_take(&mut self, amount: NonZero<usize>) -> Result<Self::Prefix<'_>, consume::Error>;
}

/// Frozen provided storage retaining its original backing.
pub trait Frozen<'d>: buffer::raw::Source + buffer::Residency {
    type Account: AsRef<[u8]> + buffer::Residency;
    fn try_account(&self, budget: &resident::Budget<'d>) -> Result<Self::Account, account::Cause>;
}

#[derive(Debug)]
#[repr(C)]
pub struct Slice<B, O> {
    bytes: B,
    owner: O,
}

/// Exclusive mutable projection into one provided item.
pub type Unique<'d, L = cell::Cell<u32>> = Slice<&'d mut [u8], Owner<'d, L>>;

/// A removed prefix borrowing its original unique owner.
pub type Prefix<'a, 'd, B = &'a mut [u8], L = cell::Cell<u32>> = Slice<B, &'a Owner<'d, L>>;

impl<'d, L: provided::Layout> Unique<'d, L> {
    pub(in crate::buffer::storage::provided) const fn new(
        view: buffer::raw::Projection<'d, '_>,
        owner: provided::Owner<'d, L>,
    ) -> Self {
        Self {
            bytes: view.into_inner(),
            owner,
        }
    }

    pub fn as_slice(&self) -> &[u8] {
        self.bytes
    }

    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        self.bytes
    }

    pub fn try_take(
        &mut self,
        amount: NonZero<usize>,
    ) -> Result<provided::Prefix<'_, 'd, &'_ mut [u8], L>, consume::Error> {
        Prefix::take_from(&mut self.bytes, &self.owner, amount)
    }

    pub fn chunks_mut<'a>(
        &'a mut self,
        size: NonZero<usize>,
    ) -> impl Iterator<Item = Prefix<'a, 'd, &'a mut [u8], L>> {
        let owner = &self.owner;
        buffer::bytes::ChunksMut::new(mem::take(&mut self.bytes), size)
            .map(move |bytes| Prefix { bytes, owner })
    }

    pub fn try_account(
        self,
        budget: &resident::Budget<'d>,
    ) -> Result<
        storage::Shared<Option<provided::Account<'d, L>>>,
        crate::mem::Rejected<provided::Unique<'d, L>, account::Cause>,
    > {
        match (provided::Prefix {
            bytes: self.as_slice(),
            owner: &self.owner,
        })
        .try_account(budget)
        {
            Ok(owner) => Ok(owner),
            Err(error) => Err(crate::mem::Rejected::new(self, error)),
        }
    }

    pub fn into_shared(self) -> storage::Shared<provided::Owner<'d, L>> {
        // SAFETY: Unique transfers the initialized slice with the external edge that retains it.
        unsafe { storage::Shared::assume(self.bytes, self.owner) }
    }
}

// SAFETY: Unique retains the exact exclusive slice and its provided owner.
unsafe impl<L: provided::Layout> buffer::raw::Consume for Unique<'_, L> {
    fn consume<const MAX: u32>(prefix: buffer::raw::Consumed<'_, Self, MAX>) {
        let (source, proof) = prefix.into_parts();
        // SAFETY: projection retains this owner's unchanged exclusive byte extent.
        <&mut [u8] as buffer::raw::Consume>::consume(unsafe {
            buffer::raw::Consumed::from_parts(&mut source.bytes, proof)
        });
    }
}

// SAFETY: narrowing this disjoint slice keeps its owned or borrowed slot edge, even when empty.
unsafe impl<O> buffer::raw::Store for Slice<&mut [u8], O> {
    fn restrict(slice: buffer::raw::Slice<'_, '_, Self>) {
        let (source, proof) = slice.into_parts();
        // SAFETY: the selection belongs to these bytes and the owner stays in place.
        let slice = unsafe { buffer::raw::Slice::from_parts(&mut source.bytes, proof) };
        <&mut [u8] as buffer::raw::Store>::project(slice);
    }
}

impl<B: AsRef<[u8]>, O> AsRef<[u8]> for Slice<B, O> {
    fn as_ref(&self) -> &[u8] {
        self.bytes.as_ref()
    }
}

impl<O> AsMut<[u8]> for Slice<&mut [u8], O> {
    fn as_mut(&mut self) -> &mut [u8] {
        self.bytes
    }
}

impl<L: provided::Layout> ops::Deref for Unique<'_, L> {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        self.bytes
    }
}

impl<B, O: buffer::Residency> buffer::Residency for Slice<B, O> {
    fn resident(&self) -> usize {
        self.owner.resident()
    }
}

impl<L: provided::Layout> Consume for Unique<'_, L> {
    fn remaining(&self) -> usize {
        self.bytes.len()
    }

    fn try_consume(&mut self, amount: usize) -> Result<(), consume::Error> {
        self.bytes.try_consume(amount)
    }

    fn consume_max(&mut self, max: usize) -> usize {
        self.bytes.consume_max(max)
    }
}

const _: () = {
    let word = mem::size_of::<usize>();
    assert!(mem::size_of::<Unique<'static>>() == 3 * word);
    assert!(
        mem::size_of::<crate::mem::Rejected<provided::Unique<'static>, account::Cause>>()
            == 6 * word
    );
    assert!(
        mem::size_of::<
            Result<
                storage::Shared<Option<provided::Account<'static>>>,
                crate::mem::Rejected<provided::Unique<'static>, account::Cause>,
            >,
        >() == 6 * word
    );
};

impl<'a, 'd, L: provided::Layout> Prefix<'a, 'd, &'a mut [u8], L> {
    fn take_from<'bytes: 'a>(
        bytes: &mut &'bytes mut [u8],
        owner: &'a Owner<'d, L>,
        amount: NonZero<usize>,
    ) -> Result<Self, consume::Error> {
        let bytes = buffer::raw::Selection::try_new(bytes, amount.get())?.take();
        Ok(Self { bytes, owner })
    }
}

impl<'a, 'd, L: provided::Layout> Mutable<'d> for Prefix<'a, 'd, &'a mut [u8], L> {
    type Account = storage::Shared<Option<provided::Account<'d, L>>>;
    type Frozen = Prefix<'a, 'd, &'a [u8], L>;
    type Prefix<'b>
        = Prefix<'a, 'd, &'a mut [u8], L>
    where
        Self: 'b;

    fn try_take(&mut self, amount: NonZero<usize>) -> Result<Self::Prefix<'_>, consume::Error> {
        Prefix::take_from(&mut self.bytes, self.owner, amount)
    }
}

impl<'a, 'd, L: provided::Layout> From<Prefix<'a, 'd, &'a mut [u8], L>>
    for Prefix<'a, 'd, &'a [u8], L>
{
    fn from(prefix: Prefix<'a, 'd, &'a mut [u8], L>) -> Self {
        let Prefix { bytes, owner } = prefix;
        Self { bytes, owner }
    }
}

impl<'a, 'd, L: provided::Layout> Frozen<'d> for Prefix<'a, 'd, &'a [u8], L> {
    type Account = storage::Shared<Option<provided::Account<'d, L>>>;

    fn try_account(
        &self,
        budget: &resident::Budget<'d>,
    ) -> Result<storage::Shared<Option<provided::Account<'d, L>>>, account::Cause> {
        let mut owner = mem::MaybeUninit::<Self::Account>::uninit();
        let ops::ControlFlow::Continue(()) =
            self.try_account_with::<_, Self::Account, Self::Account>(*budget, (), &mut owner)?;
        // SAFETY: successful accounting initialized this exact original output once.
        Ok(unsafe { owner.assume_init() })
    }
}

impl<'a, 'd, L: provided::Layout> Prefix<'a, 'd, &'a [u8], L> {
    pub(in crate::buffer) fn from_view(
        view: buffer::View<'a, storage::Shared<Owner<'d, L>>>,
    ) -> Self {
        Self {
            bytes: view.as_slice(),
            owner: view.source.owner(),
        }
    }
}

const _: () = {
    assert!(size_of::<Prefix<'static, 'static>>() == 3 * size_of::<usize>());
    assert!(size_of::<Prefix<'static, 'static, &'static [u8]>>() == 3 * size_of::<usize>());
    assert!(
        size_of::<Result<Prefix<'static, 'static>, consume::Error>>()
            == size_of::<Prefix<'static, 'static>>()
    );
};