o3 0.61.0

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

use super::{entry, root::Domain};
use crate::{
    alloc::{self, tail},
    buffer::storage::provided,
    mem::slot,
};

/// A stable native buffer mapping with a fixed admitted extent.
/// # Safety
/// Capacity and mapping are unchanged while entered. Each selected BID owns
/// disjoint storage until the final returned edge is consumed.
pub unsafe trait Context {
    fn resident(&self) -> NonZero<u32>;
    /// # Safety
    /// This BID is admitted, exclusively selected and `len <= resident()`.
    unsafe fn project(&self, bid: u16, len: usize) -> &mut [u8];
}

#[repr(C)]
struct Header<C, D = mem::MaybeUninit<Domain<'static, ()>>> {
    domain: D,
    issued: cell::Cell<u32>,
    context: C,
}

pub struct Allocation<C> {
    memory: tail::Uninit<Header<C>, entry::Entry<'static, ()>, NonZero<u16>>,
}

pub struct Arena<C> {
    entries: tail::Block<Header<C>, mem::MaybeUninit<entry::Entry<'static, ()>>, NonZero<u16>>,
}

pub struct Root<'d, C> {
    header: &'d Header<C, Domain<'d, ()>>,
}

pub struct Pending<'d, C> {
    entry: ptr::NonNull<entry::Entry<'d, ()>>,
    context: marker::PhantomData<&'d C>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Index {
    pub index: u16,
    pub capacity: NonZero<u16>,
}

pub use provided::view::LengthError as Length;

impl<C> Arena<C> {
    pub fn try_allocate(count: NonZero<u16>) -> Result<Allocation<C>, alloc::Error> {
        Ok(Allocation {
            memory: tail::Plan::try_new(count)?.try_allocate()?,
        })
    }

    pub fn context(&self) -> &C {
        &tail::View::new(&self.entries).header().context
    }

    pub fn capacity(&self) -> NonZero<u32> {
        self.entries.extent().into()
    }

    pub fn into_context(self) -> C {
        self.entries.into_header().context
    }

    /// # Safety
    /// Native completion has ended every projection, account and root borrow.
    /// Reclaim exactly once before reentering or releasing this allocation.
    pub unsafe fn refund_ended(&mut self) {
        for entry in self.entries.as_mut_slice() {
            // SAFETY: enter initialized every entry; the terminal ended all issued access.
            unsafe { entry.assume_init_ref().refund_ended() };
        }
    }
}

impl<C: Context> Arena<C> {
    /// # Safety
    /// This inactive arena and mapping are retained for one generative scope.
    /// End all native and issued access before refund_ended or reentry.
    pub unsafe fn enter(&mut self, accounts: u32) -> Root<'_, C> {
        const {
            assert!(size_of::<Header<C>>() == size_of::<Header<C, Domain<'_, ()>>>());
            assert!(align_of::<Header<C>>() == align_of::<Header<C, Domain<'_, ()>>>());
            assert!(
                mem::offset_of!(Header<C>, context)
                    == mem::offset_of!(Header<C, Domain<'_, ()>>, context)
            );
        }
        let capacity = self.entries.extent();
        let resident = self.context().resident();
        let (header, entries) = self.entries.parts_mut();
        let pointer = ptr::from_mut(header).cast::<Header<C, Domain<'_, ()>>>();
        // SAFETY: repr(C) and identical Domain storage preserve context and issued offsets.
        let header = unsafe {
            (&raw mut (*pointer).domain)
                .write(Domain::new(resident, accounts.min(u32::from(capacity.get()))));
            &*pointer
        };
        header.issued.set(0);
        for entry in entries {
            // SAFETY: this generation initializes the exact Entry layout under its root borrow.
            unsafe {
                entry
                    .as_mut_ptr()
                    .cast::<entry::Entry<'_, ()>>()
                    .write(entry::Entry::new(
                        &header.domain,
                        (),
                        mem::MaybeUninit::uninit(),
                    ))
            };
        }
        Root { header }
    }
}

impl<C> Allocation<C> {
    pub fn initialize(self, context: C) -> Arena<C> {
        Arena {
            entries: self.memory.init(Header {
                domain: mem::MaybeUninit::uninit(),
                issued: cell::Cell::new(0),
                context,
            }),
        }
    }
}

impl<'d, C> Root<'d, C> {
    fn view(
        &self,
    ) -> tail::View<'d, Header<C, Domain<'d, ()>>, entry::Entry<'d, ()>, NonZero<u16>> {
        // SAFETY: enter initialized the exact allocation whose first field is this header.
        unsafe { tail::View::from_raw(ptr::NonNull::from(self.header).cast()) }
    }

    pub fn context(&self) -> &'d C {
        &self.header.context
    }

