o3 0.62.0

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

use resident::{Admission as _, Backing as _};

use crate::{
    base::marker::ThreadBound,
    buffer::{
        self, Residency,
        hold::{
            self, Owner,
            ranges::{Error, retain},
        },
        resident,
        segments::{self, ranges},
        storage::{self, Owned, Shared, provided},
    },
    mem::Rejected,
};

/// # Safety
/// Preserve selected bytes for 'd: copy residency <= length, retained <= max(length, source residency).
/// Admit budget and limits before writing place once; failure or decline preserves source and writes nothing.
pub unsafe trait Retain<'d>: AsRef<[u8]> + Residency {
    /// # Safety
    /// `source` exposes this view's unchanged backing and complete selected range.
    /// Its borrow may be shortened, never extended.
    unsafe fn project<'a, S: ?Sized>(
        view: buffer::View<'a, S>,
        source: &'a Self,
    ) -> buffer::View<'a, Self> {
        buffer::View {
            source,
            proof: view.proof,
        }
    }

    fn try_copy<T: From<Owned<resident::Budget<'d>>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        place: &mut MaybeUninit<T>,
    ) -> Result<(), hold::Error> {
        storage::Owned::try_slice(budget, view.as_slice(), place).map_err(hold::Error::Resident)
    }

    fn try_retain<T: From<Shared<Owner<'d>>> + From<Owned<resident::Budget<'d>>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        place: &mut MaybeUninit<T>,
    ) -> Result<(), hold::Error> {
        Self::try_copy(view, budget, place)
    }

    fn try_share<T: From<Shared<Owner<'d>>>>(
        _: buffer::View<'_, Self>,
        _: &resident::Budget<'d>,
        _: usize,
        _: &mut MaybeUninit<T>,
    ) -> Result<bool, hold::Error> {
        Ok(false)
    }
}

// SAFETY: slices copy their selected immutable bytes and issue no retained source edge.
// The original copy initializer writes place once only after allocation succeeds.
unsafe impl<'d> Retain<'d> for [u8] {}
unsafe impl<'d> Retain<'d> for &[u8] {}

// SAFETY: the selected range borrows this exact provided owner and registration.
// Accounting writes this same place once after all fallible admission; decline/error writes none.
unsafe impl<'d, L: provided::raw::Layout> Retain<'d>
    for storage::Shared<provided::raw::Owner<'d, L>>
where
    resident::Kind<'d>: From<crate::mem::raw::Owner<provided::raw::Registration<'d, L>>>,
{
    fn try_retain<T: From<Shared<Owner<'d>>> + From<Owned<resident::Budget<'d>>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        place: &mut MaybeUninit<T>,
    ) -> Result<(), hold::Error> {
        let ControlFlow::Continue(()) = provided::raw::Slice::from_view(view)
            .try_register::<_, Shared<Owner<'d>>, T>(*budget, (), place)
            .map_err(hold::Error::Account)?;
        Ok(())
    }

    fn try_share<T: From<Shared<Owner<'d>>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        limit: usize,
        place: &mut MaybeUninit<T>,
    ) -> Result<bool, hold::Error> {
        Ok(provided::raw::Slice::from_view(view)
            .try_register::<_, Shared<Owner<'d>>, T>(*budget, resident::Cap(limit), place)
            .map_err(hold::Error::Account)?
            .is_continue())
    }
}

fn try_share<'d, O, T: From<Shared<Owner<'d>>>>(
    view: buffer::View<'_, storage::Shared<Option<O>>>,
    place: &mut MaybeUninit<T>,
) -> Result<(), hold::Error>
where
    Option<O>: buffer::raw::Retain + Residency + resident::Backing<'d>,
{
    let owner = if view.is_empty() {
        Shared::<Owner<'d>>::EMPTY
    } else {
        view.try_clone()
            .map_err(resident::AllocError::Retain)?
            .into()
    };
    place.write(T::from(owner));
    Ok(())
}

// SAFETY: cloning the selected immutable range retains its original allocation edge.
// The shared initializer writes the borrowed place once only after successful retention.
unsafe impl<'d, O> Retain<'d> for storage::Shared<Option<O>>
where
    Option<O>: buffer::raw::Retain + Residency + resident::Backing<'d>,
{
    fn try_retain<T: From<Shared<Owner<'d>>> + From<Owned<resident::Budget<'d>>>>(
        view: buffer::View<'_, Self>,
        _: &resident::Budget<'d>,
        place: &mut MaybeUninit<T>,
    ) -> Result<(), hold::Error> {
        try_share(view, place)
    }

    fn try_share<T: From<Shared<Owner<'d>>>>(
        view: buffer::View<'_, Self>,
        budget: &resident::Budget<'d>,
        limit: usize,
        place: &mut MaybeUninit<T>,
    ) -> Result<bool, hold::Error> {
        let resident = view.len().max(view.resident());
        let extra = view.source.owner().additional(*budget, resident);
        if resident::Cap(limit).check(*budget, extra).is_break() {
            return Ok(false);
        }
        try_share(view, place)?;
        Ok(true)
    }
}

