o3 0.62.0

shared-nothing primitives
Documentation
use crate::{
    alloc::{self, tail},
    buffer::{self, resident, storage},
    mem::{self, Rejected, rc},
};
use std::{
    iter,
    mem::{forget, take},
    num::NonZero,
    ops::{self, ControlFlow},
    ptr,
};

#[derive(Debug)]
pub struct Header<'d> {
    count: mem::raw::Count,
    source: storage::Shared<resident::State<'d>>,
}

#[derive(Debug)]
pub struct Owned<'d> {
    pub(in crate::buffer::segments) owner: mem::raw::Owner<Header<'d>>,
    pub(in crate::buffer::segments) first: u32,
    pub(in crate::buffer::segments) end: u32,
    pub(in crate::buffer::segments) start: u32,
    pub(in crate::buffer::segments) finish: u32,
    pub(in crate::buffer::segments) len: NonZero<usize>,
}

// SAFETY: each edge retains this exact immutable header and initialized tail.
unsafe impl mem::raw::Edge for Header<'_> {
    fn count(&self) -> &mem::raw::Count {
        &self.count
    }
}

// SAFETY: the final edge owns the original header-and-tail block.
unsafe impl mem::raw::Target for Header<'_> {
    unsafe fn destroy(pointer: ptr::NonNull<Self>) {
        // SAFETY: Header is the first field of the original tail block.
        let view: tail::raw::View<'_, Header<'_>, (u32, u32)> =
            unsafe { tail::raw::View::from_raw(pointer.cast()) };
        let layout = view.len_proof().layout();
        // SAFETY: all ranges are Copy; only the original source has a destructor.
        unsafe {
            ptr::drop_in_place(pointer.as_ptr());
            alloc::raw::LayoutExt::deallocate(layout, pointer);
        }
    }
}

impl<'d> Header<'d> {
    pub(in crate::buffer::segments) fn try_freeze(
        page: &mut storage::Owned,
    ) -> Result<mem::raw::Owner<Self>, alloc::Error> {
        let block = tail::Plan::<Self, (u32, u32)>::try_new(0)?.try_allocate()?;
        let block = block.init(Self {
            count: mem::raw::Count::one(),
            source: storage::Shared::<resident::State<'_>>::from(take(page).freeze()),
        });
        // SAFETY: the admitted tail has zero entries.
        let mut block = unsafe { block.assume_init() };
        let pointer = ptr::NonNull::from(block.header_mut());
        forget(block);
        // SAFETY: this initialized physical group transfers its sole edge.
        Ok(unsafe { mem::raw::Owner::from_raw(pointer) })
    }

    pub fn source(&self) -> &storage::Shared<resident::State<'d>> {
        &self.source
    }
}

impl<'d> Owned<'d> {
    pub fn source(&self) -> &storage::Shared<resident::State<'d>> {
        self.owner.get().source()
    }

    pub fn into_owner(self) -> mem::raw::Owner<Header<'d>> {
        self.owner
    }

    pub fn split_first(&self) -> (&[u8], Iter<'_, 'd, false>) {
        (
            self.first(),
            Iter {
                source: self,
                next: self.first + 1,
            },
        )
    }

    /// # Safety
    /// The nonempty ranges are admitted against this source's unchanged origin.
    /// Their count is `count`, their byte sum is `len`, and count is at least two.
    pub(in crate::buffer) unsafe fn try_new<N: buffer::raw::Length>(
        source: storage::Shared<resident::State<'d>>,
        ranges: &[(N, N)],
        count: NonZero<u32>,
        len: usize,
    ) -> Result<Self, Rejected<storage::Shared<resident::State<'d>>, alloc::Error>> {
        const { assert!(N::MAX <= u32::MAX as usize) };
        let block = match Header::allocate(count) {
            Ok(block) => block,
            Err(error) => return Err(Rejected::new(source, error)),
        };
        // SAFETY: this block has the exact admitted range count.
        Ok(unsafe { Self::initialize(block, source, ranges, count, len) })
    }

    pub(in crate::buffer::segments) const fn count(&self) -> NonZero<u32> {
        // SAFETY: this clipped owner always retains at least one complete range.
        unsafe { NonZero::new_unchecked(self.end - self.first) }
    }

    pub(in crate::buffer::segments) fn resident(&self) -> usize {
        buffer::Residency::resident(&self.owner.get().source)
    }

    pub(in crate::buffer::segments) unsafe fn span(&self, index: u32) -> (u32, u32) {
        // SAFETY: this edge retains the original header and its immutable tail.
        let view: tail::raw::View<'_, Header<'d>, (u32, u32)> =
            unsafe { tail::raw::View::from_raw(self.owner.as_ptr().cast()) };
        // SAFETY: callers hold first <= index < end within the original tail.
        let (mut start, mut end) = unsafe { *view.as_slice().get_unchecked(index as usize) };
        if index == self.first {
            start = self.start;
        }
        if index + 1 == self.end {
            end = self.finish;
        }
        (start, end)
    }

    unsafe fn bytes(&self, start: u32, end: u32) -> &[u8] {
        // SAFETY: each clipped range remains within this same immutable source.
        unsafe {
            self.owner
                .get()
                .source
                .as_ref()
                .get_unchecked(start as usize..end as usize)
        }
    }

    pub(in crate::buffer::segments) fn first(&self) -> &[u8] {
        // SAFETY: Owned always retains at least one admitted nonempty range.
        let (start, end) = unsafe { self.span(self.first) };
        unsafe { self.bytes(start, end) }
    }

    /// # Safety
    /// `next` is this exact owner's saved index, with `first <= next <= end`.
    pub(in crate::buffer::segments) unsafe fn next<const RUNS: bool>(
        &self,
        next: &mut u32,
    ) -> Option<&[u8]> {
        if *next == self.end {
            return None;
        }
        // SAFETY: this index advances once through the retained clipped range sequence.
        let (start, mut end) = unsafe { self.span(*next) };
        *next += 1;
        while RUNS && *next != self.end {
            // SAFETY: the next member remains in the same retained header.
            let (head, finish) = unsafe { self.span(*next) };
            if head != end {
                break;
            }
            end = finish;
            *next += 1;
        }
        Some(unsafe { self.bytes(start, end) })
    }

    pub(in crate::buffer::segments) fn iter<const RUNS: bool>(&self) -> Iter<'_, 'd, RUNS> {
        Iter {
            source: self,
            next: self.first,
        }
    }

    /// # Safety
    /// `index` is the saved position in this exact retained clipped range sequence.
    pub(in crate::buffer::segments) unsafe fn iter_from<const RUNS: bool>(
        &self,
        index: u32,
    ) -> Iter<'_, 'd, RUNS> {
        Iter {
            source: self,
            next: index,
        }
    }

    pub(in crate::buffer::segments) fn contiguous(&self) -> Option<&[u8]> {
        let bytes = self.iter::<true>().next()?;
        (bytes.len() == self.len.get()).then_some(bytes)
    }

    /// # Safety
    /// index and these nonempty clipped bytes belong to this unchanged owner.
    pub(in crate::buffer::segments) unsafe fn try_project(
        &self,
        index: u32,
        bytes: ops::Range<usize>,
    ) -> Result<Self, rc::Error> {
        Ok(Self {
            owner: self.owner.try_clone()?,
            first: index,
            end: index + 1,
            start: bytes.start as u32,
            finish: bytes.end as u32,
            len: unsafe { NonZero::new_unchecked(bytes.end - bytes.start) },
        })
    }

    pub(in crate::buffer::segments) fn pop_front(&mut self) -> ControlFlow<()> {
        let next = self.first + 1;
        if next == self.end {
            return ControlFlow::Break(());
        }
        // SAFETY: both ranges belong to this unchanged retained owner.
        let (start, end) = unsafe { self.span(self.first) };
        let head = unsafe { self.span(next) }.0;
        self.len = unsafe { NonZero::new_unchecked(self.len.get() - (end - start) as usize) };
        self.first = next;
        self.start = head;
        ControlFlow::Continue(())
    }
}

