o3 0.61.0

shared-nothing primitives
Documentation
use std::{borrow::BorrowMut, marker, mem::MaybeUninit, num::NonZero, ptr, slice};

use crate::buffer::{self, raw::Length, storage, write, write::consume};

/// A checked writer exposing only its initialized prefix.
pub struct Slice<'a, L = usize, N = usize, const HEAD: usize = 0, O = ()> {
    base: ptr::NonNull<u8>,
    len: L,
    capacity: usize,
    owner: O,
    borrow: marker::PhantomData<(&'a mut [MaybeUninit<u8>], N)>,
}

impl<'a> Slice<'a> {
    pub fn new(out: &'a mut [u8]) -> Self {
        let capacity = out.len();
        Self::from_parts(ptr::NonNull::from(out).cast(), 0, capacity)
    }

    pub fn uninit(out: &'a mut [MaybeUninit<u8>]) -> Self {
        let capacity = out.len();
        Self::from_parts(ptr::NonNull::from(out).cast(), 0, capacity)
    }

    /// Retains a fixed header before this admitted unpublished payload.
    pub fn try_prefix<const HEAD: usize>(
        self,
        body: u32,
    ) -> Result<Slice<'a, usize, usize, HEAD>, consume::Error> {
        const { assert!(HEAD != 0 && HEAD <= u32::MAX as usize) };
        let required = (body as usize).saturating_add(HEAD);
        consume::Error::check(required, self.remaining())?;
        // SAFETY: the admitted suffix contains this header and its complete payload.
        let base = unsafe { self.base.add(self.len + HEAD) };
        Ok(Slice::from_parts(base, 0, body as usize))
    }
}

impl<'a, N: Length> Slice<'a, &'a mut N, N> {
    /// # Safety
    /// `len <= out.len() <= N::MAX`; the first `len` bytes are initialized.
    pub unsafe fn from_raw_parts(out: &'a mut [MaybeUninit<u8>], len: &'a mut N) -> Self {
        let capacity = out.len();
        Self::from_parts(ptr::NonNull::from(out).cast(), len, capacity)
    }
}

impl<'a, L, N, const HEAD: usize> Slice<'a, L, N, HEAD> {
    fn from_parts(base: ptr::NonNull<u8>, len: L, capacity: usize) -> Self {
        Self {
            base,
            len,
            capacity,
            owner: (),
            borrow: marker::PhantomData,
        }
    }
}

impl<L: BorrowMut<N>, N: Length, const HEAD: usize, O> Slice<'_, L, N, HEAD, O> {
    pub fn body(&mut self) -> Slice<'_, &mut N, N> {
        const { assert!(HEAD != 0) };
        Slice::from_parts(self.base, self.len.borrow_mut(), self.capacity)
    }

    fn prepend_bytes(&mut self, header: &[u8; HEAD]) -> usize {
        const { assert!(HEAD != 0) };
        let body = N::into_usize(*self.len.borrow());
        // SAFETY: only prefix issuers expose this terminal; the unchanged header
        // precedes the initialized payload in the same exclusive range.
        unsafe {
            self.base
                .as_ptr()
                .sub(HEAD)
                .copy_from_nonoverlapping(header.as_ptr(), HEAD);
        }
        HEAD + body
    }
}

impl<'a, const HEAD: usize> Slice<'a, usize, usize, HEAD> {
    pub fn prepend(mut self, header: [u8; HEAD]) -> storage::NonEmpty<&'a [u8]> {
        let written = self.prepend_bytes(&header);
        // SAFETY: this terminal initialized the nonempty header and the exact
        // payload; the original exclusive loan retains this complete range.
        let bytes = unsafe { slice::from_raw_parts(self.base.as_ptr().sub(HEAD), written) };
        unsafe { storage::NonEmpty::assume(bytes) }
    }
}