    pub fn capacity(&self) -> NonZero<u32> {
        self.view().len_proof().extent().into()
    }

    pub fn is_full(&self) -> bool {
        self.header.issued.get() == self.capacity().get()
    }

    pub fn has_returned(&self) -> bool {
        self.header.domain.tail.get().is_some()
    }

    /// # Safety
    /// The native completion uniquely transferred this BID from this same mapping.
    /// Preserve this packet's original BID through every consuming transition.
    pub unsafe fn select(&self, bid: u16) -> Result<Pending<'d, C>, Index> {
        let view = self.view();
        let entry = match view.as_slice().get(usize::from(bid)) {
            Some(entry) => entry,
            None => {
                return Err(Index {
                    index: bid,
                    capacity: view.len_proof().extent(),
                });
            }
        };
        Ok(Pending {
            entry: ptr::NonNull::from(entry),
            context: marker::PhantomData,
        })
    }

    pub fn pop_returned(&self) -> Option<u16> {
        let entry = self.header.domain.pop_returned()?;
        let pending = Pending {
            entry,
            context: marker::PhantomData::<&C>,
        };
        // SAFETY: every last edge ended before this slot entered the returned queue.
        unsafe { entry.as_ref() }.state.set(entry::State::Empty);
        self.header.issued.set(self.header.issued.get() - 1);
        Some(pending.into_index())
    }
}

impl<C> Copy for Root<'_, C> {}
impl<C> Clone for Root<'_, C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'d, C> Pending<'d, C> {
    fn root(&self) -> Root<'d, C> {
        // SAFETY: select binds C to this Entry and Domain is Native Header's first field.
        let header = unsafe {
            &*ptr::from_ref(self.entry.as_ref().domain).cast::<Header<C, Domain<'d, ()>>>()
        };
        Root { header }
    }

    pub fn into_index(self) -> u16 {
        let root = self.root();
        // SAFETY: both pointers belong to the same initialized entry tail.
        let index = unsafe {
            self.entry
                .as_ptr()
                .offset_from(root.view().as_slice().as_ptr())
        };
        // Allocation accepted a NonZero<u16> extent, and select admitted this tail member.
        index as u16
    }
}

impl<'d, C: Context> Pending<'d, C> {
    /// # Safety
    /// `original_bid` is the same packet BID admitted by select. The completion
    /// initialized its prefix and this packet still owns its unique native token.
    pub unsafe fn publish<'event>(
        self,
        original_bid: u16,
        len: usize,
        output: slot::Vacant<'event, provided::Unique<'d, ()>>,
    ) -> Result<slot::Occupied<'event, provided::Unique<'d, ()>>, (Self, Length)> {
        let root = self.root();
        let capacity = root.header.domain.resident.get();
        if len > capacity as usize {
            return Err((self, Length::new(len, capacity)));
        }
        // SAFETY: original BID identity, exclusivity and length were admitted once.
        let bytes = unsafe { root.context().project(original_bid, len) };
        // SAFETY: this affine pending token owns the unoccupied native slot.
        unsafe { self.entry.as_ref() }
            .state
            .set(entry::State::Occupied);
        root.header.issued.set(root.header.issued.get() + 1);
        Ok(output.insert(provided::Unique {
            bytes,
            owner: provided::Owner { entry: self.entry },
        }))
    }
}

const _: () = {
    assert!(size_of::<Root<'_, ()>>() == size_of::<usize>());
    assert!(size_of::<Pending<'_, ()>>() == size_of::<usize>());
    assert!(size_of::<Arena<()>>() == size_of::<usize>());
};