o3 0.62.0

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

use crate::{
    buffer,
    buffer::{
        pool,
        pool::{owners, state},
        resident::{AllocError, staging, write::Cause},
        storage,
        write::{consume, consume::Error},
    },
};

pub(in crate::buffer::pool) mod append;

/// Owns one live slot edge and its initialized prefix. The backing and prefix
/// cannot be replaced independently through this capability.
#[derive(Debug)]
#[repr(C)]
pub struct Span<K: crate::buffer::raw::Backing = owners::Plain, M = pool::Owned, S = state::Uninit>
{
    pub(in crate::buffer::pool) slots: owners::raw::Ptr<K, S>,
    pub(in crate::buffer::pool) key: owners::Key,
    pub(in crate::buffer::pool) len: u32,
    pub(in crate::buffer::pool) root: M,
}

impl<K: crate::buffer::raw::Backing, S> Span<K, pool::Owned, S> {
    pub(in crate::buffer::pool) fn with_root<M>(self, root: M) -> Span<K, M, S> {
        let this = mem::ManuallyDrop::new(self);
        Span {
            slots: this.slots,
            key: this.key,
            len: this.len,
            root,
        }
    }
}

impl<'d> Span<owners::Resident<'d>> {
    pub(in crate::buffer) fn try_staged<I: buffer::raw::Transfer>(
        reserve: staging::Reserve<&staging::Pool<'d>, (&[u8], owners::Measured<I>)>,
    ) -> Result<Self, AllocError> {
        let (pool, capacity, (first, second)) = reserve.into_parts();
        let len = first.len() + second.len();
        let layout = pool::NonEmpty::new(capacity);
        let seed = owners::raw::Block::<owners::Resident<'_>, state::Uninit>::try_seed(
            layout,
            pool.budget(),
        )?;
        let span = seed.into_span();
        Ok(span.copy_in((first, second.into_input()), len))
    }
}

const _: () = {
    assert!(size_of::<Span>() == 2 * size_of::<usize>());
    assert!(size_of::<Span<owners::Plain, pool::Borrowed<'static>>>() == 2 * size_of::<usize>());
    assert!(size_of::<Span<owners::Resident<'static>>>() == 2 * size_of::<usize>());
    assert!(
        size_of::<Span<owners::Plain, pool::Owned, state::Initialized>>() == 2 * size_of::<usize>()
    );
};

impl<K: crate::buffer::raw::Backing, M, S> AsRef<[u8]> for Span<K, M, S> {
    fn as_ref(&self) -> &[u8] {
        buffer::raw::Prefix::as_slice(self)
    }
}

impl<S: state::State, L> pool::Span<owners::Plain<L>, pool::Owned, S>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    #[must_use]
    pub fn freeze(self) -> pool::Span<owners::Plain<L>, pool::Owned, pool::Frozen> {
        let this = mem::ManuallyDrop::new(self);
        Span {
            slots: this.slots.erase_state(),
            key: this.key,
            len: this.len,
            root: this.root,
        }
    }
}

impl<'pool, S: state::State, L> pool::Span<owners::Plain<L>, pool::Borrowed<'pool>, S>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    #[must_use]
    pub fn freeze(
        self,
    ) -> storage::Shared<Option<owners::Edge<owners::Plain<L>, pool::Borrowed<'pool>>>> {
        let len = self.len();
        // SAFETY: consuming the span retains its exact initialized prefix.
        unsafe { pool::raw::into_shared(self, 0, len) }
    }
}

impl<L, M> pool::Span<owners::Plain<L>, M, state::Uninit>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    pub fn try_append<'a, 'source>(
        &'a mut self,
        source: &'source [u8],
    ) -> Result<pool::Append<'a, &'source [u8], L, M>, Error> {
        let input = owners::Measured::slice(source);
        pool::Append::try_lease(self, input)
    }
}

impl pool::Span<owners::Plain<pool::Layout>, pool::Owned, state::Uninit> {
    /// Allocates one independently owned writable slot.
    pub fn try_new(cap: usize) -> Result<Self, pool::CreateError> {
        let layout = pool::NonEmpty::one(cap).map_err(pool::CreateError::Layout)?;
        let seed =
            owners::raw::Block::<owners::Plain<pool::Layout>, state::Uninit>::try_seed(layout)
                .map_err(pool::CreateError::Exhausted)?;
        Ok(seed.into_span())
    }

    pub fn try_copy<const N: usize>(
        mut self,
        source: buffer::raw::Slices<'_, N>,
    ) -> Result<pool::Span<owners::Plain, pool::Owned, pool::Frozen>, Error> {
        let start = self.len();
        let len = source.len().get();
        Error::check(len as usize, self.capacity().get() as usize - start)?;
        let target = self.slots.data(self.key);
        // SAFETY: admission retains every source and this exact exclusive suffix.
        unsafe { buffer::raw::Transfer::copy_to(source.slices(), target.add(start)) };
        self.len += len;
        Ok(self.freeze())
    }
}

