o3 0.61.0

shared-nothing primitives
Documentation
use std::num::NonZero;

use crate::{
    alloc,
    buffer::{self, resident, segments, storage},
    mem::rc,
};

#[derive(Debug)]
/// Failure while retaining a completely validated compact range set.
pub enum Error {
    Metadata(alloc::Error),
    Retain(rc::Error),
}

/// # Safety
/// The nonempty ranges lie within this source's unchanged visible origin,
/// have the supplied total length and exactly the supplied count.
pub(super) unsafe fn collect<'d, N: buffer::raw::Length>(
    source: buffer::View<'_, storage::Shared>,
    ranges: &[(N, N)],
    count: segments::Count,
    len: usize,
) -> Result<Option<segments::Data<'d>>, Error> {
    let Some(count) = NonZero::new(count.into_raw()) else {
        return Ok(None);
    };
    if count.get() == 1 {
        // SAFETY: the admitted count selects this sole nonempty range.
        let &(start, end) = unsafe { &*ranges.as_ptr() };
        let bytes = unsafe {
            source
                .as_slice()
                .get_unchecked(start.into_usize()..end.into_usize())
        };
        // SAFETY: these admitted bytes still borrow this exact visible source.
        let owner: resident::Shared<'d> = match unsafe { source.source.try_view(bytes) } {
            Ok(owner) => owner.into(),
            Err(error) => return Err(Error::Retain(error)),
        };
        // SAFETY: range admission proved this retained extent is nonempty.
        return Ok(Some(unsafe { storage::NonEmpty::assume(owner) }.into()));
    }
    let allocation = segments::Data::allocate_ranges(count).map_err(Error::Metadata)?;
    let owner = match source.try_clone() {
        Ok(owner) => owner.into(),
        Err(error) => return Err(Error::Retain(error)),
    };
    // SAFETY: the exact allocation and retained view preserve every admitted range.
    Ok(Some(unsafe {
        segments::Data::from_allocated_ranges(allocation, owner, ranges, count, len)
    }))
}

const _: () = assert!(size_of::<Error>() <= 2 * size_of::<usize>());