/// One source and compact range sequence validated as a complete logical body.
#[repr(C)]
#[derive(Debug)]
pub struct Set<'ranges, S, N = u32> {
    source: S,
    ranges: &'ranges [(N, N)],
    len: usize,
    thread: ThreadBound,
}

impl<'ranges, S: buffer::raw::Source, N: buffer::raw::Length> Set<'ranges, S, N> {
    /// # Safety
    /// Keep these admitted nonempty ranges within this source's unchanged coordinate origin.
    /// Count is <=u32::MAX and their exact sum is len; copied sources preserve all bytes.
    pub unsafe fn from_parts(source: S, ranges: &'ranges [(N, N)], len: usize) -> Self {
        const { assert!(N::MAX <= u32::MAX as usize) };
        Self {
            source,
            ranges,
            len,
            thread: ThreadBound::NEW,
        }
    }

    fn view(&self, start: N, end: N) -> buffer::View<'_, S> {
        // SAFETY: callers select validated entries from this same Set.
        unsafe { buffer::raw::Source::view(&self.source, start.into_usize()..end.into_usize()) }
    }
    /// Validates each range and its complete logical length against this source.
    /// At most `u32::MAX` ranges each contribute at most `u32::MAX` bytes,
    /// so their sum fits `usize` on the supported 64-bit or wider targets.
    pub fn try_new(
        source: S,
        ranges: &'ranges [(N, N)],
        expected: usize,
    ) -> Result<Self, Rejected<S, Error<N>>> {
        const { assert!(N::MAX <= u32::MAX as usize) };
        if ranges.len() > u32::MAX as usize {
            return Err(Rejected::new(
                source,
                Error::Count {
                    actual: ranges.len(),
                },
            ));
        }
        let len = source.as_ref().len();
        let mut actual = 0usize;
        for (index, &(start, end)) in ranges.iter().enumerate() {
            let index = index as u32;
            let first = start.into_usize();
            let last = end.into_usize();
            if first >= last {
                return Err(Rejected::new(source, Error::Order { index, start, end }));
            }
            if last > len {
                return Err(Rejected::new(
                    source,
                    Error::Bounds {
                        index,
                        start,
                        end,
                        len,
                    },
                ));
            }
            actual = actual.wrapping_add(last - first);
        }
        if actual != expected {
            return Err(Rejected::new(source, Error::Length { expected, actual }));
        }
        // SAFETY: every range, the count, and their exact sum were admitted above.
        Ok(unsafe { Self::from_parts(source, ranges, actual) })
    }

    pub fn into_parts(self) -> (S, &'ranges [(N, N)], usize) {
        (self.source, self.ranges, self.len)
    }

    pub fn get(&self, index: usize) -> Option<buffer::View<'_, S>> {
        let &(start, end) = self.ranges.get(index)?;
        Some(self.view(start, end))
    }

    pub fn iter(&self) -> Iter<'_, 'ranges, S, N> {
        Iter {
            plan: self,
            remaining: self.count(),
        }
    }

    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

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

    /// Returns the range count admitted by construction.
    pub const fn count(&self) -> segments::Count {
        segments::Count::new(self.ranges.len() as u32)
    }

    pub fn contiguous(&self) -> Option<&[u8]> {
        match self.ranges {
            [] => Some(&[]),
            &[(start, end)] => Some(self.view(start, end).as_slice()),
            _ => None,
        }
    }
}

impl<N: buffer::raw::Length> Set<'_, &storage::Shared, N> {
    /// Retains every validated range while preserving this plan for retry.
    pub fn try_retain<'d>(&self) -> Result<Option<segments::raw::Data<'d>>, retain::Error> {
        // SAFETY: this Set admitted the ranges against the owner's full visible extent.
        unsafe {
            retain::collect(
                buffer::View::new(self.source),
                self.ranges,
                self.count(),
                self.len,
            )
        }
    }
}

impl<N: buffer::raw::Length> Set<'_, buffer::View<'_, storage::Shared>, N> {
    /// Retains every validated range while preserving this plan for retry.
    pub fn try_retain<'d>(&self) -> Result<Option<segments::raw::Data<'d>>, retain::Error> {
        // SAFETY: the Set's offsets start at this view, which borrows exactly this owner.
        unsafe { retain::collect(self.source, self.ranges, self.count(), self.len) }
    }
}