/// One acquired resident-pool backing without a duplicate pool owner.
impl<'d> pool::Span<owners::Resident<'d>> {
    pub(in crate::buffer) fn try_extend<'a, I: buffer::raw::Transfer>(
        (cursor, head): (&'a mut Self, &'a mut u32),
        slab: Option<&pool::Pool<state::Uninit, owners::Resident<'d>>>,
        input: &owners::Measured<I>,
    ) -> Result<(), Cause> {
        let added = input.len();
        let src = input.input();
        let capacity = cursor.capacity().get() as usize;
        let tail = match consume::Error::check(added, capacity - cursor.len()) {
            Ok(()) => {
                let start = cursor.len();
                let target = cursor.slots.data(cursor.key);
                let end = start + added;
                // SAFETY: admission retains the exact suffix and every disjoint source.
                unsafe { src.copy_to(target.add(start)) };
                cursor.len = end as u32;
                return Ok(());
            }
            Err(error) => error,
        };
        let len = cursor.len() - *head as usize;
        consume::Error::check(added, capacity - len).map_err(Cause::Capacity)?;
        if crate::mem::raw::Edge::is_unique(cursor.slots.slot(cursor.key)) {
            let data = cursor.slots.data(cursor.key);
            let start = mem::take(head) as usize;
            // SAFETY: the exclusive slot is unique and both ranges remain within its initialized extent.
            unsafe { ptr::copy(data.add(start), data, len) };
            let end = len + added;
            // SAFETY: compaction preserves the admitted suffix and disjoint sources.
            unsafe { src.copy_to(data.add(len)) };
            cursor.len = end as u32;
            return Ok(());
        }
        let Some(slab) = slab else {
            return Err(Cause::Shared(tail));
        };
        let Some(next) = slab.acquire() else {
            return Err(Cause::Rotation(tail));
        };
        // SAFETY: the exclusive source borrow retains its exact suffix through the copy.
        let bytes = unsafe { cursor.as_slice().get_unchecked(*head as usize..) };
        let next = next.copy_in((bytes, src), bytes.len() + added);
        *head = 0;
        *cursor = next;
        Ok(())
    }
}

impl<K: crate::buffer::raw::Backing, M, S> Span<K, M, S> {
    pub const fn len(&self) -> usize {
        self.len as usize
    }

    pub fn capacity(&self) -> num::NonZero<u32> {
        self.slots.capacity()
    }

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

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

    pub(in crate::buffer::pool) fn copy_in<I: buffer::raw::Transfer>(
        mut self,
        sources: I,
        len: usize,
    ) -> Self {
        // SAFETY: fresh-slot admission proves all sources fit this retained exclusive span.
        unsafe { sources.copy_to(self.slots.data(self.key)) };
        self.len = len as u32;
        self
    }
}

impl<K: crate::buffer::raw::Backing, M, S> Drop for Span<K, M, S> {
    fn drop(&mut self) {
        // SAFETY: dropping Span transfers its exact live slot edge once.
        unsafe { owners::raw::Slot::release(self.slots.ptr(self.key), self.slots, self.key) };
    }
}

impl<K: crate::buffer::raw::Backing, M, S: state::State> Span<K, M, S> {
    pub fn truncate(&mut self, len: usize) {
        buffer::raw::Length::truncate(&mut self.len, len);
    }
}

impl<L, M, S: state::State> Span<owners::Plain<L>, M, S>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        buffer::raw::Exclusive::as_mut_slice(self)
    }
}

// SAFETY: the lease retains this exact live slot and its initialized prefix;
// shared access cannot change the prefix, including for frozen leases.
unsafe impl<K: crate::buffer::raw::Backing, M, S> buffer::raw::Prefix for Span<K, M, S> {
    fn prefix(&self) -> (*mut mem::MaybeUninit<u8>, u32) {
        let pointer = self.slots.data(self.key).cast();
        (pointer, self.len)
    }
}

// SAFETY: sharing a plain slot consumes its writable lease. Resident slots can
// retain prefix aliases through accounts and do not carry this proof. The length
// word is inline in this lease, disjoint from its slot, and bounded by capacity.
unsafe impl<L, M, S: state::State> buffer::raw::Exclusive for Span<owners::Plain<L>, M, S>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    fn as_mut_ptr(&mut self) -> *mut mem::MaybeUninit<u8> {
        self.slots.data(self.key).cast()
    }

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

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

// SAFETY: frozen ownership retains this exact initialized slot and visible range.
unsafe impl<L> buffer::raw::Source for Span<owners::Plain<L>, pool::Owned, pool::Frozen> where
    owners::Plain<L>: crate::buffer::raw::Backing
{
}

impl<L> Span<owners::Plain<L>, pool::Owned, pool::Frozen>
where
    owners::Plain<L>: crate::buffer::raw::Backing,
{
    #[must_use]
    pub fn into_shared(self) -> storage::Shared {
        let len = self.len();
        // SAFETY: consuming the frozen span retains its exact initialized prefix.
        unsafe { pool::raw::into_shared(self, 0, len) }.into()
    }
}