o3 0.62.0

shared-nothing primitives
Documentation
use std::num;

use storage::alloc;

use crate::{
    buffer,
    buffer::{
        bytes::window,
        storage,
        write::{self, consume, consume::Consume},
    },
    mem::rc,
};

/// Growable byte accumulator bounded by `MAX_CAPACITY`.
#[derive(Default)]
pub struct Snapshot<const MAX_CAPACITY: usize> {
    pub(super) state: Option<window::State<(), MAX_CAPACITY>>,
    pub(super) tail: u32,
}

impl<const MAX_CAPACITY: usize> Snapshot<MAX_CAPACITY> {
    /// Creates an empty accumulator without allocating.
    pub const fn new() -> Self {
        Self {
            state: None,
            tail: 0,
        }
    }

    pub fn try_with(capacity: num::NonZero<usize>) -> Result<Self, storage::AllocError> {
        Self::try_copy(&[], capacity)
    }

    /// Copies the input into one allocation, growing from the initial capacity as needed.
    pub fn try_copy(
        src: &[u8],
        capacity: num::NonZero<usize>,
    ) -> Result<Self, storage::AllocError> {
        let initial = window::Capacity::try_new(capacity).map_err(storage::AllocError::Capacity)?;
        let need = if src.len() > initial.get() as usize {
            let capacity = num::NonZero::<usize>::MIN.saturating_add(src.len() - 1);
            window::Capacity::try_new(capacity).map_err(storage::AllocError::Capacity)?
        } else {
            initial
        };
        let state =
            window::State::try_allocate((), initial.grow(need), need, src, src.len() as u32)
                .map_err(alloc::Error::into_alloc)
                .map_err(storage::AllocError::Exhausted)?;
        Ok(Self {
            state: Some(state),
            tail: 0,
        })
    }

    /// Borrows the physical unpublished suffix without allocating or reclaiming bytes.
    pub fn spare(&mut self) -> write::raw::Spare<'_> {
        let Some(state) = &mut self.state else {
            // SAFETY: an absent allocation has no initialized or writable bytes.
            return unsafe { write::raw::Spare::from_parts(&mut [], &mut self.tail) };
        };
        state.spare()
    }

    /// Transfers the visible suffix without retaining another reference.
    pub fn into_shared(self) -> Option<storage::Shared> {
        if self.is_empty() {
            return None;
        }
        Some(self.freeze())
    }

    /// Transfers the initialized suffix, retaining its allocation even when empty.
    pub fn freeze(self) -> storage::Shared {
        let Some(state) = self.state else {
            return storage::Shared::new();
        };
        let len = state.head - self.tail;
        // SAFETY: Snapshot transfers its exact initialized suffix and owning edge;
        // a zero-length suffix at the initialized end is a valid owned extent.
        storage::Shared::from(unsafe { buffer::raw::Header::into_range(state.buf, self.tail, len) })
    }

    pub fn try_snapshot(&self) -> Result<Option<storage::Shared>, rc::Error> {
        use buffer::raw::Retain as _;

        let Some(state) = &self.state else {
            return Ok(None);
        };
        if state.head == self.tail {
            return Ok(None);
        }
        let len = state.head - self.tail;
        // SAFETY: Snapshot keeps this exact initialized suffix within its allocation.
        Ok(Some(storage::Shared::from(unsafe {
            buffer::raw::Header::into_range(state.buf.try_retain()?, self.tail, len)
        })))
    }

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

    /// Consumes the visible bytes while retaining any acquired allocation.
    pub fn clear(&mut self) {
        if let Some(state) = &self.state {
            self.tail = state.head;
        }
    }

    /// Mutably borrows the visible suffix, copying only when another owner shares it.
    pub fn try_as_mut(&mut self) -> Result<&mut [u8], storage::AllocError> {
        let Some(state) = &mut self.state else {
            return Ok(&mut []);
        };
        state.try_as_mut(&mut self.tail)
    }
}