impl<'d, N: buffer::raw::Length> Set<'_, storage::Shared<resident::State<'d>>, N> {
    pub fn try_retain(
        self,
    ) -> Result<
        Option<segments::raw::Data<'d>>,
        Rejected<storage::Shared<resident::State<'d>>, crate::alloc::Error>,
    > {
        let Some(count) = NonZero::new(self.count().into_raw()) else {
            return Ok(None);
        };
        let mut source = self.source;
        if count.get() == 1 {
            // SAFETY: this single admitted range belongs to the retained source.
            let &(start, end) = unsafe { &*self.ranges.as_ptr() };
            buffer::raw::Store::project(unsafe {
                buffer::raw::Input::from_parts(&mut source, start.into_usize()..end.into_usize())
            });
            // SAFETY: the admitted range is nonempty.
            return Ok(Some(unsafe { storage::raw::present(source) }.into()));
        }
        // SAFETY: the source retains at least two admitted ranges and their exact sum.
        let owner = unsafe { ranges::raw::Owned::try_new(source, self.ranges, count, self.len) }?;
        Ok(Some(owner.into()))
    }
}

const _: () = {
    assert!(size_of::<Set<'static, &'static [u8]>>() == 5 * size_of::<usize>());
    assert!(size_of::<Set<'static, &'static storage::Shared>>() == 4 * size_of::<usize>());
};

/// Views over one completely validated compact range sequence.
pub struct Iter<'plan, 'ranges, S, N = u32> {
    plan: &'plan Set<'ranges, S, N>,
    remaining: segments::Count,
}

impl<'plan, S: buffer::raw::Source, N: buffer::raw::Length> Iterator for Iter<'plan, '_, S, N> {
    type Item = buffer::View<'plan, S>;

    fn next(&mut self) -> Option<Self::Item> {
        let left = NonZero::new(self.remaining.into_raw())?.get();
        let plan = self.plan;
        let total = plan.count().into_raw();
        let index = (total - left) as usize;
        // SAFETY: `Set::iter` binds this private cursor to `plan` and its exact
        // validated count. Every yielded item decrements it once, so nonzero
        // `left` proves both the range index and the successor count.
        let (start, end) = unsafe { *plan.ranges.as_ptr().add(index) };
        self.remaining = segments::Count::new(left - 1);
        Some(plan.view(start, end))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let left = self.remaining.into_raw() as usize;
        (left, Some(left))
    }
}

impl<S: buffer::raw::Source, N: buffer::raw::Length> ExactSizeIterator for Iter<'_, '_, S, N> {}
impl<S: buffer::raw::Source, N: buffer::raw::Length> FusedIterator for Iter<'_, '_, S, N> {}

const _: () = assert!(size_of::<Iter<'static, 'static, &'static [u8]>>() == 2 * size_of::<usize>());

impl<S: buffer::raw::Source, N: buffer::raw::Length> buffer::raw::Transfer for Set<'_, S, N> {
    unsafe fn copy_to(&self, target: *mut u8) {
        // SAFETY: Set retains every admitted range; the destination covers their exact sum.
        unsafe {
            buffer::raw::IteratorExt::copy_to(self.iter().map(|view| view.as_slice()), target)
        };
    }
}

impl<S: buffer::raw::Source, N: buffer::raw::Length> Set<'_, S, N> {
    pub fn try_copy(
        &self,
    ) -> Result<Option<storage::NonEmpty<storage::Shared>>, storage::AllocError> {
        let Some(len) = NonZero::new(self.len()) else {
            return Ok(None);
        };
        // SAFETY: admission retained all ranges and their exact byte sum.
        let init = unsafe { storage::raw::Init::try_bytes(len, self) }?;
        Ok(Some(storage::NonEmpty::from(init)))
    }
}

impl<'frame, N: buffer::raw::Length> Set<'_, &'frame [u8], N> {
    pub fn try_slice<T: From<storage::Shared>>(
        self,
    ) -> Result<ControlFlow<T, &'frame [u8]>, storage::AllocError> {
        match self.count().into_raw() {
            0 => Ok(ControlFlow::Continue(&[])),
            1 => {
                let (source, ranges, _) = self.into_parts();
                // SAFETY: Set admitted this sole range against the unchanged source.
                let &(start, end) = unsafe { ranges.get_unchecked(0) };
                // SAFETY: the original source retains this admitted range for 'frame.
                let bytes = unsafe { source.get_unchecked(start.into_usize()..end.into_usize()) };
                Ok(ControlFlow::Continue(bytes))
            }
            _ => {
                // SAFETY: at least two admitted nonempty ranges give a positive exact sum.
                let len = unsafe { NonZero::new_unchecked(self.len()) };
                // SAFETY: these same admitted ranges retain exactly len bytes.
                let init = unsafe { storage::raw::Init::try_bytes(len, &self) }?;
                let owner = storage::NonEmpty::from(init);
                Ok(ControlFlow::Break(T::from(owner.into_storage())))
            }
        }
    }
}