o3 0.62.0

shared-nothing primitives
Documentation
use std::{convert, num, ops};

use storage::{inline, provided, range};
use write::consume::{self, scope};

use crate::{buffer::pool::owners, mem::rc};

pub mod raw;

pub mod bytes;
pub mod hold;
pub mod pool;
pub mod resident;
pub mod segments;
pub mod storage;
pub mod write;

/// A selected range retaining its immutable original source borrow.
#[must_use]
#[derive(Debug)]
#[repr(C)]
pub struct View<'source, S: ?Sized> {
    pub(in crate::buffer) source: &'source S,
    pub(in crate::buffer) proof: &'source [u8],
}

impl<S: ?Sized> Copy for View<'_, S> {}

impl<S: ?Sized> Clone for View<'_, S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'source, S: ?Sized> View<'source, S> {
    pub fn source(&self) -> &'source S {
        self.source
    }

    pub fn as_slice(&self) -> &'source [u8] {
        self.proof
    }

    pub fn is_empty(&self) -> bool {
        self.proof.is_empty()
    }

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

    pub fn select(&self, bytes: &[u8]) -> Option<View<'source, S>> {
        let range: ops::Range<usize> = self.proof.subslice_range(bytes)?.into();
        // SAFETY: containment proved this exact range of the retained source;
        // reconstructing its borrow preserves the source lifetime and provenance.
        Some(Self {
            source: self.source,
            proof: unsafe { self.proof.get_unchecked(range) },
        })
    }

    pub fn get(&self, range: ops::Range<usize>) -> Option<View<'source, S>> {
        let bytes = self.proof.get(range)?;
        Some(View {
            source: self.source,
            proof: bytes,
        })
    }

    pub fn try_get(&self, range: ops::Range<usize>) -> Result<Self, range::Error> {
        self.get(range.clone())
            .ok_or_else(|| range::Error::new(range, self.len()))
    }

    /// Borrows the complete initialized source without retaining or copying it.
    pub fn new(source: &'source S) -> Self
    where
        S: AsRef<[u8]>,
    {
        Self {
            source,
            proof: source.as_ref(),
        }
    }
}

impl<S: Residency + ?Sized> Residency for View<'_, S> {
    /// Backing capacity kept live by retaining this selection; zero when empty.
    fn resident(&self) -> usize {
        if self.is_empty() {
            0
        } else {
            self.source.resident()
        }
    }
}

impl View<'_, storage::Shared<resident::State<'_>>> {
    /// Retains this validated range when its existing owner is independent.
    /// A scoped owner returns `None` without retaining or copying its bytes.
    pub fn try_own(self) -> Result<Option<storage::Shared>, rc::Error> {
        if self.is_empty() {
            return Ok(Some(storage::Shared::new()));
        }
        let owner = match &self.source.owner().0 {
            resident::Kind::Owned(owner) => Some(owner.try_clone()?),
            resident::Kind::Static => None,
            resident::Kind::Slice
            | resident::Kind::Resident(_)
            | resident::Kind::Accounted(_)
            | resident::Kind::Provided(_)
            | resident::Kind::Fixed(_) => return Ok(None),
        };
        // SAFETY: this view retains the exact source borrow and validated slice;
        // the selected independent edge keeps that same immutable extent live.
        Ok(Some(unsafe {
            storage::raw::Extent::from_bytes(self.as_slice()).bind(owner)
        }))
    }
}

const _: () = assert!(size_of::<View<'static, storage::Shared>>() == 3 * size_of::<usize>());

impl<S: ?Sized> AsRef<[u8]> for View<'_, S> {
    fn as_ref(&self) -> &[u8] {
        self.proof
    }
}

impl<'input, S: ?Sized> View<'input, S> {
    pub fn try_split<const N: usize>(mut self) -> Result<(&'input [u8; N], Self), consume::Error> {
        let (head, tail) = self.proof.split_first_chunk::<N>().ok_or_else(|| {
            consume::Error::new(
                num::NonZero::<usize>::MIN.saturating_add(N.saturating_sub(1)),
                self.proof.len(),
            )
        })?;
        self.proof = tail;
        Ok((head, self))
    }
}

