o3 0.62.0

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

use storage::alloc;

use crate::{
    buffer::{
        self, bytes::window::Capacity, pool::owners, resident, resident::staging, storage, write,
    },
    mem::credit,
};

pub(in crate::buffer) struct State<P: buffer::raw::Policy, const MAX_CAPACITY: usize> {
    pub(in crate::buffer) buf: crate::mem::raw::Owner<buffer::raw::Header<P>>,
    pub(in crate::buffer::bytes::window) cap: Capacity<MAX_CAPACITY>,
    pub(in crate::buffer::bytes::window) head: u32,
}

impl<P: buffer::raw::Policy, const MAX_CAPACITY: usize> State<P, MAX_CAPACITY> {
    pub(in crate::buffer) fn seed(&self) -> P {
        self.buf.get().seed()
    }

    pub(in crate::buffer) fn len(&self) -> u32 {
        self.head
    }

    pub(in crate::buffer) fn capacity(&self) -> num::NonZero<u32> {
        self.cap.nonzero()
    }

    pub(in crate::buffer) fn as_slice(&self) -> &[u8] {
        buffer::raw::Prefix::as_slice(self)
    }

    pub(in crate::buffer) fn spare(&mut self) -> write::raw::Spare<'_> {
        let pointer = buffer::raw::Header::data(self.buf.as_ptr())
            .as_ptr()
            .cast::<mem::MaybeUninit<u8>>();
        let start = self.head as usize;
        let len = (self.cap.get() - self.head) as usize;
        // SAFETY: head excludes every published range and this loan owns the unpublished suffix.
        let spare = unsafe { slice::from_raw_parts_mut(pointer.add(start), len) };
        // SAFETY: the same allocation owns the suffix and its unchanged initialization word.
        unsafe { write::raw::Spare::from_parts(spare, &mut self.head) }
    }
}

#[derive(Clone, Copy)]
#[repr(C)]
struct Growth<const MAX: usize> {
    capacity: Capacity<MAX>,
    amount: num::NonZero<u32>,
}

impl<const MAX: usize> Growth<MAX> {
    fn new(current: Capacity<MAX>, target: Capacity<MAX>) -> Option<Self> {
        let amount = num::NonZero::new(target.get().saturating_sub(current.get()))?;
        Some(Self {
            capacity: target,
            amount,
        })
    }
}

const _: () = {
    assert!(size_of::<Growth<1>>() == size_of::<u64>());
    assert!(size_of::<Option<Growth<1>>>() == size_of::<Growth<1>>());
};

impl<P: buffer::raw::Policy, const MAX_CAPACITY: usize> State<P, MAX_CAPACITY> {
    pub(super) fn append_end(&self, added: usize) -> Option<u32> {
        if added <= (self.cap.get() - self.head) as usize {
            Some(self.head + added as u32)
        } else {
            None
        }
    }

    pub(super) fn append_at<I: buffer::raw::Transfer>(&mut self, start: u32, src: I, end: u32) {
        let target = buffer::raw::Header::data(self.buf.as_ptr()).as_ptr();
        // SAFETY: the owner admitted this disjoint source for the suffix at start.
        unsafe { src.copy_to(target.add(start as usize)) };
        self.head = end;
    }

    pub(super) fn try_full<I: buffer::raw::Transfer>(
        &mut self,
        tail: &mut u32,
        src: I,
        required: Capacity<MAX_CAPACITY>,
        ideal: Capacity<MAX_CAPACITY>,
    ) -> Result<(), alloc::Error<P::Failure>> {
        let Some(growth) = Growth::new(self.cap, required) else {
            if !crate::mem::raw::Edge::is_unique(self.buf.get()) {
                return self.fresh(tail, self.cap, required, src, required.get());
            }
            let start = *tail;
            let len = self.head - start;
            if start != 0 && len != 0 {
                let pointer = buffer::raw::Header::data(self.buf.as_ptr()).as_ptr();
                // SAFETY: this is the sole owner of the initialized suffix.
                unsafe { ptr::copy(pointer.add(start as usize), pointer, len as usize) };
            }
            self.append_at(len, src, required.get());
            *tail = 0;
            return Ok(());
        };
        let ideal = Growth::new(self.cap, ideal).unwrap_or(growth);
        self.try_grow(tail, ideal, growth, required.get(), src)
    }

    fn try_grow<I: buffer::raw::Transfer>(
        &mut self,
        tail: &mut u32,
        ideal: Growth<MAX_CAPACITY>,
        required: Growth<MAX_CAPACITY>,
        end: u32,
        src: I,
    ) -> Result<(), alloc::Error<P::Failure>> {
        let Some(heap) = buffer::raw::Heap::try_borrow(&mut self.buf) else {
            return self.fresh(tail, ideal.capacity, required.capacity, src, end);
        };
        let mut growth = if ideal.amount.get() as usize <= heap.seed().available() {
            ideal
        } else {
            required
        };
        loop {
            // SAFETY: both growth choices carry the exact delta for this exclusive
            // allocation and admit the initialized suffix followed by src.
            match unsafe {
                heap.try_grow(
                    growth.capacity.nonzero(),
                    growth.amount,
                    *tail..self.head,
                    &src,
                )
            } {
                Ok(()) => {
                    self.cap = growth.capacity;
                    self.head = end;
                    *tail = 0;
                    return Ok(());
                }
                Err(alloc::Error::Allocation(_)) if growth.capacity != required.capacity => {
                    growth = required
                }
                Err(error) => return Err(error),
            }
        }
    }

