o3 0.62.0

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

use crate::{
    alloc::array,
    depot::{
        capacity,
        index::Stored,
        map::direct::{
            self,
            sealed::{Live, Selection},
        },
        queue::links,
    },
};

/// One-allocation direct table for caller-owned exact keys.
pub struct Table<K: crate::depot::raw::Key, V> {
    pub(in crate::depot) block:
        array::raw::Block<direct::raw::Entry<K, V>, capacity::Count, capacity::Count>,
}

impl<K: crate::depot::raw::Key, V> Table<K, V> {
    /// Allocates and initializes one exact backing table.
    pub fn try_new(capacity: capacity::Count) -> Result<Self, crate::alloc::Error> {
        let block = array::raw::Block::try_new(capacity, capacity::Count::EMPTY)?
            .repeat_with(direct::raw::Entry::vacant);
        Ok(Self { block })
    }

    pub const fn capacity(&self) -> usize {
        self.block.extent().get()
    }

    pub const fn len(&self) -> usize {
        self.block.state().get()
    }

    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// # Safety
    /// `index` is occupied in this exact table for the retained borrow.
    pub(in crate::depot) unsafe fn value(&self, index: links::Index) -> &V {
        unsafe {
            self.block
                .get_unchecked(index.get())
                .value
                .assume_init_ref()
        }
    }

    /// # Safety
    /// This table exclusively retains a vacant row at `key`'s admitted index.
    /// Its value is fully initialized without other loans.
    pub(in crate::depot) unsafe fn publish(
        &mut self,
        row: ptr::NonNull<direct::raw::Entry<K, V>>,
        key: K,
    ) {
        unsafe { ptr::addr_of_mut!((*row.as_ptr()).key).write(key.into_raw()) };
        let len = self.block.state_mut();
        *len = capacity::Count::new((len.get() + 1) as u32);
    }

    /// # Safety
    /// This table owns this row. Its key and count are exclusively accessible.
    /// The returned pointer does not end any outstanding payload loan.
    pub(in crate::depot) unsafe fn vacate(
        &mut self,
        row: ptr::NonNull<direct::raw::Entry<K, V>>,
    ) -> ptr::NonNull<V> {
        let len = self.block.state_mut();
        *len = capacity::Count::new((len.get() - 1) as u32);
        // SAFETY: only the exact key changes; the payload retains its original address.
        unsafe {
            ptr::addr_of_mut!((*row.as_ptr()).key).write(K::VACANT);
            direct::raw::Entry::payload(row)
        }
    }

    pub fn get(&self, key: K) -> Option<&V> {
        let slot = self.block.get(key.index())?;
        (slot.key == key.into_raw()).then(|| unsafe { slot.value.assume_init_ref() })
    }

    pub fn entry_at(&self, index: usize) -> Option<(K, &V)> {
        let row = self.block.get(index)?;
        Some((row.key()?, unsafe { row.value.assume_init_ref() }))
    }

    pub(in crate::depot) fn entry_row(
        &mut self,
        index: usize,
    ) -> Option<(K, ptr::NonNull<direct::raw::Entry<K, V>>)> {
        let row = self.block.get_mut(index)?;
        let key = row.key()?;
        Some((key, ptr::NonNull::from(row)))
    }

    pub fn key_at(&self, index: usize) -> Option<K> {
        self.block.get(index)?.key()
    }

    /// Returns the raw address and complete identity of the admitted slot.
    pub fn project<P>(live: Live<&Self, P>) -> (ptr::NonNull<V>, K) {
        let (read, index) = live.into_inner();
        // SAFETY: the retained proof names this initialized slot and its emitted key.
        unsafe {
            let row = ptr::NonNull::new_unchecked(read.block.as_ptr().add(index.get()).cast_mut());
            (
                direct::raw::Entry::payload(row),
                direct::raw::Entry::identity(row),
            )
        }
    }

    pub fn select(
        &mut self,
        key: K,
    ) -> Selection<K, direct::Occupied<'_, K, V>, direct::raw::Vacant<'_, K, V>> {
        Ok(match self.select_row(key)? {
            ControlFlow::Break(row) => ControlFlow::Break(direct::Occupied {
                table: self,
                row,
                plane: marker::PhantomData,
            }),
            ControlFlow::Continue(_) => ControlFlow::Continue(direct::raw::Vacant {
                table: self,
                key,
                plane: marker::PhantomData,
            }),
        })
    }

    pub(in crate::depot) fn select_row(
        &mut self,
        key: K,
    ) -> Selection<K, ptr::NonNull<direct::raw::Entry<K, V>>> {
        let index = key.index();
        let capacity = self.capacity();
        let row = self.block.get_mut(index).ok_or(direct::Error::Outside {
            key,
            index,
            capacity,
        })?;
        let stored = row.key;
        let row = ptr::NonNull::from(row);
        if stored == key.into_raw() {
            return Ok(ControlFlow::Break(row));
        }
        if stored == K::VACANT {
            return Ok(ControlFlow::Continue(row));
        }
        // SAFETY: this initialized row retains its complete non-vacant key encoding.
        let stored = K::from_raw(unsafe { Stored::new(stored) });
        Err(direct::Error::Occupied { key, stored })
    }

    pub fn clear(&mut self) {
        if self.is_empty() {
            return;
        }
        let (len, entries) = self.block.parts_mut();
        for entry in entries {
            if entry.key != K::VACANT {
                *entry = direct::raw::Entry::vacant();
            }
        }
        *len = capacity::Count::EMPTY;
    }
}