o3 0.62.0

shared-nothing primitives
Documentation
//! Fixed lazy storage and its slot reservations.

use std::{mem, num::NonZero};

use crate::{
    alloc::{self, array},
    base::marker::ThreadBound,
    depot::{
        arena::{self, linked},
        array::copy,
        capacity,
    },
};

/// Fixed lazy storage for dropless nodes with an embedded free link.
///
/// Physical indices identify the current slot, not an occupant generation.
pub struct Fixed<N: arena::raw::LinkedNode> {
    nodes: array::raw::Block<mem::MaybeUninit<N>, u16, State>,
}

pub(super) struct State {
    free: Option<NonZero<u16>>,
    initialized: u16,
    pub(super) available: u16,
    _thread: ThreadBound,
}

impl State {
    /// # Safety
    /// This is the exact live node at index in this state's backing. Its sole
    /// return right is transferred here before its reserved credit is refunded.
    pub(super) unsafe fn recycle<N: arena::raw::LinkedNode>(
        &mut self,
        index: NonZero<u16>,
        node: &mut N,
    ) {
        unsafe { node.set_next(Some(self.free.unwrap_or(index))) };
        self.free = Some(index);
    }
}

impl<N: arena::raw::LinkedNode> Fixed<N> {
    /// Admits at most u16::MAX resident slots before allocating their backing.
    pub fn try_new(capacity: capacity::Count) -> Result<Self, alloc::Error> {
        const {
            assert!(!mem::needs_drop::<N>());
            assert!(mem::size_of::<Self>() == mem::size_of::<usize>() + 8);
        }
        let Ok(count) = u16::try_from(capacity.raw()) else {
            return Err(alloc::Overflow.into());
        };
        let state = State {
            free: None,
            initialized: 0,
            available: count,
            _thread: ThreadBound::NEW,
        };
        Ok(Self {
            nodes: array::raw::Block::try_new(count, state)?,
        })
    }

    /// Reserves and initializes the complete batch before lending its exact owner.
    pub fn reserve<const C: usize>(
        &mut self,
        inputs: &copy::Vec<N::Input, C>,
    ) -> Option<linked::raw::Batch<'_, N, C>> {
        let (state, nodes) = self.nodes.parts_mut();
        if inputs.len() > usize::from(state.available) {
            return None;
        }
        let len = inputs.len() as u16;
        state.available -= len;
        let mut indices = [const { mem::MaybeUninit::uninit() }; C];
        for (target, &input) in indices.iter_mut().zip(inputs.iter()) {
            let index = if let Some(index) = state.free {
                // SAFETY: the free head names an initialized slot in these nodes.
                let node = unsafe {
                    nodes
                        .get_unchecked_mut(usize::from(index.get() - 1))
                        .assume_init_mut()
                };
                let next = node.next();
                node.reset(input);
                unsafe { node.set_next(None) };
                state.free = if next == Some(index) { None } else { next };
                index
            } else {
                let offset = state.initialized;
                // SAFETY: one debited credit and an empty free chain prove
                // offset < capacity <= u16::MAX. Each new node extends the prefix.
                unsafe { nodes.get_unchecked_mut(usize::from(offset)) }.write(N::new(input));
                state.initialized = offset.wrapping_add(1);
                unsafe { NonZero::new_unchecked(state.initialized) }
            };
            target.write(index);
        }
        Some(linked::raw::Batch {
            owner: self,
            indices,
            len,
            next: 0,
        })
    }

    pub fn get(&self, index: NonZero<u16>) -> Option<&N> {
        if index.get() > self.nodes.state().initialized {
            return None;
        }
        // SAFETY: all positions below initialized have been written.
        let node = unsafe {
            self.nodes
                .get_unchecked(usize::from(index.get() - 1))
                .assume_init_ref()
        };
        node.next().is_none().then_some(node)
    }

    pub fn get_mut(&mut self, index: NonZero<u16>) -> Option<&mut N> {
        let node = self.parts().1.get_mut(usize::from(index.get() - 1))?;
        node.next().is_none().then_some(node)
    }

    /// Lends both live slots only when the physical indices are distinct.
    pub fn pair_mut(&mut self, indices: [NonZero<u16>; 2]) -> Option<[&mut N; 2]> {
        let [a, b] = indices;
        let [left, right] = self
            .parts()
            .1
            .get_disjoint_mut([usize::from(a.get() - 1), usize::from(b.get() - 1)])
            .ok()?;
        if left.next().is_some() || right.next().is_some() {
            return None;
        }
        Some([left, right])
    }

    pub fn remove(&mut self, index: NonZero<u16>) -> Option<linked::raw::Released> {
        let (state, nodes) = self.parts();
        let node = nodes.get_mut(usize::from(index.get() - 1))?;
        if node.next().is_some() {
            return None;
        }
        // SAFETY: the exclusive initialized slot was live at this exact index.
        unsafe { state.recycle(index, node) };
        state.available = state.available.wrapping_add(1);
        Some(linked::raw::Released)
    }

    pub(super) fn parts(&mut self) -> (&mut State, &mut [N]) {
        let (state, nodes) = self.nodes.parts_mut();
        // SAFETY: fresh inserts extend this prefix only after N is initialized;
        // recycled nodes keep their initialization throughout their lifetime.
        let nodes = unsafe {
            nodes
                .get_unchecked_mut(..usize::from(state.initialized))
                .assume_init_mut()
        };
        (state, nodes)
    }
}