o3 0.62.0

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

use pool::state;

use crate::{
    buffer,
    buffer::{
        pool,
        pool::owners,
        resident::{self, staging},
        storage,
    },
};

#[repr(C, align(8))]
pub(in crate::buffer) struct Accounts<'d> {
    root: mem::ManuallyDrop<resident::Charge<'d>>,
    head: cell::Cell<u32>,
    fresh: cell::Cell<u32>,
}

impl<'d> Accounts<'d> {
    pub(in crate::buffer) fn try_grow<I: buffer::raw::Transfer>(
        reserve: staging::Reserve<
            (&mut pool::Span<owners::Resident<'d>>, &mut u32),
            &owners::Measured<I>,
        >,
    ) -> Result<bool, resident::AllocError> {
        let ((span, head), capacity, input) = reserve.into_parts();
        let core = span.slots;
        let header = core.header();
        let previous = header.capacity();
        if capacity <= previous
            || header.slots() != 1
            || !header.is_detached()
            || !crate::mem::raw::Edge::is_unique(span.slots.slot(span.key))
        {
            return Ok(false);
        }
        let shape =
            owners::Shape::<owners::Resident<'d>>::try_new(pool::NonEmpty::new(capacity).into())
                .map_err(resident::AllocError::Layout)?;
        // SAFETY: the detached one-slot block has one live edge and no
        // active account. Its root charge is exclusively owned here.
        let accounts = unsafe { core.accounts().as_mut() };
        accounts
            .root
            .try_resize(capacity.get() as usize)
            .map_err(resident::AllocError::Budget)?;
        let block = match owners::raw::Block::<owners::Resident<'d>, state::Uninit>::allocate(shape)
        {
            Ok(block) => block,
            Err(error) => {
                accounts.root.truncate(previous.get() as usize);
                return Err(resident::AllocError::Exhausted(error));
            }
        };
        // SAFETY: transfer the sole root after all fallible work. The old block
        // will be deallocated without dropping this charge again.
        let root = unsafe { mem::ManuallyDrop::take(&mut accounts.root) };
        // SAFETY: the one-slot shape reserves one account and root covers its capacity.
        let next = unsafe { block.account(root, 1) };
        // SAFETY: the new block has a nonempty slot list with no published owner.
        let seed = unsafe { owners::raw::Seed::from_ptr(next) };
        // SAFETY: Slot retains this span's initialized suffix and admitted target.
        let bytes = unsafe { span.as_slice().get_unchecked(*head as usize..) };
        let next = seed
            .into_span()
            .copy_in((bytes, input.input()), bytes.len() + input.len());
        // SAFETY: the copy ended every payload borrow. The sole old edge and
        // its transferred root must not run Drop after deallocation.
        unsafe {
            core.deallocate();
            ptr::write(span, next);
        }
        *head = 0;
        Ok(true)
    }

    pub(in crate::buffer::pool::owners) fn new(root: resident::Charge<'d>, limit: u32) -> Self {
        Self {
            root: mem::ManuallyDrop::new(root),
            head: cell::Cell::new(limit.wrapping_sub(1)),
            fresh: cell::Cell::new(limit),
        }
    }

    /// # Safety
    /// The caller owns the terminal allocation and its one outstanding root debit.
    pub(in crate::buffer) unsafe fn release<S>(core: owners::raw::Ptr<owners::Resident<'d>, S>) {
        // SAFETY: return the debit before freeing its exclusive allocation.
        unsafe {
            mem::ManuallyDrop::drop(&mut core.accounts().as_mut().root);
            core.deallocate();
        }
    }

    /// # Safety
    /// The slot link or this table's free head supplied a non-sentinel index.
    unsafe fn entry(table: ptr::NonNull<Self>, index: u32) -> ptr::NonNull<Account<'d>> {
        // SAFETY: the admitted allocation reserves this array directly after its header.
        unsafe { table.add(1).cast::<Account<'d>>().add(index as usize) }
    }
}

#[repr(C, align(8))]
#[derive(Debug)]
pub(in crate::buffer) struct Account<'d> {
    prefix: storage::raw::Prefix,
    slot: ptr::NonNull<owners::raw::Slot<owners::Resident<'d>>>,
    budget: resident::Budget<'d>,
}

