o3 0.62.0

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

use crate::{
    alloc::{self, array},
    depot::{capacity, queue::ring},
    mem::slot,
};

mod slots;
mod state;
pub(super) use slots::{Index, Slots};
pub(crate) use state::State;

pub(crate) fn runs(start: usize, capacity: usize, len: usize) -> (usize, [usize; 2]) {
    let first = len.min(capacity - start);
    (start, [first, len - first])
}

/// One initialized front of its exclusively borrowed FIFO.
#[must_use]
pub struct Front<'a, T>(pub(super) &'a mut ring::Fifo<T>);

/// One vacant slot of its exclusively borrowed FIFO.
#[must_use]
pub struct Vacant<'a, T>(pub(super) &'a mut ring::Fifo<T>);

impl<'a, T> Front<'a, T> {
    /// # Safety
    /// The exclusively borrowed FIFO contains at least one value.
    pub unsafe fn new(queue: &'a mut ring::Fifo<T>) -> Self {
        Self(queue)
    }

    pub fn get(&self) -> &T {
        let queue = &*self.0;
        // SAFETY: the exclusive front keeps this exact slot initialized.
        unsafe { &*queue.storage.at(queue.state.head()) }
    }

    pub fn get_mut(&mut self) -> &mut T {
        let queue = &mut *self.0;
        // SAFETY: the exclusive front owns this initialized slot.
        unsafe { &mut *queue.storage.at(queue.state.head()) }
    }

    pub fn remove(self) -> T {
        self.detach().into_inner()
    }

    pub fn take(self) -> (T, Vacant<'a, T>) {
        let queue = self.0;
        let value = Front(queue).remove();
        (value, Vacant(queue))
    }

    pub fn discard(self) {
        drop(self.detach());
    }

    pub fn detach(self) -> slot::Occupied<'a, T> {
        // SAFETY: unlinking transfers this initialized front into the occupied loan.
        unsafe { self.into_uninit().assume_init() }
    }

    pub fn into_uninit(self) -> slot::raw::Vacant<'a, T> {
        let queue = self.0;
        // SAFETY: Front proves nonempty. The exclusive loan outlives the detached slot.
        unsafe { slot::raw::Vacant::new(&mut *queue.storage.unlink(&mut queue.state)) }
    }
}

impl<'a, T> Vacant<'a, T> {
    /// # Safety
    /// The exclusively borrowed FIFO has at least one spare slot.
    pub unsafe fn new(queue: &'a mut ring::Fifo<T>) -> Self {
        Self(queue)
    }

    pub fn push_front(self, value: T) {
        // SAFETY: the consumed vacancy admits one write.
        unsafe { self.0.storage.write::<true>(&mut self.0.state, value) }
    }

    pub fn push_back(self, value: T) {
        // SAFETY: the consumed vacancy admits one write.
        unsafe { self.0.storage.write::<false>(&mut self.0.state, value) }
    }
}

pub(super) struct Storage<T, S = ()> {
    block: array::raw::Block<MaybeUninit<T>, capacity::Count, S>,
}

impl<T, S> Storage<T, S> {
    pub(super) fn try_new(extent: capacity::Count, state: S) -> Result<Self, alloc::Error> {
        Ok(Self {
            block: array::raw::Block::try_new(extent, state)?,
        })
    }

    pub(super) const fn extent(&self) -> capacity::Count {
        *self.block.extent()
    }

    fn at(&self, index: usize) -> *mut T {
        self.block.as_ptr().cast_mut().wrapping_add(index).cast()
    }

    // SAFETY: the matching state admits a nonempty front with no outstanding slot loans.
    unsafe fn unlink(&self, state: &mut State<u32>) -> *mut MaybeUninit<T> {
        let index = unsafe { state.pop_front(self.extent().get()) };
        self.at(index).cast()
    }

    // SAFETY: the matching state admits this insertion through a vacancy or a reservation.
    unsafe fn write<const FRONT: bool>(&self, state: &mut State<u32>, value: T) {
        let index = unsafe { state.push::<FRONT>(self.extent().get()) };
        unsafe { self.at(index).write(value) };
    }

    fn spans(&self, state: State<u32>) -> [*mut [T]; 2] {
        let (start, [front, back]) = runs(state.head(), self.extent().get(), state.len());
        [
            ptr::slice_from_raw_parts_mut(self.at(start), front),
            ptr::slice_from_raw_parts_mut(self.at(0), back),
        ]
    }

    // SAFETY: the exclusive owner surrenders exactly these initialized runs.
    unsafe fn drop_values(&mut self, state: State<u32>) {
        let [front, back] = self.spans(state);
        unsafe {
            ptr::drop_in_place(front);
            ptr::drop_in_place(back);
        }
    }
}

/// # Safety
/// `index` is in this FIFO's initialized logical range for the shared borrow.
pub(crate) unsafe fn get<T>(queue: &ring::Fifo<T>, index: usize) -> &T {
    let position = queue.state.position(queue.capacity(), index);
    unsafe { &*queue.storage.at(position) }
}

impl<T> Storage<T> {
    pub(super) fn front(queue: &ring::Fifo<T>) -> Option<&T> {
        let state = queue.state;
        if state.is_empty() {
            return None;
        }
        // SAFETY: nonempty occupancy admits the initialized physical head.
        Some(unsafe { &*queue.storage.at(state.head()) })
    }

    pub(super) fn get(queue: &ring::Fifo<T>, index: usize) -> Option<&T> {
        if index >= queue.len() {
            return None;
        }
        // SAFETY: this logical offset belongs to the shared initialized range.
        Some(unsafe { get(queue, index) })
    }

    pub(super) fn slices(queue: &ring::Fifo<T>) -> (&[T], &[T]) {
        let [front, back] = queue.storage.spans(queue.state);
        // SAFETY: the FIFO retains both initialized runs for the shared loan.
        unsafe { (&*front, &*back) }
    }

    pub(super) fn slices_mut(queue: &mut ring::Fifo<T>) -> (&mut [T], &mut [T]) {
        let [front, back] = queue.storage.spans(queue.state);
        // SAFETY: this exclusive loan owns both disjoint initialized runs.
        unsafe { (&mut *front, &mut *back) }
    }

    pub(super) fn retire(queue: &mut ring::Fifo<T>) {
        // SAFETY: take the initialized span from its owner before dropping any value.
        let state = mem::replace(&mut queue.state, State::EMPTY);
        unsafe { queue.storage.drop_values(state) };
    }
}

impl<T> Storage<T, Cell<u32>> {
    pub(super) fn free(&self) -> &Cell<u32> {
        self.block.state()
    }

    pub(super) fn take(pool: &ring::Pool<T>) -> Option<T> {
        let mut state = pool.state.get();
        if state.is_empty() {
            return None;
        }
        // SAFETY: nonempty occupancy owns this value and reservations lend no payload.
        let value = unsafe { (*pool.storage.unlink(&mut state)).assume_init_read() };
        pool.state.set(state);
        Some(value)
    }

    pub(super) fn publish<const FRONT: bool>(lease: ring::Lease<'_, T>, value: T) {
        let pool = lease.pool;
        let mut state = pool.state.get();
        // SAFETY: this consumed reservation admits one write in the original pool.
        unsafe { pool.storage.write::<FRONT>(&mut state, value) };
        pool.state.set(state);
    }

    pub(super) fn retire_pool(pool: &mut ring::Pool<T>) {
        // SAFETY: exclusive ownership surrenders every resident value exactly once.
        let state = pool.state.replace(State::EMPTY);
        unsafe { pool.storage.drop_values(state) };
    }
}