o3 0.62.0

shared-nothing primitives
Documentation
use std::{mem, num::NonZero};

use crate::depot::arena::{self, linked};

/// Initialized slots retained by their exact owner until publication or refund.
#[must_use]
pub struct Batch<'a, N: arena::raw::LinkedNode, const C: usize> {
    pub(super) owner: &'a mut linked::raw::Fixed<N>,
    pub(super) indices: [mem::MaybeUninit<NonZero<u16>>; C],
    pub(super) len: u16,
    pub(super) next: u16,
}

impl<N: arena::raw::LinkedNode, const C: usize> Batch<'_, N, C> {
    /// Publishes the next reserved physical slot and lends its initialized node.
    pub fn take(&mut self) -> Option<(NonZero<u16>, &mut N)> {
        if self.next == self.len {
            return None;
        }
        // SAFETY: reserve initialized exactly len indices and retains all their
        // distinct live slots under this exclusive owner until publication.
        let index = unsafe {
            self.indices
                .get_unchecked(usize::from(self.next))
                .assume_init_read()
        };
        self.next += 1;
        let node = unsafe {
            self.owner
                .parts()
                .1
                .get_unchecked_mut(usize::from(index.get() - 1))
        };
        Some((index, node))
    }

    pub fn get_mut(&mut self, index: NonZero<u16>) -> Option<&mut N> {
        self.owner.get_mut(index)
    }
}

impl<N: arena::raw::LinkedNode, const C: usize> Drop for Batch<'_, N, C> {
    fn drop(&mut self) {
        if self.next == self.len {
            return;
        }
        let (state, nodes) = self.owner.parts();
        // SAFETY: all remaining indices were initialized at reservation. Neither
        // publication nor safe node access can free an unpublished reservation.
        let pending = unsafe {
            self.indices
                .get_unchecked(usize::from(self.next)..usize::from(self.len))
                .assume_init_ref()
        };
        for &index in pending {
            unsafe { state.recycle(index, nodes.get_unchecked_mut(usize::from(index.get() - 1))) };
        }
        state.available = state.available.wrapping_add(self.len - self.next);
    }
}