o3 0.61.0

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

use provided::account;

use crate::{
    base::num::bounded::U32,
    buffer,
    buffer::{
        bytes::bounded,
        hold, resident, storage,
        storage::{provided, range},
        write::consume,
    },
    mem::rc,
};

/// Value whose stable extent fits a signed 32-bit count.
///
/// Admission requires an extent stable through shared access.
#[derive(Debug)]
#[repr(transparent)]
pub struct Value<T>(pub(in crate::buffer) T);

impl<const N: usize> Value<[u8; N]> {
    pub const fn new(value: [u8; N]) -> Self {
        const { assert!(N <= bounded::MAX) };
        Self(value)
    }
}

impl<T: buffer::raw::Source> Value<T> {
    pub fn try_new(value: T) -> Result<Self, bounded::Rejected<T>> {
        if U32::<0, { bounded::MAX as u32 }>::try_usize(value.as_ref().len()).is_err() {
            return Err(bounded::Rejected::new(value));
        }
        Ok(Self(value))
    }
}

impl<'a> TryFrom<&'a mut [MaybeUninit<u8>]> for Value<&'a mut [MaybeUninit<u8>]> {
    type Error = bounded::Overflow;

    fn try_from(value: &'a mut [MaybeUninit<u8>]) -> Result<Self, Self::Error> {
        U32::<0, { bounded::MAX as u32 }>::try_usize(value.len())?;
        Ok(Self(value))
    }
}

impl<'d, L: provided::Layout> Value<provided::Unique<'d, L>> {
    pub fn try_take(
        &mut self,
        amount: NonZero<usize>,
    ) -> Result<Value<provided::Prefix<'_, 'd, &'_ mut [u8], L>>, consume::Error> {
        Ok(Value(self.0.try_take(amount)?))
    }
}

impl<T: buffer::raw::Mutable> AsMut<[u8]> for Value<T> {
    fn as_mut(&mut self) -> &mut [u8] {
        self.0.as_mut()
    }
}

impl<'d, L: provided::Layout> From<Value<provided::Unique<'d, L>>>
    for Value<storage::Shared<provided::Owner<'d, L>>>
{
    fn from(bytes: Value<provided::Unique<'d, L>>) -> Self {
        Value(bytes.0.into_shared())
    }
}

impl<T> std::borrow::Borrow<T> for Value<T> {
    fn borrow(&self) -> &T {
        &self.0
    }
}

impl<T> Value<T> {
    /// Transfers storage while preserving its admitted extent.
    pub fn into_storage<U>(self) -> Value<U>
    where
        T: buffer::raw::Convert<U>,
    {
        Value(buffer::raw::Convert::into(self.0))
    }

    /// Seals the original producer's extent proof into its bytes.
    pub fn from_raw(proof: bounded::raw::Input<T>) -> Self {
        Self(proof.into_inner())
    }

    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

const _: () = assert!(size_of::<Value<[u8; 1]>>() == 1);

impl<T: AsRef<[u8]>> AsRef<[u8]> for Value<T> {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl<T: AsRef<[u8]>> From<&Value<T>> for U32<0, { bounded::MAX as u32 }> {
    fn from(bytes: &Value<T>) -> Self {
        bounded::raw::Input::count(bytes)
    }
}

impl<T: buffer::Residency> buffer::Residency for Value<T> {
    fn resident(&self) -> usize {
        self.0.resident()
    }
}

impl<'d, L: provided::Layout> provided::Frozen<'d>
    for Value<storage::Shared<provided::Owner<'d, L>>>
{
    type Account = Value<storage::Shared<Option<provided::Account<'d, L>>>>;

    fn try_account(&self, budget: &resident::Budget<'d>) -> Result<Self::Account, account::Cause> {
        Ok(Value(self.0.try_account(budget)?))
    }
}

impl<'d, L: provided::Layout> Value<storage::Shared<provided::Owner<'d, L>>> {
    pub fn try_get(
        &self,
        range: ops::Range<usize>,
        budget: &resident::Budget<'d>,
    ) -> Result<Value<storage::Shared<Option<provided::Account<'d, L>>>>, account::Error> {
        Ok(Value(self.0.try_get(range, budget)?))
    }
}

impl<T: buffer::raw::Store + buffer::raw::Source> consume::Consume for Value<T> {
    fn remaining(&self) -> usize {
        self.0.as_ref().len()
    }

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

    fn consume_max(&mut self, max: usize) -> usize {
        buffer::raw::Store::advance_max(&mut self.0, max)
    }
}

impl<L: provided::Layout> Default for Value<storage::Shared<Option<provided::Account<'_, L>>>> {
    fn default() -> Self {
        Value(storage::Shared::<Option<provided::Account<'_, L>>>::new())
    }
}

impl<'d, L: provided::Layout> Value<storage::Shared<Option<provided::Account<'d, L>>>> {
    pub fn try_clone(&self) -> Result<Self, rc::Error> {
        Ok(Value(self.0.try_clone()?))
    }

