o3 0.62.0

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

use crate::{
    buffer::{self, resident, storage, storage::range, write::consume},
    mem::rc,
};
use consume::scope::{Error, Prefix};

/// One source and the proof admitted against that source.
#[must_use]
#[repr(C)]
#[derive(Debug)]
pub struct Input<S, P = ()> {
    pub(in crate::buffer) source: S,
    pub(in crate::buffer) proof: P,
}

impl<'a, R> From<&'a mut R> for Input<&'a mut R> {
    fn from(source: &'a mut R) -> Self {
        Self { source, proof: () }
    }
}

impl<'a, R: buffer::raw::Source> Input<&'a mut R> {
    pub fn try_prefix<const MAX: u32>(
        self,
        start: usize,
        count: NonZero<usize>,
    ) -> Result<Input<&'a mut R, Prefix<MAX>>, Error> {
        if count.get() > MAX as usize {
            return Err(Error::Maximum {
                count,
                maximum: MAX,
            });
        }
        let bounds = start..count.get();
        let len = self.source.as_ref().len();
        if !buffer::is_within(&bounds, len) {
            return Err(Error::Range(range::Error::new(bounds, len)));
        }
        // SAFETY: the maximum and range checks admitted this unchanged source prefix.
        Ok(unsafe { self.prefix(start, count) })
    }
}

impl<R: buffer::raw::Source, const MAX: u32> Input<&mut R, Prefix<MAX>> {
    pub fn left(&self) -> usize {
        self.source.as_ref().len() - self.proof.end.get() as usize
    }

    pub fn view(&self) -> buffer::View<'_, R> {
        let bounds = ops::Range {
            start: self.proof.start as usize,
            end: self.proof.end.get() as usize,
        };
        // SAFETY: the input retains the original stable source and its admitted range.
        unsafe { buffer::raw::Source::view(&*self.source, bounds) }
    }
}

impl<'a, R: buffer::raw::Consume, const MAX: u32> Input<&'a mut R, Prefix<MAX>> {
    pub fn commit(self) -> &'a mut R {
        let Self { source, proof } = self;
        R::consume(Input {
            source: &mut *source,
            proof,
        });
        source
    }
}

const _: () = {
    assert!(size_of::<Input<&'static mut storage::Shared>>() == size_of::<usize>());
    assert!(size_of::<Prefix<{ u32::MAX }>>() == 8);
    assert!(size_of::<Option<Prefix<{ u32::MAX }>>>() == 8);
};

impl<'a, 'd> Input<&'a mut storage::Shared<resident::State<'d>>> {
    pub fn project(
        self,
        index: usize,
        range: ops::Range<usize>,
    ) -> Option<Input<&'a mut storage::Shared<resident::State<'d>>, ops::Range<usize>>> {
        if index != 0 {
            return None;
        }
        let len = NonZero::new(self.source.len())?;
        if range.start > range.end || range.end > len.get() {
            return None;
        }
        Some(Input {
            source: self.source,
            proof: range,
        })
    }
}

impl<'d> Input<&mut storage::Shared<resident::State<'d>>, ops::Range<usize>> {
    pub fn try_project(
        self,
    ) -> Result<Option<storage::NonEmpty<storage::Shared<resident::State<'d>>>>, rc::Error> {
        if self.proof.start == self.proof.end {
            return Ok(None);
        }
        let bytes = self.as_ref();
        let owner = buffer::View {
            source: &*self.source,
            proof: bytes,
        }
        .try_clone()?;
        // SAFETY: the admitted range is nonempty and retaining preserves its exact extent.
        Ok(Some(unsafe { storage::raw::present(owner) }))
    }
}

impl AsRef<[u8]> for Input<&mut storage::Shared<resident::State<'_>>, ops::Range<usize>> {
    fn as_ref(&self) -> &[u8] {
        // SAFETY: the exclusive source loan preserves the admitted range until consumption.
        unsafe { self.source.as_ref().get_unchecked(self.proof.clone()) }
    }
}

