o3 0.61.0

shared-nothing primitives
Documentation
pub use error::Error;
pub use iter::Iter;

use crate::{
    base::marker::ThreadBound,
    buffer,
    buffer::{resident, segments, storage},
    mem::Rejected,
};

mod error;
mod iter;
pub mod retain;

/// 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::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::new(self)
    }

    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::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::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<'_, resident::Shared<'d>, N> {
    pub fn try_retain(
        self,
    ) -> Result<Option<segments::Data<'d>>, Rejected<resident::Shared<'d>, crate::alloc::Error>>
    {
        let count = self.count();
        // SAFETY: the owned source retains every admitted range at its original origin.
        unsafe { segments::Data::from_ranges(self.source, self.ranges, count, self.len) }
    }
}

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