/// Payload backing capacity retained by this owner, excluding metadata and padding.
/// Borrowed and static bytes retain zero bytes.
pub trait Residency {
    fn resident(&self) -> usize;
}

impl<L, S> Residency for pool::Span<owners::Plain<L>, pool::Owned, S>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    fn resident(&self) -> usize {
        self.capacity().get() as usize
    }
}

impl<L> Residency for pool::Cursor<L>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    fn resident(&self) -> usize {
        self.len() + self.spare_len()
    }
}

impl Residency for Vec<u8> {
    fn resident(&self) -> usize {
        self.capacity()
    }
}

impl<const CAP: usize, L> Residency for inline::Bytes<CAP, L> {
    fn resident(&self) -> usize {
        CAP
    }
}

impl Residency for [u8] {
    fn resident(&self) -> usize {
        0
    }
}

impl Residency for &[u8] {
    /// A borrowed slice retains no complete backing allocation of its own.
    fn resident(&self) -> usize {
        0
    }
}

impl Residency for convert::Infallible {
    fn resident(&self) -> usize {
        match *self {}
    }
}

pub const BLOCK_CAPACITY: u32 = 64 * 1024;

fn is_within(range: &ops::Range<usize>, len: usize) -> bool {
    range.start <= range.end && range.end <= len
}

impl<'d, L: provided::raw::Layout>
    View<'_, storage::Shared<Option<crate::mem::raw::Owner<provided::raw::Registration<'d, L>>>>>
{
    /// Retains the proved extent using its existing registration, without admission.
    pub fn try_retain(
        self,
    ) -> Result<
        storage::Shared<Option<crate::mem::raw::Owner<provided::raw::Registration<'d, L>>>>,
        rc::Error,
    > {
        if self.is_empty() {
            return Ok(storage::Shared::<
                Option<crate::mem::raw::Owner<provided::raw::Registration<'d, L>>>,
            >::new());
        }
        self.try_clone()
    }
}
const _: () = {
    assert!(
        size_of::<
            storage::Shared<Option<crate::mem::raw::Owner<provided::raw::Registration<'static>>>>,
        >() == 3 * size_of::<usize>()
    );
    assert!(
        size_of::<
            Option<
                storage::Shared<
                    Option<crate::mem::raw::Owner<provided::raw::Registration<'static>>>,
                >,
            >,
        >() == 3 * size_of::<usize>()
    );
};

// SAFETY: the original source and immutable byte borrow stay live; consumption
// selects only the admitted suffix.
unsafe impl<S: ?Sized> raw::Consume for View<'_, S> {
    fn consume<const MAX: u32>(prefix: raw::Input<&mut Self, scope::Prefix<MAX>>) {
        let (view, end) = prefix.into_parts();
        // SAFETY: the prefix owns this exact view and its admitted bound.
        view.proof = unsafe { view.proof.get_unchecked(end.count().get() as usize..) };
    }
}

// SAFETY: projection narrows only this source's retained immutable byte borrow.
unsafe impl<S: ?Sized> raw::Store for View<'_, S> {
    fn restrict(slice: raw::Input<&mut Self, ops::Range<usize>>) {
        let (target, range) = slice.into_parts();
        // SAFETY: this range is admitted for the unchanged source.
        target.proof = unsafe { target.proof.get_unchecked(range) };
    }
}

impl<O: raw::Retain> View<'_, storage::Shared<O>> {
    pub(in crate::buffer) fn try_clone(&self) -> Result<storage::Shared<O>, rc::Error> {
        let owner = raw::Retain::try_retain(self.source.owner())?;
        // SAFETY: this selection retains the original source and its admitted bytes.
        Ok(unsafe { storage::raw::Extent::from_bytes(self.proof).bind(owner) })
    }
}

impl<S: raw::Segment> View<'_, S> {
    /// Retains this admitted range without allocating or copying.
    pub fn try_retain(self) -> Result<S, rc::Error> {
        if self.is_empty() {
            return Ok(S::EMPTY);
        }
        // SAFETY: this branch retains the same admitted nonempty source view.
        S::try_share(&unsafe { raw::Source::nonempty(self) })
    }
}