o3 0.62.0

shared-nothing primitives
Documentation
use crate::buffer::{
    self,
    bytes::bounded,
    write,
    write::{consume, spans},
};
use std::{mem, ptr};

/// Exclusive staged writer over one owner's uninitialized suffix.
#[must_use = "call commit to publish initialized bytes"]
#[repr(C)]
pub struct Spare<'a, const N: usize = 0, T = u32> {
    pub(in crate::buffer) pointer: ptr::NonNull<mem::MaybeUninit<u8>>,
    pub(in crate::buffer) target: &'a mut T,
    pub(in crate::buffer) capacity: u32,
    pub(in crate::buffer) len: u32,
}

impl<'a> Spare<'a> {
    /// # Safety
    /// `spare` is this live owner's exclusive unpublished suffix for `'a`;
    /// `target` counts its initialized prefix and their total length fits `u32`.
    pub unsafe fn from_parts(spare: &'a mut [mem::MaybeUninit<u8>], target: &'a mut u32) -> Self {
        Self {
            capacity: spare.len() as u32,
            pointer: ptr::NonNull::from(spare).cast(),
            target,
            len: 0,
        }
    }

    /// Publishes the largest fitting prefix and leaves the original source's tail.
    pub fn drain(mut self, source: &mut &[u8]) {
        let tail = copy_prefix(buffer::raw::Exclusive::spare_parts(&mut self), source);
        write::Commit::commit(self);
        *source = tail;
    }

    /// Publishes only when the entire original suffix has been initialized.
    pub fn try_complete(self) -> Result<(), spans::Gap> {
        spans::Gap::check(self.capacity, self.len)?;
        write::Commit::commit(self);
        Ok(())
    }
}

impl<'a> Spare<'a, 0, bounded::Value<Vec<u8>>> {
    /// # Safety
    /// `capacity` fits the original spare and prefix plus capacity fits bounded::MAX.
    pub unsafe fn from_vec(target: &'a mut bounded::Value<Vec<u8>>, capacity: u32) -> Self {
        Self {
            pointer: ptr::NonNull::from(target.0.spare_capacity_mut()).cast(),
            target,
            capacity,
            len: 0,
        }
    }
}

impl<'a, T> Spare<'a, 0, T> {
    pub fn try_tail<const N: usize>(self, minimum: usize) -> Result<Spare<'a, N, T>, Self> {
        let room = (self.capacity - self.len) as usize;
        if N > room || minimum > room - N {
            return Err(self);
        }
        Ok(Spare {
            pointer: self.pointer,
            target: self.target,
            capacity: self.capacity - N as u32,
            len: self.len,
        })
    }
}

impl<'a, const N: usize, T> Spare<'a, N, T> {
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

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

    pub fn remaining(&self) -> usize {
        buffer::raw::Exclusive::remaining(self)
    }

    /// # Safety
    /// Advance the count only over initialized bytes within the returned suffix.
    pub unsafe fn spare_parts(&mut self) -> (&mut u32, &mut [mem::MaybeUninit<u8>]) {
        buffer::raw::Exclusive::spare_parts(self)
    }

    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        buffer::raw::Exclusive::as_mut_slice(self)
    }

    pub fn fill(&mut self, byte: u8) {
        buffer::raw::Exclusive::fill(self, byte)
    }

    /// Appends the largest source prefix that fits and returns its length.
    pub fn write(&mut self, src: &[u8]) -> usize {
        src.len() - copy_prefix(buffer::raw::Exclusive::spare_parts(self), src).len()
    }

    /// Appends the complete write only if it fits the remaining range and `room`.
    pub fn try_write<const M: usize>(
        &mut self,
        slices: [&[u8]; M],
        room: usize,
    ) -> Result<(), consume::Error> {
        let (len, out) = buffer::raw::Exclusive::spare_parts(self);
        let limit = room.min(out.len());
        // SAFETY: narrowing the original suffix preserves its count and length bound.
        unsafe { write::raw::try_append((len, &mut out[..limit]), slices) }
    }

    pub fn tail(self, bytes: &[u8; N]) -> Spare<'a, 0, T> {
        // SAFETY: admission retained N exclusive bytes beyond this prefix capacity.
        unsafe {
            self.pointer
                .as_ptr()
                .add(self.len as usize)
                .cast::<u8>()
                .copy_from_nonoverlapping(bytes.as_ptr(), N);
        }
        Spare {
            pointer: self.pointer,
            target: self.target,
            capacity: self.capacity + N as u32,
            len: self.len + N as u32,
        }
    }
}

impl<const N: usize, T> AsRef<[u8]> for Spare<'_, N, T> {
    fn as_ref(&self) -> &[u8] {
        buffer::raw::Prefix::as_slice(self)
    }
}

// SAFETY: Spare retains the disjoint staged word and its unpublished allocation.
unsafe impl<const N: usize, T> write::raw::Writer for Spare<'_, N, T> {
    type Len = u32;

    fn parts(&mut self) -> (&mut u32, &mut [mem::MaybeUninit<u8>]) {
        buffer::raw::Exclusive::spare_parts(self)
    }
}

const _: () = assert!(size_of::<Spare<'static>>() == size_of::<usize>() * 3);
const _: () = assert!(size_of::<Option<Spare<'static>>>() == size_of::<Spare<'static>>());
const _: () = assert!(size_of::<Spare<'static, 16>>() == size_of::<Spare<'static>>());

// SAFETY: Spare retains its original suffix and counts only initialized bytes.
unsafe impl<const N: usize, T> buffer::raw::Prefix for Spare<'_, N, T> {
    fn prefix(&self) -> (*mut mem::MaybeUninit<u8>, u32) {
        (self.pointer.as_ptr(), self.len)
    }
}

// SAFETY: the staged length word is disjoint from the exclusive suffix;
// the original owner's length remains a separate publication target.
unsafe impl<const N: usize, T> buffer::raw::Exclusive for Spare<'_, N, T> {
    fn as_mut_ptr(&mut self) -> *mut mem::MaybeUninit<u8> {
        self.pointer.as_ptr()
    }

    fn len_mut(&mut self) -> &mut u32 {
        &mut self.len
    }

    fn capacity(&self) -> u32 {
        self.capacity
    }
}

fn copy_prefix<'s, L: buffer::raw::Length>(
    (len, out): (&mut L, &mut [mem::MaybeUninit<u8>]),
    src: &'s [u8],
) -> &'s [u8] {
    let copied = out.len().min(src.len());
    let (prefix, tail) = src.split_at(copied);
    out[..copied].write_copy_of_slice(prefix);
    *len = L::from_usize(len.into_usize() + copied);
    tail
}