o3 0.62.0

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

use provided::account;

use crate::{
    base::num::bounded,
    buffer,
    buffer::{
        bytes::bounded::{MAX, Rejected, Source},
        hold, resident, storage,
        storage::{provided, range},
        write::consume::{self, scope},
    },
    mem::{self, 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 <= MAX) };
        Self(value)
    }
}

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

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

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

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

    fn try_take(&mut self, amount: NonZero<usize>) -> Result<Self::Prefix<'_>, 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::raw::Layout>
    From<Value<provided::raw::Slice<&'d mut [u8], provided::raw::Owner<'d, L>>>>
    for Value<storage::Shared<provided::raw::Owner<'d, L>>>
{
    fn from(bytes: Value<provided::raw::Slice<&'d mut [u8], provided::raw::Owner<'d, L>>>) -> Self {
        Value(bytes.0.into_shared())
    }
}

impl<T> 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: mem::raw::Convert<U>,
    {
        Value(mem::raw::Convert::into(self.0))
    }

    /// Seals the original producer's extent proof into its bytes.
    pub fn from_raw(proof: super::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 bounded::raw::U32<0, { MAX as u32 }> {
    fn from(bytes: &Value<T>) -> Self {
        super::raw::Input::count(bytes)
    }
}

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

impl<'d, L: provided::raw::Layout> provided::Frozen<'d>
    for Value<storage::Shared<provided::raw::Owner<'d, L>>>
{
    type Account = Value<account::Bytes<'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::raw::Layout> Value<storage::Shared<provided::raw::Owner<'d, L>>> {
    pub fn try_get(
        &self,
        range: ops::Range<usize>,
        budget: &resident::Budget<'d>,
    ) -> Result<Value<account::Bytes<'d, L>>, account::Error> {
        Ok(Value(self.0.try_get(range, budget)?))
    }
}

impl<L: provided::raw::Layout> Default for Value<account::Bytes<'_, L>> {
    fn default() -> Self {
        Value(account::Bytes::<'_, L>::new())
    }
}

impl<'d, L: provided::raw::Layout> Value<account::Bytes<'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, mem::Rejected<Self, range::Error>> {
        match self.0.project(range) {
            Ok(value) => Ok(Value(value)),
            Err(rejected) => {
                let (value, error) = rejected.into_parts();
                Err(mem::Rejected::new(Value(value), error))
            }
        }
    }
}

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 Source for Value<&[u8]> {}

const _: () = {
    assert!(size_of::<Value<&[u8]>>() == 2 * size_of::<usize>());
    assert!(size_of::<Value<account::Bytes<'static>>>() == 3 * size_of::<usize>());
    assert!(size_of::<Option<Value<account::Bytes<'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 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 MaybeUninit<T>,
    ) -> Result<(), hold::Error> {
        Ok(storage::Owned::try_copy(&view, budget, place)?)
    }

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

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

impl<'a, 'd, L: provided::raw::Layout> provided::Mutable<'d>
    for Value<provided::raw::Slice<&'a mut [u8], &'a provided::raw::Owner<'d, L>>>
{
    type Account = Value<account::Bytes<'d, L>>;
    type Frozen = Value<provided::raw::Slice<&'a [u8], &'a provided::raw::Owner<'d, L>>>;
    type Prefix<'b>
        = Value<provided::raw::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> {
        Ok(Self(self.0.try_take(amount)?))
    }
}

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

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

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

impl<'a, 'd, L: provided::raw::Layout>
    From<Value<provided::raw::Slice<&'a mut [u8], &'a provided::raw::Owner<'d, L>>>>
    for Value<provided::raw::Slice<&'a [u8], &'a provided::raw::Owner<'d, L>>>
{
    fn from(
        prefix: Value<provided::raw::Slice<&'a mut [u8], &'a provided::raw::Owner<'d, 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> Source for buffer::View<'_, Value<T>> {}

impl<'d, L: provided::raw::Layout> buffer::View<'_, Value<account::Bytes<'d, L>>> {
    pub fn try_retain(self) -> Result<Value<account::Bytes<'d, L>>, rc::Error> {
        Ok(Value(
            buffer::View {
                source: &self.source.0,
                proof: self.proof,
            }
            .try_retain()?,
        ))
    }
}

const _: () = {
    assert!(
        size_of::<buffer::View<'static, Value<storage::Shared<provided::raw::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::Input<&mut Self, scope::Prefix<MAX>>) {
        let (source, proof) = prefix.into_parts();
        // SAFETY: the transparent bound retains its exact inner owner's byte extent.
        T::consume(unsafe { buffer::raw::Input::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::Input<&mut Self, ops::Range<usize>>) {
        let (target, range) = slice.into_parts();
        // SAFETY: the transparent bound preserves this owner's admitted extent.
        T::restrict(unsafe { buffer::raw::Input::from_parts(&mut target.0, range) });
    }
}