o3 0.62.0

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

use crate::{
    alloc,
    buffer::{
        self, resident,
        segments::{self, ranges},
        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(in crate::buffer::hold) unsafe fn collect<'d, N: buffer::raw::Length>(
    source: buffer::View<'_, storage::Shared>,
    ranges: &[(N, N)],
    count: segments::Count,
    len: usize,
) -> Result<Option<segments::raw::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())
        };
        let owner: storage::Shared<resident::State<'d>> = match (buffer::View {
            source: source.source,
            proof: bytes,
        })
        .try_clone()
        {
            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::raw::present(owner) }.into()));
    }
    let alloc = ranges::raw::Header::allocate(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 alloc and retained view preserve every admitted range.
    Ok(Some(
        unsafe { ranges::raw::Owned::initialize(alloc, owner, ranges, count, len) }.into(),
    ))
}

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