impl<const MAX_CAPACITY: usize> Consume for Snapshot<MAX_CAPACITY> {
    fn remaining(&self) -> usize {
        self.state
            .as_ref()
            .map_or(0, |state| (state.head - self.tail) as usize)
    }

    fn try_consume(&mut self, amount: usize) -> Result<(), consume::Error> {
        consume::Error::check(amount, self.remaining())?;
        self.tail += amount as u32;
        Ok(())
    }

    fn consume_max(&mut self, max: usize) -> usize {
        let amount = max.min(self.remaining());
        self.tail += amount as u32;
        amount
    }
}

impl<const MAX_CAPACITY: usize> AsRef<[u8]> for Snapshot<MAX_CAPACITY> {
    fn as_ref(&self) -> &[u8] {
        self.state.as_ref().map_or(&[], |state| {
            // SAFETY: construction, checked consumption, and publication keep tail
            // within head; edits preserve this same initialized suffix.
            unsafe { state.as_slice().get_unchecked(self.tail as usize..) }
        })
    }
}

impl<const MAX_CAPACITY: usize> buffer::Residency for Snapshot<MAX_CAPACITY> {
    fn resident(&self) -> usize {
        self.state
            .as_ref()
            .map_or(0, |state| state.capacity().get() as usize)
    }
}

impl<const MAX_CAPACITY: usize> buffer::View<'_, Snapshot<MAX_CAPACITY>> {
    /// Retains this selected range without copying or rechecking its bounds.
    pub fn try_retain(self) -> Result<storage::Shared, rc::Error> {
        use buffer::raw::Retain as _;

        match &self.source.state {
            Some(state) if !self.is_empty() => {
                let owner = state.buf.try_retain()?;
                // SAFETY: this view borrows the original Snapshot and its exact
                // initialized selection; the retained edge keeps that backing live.
                Ok(storage::Shared::from(unsafe {
                    storage::raw::Extent::from_bytes(self.as_slice()).bind(owner)
                }))
            }
            _ => Ok(storage::Shared::new()),
        }
    }
}

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

// SAFETY: Snapshot exposes its retained initialized suffix; appends and consumption
// require its exclusive borrow and cannot mutate bytes during a source loan.
unsafe impl<const MAX_CAPACITY: usize> buffer::raw::Source for Snapshot<MAX_CAPACITY> {}

impl<const MAX: usize> write::Sink for Snapshot<MAX> {
    type Error = storage::AllocError;

    fn write_slice(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
        if bytes.is_empty() {
            return Ok(());
        }
        if let Some(state) = &mut self.state
            && let Some(end) = state.append_end(bytes.len())
        {
            state.append_at(state.head, bytes, end);
            return Ok(());
        }
        let required = window::Capacity::try_append(self, bytes.len(), &[])
            .map_err(storage::AllocError::Capacity)?;
        self.try_store::<false, _>(bytes, required)
    }

    fn write_slices<const N: usize>(&mut self, slices: [&[u8]; N]) -> Result<(), Self::Error> {
        if let [bytes] = slices.as_slice() {
            return self.write_slice(bytes);
        }
        let required = window::Capacity::try_append(self, 0, &slices)
            .map_err(storage::AllocError::Capacity)?;
        self.try_store::<true, _>(&slices, required)
    }
}

impl<const MAX: usize> Snapshot<MAX> {
    fn try_store<const CHECK_SPARE: bool, I: buffer::raw::Transfer>(
        &mut self,
        src: I,
        required: Option<window::Capacity<MAX>>,
    ) -> Result<(), storage::AllocError> {
        let Some(required) = required else {
            return Ok(());
        };
        match &mut self.state {
            Some(state) => {
                if CHECK_SPARE && required.get() <= state.cap.get() - self.tail {
                    state.append_at(state.head, src, self.tail + required.get());
                    return Ok(());
                }
                state.try_full(&mut self.tail, src, required, state.cap.grow(required))
            }
            slot @ None => window::State::try_allocate((), required, required, src, required.get())
                .map(|state| *slot = Some(state)),
        }
        .map_err(alloc::Error::into_alloc)
        .map_err(storage::AllocError::Exhausted)
    }
}