o3 0.62.0

shared-nothing primitives
Documentation
use crate::{
    buffer::{resident, storage::provided},
    mem,
};
use std::{
    cell,
    mem::{MaybeUninit, align_of, size_of},
    num::NonZero,
    ptr,
};

/// Last-edge accounting and returned slots share one owning domain.
#[repr(C)]
pub(in crate::buffer::storage::provided) struct Domain<L: provided::raw::Layout> {
    pub(in crate::buffer::storage::provided) returned: Returns<L>,
    pub(super) accounted: cell::Cell<u32>,
    pub(super) limit: u32,
    pub(in crate::buffer::storage::provided) resident: L::Shared,
}

#[repr(C)]
pub(in crate::buffer::storage::provided) struct Returns<L: provided::raw::Layout> {
    head: cell::Cell<MaybeUninit<provided::raw::Link<L>>>,
    tail: cell::Cell<Option<provided::raw::Link<L>>>,
}

impl<L: provided::raw::Layout> Domain<L> {
    pub(in crate::buffer::storage::provided) fn new(
        resident: L::Shared,
        accounts: u32,
        capacity: NonZero<u32>,
    ) -> Self {
        Self {
            returned: Returns {
                head: cell::Cell::new(MaybeUninit::uninit()),
                tail: cell::Cell::new(None),
            },
            accounted: cell::Cell::new(0),
            limit: accounts.min(capacity.get()),
            resident,
        }
    }
}

impl<L: provided::raw::Layout> Returns<L> {
    pub(in crate::buffer::storage::provided) fn has_items(&self) -> bool {
        self.tail.get().is_some()
    }

    pub(in crate::buffer::storage::provided) fn pop(&self) -> Option<provided::raw::Link<L>> {
        let tail = self.tail.get()?;
        // SAFETY: a tail proves an initialized head in this same domain.
        let head = unsafe { self.head.get().assume_init() };
        if head == tail {
            self.tail.set(None);
        } else {
            // SAFETY: finish initialized the successor of every nontail entry.
            let next = unsafe { head.as_ref().data.get().assume_init().returned };
            self.head.set(MaybeUninit::new(next));
        }
        // SAFETY: the detached head has no remaining external or accounting edge.
        unsafe { head.as_ref() }.state.set(Phase::Empty);
        Some(head)
    }

    pub(super) fn finish(&self, node: provided::raw::Ready<'_, L>) {
        if let Some(last) = self.tail.get() {
            // SAFETY: the old tail gains its first initialized successor.
            unsafe { last.as_ref() }.data.set(MaybeUninit::new(Data {
                returned: node.entry,
            }));
        } else {
            self.head.set(MaybeUninit::new(node.entry));
        }
        self.tail.set(Some(node.entry));
    }
}

/// The hidden scope's authority to reclaim an initialized item.
#[derive(Clone, Copy)]
pub(in crate::buffer::storage::provided) enum Phase {
    Empty,
    ReturnOnLastAccount,
    Occupied,
}

/// An account can only exist while the slot is detached from both lists.
pub(in crate::buffer::storage::provided) union Data<L: provided::raw::Layout> {
    pub(super) free: Option<provided::raw::Link<L>>,
    pub(super) returned: provided::raw::Link<L>,
}

#[repr(C, align(8))]
pub(in crate::buffer::storage::provided) struct Entry<L: provided::raw::Layout = cell::Cell<u32>> {
    count: mem::raw::Count,
    pub(super) state: cell::Cell<Phase>,
    pub(super) resident: L::Slot,
    pub(super) data: cell::Cell<MaybeUninit<Data<L>>>,
    pub(in crate::buffer::storage::provided) domain: ptr::NonNull<Domain<L>>,
}

impl<L: provided::raw::Layout> Entry<L> {
    pub(in crate::buffer::storage::provided) fn new(
        domain: ptr::NonNull<Domain<L>>,
        data: MaybeUninit<Data<L>>,
    ) -> Self {
        Self {
            count: mem::raw::Count::empty(),
            state: cell::Cell::new(Phase::Empty),
            resident: L::empty(),
            data: cell::Cell::new(data),
            domain,
        }
    }

    /// # Safety
    /// Admission initialized this u32 ceiling and the slot cannot be reused during the borrow.
    pub(super) unsafe fn capacity(&self) -> u32 {
        unsafe { L::resident(&self.resident, &self.domain.as_ref().resident) }
    }

    /// # Safety
    /// This exact live registration retains its original budget throughout 'd.
    pub(super) unsafe fn payer<'d>(&self) -> resident::Budget<'d> {
        unsafe { self.data.as_ptr().cast::<resident::Budget<'d>>().read() }
    }

    /// # Safety
    /// All charged access ended and the original paying budget remains alive until this debit is returned.
    pub(super) unsafe fn refund(&self) {
        // SAFETY: terminal or last-edge ownership retains the original initialized budget and capacity.
        unsafe { self.payer().release(self.capacity() as usize) };
    }

    /// # Safety
    /// The native terminal ended every projection and account in this generation.
    pub(in crate::buffer::storage::provided) unsafe fn refund_ended(&self) -> Phase {
        let phase = self.state.get();
        if !matches!(phase, Phase::Empty) && !mem::raw::Edge::is_empty(self) {
            // SAFETY: the terminal owns the remaining debit, including forgotten account edges.
            unsafe { self.refund() };
        }
        phase
    }
}

// SAFETY: an Entry's count is embedded for the entire same-owner scope.
unsafe impl<L: provided::raw::Layout> mem::raw::Edge for Entry<L> {
    fn count(&self) -> &mem::raw::Count {
        &self.count
    }
}

const _: () = {
    assert!(size_of::<Data<()>>() == size_of::<resident::Budget<'_>>());
    assert!(align_of::<Data<()>>() == align_of::<resident::Budget<'_>>());
    assert!(size_of::<Data<cell::Cell<u32>>>() == size_of::<resident::Budget<'_>>());
    assert!(align_of::<Data<cell::Cell<u32>>>() == align_of::<resident::Budget<'_>>());
};

const _: () = {
    assert!(size_of::<Entry>() == 4 * size_of::<usize>());
    assert!(size_of::<Entry<()>>() == 3 * size_of::<usize>());
    assert!(align_of::<Entry>() == 8);
};

impl<L: provided::raw::Layout> Clone for Data<L> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<L: provided::raw::Layout> Copy for Data<L> {}