o3 0.62.0

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

use crate::depot::{capacity::Physical, index::bitmap};

/// One checked position retaining its original source owner.
pub struct Row<S, P = (), M = (), W = usize> {
    pub(in crate::depot::index::bitmap) phase: Phase<M, W>,
    pub(in crate::depot::index::bitmap) plane: P,
    pub(in crate::depot) source: S,
    pub(in crate::depot::index::bitmap) index: NonZero<u32>,
}

impl<S: Copy, W> Clone for Row<S, (), (), W> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<S: Copy, W> Copy for Row<S, (), (), W> {}

impl<W: bitmap::Width, S: crate::depot::raw::Words<W>> Row<S, (), (), W> {
    /// Projects an admitted one-based row position in its exact source domain.
    /// This retains a physical bound, without claiming current membership.
    pub fn from_source(source: crate::depot::raw::Proof<(S, NonZero<u32>), Physical>) -> Self {
        let (source, index) = source.into_inner();
        Self {
            source,
            index,
            plane: (),
            phase: marker::PhantomData,
        }
    }

    pub fn try_new(source: S, index: usize) -> Result<Self, bitmap::Error> {
        let capacity = source.shape().bits();
        if index >= capacity {
            return Err(bitmap::Error { index, capacity });
        }
        // SAFETY: admission bounds this index in the exact retained source.
        Ok(unsafe { Self::new(source, index) })
    }

    /// # Safety
    /// The index belongs to this exact retained source's immutable domain.
    pub(in crate::depot) unsafe fn new(source: S, index: usize) -> Self {
        // SAFETY: the retained u32 domain bounds the nonzero encoded position.
        let index = unsafe { NonZero::new_unchecked(index as u32 + 1) };
        // SAFETY: the same retained domain admits this one-based row position.
        Self::from_source(unsafe { crate::depot::raw::Proof::new((source, index)) })
    }
}

impl<W: bitmap::Width, S: crate::depot::raw::Words<W>, P, M> Row<S, P, M, W> {
    /// # Safety
    /// Mutation preserves this source's storage, immutable domain, row, and phase membership.
    pub unsafe fn source_mut(&mut self) -> &mut S {
        &mut self.source
    }

    pub(in crate::depot) const fn plane(&self) -> P
    where
        P: Copy,
    {
        self.plane
    }

    pub(in crate::depot::index::bitmap) fn borrow(&self) -> Row<&S, (), (), W> {
        Row {
            source: &self.source,
            index: self.index,
            plane: (),
            phase: marker::PhantomData,
        }
    }

    pub const fn index(&self) -> usize {
        self.index.get() as usize - 1
    }

    pub fn contains(&self, plane: S::Plane) -> bool {
        let index = self.index();
        let words = S::row(self.borrow(), plane);
        // SAFETY: this row retains the checked position in its exact plane.
        let word = unsafe { words.get_unchecked(index / W::BITS as usize) };
        word.get() & (1usize << (index % W::BITS as usize)) != 0
    }
}

impl<W: bitmap::Width, S: crate::depot::raw::Words<W>, P> Row<S, P, (), W> {
    pub const fn source(&self) -> &S {
        &self.source
    }
}

impl<'a, W: bitmap::Width, S: crate::depot::raw::Bitmap<W>> Row<&'a mut S, (), (), W> {
    pub fn occupied(
        self,
        plane: S::Plane,
    ) -> Result<Mutable<'a, S, Occupied, W>, Mutable<'a, S, Absent, W>> {
        let entry: Row<_, _, (), W> = Row {
            source: self.source,
            index: self.index,
            plane,
            phase: marker::PhantomData,
        };
        if entry.contains(plane) {
            Ok(entry.with_phase())
        } else {
            Err(entry.with_phase())
        }
    }
}

impl<W: bitmap::Width, S: crate::depot::raw::Words<W, Size = NonZero<u32>>> Row<S, (), (), W> {
    /// Selects the requested row, saturating at this nonempty source's final row.
    pub fn clamp(source: S, index: usize) -> Self {
        let capacity = source.shape().bits;
        let index = index.min(capacity.get() as usize - 1);
        // SAFETY: the nonzero exact domain and clamp bound this encoded position.
        unsafe { Self::new(source, index) }
    }
}

impl<S, P, M, W> Row<S, P, M, W> {
    /// The compact one-based position retained by this row's source proof.
    pub const fn position(&self) -> NonZero<u32> {
        self.index
    }

    pub(in crate::depot) fn with_phase<N>(self) -> Row<S, P, N, W> {
        Row {
            source: self.source,
            index: self.index,
            plane: self.plane,
            phase: marker::PhantomData,
        }
    }
}

/// An exclusive row retains its bitmap owner and selected plane across phase changes.
type Mutable<'a, S, P, W> = Row<&'a mut S, <S as crate::depot::raw::Words<W>>::Plane, P, W>;

type Phase<M, W> = marker::PhantomData<fn(M, W) -> (M, W)>;

const _: () = {
    assert!(size_of::<Row<&()>>() == 2 * size_of::<usize>());
    assert!(size_of::<Option<Row<&()>>>() == size_of::<Row<&()>>());
};