impl<'d> Account<'d> {
    pub(in crate::buffer) fn try_bind<M, A: resident::Admission>(
        span: &pool::Span<owners::Resident<'d>, M>,
        budget: &resident::Budget<'d>,
        admit: A,
    ) -> Result<Option<crate::mem::raw::Owner<Self>>, resident::AllocError> {
        use crate::mem::raw::{Edge, Owner};

        let table = span.slots.accounts();
        let slot = span.slots.ptr(span.key);
        // SAFETY: the span retains this slot and its accounted allocation throughout admission.
        let link = unsafe { &slot.as_ref().backing.account };
        let index = link.get();
        if index != super::END {
            // SAFETY: this slot publishes an account index only after initializing its entry.
            let entry = unsafe { Accounts::entry(table, index) };
            let account = unsafe { entry.as_ref() };
            if !ptr::eq(budget.core(), account.budget.core()) || admit.check(*budget, 0).is_break()
            {
                return Ok(None);
            }
            // SAFETY: this association retains the live account until the new edge is issued.
            unsafe {
                Edge::try_retain(account).map_err(resident::AllocError::Retain)?;
                return Ok(Some(Owner::from_raw(entry)));
            }
        }
        // SAFETY: the span retains the table header, disjoint from its trailing entries.
        let accounts = unsafe { table.as_ref() };
        let index = accounts.head.get();
        if index == super::END {
            return Ok(None);
        }
        let capacity = span.capacity().get();
        if admit.check(*budget, capacity as usize).is_break() {
            return Ok(None);
        }
        let charge = budget
            .try_charge(capacity as usize)
            .map_err(resident::AllocError::Budget)?;
        // SAFETY: admission completed without reentry. Recycled entries hold their successor;
        // the untouched indices below fresh are issued in descending order, ending at END.
        unsafe {
            let entry = Accounts::entry(table, index);
            let next = if index < accounts.fresh.get() {
                accounts.fresh.set(index);
                index.wrapping_sub(1)
            } else {
                entry.cast::<u32>().read()
            };
            accounts.head.set(next);
            entry.write(Self {
                prefix: storage::raw::Prefix::one(capacity),
                slot,
                budget: charge.into(),
            });
            // SAFETY: the unassociated span supplies the sole slot edge for this pair.
            Edge::start_pair(slot.as_ref());
            link.set(index);
            Ok(Some(Owner::from_raw(entry)))
        }
    }

    pub(in crate::buffer) fn bytes(&self) -> usize {
        self.prefix.word() as usize
    }
}

// SAFETY: every published account edge retains this exact embedded count.
unsafe impl crate::mem::raw::Edge for Account<'_> {
    fn count(&self) -> &crate::mem::raw::Count {
        crate::mem::raw::Edge::count(&self.prefix)
    }
}

// SAFETY: the last edge owns the debit and retains its slot through table recycling.
unsafe impl<'d> crate::mem::raw::Target for Account<'d> {
    unsafe fn destroy(entry: ptr::NonNull<Self>) {
        // SAFETY: the last edge ends every borrow before repurposing the account storage.
        // Its published slot link supplies the exact index in this table.
        unsafe {
            let account = entry.as_ref();
            let slot = account.slot;
            let (core, key) = owners::raw::Slot::locate(slot);
            account.budget.release(account.bytes());
            let index = slot.as_ref().backing.account.replace(super::END);
            let table = core.accounts().as_ref();
            entry.cast::<u32>().write(table.head.get());
            table.head.set(index);
            owners::raw::Slot::release(slot, core, key);
        }
    }
}

const _: () = {
    assert!(size_of::<Accounts<'static>>() == 24);
    assert!(size_of::<Account<'static>>() == 24);
    assert!(size_of::<crate::mem::raw::Owner<Account<'_>>>() == size_of::<usize>());
    assert!(size_of::<Option<crate::mem::raw::Owner<Account<'_>>>>() == size_of::<usize>());
};