o3 0.62.0

shared-nothing primitives
Documentation
use std::{cmp, convert::Infallible, mem, ptr};

use crate::{
    alloc,
    depot::{
        heap,
        map::{self, priority::Plan},
    },
};

pub(super) mod entries;
pub(super) mod min;
pub(super) mod plan;

struct Node<K, V, P> {
    key: K,
    value: V,
    priority: P,
    bucket: u32,
    position: mem::MaybeUninit<u32>,
}

/// The heap occupies `0..len`. When `len < retired`, `len..retired` holds
/// the recycled slots. Otherwise every issued slot is live and the next is `len`.
struct Core<K, V, P: Ord> {
    table: map::raw::Table<u32>,
    nodes: ptr::NonNull<Node<K, V, P>>,
    indices: ptr::NonNull<u32>,
    plan: Plan<K, P, V>,
    len: u32,
    retired: u32,
}

impl<K, V, P: Ord> Core<K, V, P> {
    fn try_new(plan: Plan<K, P, V>) -> Result<Self, alloc::Exhausted> {
        let (bundle, buckets) = plan.into_bundle();
        let fields = bundle.try_allocate()?;
        // SAFETY: the plan admitted this directory, node plane and index plane together.
        let table = unsafe { map::raw::Table::from_fields(fields.prior().prior(), buckets) };
        Ok(Self {
            table,
            nodes: fields.prior().tail(),
            indices: fields.tail(),
            plan,
            len: 0,
            retired: 0,
        })
    }

    // SAFETY: index names an initialized resident of this core.
    unsafe fn node(&self, index: u32) -> &Node<K, V, P> {
        unsafe { self.nodes.add(index as usize).as_ref() }
    }

    // SAFETY: index names an initialized resident under this core's exclusive loan.
    unsafe fn node_mut(&mut self, index: u32) -> &mut Node<K, V, P> {
        unsafe { self.nodes.add(index as usize).as_mut() }
    }

    fn first(&self) -> Option<u32> {
        if self.len == 0 {
            return None;
        }
        // SAFETY: slot zero is initialized in the nonempty heap prefix.
        Some(unsafe { self.indices.read() })
    }

    fn probe(&self, hash: u64, key: &K) -> Option<map::Entry<u32, map::raw::Vacant>>
    where
        K: Eq,
    {
        // SAFETY: twice the logical capacity leaves a spare bucket in every nonempty directory.
        let Ok(found) =
            map::raw::scan::<_, Infallible, _, true>(&self.table.directory, hash, |bucket| {
                // SAFETY: the probe supplies an occupied bucket from this table.
                let index = unsafe { *self.table.payload(&bucket) };
                Ok(unsafe { self.node(index) }.key.eq(key).then_some(index))
            });
        found
    }

    fn find(&self, hash: u64, key: &K) -> Option<u32>
    where
        K: Eq,
    {
        match self.probe(hash, key)? {
            map::Entry::Occupied(index) => Some(index),
            map::Entry::Vacant(_) => None,
        }
    }
}

// SAFETY: each published bucket holds the stable index of the same live row.
// Backshift updates only the directory and that row's reverse bucket.
unsafe impl<K, V, P: Ord> map::raw::Shift for Core<K, V, P> {
    fn directory(&self) -> &impl map::raw::Directory {
        &self.table.directory
    }

    unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64) {
        let (bucket, index) = unsafe { self.table.shift(hole, next, hash) };
        let index = *index;
        unsafe { self.node_mut(index) }.bucket = bucket.index() as u32;
    }
}

// SAFETY: heap operations touch only the live index prefix or its admitted next slot.
// Each placement repairs the reverse heap position of that stable resident.
unsafe impl<K, V, P: Ord> heap::raw::Source for Core<K, V, P> {
    type Value = u32;

    fn len(&self) -> u32 {
        self.len
    }

    unsafe fn len_mut(&mut self) -> &mut u32 {
        &mut self.len
    }

    unsafe fn compare(&self, position: usize, index: &u32) -> cmp::Ordering {
        let other = unsafe { self.indices.add(position).read() };
        let left = &unsafe { self.node(*index) }.priority;
        let right = &unsafe { self.node(other) }.priority;
        (left, *index).cmp(&(right, other))
    }

    unsafe fn compare_at(&self, left: usize, right: usize) -> cmp::Ordering {
        let index = unsafe { self.indices.add(left).read() };
        unsafe { self.compare(right, &index) }
    }

    unsafe fn read<const REMOVE: bool>(&mut self, position: usize) -> u32 {
        unsafe { self.indices.add(position).read() }
    }

    unsafe fn shift(&mut self, source: usize, target: usize) {
        let index = unsafe { self.indices.add(source).read() };
        unsafe { self.write::<true>(target, index) };
    }

    unsafe fn write<const PLACE: bool>(&mut self, position: usize, index: u32) {
        unsafe { self.indices.add(position).write(index) };
        if PLACE {
            unsafe { self.node_mut(index) }
                .position
                .write(position as u32);
        }
    }
}

impl<K, V, P: Ord> Drop for Core<K, V, P> {
    fn drop(&mut self) {
        if mem::needs_drop::<Node<K, V, P>>() {
            for position in 0..self.len {
                // SAFETY: only the heap prefix owns live nodes, exactly once per index.
                unsafe {
                    let index = self.indices.add(position as usize).read();
                    self.nodes.add(index as usize).drop_in_place();
                }
            }
        }
        let (bundle, _) = self.plan.into_bundle();
        // SAFETY: all live nodes are retired and this is the original allocation base.
        unsafe { bundle.deallocate(self.table.base()) }
    }
}