o3 0.62.0

shared-nothing primitives
Documentation
use crate::{
    buffer::{
        self, bytes, resident,
        storage::{
            self,
            provided::{self, Frozen, Mutable, account},
        },
        write::consume,
    },
    mem,
};
use consume::scope;
use std::{
    cell, marker,
    mem::{MaybeUninit, size_of, take},
    num::NonZero,
    ops, ptr,
};

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

impl<'d, L: provided::raw::Layout> Slice<&[u8], &'_ provided::raw::Owner<'d, L>> {
    pub(in crate::buffer) fn try_register<A, F, T>(
        &self,
        budget: resident::Budget<'d>,
        admit: A,
        place: &mut MaybeUninit<T>,
    ) -> Result<ops::ControlFlow<A::Declined>, account::Cause>
    where
        A: resident::Admission,
        F: From<account::Bytes<'d, L>>,
        T: From<F>,
    {
        if self.bytes.is_empty() {
            place.write(T::from(F::from(account::Bytes::<'d, L>::new())));
            return Ok(ops::ControlFlow::Continue(()));
        }
        use buffer::raw::Policy as _;
        use mem::raw::Edge as _;
        let pointer = self.owner.entry;
        // SAFETY: the owner retains this scope's stable slot. Occupied
        // registrations remain shared; admission invokes no user callbacks.
        let entry: &'d provided::raw::Entry<L> = unsafe { pointer.as_ref() };
        if !entry.is_empty() {
            // SAFETY: the live account keeps this slot detached with its original paying budget.
            let paying = unsafe { entry.payer() };
            if !ptr::eq(paying.core(), budget.core()) {
                return Err(account::Cause::Foreign);
            }
            if let ops::ControlFlow::Break(declined) = admit.check(budget, 0) {
                return Ok(ops::ControlFlow::Break(declined));
            }
            // SAFETY: the slot owner retains this proved live registration;
            // no callbacks or edge releases intervene before the increment.
            unsafe { entry.try_retain() }.map_err(account::Cause::Retain)?;
        } else {
            let domain = unsafe { entry.domain.as_ref() };
            let count = domain.accounted.get();
            let limit = domain.limit;
            if count >= limit {
                return Err(account::Cause::Exhausted { count, limit });
            }
            // SAFETY: the admitted projection fits this slot's initialized ceiling,
            // and the nonempty prefix retains at least one byte of that projection.
            let resident = unsafe { NonZero::new_unchecked(entry.capacity()) };
            if let ops::ControlFlow::Break(declined) = admit.check(budget, resident.get() as usize)
            {
                return Ok(ops::ControlFlow::Break(declined));
            }
            let charge = budget
                .try_acquire(resident)
                .map_err(account::Cause::Budget)?;
            domain.accounted.set(count + 1);
            // SAFETY: detached data has the exact Budget size and alignment; this stores its original authority.
            unsafe {
                entry
                    .data
                    .as_ptr()
                    .cast::<resident::Budget<'d>>()
                    .write(charge.into())
            };
            // SAFETY: the detached slot owns the debit and its count is still empty.
            unsafe { entry.activate() };
        }
        // SAFETY: admission transfers one edge to the first field of this repr(C) entry.
        let owner = unsafe { mem::raw::Owner::from_raw(pointer.cast()) };
        // SAFETY: the counted edge retains the same slot as these admitted prefix bytes.
        let extent = unsafe { storage::raw::Extent::from_bytes(self.bytes).bind(Some(owner)) };
        place.write(T::from(F::from(extent)));
        Ok(ops::ControlFlow::Continue(()))
    }
}

impl<'d, L: provided::raw::Layout> Slice<&'d mut [u8], provided::raw::Owner<'d, L>> {
    /// # Safety
    /// This initialized projection belongs to the detached entry's sole external edge.
    pub(in crate::buffer::storage::provided) unsafe fn publish(
        entry: &'d provided::raw::Entry<L>,
        bytes: &'d mut [u8],
    ) -> Self {
        entry.state.set(provided::raw::Phase::Occupied);
        Self {
            bytes,
            owner: provided::raw::Owner {
                entry: ptr::NonNull::from(entry),
                scope: marker::PhantomData,
            },
        }
    }

    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<Slice<&'_ mut [u8], &'_ provided::raw::Owner<'d, L>>, consume::Error> {
        Slice::take_from(&mut self.bytes, &self.owner, amount)
    }

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

    pub fn try_account(
        self,
        budget: &resident::Budget<'d>,
    ) -> Result<account::Bytes<'d, L>, mem::Rejected<Self, account::Cause>> {
        let view = Slice {
            bytes: self.as_slice(),
            owner: &self.owner,
        };
        match view.try_account(budget) {
            Ok(charge) => Ok(charge),
            Err(error) => Err(mem::Rejected::new(self, error)),
        }
    }

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