#[derive(Clone)]
pub struct Iter<'a, 'd, const RUNS: bool = false> {
    source: &'a Owned<'d>,
    next: u32,
}

impl<const RUNS: bool> Iter<'_, '_, RUNS> {
    pub(in crate::buffer::segments) const fn position(&self) -> u32 {
        self.next
    }
}

impl<'a, const RUNS: bool> Iterator for Iter<'a, '_, RUNS> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        // SAFETY: this iterator retains the same owner and its admitted next index.
        unsafe { self.source.next::<RUNS>(&mut self.next) }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = (self.source.end - self.next) as usize;
        if RUNS && len != 0 {
            (1, Some(len))
        } else {
            (len, Some(len))
        }
    }
}

impl ExactSizeIterator for Iter<'_, '_, false> {}
impl<const RUNS: bool> iter::FusedIterator for Iter<'_, '_, RUNS> {}

impl<'d> Header<'d> {
    pub(in crate::buffer) fn allocate(
        count: NonZero<u32>,
    ) -> Result<tail::raw::Uninit<Header<'d>, (u32, u32)>, alloc::Error> {
        Ok(tail::Plan::<Header<'d>, (u32, u32)>::try_new(count.get() as usize)?.try_allocate()?)
    }
}

impl<'d> Owned<'d> {
    /// # Safety
    /// The block, range count, sum, and source origin were admitted together.
    pub(in crate::buffer) unsafe fn initialize<N: buffer::raw::Length>(
        block: tail::raw::Uninit<Header<'d>, (u32, u32)>,
        source: storage::Shared<resident::State<'d>>,
        ranges: &[(N, N)],
        count: NonZero<u32>,
        len: usize,
    ) -> Owned<'d> {
        // SAFETY: the admitted count is nonzero and exactly matches this range slice.
        let start = unsafe { (*ranges.as_ptr()).0 }.into_usize() as u32;
        let finish =
            unsafe { (*ranges.as_ptr().add(count.get() as usize - 1)).1 }.into_usize() as u32;
        let mut block = block.init(Header {
            count: mem::raw::Count::one(),
            source,
        });
        for (slot, &(first, last)) in block.as_mut_slice().iter_mut().zip(ranges) {
            slot.write((first.into_usize() as u32, last.into_usize() as u32));
        }
        // SAFETY: the admitted slice initialized every slot of this exact block.
        let mut block = unsafe { block.assume_init() };
        let pointer = ptr::NonNull::from(block.header_mut());
        forget(block);
        Owned {
            // SAFETY: the initialized header has exactly one edge, transferred here.
            owner: unsafe { mem::raw::Owner::from_raw(pointer) },
            first: 0,
            end: count.get(),
            start,
            finish,
            len: unsafe { NonZero::new_unchecked(len) },
        }
    }
}