impl<'a, S: buffer::raw::Store> Input<&'a mut S> {
    pub fn try_tail(
        self,
        start: usize,
    ) -> Result<Input<&'a mut S, (usize, usize)>, consume::Error> {
        let len = self.source.as_ref().len();
        consume::Error::check(start, len)?;
        Ok(Input {
            source: self.source,
            proof: (start, len - start),
        })
    }
}

impl<S: buffer::raw::Store> Input<&mut S, (usize, usize)> {
    pub(in crate::buffer) fn project<const SUFFIX: bool>(self) -> usize {
        let (start, rest) = self.proof;
        let proof = if SUFFIX {
            start..start + rest
        } else {
            0..start
        };
        S::project(Input {
            source: self.source,
            proof,
        });
        start
    }
}

impl buffer::Residency for Input<&mut storage::Shared, (usize, usize)> {
    fn resident(&self) -> usize {
        buffer::Residency::resident(&*self.source)
    }
}

impl<S, P> Input<S, P> {
    /// # Safety
    /// The source retains the original owner and unchanged bytes for this proof.
    /// Every bound and count in the proof must remain valid for this exact source.
    pub unsafe fn from_parts(source: S, proof: P) -> Self {
        Self { source, proof }
    }

    pub fn as_parts(&self) -> (&S, &P) {
        (&self.source, &self.proof)
    }

    pub fn into_parts(self) -> (S, P) {
        (self.source, self.proof)
    }
}

impl<'a, S: buffer::raw::Source> Input<&'a mut S> {
    /// # Safety
    /// This unchanged source has `start <= count <= len` and `count <= MAX`.
    /// The original source loan used to prove these bounds must have ended.
    pub unsafe fn prefix<const MAX: u32>(
        self,
        start: usize,
        count: NonZero<usize>,
    ) -> Input<&'a mut S, Prefix<MAX>> {
        Input {
            source: self.source,
            proof: Prefix {
                start: start as u32,
                end: NonZero::<u32>::MIN.saturating_add(count.get() as u32 - 1),
            },
        }
    }
}

impl<'a, S, const MAX: u32> From<Input<&'a mut S, Prefix<MAX>>> for Input<&'a mut S, usize> {
    fn from(prefix: Input<&'a mut S, Prefix<MAX>>) -> Self {
        let (source, end) = prefix.into_parts();
        Self {
            source,
            proof: end.count().get() as usize,
        }
    }
}

impl<'a, S: buffer::raw::Source> Input<&'a mut S, usize> {
    /// Admits one prefix length and retains its exact exclusive source.
    pub(in crate::buffer) fn try_new(
        source: &'a mut S,
        len: usize,
    ) -> Result<Self, consume::Error> {
        consume::Error::check(len, source.as_ref().len())?;
        Ok(Self { source, proof: len })
    }

    pub(in crate::buffer) fn new(source: &'a mut S, max: usize) -> Self {
        let len = max.min(source.as_ref().len());
        Self { source, proof: len }
    }
}

impl Input<&mut storage::Shared, (usize, usize)> {
    pub fn try_prefix(
        self,
        limit: usize,
    ) -> Result<Option<storage::NonEmpty<storage::Shared>>, rc::Error> {
        let (start, len) = self.proof;
        let Some(amount) = NonZero::new(limit.min(len)) else {
            return Ok(None);
        };
        let mut owner = if amount.get() == len {
            mem::take(self.source)
        } else {
            buffer::raw::Segment::try_clone(&*self.source)?
        };
        // SAFETY: this exclusive loan preserves the admitted tail; clamping stays within it.
        buffer::raw::Store::project(unsafe {
            Input::from_parts(&mut owner, start..start + amount.get())
        });
        // SAFETY: this same original projection contains the positive clamped prefix.
        Ok(Some(unsafe { storage::raw::present(owner) }))
    }
}