/// One set bit kept unchanged by an exclusive borrow of its source.
pub struct Occupied;

impl<'a, W: bitmap::Width, S: crate::depot::raw::Bitmap<W>> Row<&'a mut S, S::Plane, Occupied, W> {
    pub fn remove(self) -> Row<&'a mut S, S::Plane, Removed, W> {
        let row: Row<_, _, (), W> = self.with_phase();
        row.update::<false>(row.plane());
        row.with_phase()
    }
}

/// Failed occupancy admission retaining the exact checked source and index.
pub struct Absent;

/// A completed removal retaining its original bounded row and source plane.
pub struct Removed;

pub(in crate::depot::index::bitmap) struct Level<'a, W: bitmap::Width> {
    words: &'a [bitmap::Word<W>],
    bits: usize,
}

impl<'a, W: bitmap::Width> Level<'a, W> {
    pub(in crate::depot::index::bitmap) fn new<S: crate::depot::raw::Words<W>>(
        source: &'a S,
        plane: S::Plane,
    ) -> Self {
        Self {
            words: source.words(plane),
            bits: source.shape().bits(),
        }
    }

    pub(in crate::depot::index::bitmap) fn find(
        &self,
        mut start: usize,
    ) -> Option<(NonZero<u32>, W)> {
        let mut count = NonZero::new(self.bits)?;
        let mut offset = 0;
        let mut shift = 0;
        let radix = NonZero::<usize>::MIN.saturating_add(W::BITS as usize - 1);
        loop {
            if start >= count.get() {
                return None;
            }
            let mut index = start / radix;
            // SAFETY: the checked position belongs to this exact level; each
            // preceding level contributes exactly its word count to offset.
            let word = unsafe { self.words.get_unchecked(offset + index) };
            let mut current = word.value.get();
            let bits = (current & (!W::ZERO << (start % radix))).offset();
            if let Some(mut bits) = NonZero::new(bits) {
                loop {
                    if shift == 0 {
                        let position = index * radix.get() + bits.trailing_zeros() as usize;
                        return Some((
                            // SAFETY: exact tail bits and this source's u32 domain bound the selection.
                            unsafe { NonZero::new_unchecked(position as u32 + 1) },
                            current,
                        ));
                    }
                    index = index * radix.get() + bits.trailing_zeros() as usize;
                    offset -= ((self.bits - 1) >> shift) + 1;
                    shift -= W::BITS.trailing_zeros();
                    // SAFETY: offset subtracts this preceding level's exact length;
                    // the set summary bit proves this exact child is nonempty.
                    let word = unsafe { self.words.get_unchecked(offset + index) };
                    current = word.value.get();
                    bits = unsafe { NonZero::new_unchecked(current.offset()) };
                }
            }
            let words = count.div_ceil(radix);
            if words.get() == 1 {
                return None;
            }
            offset += words.get();
            count = words;
            start = index + 1;
            shift += W::BITS.trailing_zeros();
        }
    }

    /// # Safety
    /// The index belongs to this level's exact retained source and plane.
    unsafe fn update<const SET: bool>(&self, index: usize) {
        // SAFETY: the retained row supplies this exact first leaf position.
        let word = unsafe { self.words.get_unchecked(index / W::BITS as usize) };
        // SAFETY: observation and update retain this source without intervening mutation.
        unsafe { self.write::<SET>(index, word.value.get()) };
    }

    /// # Safety
    /// `index` belongs to this exact source and `current` is its unchanged leaf word.
    pub(in crate::depot::index::bitmap) unsafe fn write<const SET: bool>(
        &self,
        mut index: usize,
        mut current: W,
    ) {
        let mut words = self.words;
        // SAFETY: a retained row is strictly below bits, so the domain is nonempty.
        let mut count = unsafe { NonZero::new_unchecked(self.bits) };
        let radix = NonZero::<usize>::MIN.saturating_add(W::BITS as usize - 1);
        count = count.div_ceil(radix);
        loop {
            let offset = index / W::BITS as usize;
            let word = unsafe { words.get_unchecked(offset) };
            // SAFETY: both sealed primitive widths represent the bit value one.
            let mask = unsafe { W::from_offset(1) } << (index % W::BITS as usize);
            let next = if SET { current | mask } else { current & !mask };
            word.value.set(next);
            let stable = if SET {
                current != W::ZERO
            } else {
                next != W::ZERO
            };
            if stable || count.get() == 1 {
                return;
            }
            words = unsafe { words.get_unchecked(count.get()..) };
            count = count.div_ceil(radix);
            index = offset;
            // SAFETY: the exact summary hierarchy contains this parent word;
            // prior propagation changed only its child, not the parent itself.
            current = unsafe { words.get_unchecked(index / W::BITS as usize) }
                .value
                .get();
        }
    }
}

impl<W: bitmap::Width, S: crate::depot::raw::Words<W>, P> Row<S, P, (), W> {
    pub fn update<const SET: bool>(&self, plane: S::Plane) {
        let level = Level {
            words: S::row(self.borrow(), plane),
            bits: self.source.shape().bits(),
        };
        // SAFETY: this retained row bounds its position in the exact selected plane.
        unsafe { level.update::<SET>(self.index()) };
    }
}