impl<const HEAD: usize> Slice<'static, u32, u32, HEAD, storage::Owned> {
    pub fn try_with(body: u32) -> Result<Self, storage::AllocError> {
        const { assert!(HEAD != 0 && HEAD <= u32::MAX as usize) };
        consume::Error::check(body as usize, u32::MAX as usize - HEAD).map_err(|error| {
            let (required, _) = error.into_parts();
            storage::AllocError::Capacity(consume::Error::new(
                required.saturating_add(HEAD),
                u32::MAX as usize,
            ))
        })?;
        // SAFETY: the fixed positive header and admitted payload fit u32.
        let capacity = unsafe { NonZero::new_unchecked(body + HEAD as u32) };
        let mut owner = storage::Owned::try_with_nonzero(capacity)?;
        // SAFETY: this fresh heap retains the complete header and payload.
        let base = unsafe { ptr::NonNull::new_unchecked(owner.as_mut_ptr().add(HEAD)) };
        Ok(Self {
            base,
            len: 0,
            capacity: body as usize,
            owner,
            borrow: marker::PhantomData,
        })
    }

    pub fn prepend(mut self, header: [u8; HEAD]) -> storage::NonEmpty<storage::Owned> {
        let written = self.prepend_bytes(&header);
        // SAFETY: the header and this owner's payload now form one initialized
        // nonempty prefix within the originally admitted heap.
        unsafe {
            self.owner.set_len(written);
            storage::NonEmpty::assume(self.owner)
        }
    }
}

impl<'a, L: BorrowMut<N>, N: Length> Slice<'a, L, N> {
    pub fn len(&self) -> usize {
        N::into_usize(*self.len.borrow())
    }

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

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

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

    pub fn try_limit(
        mut self,
        required: usize,
        reserved_tail: usize,
    ) -> Result<Self, consume::Error> {
        let used = self.len();
        let room = (self.capacity - used).saturating_sub(reserved_tail);
        consume::Error::check(required, room)?;
        self.capacity = used + required;
        Ok(self)
    }

    /// # Safety
    /// The last `width` bytes are initialized and `len` fits the unchanged suffix.
    pub unsafe fn repeat(&mut self, width: std::num::NonZero<usize>, len: usize) {
        let old = self.len();
        let start = old - width.get();
        let end = old + len;
        let mut written = old;
        while written < end {
            let copied = (written - start).min(end - written);
            // SAFETY: the initialized source and its unwritten suffix are disjoint;
            // both remain inside this writer's admitted exclusive range.
            unsafe {
                ptr::copy_nonoverlapping(
                    self.base.as_ptr().add(start),
                    self.base.as_ptr().add(written),
                    copied,
                );
            }
            written += copied;
        }
        *self.len.borrow_mut() = N::from_usize(end);
    }

    /// # Safety
    /// Advance the count only over initialized bytes within the returned suffix.
    pub unsafe fn spare_parts(&mut self) -> (&mut N, &mut [MaybeUninit<u8>]) {
        let len = self.len.borrow_mut();
        let initialized = N::into_usize(*len);
        // SAFETY: this writer retains its entire exclusive range and its disjoint count.
        let out = unsafe {
            slice::from_raw_parts_mut(
                self.base.as_ptr().add(initialized).cast(),
                self.capacity - initialized,
            )
        };
        (len, out)
    }

    /// Lends this writer's actual progress without lending its identity.
    pub fn reborrow(&mut self) -> Slice<'_, &mut N, N> {
        Slice::from_parts(self.base, self.len.borrow_mut(), self.capacity)
    }

    pub fn stage(&mut self) -> Stage<'_, 'a, L, N> {
        Stage {
            parent: self,
            len: 0,
        }
    }

    /// Returns exactly the written prefix under the original exclusive borrow.
    pub fn into_mut(self) -> &'a mut [u8] {
        // SAFETY: only successful writes extend this exact initialized prefix;
        // a lent count retains its parent's exclusive borrow for the returned slice.
        unsafe { buffer::raw::range_mut(self.base.as_ptr(), 0, self.finish()) }
    }

    /// Succeeds only after the complete original output slice was written.
    pub fn try_complete(self) -> Result<(), consume::Error> {
        consume::Error::check(self.capacity, self.len())
    }

    /// Stages adjacent head and body regions without advancing this writer.
    pub fn try_split(
        &mut self,
        head: usize,
        body: usize,
    ) -> Result<Split<'_, 'a, L, N>, consume::Error> {
        let room = self.remaining();
        consume::Error::check(head, room)?;
        consume::Error::check(body, room - head)?;
        Ok(Split {
            parent: self,
            head,
            capacity: head + body,
            head_len: 0,
            body_len: 0,
        })
    }
}