// SAFETY: this slice retains the exact exclusive slice and its provided owner.
unsafe impl<L: provided::raw::Layout> buffer::raw::Consume
    for Slice<&'_ mut [u8], provided::raw::Owner<'_, L>>
{
    fn consume<const MAX: u32>(prefix: buffer::raw::Input<&mut Self, scope::Prefix<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::Input::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::Input<&mut Self, ops::Range<usize>>) {
        let (source, proof) = slice.into_parts();
        // SAFETY: the selection belongs to these bytes and the owner stays in place.
        let slice = unsafe { buffer::raw::Input::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::raw::Layout> ops::Deref for Slice<&'_ mut [u8], provided::raw::Owner<'_, 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()
    }
}

const _: () = {
    type Source<'d> = Slice<&'d mut [u8], provided::raw::Owner<'d>>;
    type Reject<'d> = mem::Rejected<Source<'d>, account::Cause>;
    let word = size_of::<usize>();
    assert!(size_of::<Source<'_>>() == 3 * word);
    assert!(size_of::<Reject<'_>>() == 6 * word);
    assert!(size_of::<Result<account::Bytes<'_, cell::Cell<u32>>, Reject<'_>>>() == 6 * word);
};

impl<'a, 'd, L: provided::raw::Layout> Slice<&'a mut [u8], &'a provided::raw::Owner<'d, L>> {
    fn take_from<'bytes: 'a>(
        bytes: &mut &'bytes mut [u8],
        owner: &'a provided::raw::Owner<'d, L>,
        amount: NonZero<usize>,
    ) -> Result<Self, consume::Error> {
        consume::Error::check(amount.get(), bytes.len())?;
        let source = take(bytes);
        // SAFETY: the check admitted this unchanged slice before its exclusive split.
        let (head, tail) = unsafe { source.split_at_mut_unchecked(amount.get()) };
        *bytes = tail;
        Ok(Self { bytes: head, owner })
    }
}

impl<'a, 'd, L: provided::raw::Layout> Mutable<'d>
    for Slice<&'a mut [u8], &'a provided::raw::Owner<'d, L>>
{
    type Account = account::Bytes<'d, L>;
    type Frozen = Slice<&'a [u8], &'a provided::raw::Owner<'d, L>>;
    type Prefix<'b>
        = Slice<&'a mut [u8], &'a provided::raw::Owner<'d, L>>
    where
        Self: 'b;

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

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

impl<'a, 'd, L: provided::raw::Layout> Frozen<'d>
    for Slice<&'a [u8], &'a provided::raw::Owner<'d, L>>
{
    type Account = account::Bytes<'d, L>;

    fn try_account(&self, budget: &resident::Budget<'d>) -> Result<Self::Account, account::Cause> {
        let mut owner = MaybeUninit::<Self::Account>::uninit();
        let ops::ControlFlow::Continue(()) =
            self.try_register::<_, 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::raw::Layout> Slice<&'a [u8], &'a provided::raw::Owner<'d, L>> {
    pub(in crate::buffer) fn from_view(
        view: buffer::View<'a, storage::Shared<provided::raw::Owner<'d, L>>>,
    ) -> Self {
        Self {
            bytes: view.as_slice(),
            owner: view.source.owner(),
        }
    }
}

const _: () = {
    assert!(
        size_of::<Slice<&'_ mut [u8], &'_ provided::raw::Owner<'_, cell::Cell<u32>>>>()
            == 3 * size_of::<usize>()
    );
    assert!(
        size_of::<Slice<&'_ [u8], &'_ provided::raw::Owner<'_, cell::Cell<u32>>>>()
            == 3 * size_of::<usize>()
    );
    assert!(
        size_of::<
            Result<
                Slice<&'_ mut [u8], &'_ provided::raw::Owner<'_, cell::Cell<u32>>>,
                consume::Error,
            >,
        >() == size_of::<Slice<&'_ mut [u8], &'_ provided::raw::Owner<'_, cell::Cell<u32>>>>()
    );
};