o3 0.62.0

shared-nothing primitives
Documentation
use crate::{
    alloc::{self, tail},
    buffer::storage::provided,
    mem::slot,
};
use provided::view;
use std::{
    cell, marker, mem,
    mem::{align_of, size_of},
    num::NonZero,
    ptr, slice,
};

/// # Safety
/// During entry, `resident()` and each admitted BID's address stay fixed.
/// Each selected region is disjoint and valid for a mutable `[MaybeUninit<u8>]`
/// of that length through its final returned edge.
pub unsafe trait Context {
    fn resident(&self) -> NonZero<u32>;
    fn buffer_ptr(&self, bid: u16) -> *mut u8;
}

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

pub struct Allocation<C> {
    memory: tail::raw::Uninit<Header<C>, provided::raw::Entry<()>, NonZero<u16>>,
}

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

pub struct Root<'d, C> {
    scope: marker::PhantomData<fn(&'d ()) -> &'d ()>,
    view: tail::raw::View<
        'd,
        Header<C, provided::raw::Domain<()>>,
        provided::raw::Entry<()>,
        NonZero<u16>,
    >,
}

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

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

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::raw::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, provided::raw::Domain<()>>>());
            assert!(align_of::<Header<C>>() == align_of::<Header<C, provided::raw::Domain<()>>>());
            assert!(
                mem::offset_of!(Header<C>, context)
                    == mem::offset_of!(Header<C, provided::raw::Domain<()>>, context)
            );
        }
        let capacity = self.entries.extent();
        let resident = self.context().resident();
        let base = tail::raw::View::new(&self.entries).as_ptr();
        let (header, entries) = self.entries.parts_mut();
        header.domain.write(provided::raw::Domain::new(
            resident,
            accounts,
            capacity.into(),
        ));
        header.issued.set(0);
        for entry in entries {
            entry.write(provided::raw::Entry::new(
                base.cast(),
                mem::MaybeUninit::uninit(),
            ));
        }
        Root {
            // SAFETY: this original allocation now contains its admitted active layout.
            view: unsafe { tail::raw::View::from_raw(base) },
            scope: marker::PhantomData,
        }
    }
}

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> {
    pub fn context(&self) -> &'d C {
        &self.view.header().context
    }

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

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

    pub fn has_returned(&self) -> bool {
        self.view.header().domain.returned.has_items()
    }

    /// # 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.view.header().domain.returned.pop()?;
        let pending: Pending<'d, C> = Pending {
            entry,
            context: marker::PhantomData,
        };
        self.view
            .header()
            .issued
            .set(self.view.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 this entry to its original complete header-and-tail allocation.
        let view = unsafe { tail::raw::View::from_raw(self.entry.as_ref().domain.cast()) };
        Root {
            view,
            scope: marker::PhantomData,
        }
    }

    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())
        };
        // SAFETY: allocation accepted a NonZero<u16> extent and select admitted this tail member.
        index as u16
    }
}

impl<'d, C: Context> Pending<'d, C> {
    /// # Safety
    /// `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,
        bid: u16,
        len: usize,
        output: slot::raw::Vacant<'event, provided::raw::Loan<'d, ()>>,
    ) -> Result<slot::Occupied<'event, provided::raw::Loan<'d, ()>>, (Self, view::LengthError)>
    {
        let root = self.root();
        let capacity = root.view.header().domain.resident.get();
        if len > capacity as usize {
            return Err((self, view::LengthError::new(len, capacity)));
        }
        // SAFETY: this pending BID owns the initialized prefix in the same live
        // mapping, and len is bounded by that mapping's resident capacity.
        let bytes = unsafe { slice::from_raw_parts_mut(root.context().buffer_ptr(bid), len) };
        // SAFETY: this affine pending token owns the native slot and its admitted disjoint bytes.
        let loan = unsafe { provided::raw::Slice::publish(self.entry.as_ref(), bytes) };
        root.view
            .header()
            .issued
            .set(root.view.header().issued.get() + 1);
        Ok(output.insert(loan))
    }
}

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