    pub fn project(
        self,
        range: ops::Range<usize>,
    ) -> Result<Self, crate::mem::Rejected<Self, range::Error>> {
        match self.0.project(range) {
            Ok(value) => Ok(Value(value)),
            Err(error) => Err(error.map(Value)),
        }
    }
}

impl Value<&[u8]> {
    pub fn try_get(&self, range: ops::Range<usize>) -> Result<Self, range::Error> {
        Ok(Value(
            self.0
                .get(range.clone())
                .ok_or_else(|| range::Error::new(range, self.0.len()))?,
        ))
    }
}

impl bounded::Source for Value<&[u8]> {}

const _: () = {
    assert!(size_of::<Value<&[u8]>>() == 2 * size_of::<usize>());
    assert!(
        size_of::<Value<storage::Shared<Option<provided::Account<'static>>>>>()
            == 3 * size_of::<usize>()
    );
    assert!(
        size_of::<Option<Value<storage::Shared<Option<provided::Account<'static>>>>>>()
            == 3 * size_of::<usize>()
    );
};

// SAFETY: this selected bounded slice copies its bytes without retaining a source edge.
// Its original copy initializer writes the same destination once after successful admission.
unsafe impl<'d> hold::raw::Retain<'d> for Value<&[u8]> {
    fn try_copy<T: From<storage::Owned<resident::Budget<'d>>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        place: &mut std::mem::MaybeUninit<T>,
    ) -> Result<(), hold::Error> {
        Ok(storage::Owned::try_copy(&view, budget, place)?)
    }
}

// SAFETY: the transparent bound preserves its original immutable owner and exact selection.
// The same destination loan is delegated unchanged to the original initializer.
unsafe impl<'d, O> hold::raw::Retain<'d> for Value<storage::Shared<O>>
where
    storage::Shared<O>: hold::raw::Retain<'d>,
{
    fn try_copy<T: From<storage::Owned<resident::Budget<'d>>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        place: &mut std::mem::MaybeUninit<T>,
    ) -> Result<(), hold::Error> {
        Ok(storage::Owned::try_copy(&view, budget, place)?)
    }

    fn try_retain<T: From<hold::Retained<'d>> + From<storage::Owned<resident::Budget<'d>>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        place: &mut std::mem::MaybeUninit<T>,
    ) -> Result<(), hold::Error> {
        let (source, proof) = view.into_parts();
        <storage::Shared<O> as hold::raw::Retain<'d>>::try_retain(
            buffer::View {
                source: &source.0,
                proof,
            },
            budget,
            place,
        )
    }

    fn try_retain_with<T: From<hold::Retained<'d>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        limit: usize,
        place: &mut std::mem::MaybeUninit<T>,
    ) -> Result<bool, hold::Error> {
        let (source, proof) = view.into_parts();
        <storage::Shared<O> as hold::raw::Retain<'d>>::try_retain_with(
            buffer::View {
                source: &source.0,
                proof,
            },
            budget,
            limit,
            place,
        )
    }
}

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

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

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

    fn try_account(
        &self,
        budget: &resident::Budget<'d>,
    ) -> Result<bounded::Value<storage::Shared<Option<provided::Account<'d, L>>>>, account::Cause>
    {
        Ok(bounded::Value(self.0.try_account(budget)?))
    }
}

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

impl<'a, 'd, L: provided::Layout> From<Value<provided::Prefix<'a, 'd, &'a mut [u8], L>>>
    for Value<provided::Prefix<'a, 'd, &'a [u8], L>>
{
    fn from(prefix: Value<provided::Prefix<'a, 'd, &'a mut [u8], L>>) -> Self {
        Value(prefix.0.into())
    }
}

impl<T: AsRef<[u8]>> Value<T> {
    pub fn view(&self) -> Value<&[u8]> {
        Value(self.0.as_ref())
    }
}

impl<T> bounded::Source for buffer::View<'_, Value<T>> {}

impl<'d, L: provided::Layout>
    buffer::View<'_, Value<storage::Shared<Option<provided::Account<'d, L>>>>>
{
    pub fn try_retain(
        self,
    ) -> Result<Value<storage::Shared<Option<provided::Account<'d, L>>>>, rc::Error> {
        let (source, proof) = self.into_parts();
        Ok(Value(
            buffer::View {
                source: &source.0,
                proof,
            }
            .try_retain()?,
        ))
    }
}

const _: () = {
    assert!(
        size_of::<buffer::View<'static, Value<storage::Shared<provided::Owner<'static>>>>>()
            == 3 * size_of::<usize>()
    );
};

// SAFETY: consuming an exact prefix cannot enlarge the admitted range.
unsafe impl<T: buffer::raw::Consume> buffer::raw::Consume for Value<T> {
    fn consume<const MAX: u32>(prefix: buffer::raw::Consumed<'_, Self, MAX>) {
        let (source, proof) = prefix.into_parts();
        // SAFETY: the transparent bound retains its exact inner owner's byte extent.
        T::consume(unsafe { buffer::raw::Consumed::from_parts(&mut source.0, proof) });
    }
}

// SAFETY: a projection only restricts the exact admitted storage extent.
unsafe impl<T: buffer::raw::Store> buffer::raw::Store for Value<T> {
    fn empty() -> Option<Self> {
        T::empty().map(Self)
    }

    fn restrict(slice: buffer::raw::Slice<'_, '_, Self>) {
        let (target, range) = slice.into_parts();
        // SAFETY: the transparent bound preserves this owner's admitted extent.
        T::restrict(unsafe { buffer::raw::Slice::from_parts(&mut target.0, range) });
    }
}