o3 0.61.0

shared-nothing primitives
Documentation
use std::cell::Cell;

use crate::{buffer::storage::regions, depot::queue::links};

pub(super) const END: u32 = links::Index::encode(None);

pub(super) const fn link(index: u32, limit: u32) -> u32 {
    if index == limit { END } else { index }
}

#[repr(transparent)]
pub(super) struct Free<const ACCOUNT: bool = false>(Cell<u32>);

impl<const ACCOUNT: bool> Free<ACCOUNT> {
    pub(super) const fn new(limit: u32) -> Self {
        Self(Cell::new(link(0, limit)))
    }

    pub(super) fn head(&self) -> Option<Key<ACCOUNT>> {
        // SAFETY: only this list's initialized or recycled entries reach its head.
        unsafe { Key::decode(self.0.get()) }
    }
}

/// One index from an exact slot list, or its distinct accounting table.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::buffer::pool) struct Key<const ACCOUNT: bool = false>(u32);

impl<const ACCOUNT: bool> Key<ACCOUNT> {
    /// # Safety
    /// The index belongs to this exact initialized pool's Accounts table when
    /// ACCOUNT is true, and to its Slot list otherwise.
    pub(super) const unsafe fn new(index: u32) -> Self {
        // SAFETY: both initialized arrays exclude the compact sentinel.
        Self(unsafe { links::Index::new_raw(index) }.raw())
    }

    pub(super) const fn get(self) -> u32 {
        self.0
    }

    /// # Safety
    /// Every non-sentinel word belongs to the exact initialized table selected
    /// by ACCOUNT; the caller preserves the word's vacant or published state.
    pub(super) const unsafe fn decode(word: u32) -> Option<Self> {
        match links::Index::decode(word) {
            Some(index) => Some(Self(index.raw())),
            None => None,
        }
    }

    /// # Safety
    /// The caller owns this retired entry in the head's exact table.
    pub(super) unsafe fn recycle(self, head: &Free<ACCOUNT>, prefix: &regions::Prefix) {
        unsafe { prefix.write(head.0.get()) };
        head.0.set(self.0);
    }
}

impl Key {
    /// # Safety
    /// The prefix belongs to the exclusively claimed head; its live word will name this slot.
    pub(super) unsafe fn occupy<const ACCOUNT: bool>(
        self,
        head: &Free<ACCOUNT>,
        prefix: &regions::Prefix,
    ) {
        head.0.set(prefix.word());
        unsafe { prefix.write(self.0) };
    }
}

const _: () = {
    assert!(size_of::<Key>() == size_of::<u32>());
    assert!(size_of::<Key<true>>() == size_of::<u32>());
    assert!(size_of::<Free>() == size_of::<u32>());
    assert!(size_of::<Free<true>>() == size_of::<u32>());
};