impl<'a, S: buffer::raw::Store> Input<&'a mut S, ops::Range<usize>> {
    pub fn try_select(source: &'a mut S, bounds: ops::Range<usize>) -> Result<Self, range::Error> {
        let len = source.as_ref().len();
        if !buffer::is_within(&bounds, len) {
            return Err(range::Error::new(bounds, len));
        }
        Ok(Self {
            source,
            proof: bounds,
        })
    }
}

const _: () = {
    assert!(size_of::<Input<&'static mut Vec<u8>, ops::Range<usize>>>() == 3 * size_of::<usize>());
    assert!(
        size_of::<Option<Input<&'static mut Vec<u8>, ops::Range<usize>>>>()
            == size_of::<Input<&'static mut Vec<u8>, ops::Range<usize>>>()
    );
};

// SAFETY: admission retains this exact initialized slice exclusively.
unsafe impl buffer::raw::Consume for &mut [u8] {
    fn consume<const MAX: u32>(prefix: Input<&mut Self, Prefix<MAX>>) {
        let (target, end) = prefix.into_parts();
        let bytes = mem::take(target);
        // SAFETY: the source-bound end is within this unchanged slice.
        *target = unsafe { bytes.get_unchecked_mut(end.count().get() as usize..) };
    }
}

// SAFETY: the stronger cursor contract requires this stable-source contract.
unsafe impl<T: buffer::raw::Consume> buffer::raw::Source for T {}

// SAFETY: this immutable borrow preserves the owner's visible range and contents.
unsafe impl buffer::raw::Source for &storage::Shared {}

// SAFETY: shared access through this exclusive loan preserves the owner's range and contents.
unsafe impl buffer::raw::Source for &mut storage::Shared<resident::State<'_>> {}

// SAFETY: shared access preserves the slice's exact range and contents.
unsafe impl buffer::raw::Source for [u8] {}

// SAFETY: shared access preserves the array's complete range and contents.
unsafe impl<const N: usize> buffer::raw::Source for [u8; N] {}

// SAFETY: the immutable borrow preserves the exact slice and its contents.
unsafe impl buffer::raw::Source for &[u8] {}

// SAFETY: the immutable borrow preserves the exact array and its contents.
unsafe impl<const N: usize> buffer::raw::Source for &[u8; N] {}

// SAFETY: shared access cannot mutate Vec; its Sink implementation only appends.
unsafe impl buffer::raw::Source for Vec<u8> {}

// SAFETY: Vec's byte projection returns its existing initialized range unchanged.
unsafe impl buffer::raw::Mutable for Vec<u8> {}

// SAFETY: reborrowing this exclusive slice preserves its descriptor and contents.
unsafe impl buffer::raw::Mutable for &mut [u8] {}

// SAFETY: the exclusive slice retains its initialized range and original borrow.
unsafe impl buffer::raw::Store for &mut [u8] {
    fn empty() -> Option<Self> {
        Some(&mut [])
    }

    fn restrict(slice: Input<&mut Self, ops::Range<usize>>) {
        let (target, range) = slice.into_parts();
        let bytes = mem::take(target);
        // SAFETY: this admitted range belongs to the unchanged exclusive slice.
        *target = unsafe { bytes.get_unchecked_mut(range) };
    }
}

// SAFETY: shared Vec access preserves its bytes; projection keeps its allocation.
unsafe impl buffer::raw::Store for Vec<u8> {
    fn restrict(slice: Input<&mut Self, ops::Range<usize>>) {
        let (target, range) = slice.into_parts();
        let len = range.end - range.start;
        if range.start != 0 {
            let pointer = target.as_mut_ptr();
            // SAFETY: the retained selection proves this initialized range;
            // copying to its prefix stays in the same allocation and may overlap.
            unsafe { ptr::copy(pointer.add(range.start), pointer, len) };
        }
        target.truncate(len);
    }
}