o3 0.60.0

shared-nothing primitives
Documentation
use std::{num::NonZero, ptr};

use super::{State, try_copy};
use crate::{
    buffer::{self, resident, storage, write::{Sink as _, consume}},
    mem::rc,
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CopyError {
    Partition { offset: usize, requested: usize, capacity: usize },
    Retain(rc::Error),
}

pub struct Copies {
    pub(in crate::buffer) state: Option<State<(), { u32::MAX as usize }>>,
    total: u32,
    pub(in crate::buffer) remaining: u32,
}

impl Copies {
    pub fn try_new(bytes: usize) -> Result<Self, storage::AllocError> {
        let state = match NonZero::new(bytes) {
            None => None,
            Some(capacity) => Some(try_copy(&[], capacity)?),
        };
        Ok(Self { state, total: bytes as u32, remaining: bytes as u32 })
    }

    pub fn try_retain(&mut self, owner: resident::Shared<'_>) -> Result<storage::Shared, CopyError> {
        match owner.try_detach() {
            Ok(owner) => Ok(owner),
            Err(owner) => self.copy(owner.as_slice()),
        }
    }

    pub(in crate::buffer) fn try_retain_nonempty(&mut self, owner: storage::NonEmpty<resident::Shared<'_>>) -> Result<storage::NonEmpty<storage::Shared>, CopyError> {
        match owner.try_detach() {
            Ok(owner) => Ok(owner),
            Err(owner) => {
                let copied = self.copy(owner.as_ref())?;
                // SAFETY: copy returns exactly this original nonempty extent, never an accumulated prefix.
                Ok(unsafe { storage::NonEmpty::assume(copied) })
            }
        }
    }

    fn copy(&mut self, bytes: &[u8]) -> Result<storage::Shared, CopyError> {
        if bytes.is_empty() { return Ok(storage::Shared::new()); }
        let place = ptr::addr_of_mut!(self.state);
        let Some(state) = &mut self.state else {
            return Err(CopyError::Partition {
                offset: (self.total - self.remaining) as usize,
                requested: bytes.len(),
                capacity: self.total as usize,
            });
        };
        let start = state.len();
        let mut spare = state.spare();
        let result = spare.write_slice(bytes);
        spare.commit();
        if let Err(cause) = result { return Err(self.partition(cause)); }
        // SAFETY: this same matched state just initialized precisely start..head.
        unsafe { Self::finish(place, state, &mut self.remaining, start) }
    }

    pub(in crate::buffer) fn partition(&self, cause: consume::Error) -> CopyError {
        let (need, _) = cause.into_parts();
        CopyError::Partition {
            offset: (self.total - self.remaining) as usize,
            requested: need.get(),
            capacity: self.total as usize,
        }
    }

    /// # Safety
    /// `state` is the Some field of `place`; start..head was just initialized in its admitted suffix.
    pub(in crate::buffer) unsafe fn finish(
        place: *mut Option<State<(), { u32::MAX as usize }>>,
        state: &mut State<(), { u32::MAX as usize }>,
        remaining: &mut u32,
        start: u32,
    ) -> Result<storage::Shared, CopyError> {
        use buffer::raw::Retain as _;

        let len = state.len() - start;
        let owner = if len == *remaining {
            // SAFETY: the actual Some state is consumed once and its place is cleared before returning.
            let state = unsafe { ptr::read(state) };
            unsafe { ptr::write(place, None) };
            unsafe { state.buf.into_range(start, len) }
        } else {
            let owner = state.buf.try_retain().map_err(CopyError::Retain)?;
            // SAFETY: this retained edge names only the exact newly initialized range.
            unsafe { owner.into_range(start, len) }
        };
        // Successful copies never exceed the original capacity; failed publications only consume space.
        *remaining -= len;
        Ok(storage::Shared::from(owner))
    }
}

const _: () = assert!(size_of::<Copies>() == 3 * size_of::<usize>());