    fn fresh<I: buffer::raw::Transfer>(
        &mut self,
        tail: &mut u32,
        ideal: Capacity<MAX_CAPACITY>,
        required: Capacity<MAX_CAPACITY>,
        src: I,
        len: u32,
    ) -> Result<(), alloc::Error<P::Failure>> {
        // SAFETY: the owner's cursor lies within this unchanged initialized prefix.
        let first = unsafe { self.as_slice().get_unchecked(*tail as usize..) };
        *self = Self::try_allocate(self.seed(), ideal, required, (first, src), len)?;
        *tail = 0;
        Ok(())
    }
}

impl<const MAX: usize> State<(), MAX> {
    pub(in crate::buffer::bytes::window) fn try_as_mut<'a>(
        &'a mut self,
        tail: &'a mut u32,
    ) -> Result<&'a mut [u8], storage::AllocError> {
        let len = self.head - *tail;
        if len == 0 {
            return Ok(&mut []);
        }
        if !crate::mem::raw::Edge::is_unique(self.buf.get()) {
            self.fresh(tail, self.cap, self.cap, &[][..], len)
                .map_err(alloc::Error::into_alloc)
                .map_err(storage::AllocError::Exhausted)?;
        }
        // SAFETY: uniqueness admission or fresh replacement retains this exact
        // initialized suffix exclusively for the original mutable owner loan.
        Ok(unsafe {
            buffer::raw::range_mut(
                buffer::raw::Header::data(self.buf.as_ptr()).as_ptr(),
                *tail as usize,
                len as usize,
            )
        })
    }
}

impl<'d> State<resident::Budget<'d>, { u32::MAX as usize }> {
    /// Consumes strict growth bound to this unchanged exclusive state.
    pub(in crate::buffer) fn try_reserve(
        reserve: staging::Reserve<(&mut Self, &mut u32), ()>,
    ) -> Result<(), alloc::Error<credit::Error>> {
        let ((state, tail), target, ()) = reserve.into_parts();
        let growth = Growth {
            capacity: target.into(),
            // SAFETY: the sealed reserve retains strict growth for this unchanged state.
            amount: unsafe { crate::mem::raw::Counter::nonzero(target.get() - state.cap.get()) },
        };
        let len = state.head - *tail;
        state.try_grow(tail, growth, growth, len, &[][..])
    }

    pub(in crate::buffer) fn try_staged<I: buffer::raw::Transfer>(
        reserve: staging::Reserve<(&mut Self, &mut u32), owners::Measured<I>>,
    ) -> Result<(), alloc::Error<credit::Error>> {
        let ((state, tail), target, src) = reserve.into_parts();
        if let Some(end) = state.append_end(src.len()) {
            state.append_at(state.head, src.into_input(), end);
            return Ok(());
        }
        let required = num::NonZero::<u32>::MIN
            .saturating_add(((state.head - *tail) as usize + src.len() - 1) as u32);
        state.try_full(tail, src.into_input(), required.into(), target.into())
    }
}

impl<P: buffer::raw::Policy, const MAX_CAPACITY: usize> State<P, MAX_CAPACITY> {
    pub(super) fn try_allocate<I: buffer::raw::Transfer>(
        seed: P,
        ideal: Capacity<MAX_CAPACITY>,
        need: Capacity<MAX_CAPACITY>,
        sources: I,
        len: u32,
    ) -> Result<Self, alloc::Error<P::Failure>> {
        let target = if ideal.get() as usize <= P::available(seed) {
            ideal
        } else {
            need
        };
        let (mut heap, cap) = match buffer::raw::Heap::try_new(seed, target.nonzero()) {
            Ok(heap) => (heap, target),
            Err(alloc::Error::Allocation(crate::alloc::Exhausted)) if target != need => {
                (buffer::raw::Heap::try_new(seed, need.nonzero())?, need)
            }
            Err(error) => return Err(error),
        };
        // SAFETY: the admitted sources fit this fresh allocation, which remains
        // exclusively owned until the complete initialized prefix is published.
        unsafe { sources.copy_to(heap.as_mut_ptr().cast()) };
        Ok(Self {
            buf: heap.into_shared(),
            cap,
            head: len,
        })
    }
}
impl<'d> State<resident::Budget<'d>, { u32::MAX as usize }> {
    pub(in crate::buffer) fn from_staged<I: buffer::raw::Transfer>(
        reserve: staging::Reserve<resident::Budget<'d>, (&[u8], owners::Measured<I>)>,
    ) -> Result<Self, alloc::Error<credit::Error>> {
        let (budget, target, (first, second)) = reserve.into_parts();
        let capacity = Capacity::from(target);
        let len = (first.len() + second.len()) as u32;
        Self::try_allocate(
            budget,
            capacity,
            capacity,
            (first, second.into_input()),
            len,
        )
    }
}
// SAFETY: State retains the allocation and its exact initialized prefix;
// shared snapshots cannot mutate that prefix while this state is borrowed.
unsafe impl<P: buffer::raw::Policy, const MAX: usize> buffer::raw::Prefix for State<P, MAX> {
    fn prefix(&self) -> (*mut mem::MaybeUninit<u8>, u32) {
        (
            buffer::raw::Header::data(self.buf.as_ptr()).as_ptr().cast(),
            self.head,
        )
    }
}

const _: () = assert!(size_of::<State<(), 1>>() == 2 * size_of::<usize>());