o3 0.62.0

shared-nothing primitives
Documentation
use std::{mem, ops::ControlFlow, ptr};

use node::Node;

pub(in crate::depot) mod node;

use crate::depot::{
    array::Index,
    capacity,
    index::Initialized,
    map::direct,
    queue::{indexed::lanes::entry, links},
};

type Selection<'a, K, V, const N: usize> =
    ControlFlow<entry::raw::Slot<'a, K, V, N, true>, entry::raw::Slot<'a, K, V, N, false>>;

/// Key-indexed values and their exclusive FIFO membership.
pub struct Table<K: crate::depot::raw::Key, V, const N: usize> {
    pub(in crate::depot) values: direct::Table<K, Node<V, N>>,
    pub(in crate::depot) queues: [links::raw::Chain; N],
}

// SAFETY: the retained table keeps each admitted hook initialized independently of its payload.
unsafe impl<K: crate::depot::raw::Key, V, const N: usize> crate::depot::raw::Hooks
    for direct::Table<K, Node<V, N>>
{
    unsafe fn hook_raw(&self, index: links::Index) -> &links::Hook {
        // SAFETY: this admitted hook remains initialized at its stable address,
        // independently of the resident payload.
        unsafe {
            let row = self.block.as_ptr().add(index.get());
            let node = ptr::addr_of!((*row).value).cast::<Node<V, N>>();
            &*ptr::addr_of!((*node).hook)
        }
    }
}

impl<K: crate::depot::raw::Key, V, const N: usize> Table<K, V, N> {
    /// Bytes reserved for each exact key, value, and its lane links.
    pub const NODE_BYTES: usize = mem::size_of::<direct::raw::Entry<K, Node<V, N>>>();

    pub fn try_new(cap: capacity::Count) -> Result<Self, crate::alloc::Error> {
        const { assert!(N <= u8::MAX as usize) };
        Ok(Self {
            values: direct::Table::try_new(cap)?,
            queues: [const { links::raw::Chain::new() }; N],
        })
    }

    pub const fn capacity(&self) -> usize {
        self.values.capacity()
    }

    pub const fn len(&self) -> usize {
        self.values.len()
    }

    pub const fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    pub fn get(&self, key: K) -> Option<&V> {
        self.values.get(key).map(|node| &node.value)
    }

    pub fn entry_at_mut(&mut self, index: usize) -> Option<entry::raw::Slot<'_, K, V, N, true>> {
        let (key, row) = self.values.entry_row(index)?;
        Some(entry::raw::Slot {
            root: self,
            key,
            row,
        })
    }

    pub fn key_at(&self, index: usize) -> Option<K> {
        self.values.key_at(index)
    }

    pub fn try_vacant(
        &mut self,
        key: K,
    ) -> Result<entry::raw::Slot<'_, K, V, N, false>, direct::Error<K>> {
        match self.select(key)? {
            ControlFlow::Continue(vacant) => Ok(vacant),
            ControlFlow::Break(occupied) => Err(direct::Error::Occupied {
                key,
                stored: occupied.key(),
            }),
        }
    }

    pub fn entry(&mut self, key: K) -> Option<entry::raw::Slot<'_, K, V, N, true>> {
        self.select(key).ok()?.break_value()
    }

    pub fn select(&mut self, key: K) -> Result<Selection<'_, K, V, N>, direct::Error<K>> {
        Ok(match self.values.select_row(key)? {
            ControlFlow::Break(row) => ControlFlow::Break(entry::raw::Slot {
                root: self,
                key,
                row,
            }),
            ControlFlow::Continue(row) => ControlFlow::Continue(entry::raw::Slot {
                root: self,
                key,
                row,
            }),
        })
    }

    pub fn front(&mut self, lane: Index<N>) -> Option<entry::raw::Slot<'_, K, V, N, true>> {
        let index = lane.get(&self.queues).first()?;
        // SAFETY: this root's queue retains its exact initialized front row.
        let (key, row) = unsafe { direct::raw::Entry::occupied(&mut self.values, index.get()) };
        Some(entry::raw::Slot {
            root: self,
            key,
            row,
        })
    }

    pub fn back(&self, lane: Index<N>) -> Option<K> {
        let index = lane.get(&self.queues).last()?;
        // SAFETY: this exact queue's retained tail belongs to the paired table.
        let live = unsafe {
            crate::depot::raw::Proof::<(_, _), Initialized<()>>::new((&self.values, index))
        };
        Some(direct::Table::project(live).1)
    }

    pub fn is_vacant(&self, lane: Index<N>) -> bool {
        lane.get(&self.queues).is_empty()
    }

    pub fn move_all(&mut self, source: Index<N>, target: Index<N>) -> usize {
        move_all(&self.values, &self.queues, source, target)
    }

    pub fn clear(&mut self) {
        if self.is_empty() {
            return;
        }
        self.queues = [const { links::raw::Chain::new() }; N];
        self.values.clear();
    }
}

pub(super) fn move_all<K: crate::depot::raw::Key, V, const N: usize>(
    values: &direct::Table<K, Node<V, N>>,
    queues: &[links::raw::Chain; N],
    source: Index<N>,
    target: Index<N>,
) -> usize {
    if source == target {
        return 0;
    }
    let source = source.get(queues);
    let Some(head) = source.first() else { return 0 };
    // SAFETY: the source head identifies this initialized node for the entire transfer.
    let first = unsafe { values.value(head) };
    let mut node = first;
    let mut moved = 0;
    loop {
        node.lane.set(Some(target));
        moved += 1;
        let Some(next) = node.hook.next_index() else {
            break;
        };
        node = unsafe { values.value(next) };
    }
    let target = target.get(queues);
    let join = target
        .last()
        .map(|last| (&first.hook, last, &unsafe { values.value(last) }.hook));
    // SAFETY: the distinct source and target still retain their original reciprocal endpoints.
    unsafe { target.splice(source, head, join) };
    moved
}