o3 0.62.0

shared-nothing primitives
Documentation
use std::{marker, mem, num, slice};

use crate::{
    alloc::{self, array},
    base::marker::ThreadBound,
    buffer::{
        self,
        bytes::window::reserve::{Append, Plan},
    },
    depot::queue::ring,
};

/// An owned ring whose open state always retains its terminal reservation.
pub struct Ring<const N: usize> {
    pub(super) buf: array::raw::Block<mem::MaybeUninit<u8>, num::NonZero<usize>>,
    thread: marker::PhantomData<ThreadBound>,
    state: ring::raw::State<usize>,
    pub(super) closed: bool,
}

impl<const N: usize> Ring<N> {
    pub fn try_new(plan: Plan<N>) -> Result<Self, alloc::Exhausted> {
        Ok(Self {
            buf: plan.capacity.try_allocate(())?,
            thread: marker::PhantomData,
            state: ring::raw::State::EMPTY,
            closed: false,
        })
    }

    pub fn capacity(&self) -> usize {
        self.buf.len() - N
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn len(&self) -> usize {
        self.state.len()
    }

    pub fn as_slices(&self) -> (&[u8], &[u8]) {
        self.prefix(self.state.len())
    }

    /// # Safety
    /// The sources together fit in the vacant bytes, excluding the open ring's
    /// `N` terminal bytes. They are disjoint from both destination spans across wrap.
    pub unsafe fn extend<const S: usize>(&mut self, slices: [&[u8]; S]) {
        Append { ring: self, slices }.commit();
    }

    pub(super) fn prefix(&self, len: usize) -> (&[u8], &[u8]) {
        let (start, [front, back]) = ring::raw::runs(self.state.head(), self.buf.len(), len);
        let pointer = self.buf.as_ptr().cast::<u8>();
        // SAFETY: the ring exposes exactly its initialized front and back ranges
        // of this unchanged block allocation.
        unsafe {
            (
                buffer::raw::range(pointer, start, front),
                buffer::raw::range(pointer, 0, back),
            )
        }
    }

    /// Appends one admitted source at the logical tail.
    ///
    /// Admission proves that the source fits; this owner updates its tail and length.
    pub(super) fn append(&mut self, src: &[u8]) {
        use buffer::raw::Transfer as _;

        let mut next = self.state;
        // SAFETY: Append or the retained terminal reservation admitted this
        // complete source against the unchanged nonzero allocation capacity.
        let (start, [front, back]) = unsafe { next.extend(self.buf.len(), src.len()) };
        let (head, tail) = src.split_at(front);
        let pointer = self.buf.as_mut_ptr().cast::<u8>();
        // SAFETY: admission retains disjoint sources and enough vacant storage
        // for both slices in this unchanged block.
        unsafe { head.copy_to(pointer.add(start)) };
        if back != 0 {
            // SAFETY: the same admission leaves this disjoint back range vacant.
            unsafe { tail.copy_to(pointer) };
        }
        self.state = next;
    }

    pub(super) fn consume(&mut self, len: usize) {
        // SAFETY: Prefix retains an admitted prefix of this exact owner.
        unsafe { self.state.consume(self.buf.len(), len) };
    }

    /// Borrows the contiguous vacant suffix available to an ordinary write.
    pub fn tail(&mut self, room: usize) -> &mut [mem::MaybeUninit<u8>] {
        let capacity = self.buf.len();
        let used = self.len();
        let free = capacity - used - if self.closed { 0 } else { N };
        let start = self.state.position(capacity, used);
        let len = room.min(free).min(capacity - start);
        // SAFETY: the suffix ends before occupied bytes, wrap, or terminal reserve.
        unsafe { slice::from_raw_parts_mut(self.buf.as_mut_ptr().add(start), len) }
    }

    /// # Safety
    /// `len` bytes were initialized at the start of `tail` on this same ring.
    /// Its output and reservations have not changed since that borrow ended.
    pub unsafe fn publish(&mut self, len: usize) {
        // SAFETY: the caller owns the exact initialized and previously admitted suffix.
        unsafe { self.state.extend(self.buf.len(), len) };
    }

    /// Publishes the reserved terminal bytes once, without capacity validation.
    pub fn finish(&mut self, source: &[u8; N]) {
        if !self.closed {
            self.append(source);
            self.closed = true;
        }
    }
}

const _: () = {
    assert!(size_of::<Ring<17>>() == 5 * size_of::<usize>());
    assert!(size_of::<Option<Ring<17>>>() == size_of::<Ring<17>>());
};