o3 0.59.0

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

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

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<'source, 'ranges, S: ?Sized, N = u32> {
    source: &'source S,
    ranges: &'ranges [(N, N)],
    len: usize,
    thread: ThreadBound,
}

impl<'source, 'ranges, S: buffer::raw::Source + ?Sized, N: buffer::raw::Length>
    Set<'source, '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: &'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<'source, 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: &'source S,
        ranges: &'ranges [(N, N)],
        expected: usize,
    ) -> Result<Self, Error<N>> {
        const { assert!(N::MAX <= u32::MAX as usize) };
        if ranges.len() > u32::MAX as usize {
            return Err(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(Error::Order { index, start, end });
            }
            if last > len {
                return Err(Error::Bounds {
                    index,
                    start,
                    end,
                    len,
                });
            }
            actual = actual.wrapping_add(last - first);
        }
        if actual != expected {
            return Err(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 get(&self, index: usize) -> Option<buffer::View<'source, S>> {
        let &(start, end) = self.ranges.get(index)?;
        Some(self.view(start, end))
    }

    pub fn iter(&self) -> Iter<'_, 'source, '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<&'source [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<segments::Shape<resident::Shared<'d>>, retain::Error> {
        // SAFETY: this Set admitted the ranges against the owner's full visible extent.
        unsafe { retain::collect(self.source, self.source.as_slice(), self.ranges, 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<segments::Shape<resident::Shared<'d>>, retain::Error> {
        // SAFETY: the Set's offsets start at this view, which borrows exactly this owner.
        unsafe { retain::collect(self.source.source, self.source.bytes, self.ranges, 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>());
};