impl<L: BorrowMut<N>, N: Length> AsRef<[u8]> for Slice<'_, L, N> {
    fn as_ref(&self) -> &[u8] {
        // SAFETY: the original exclusive loan retains this initialized prefix.
        unsafe { buffer::raw::range(self.base.as_ptr(), 0, self.len()) }
    }
}

impl<L: BorrowMut<N>, N: Length> write::Sink for Slice<'_, L, N> {
    type Error = consume::Error;

    fn write_slices<const S: usize>(&mut self, slices: [&[u8]; S]) -> Result<(), Self::Error> {
        // SAFETY: checked append initializes the suffix before advancing its count.
        write::try_append(unsafe { self.spare_parts() }, slices)
    }
}

impl<L: BorrowMut<N>, N: Length> write::Init for Slice<'_, L, N> {
    #[inline(always)]
    fn try_init<I: buffer::raw::Initializer>(&mut self, source: I) -> Result<(), consume::Error> {
        // SAFETY: checked initialization completes before advancing the count.
        write::try_initialize(unsafe { self.spare_parts() }, source)
    }
}

/// An unpublished suffix retained by its original writer.
pub struct Stage<'writer, 'target, L = usize, N = usize> {
    parent: &'writer mut Slice<'target, L, N>,
    len: usize,
}

impl<L: BorrowMut<N>, N: Length> Stage<'_, '_, L, N> {
    pub fn body(&mut self) -> Slice<'_, &mut usize> {
        // SAFETY: the exclusive parent loan retains its unchanged suffix.
        let base = unsafe { self.parent.base.add(self.parent.len()) };
        Slice::from_parts(base, &mut self.len, self.parent.remaining())
    }

    pub fn commit(self) {
        let len = self.parent.len.borrow_mut();
        *len = N::from_usize(N::into_usize(*len) + self.len);
    }
}

/// Unpublished adjacent regions retained by one parent writer.
pub struct Split<'writer, 'target, L = usize, N = usize> {
    parent: &'writer mut Slice<'target, L, N>,
    head: usize,
    capacity: usize,
    head_len: usize,
    body_len: usize,
}

impl<L: BorrowMut<N>, N: Length> Split<'_, '_, L, N> {
    pub fn head(&mut self) -> Slice<'_, &mut usize> {
        // SAFETY: admission retained this parent's entire unpublished suffix.
        let base = unsafe { self.parent.base.add(self.parent.len()) };
        Slice::from_parts(base, &mut self.head_len, self.head)
    }

    pub fn body(&mut self) -> Slice<'_, &mut usize> {
        // SAFETY: the admitted head separates this body's exact disjoint region.
        let base = unsafe { self.parent.base.add(self.parent.len() + self.head) };
        Slice::from_parts(base, &mut self.body_len, self.capacity - self.head)
    }

    /// Publishes the contiguous prefix only after the entire head is initialized.
    pub fn try_commit(self) -> Result<(), consume::Error> {
        consume::Error::check(self.head, self.head_len)?;
        let len = self.parent.len.borrow_mut();
        *len = N::from_usize(N::into_usize(*len) + self.head + self.body_len);
        Ok(())
    }
}

const _: () = {
    assert!(size_of::<Slice<'static>>() == 3 * size_of::<usize>());
    assert!(size_of::<Option<Slice<'static>>>() == size_of::<Slice<'static>>());
    assert!(size_of::<Slice<'static, &'static mut usize>>() == 3 * size_of::<usize>());
    assert!(size_of::<Stage<'static, 'static>>() == 2 * size_of::<usize>());
    assert!(size_of::<Split<'static, 'static>>() == 5 * size_of::<usize>());
};