o3 0.62.0

shared-nothing primitives
Documentation
use std::{borrow::Borrow, marker::PhantomData, mem};

use crate::{
    alloc,
    base::marker::ThreadBound,
    depot::{
        self, map,
        map::flat::{self, errors::Insert},
    },
};

type Entry<Q> = map::Entry<map::Found<Q>, map::Vacancy<Q, u64>>;

/// A bounded hash table owning its directory, payloads and exact live count.
pub struct Flat<V, C: depot::raw::Count = map::Plan> {
    table: map::raw::Table<V>,
    len: u32,
    capacity: C,
    thread: PhantomData<ThreadBound>,
}

impl<V, C: depot::raw::Count> Flat<V, C> {
    pub fn try_new(capacity: C) -> Result<Self, alloc::Error> {
        const { assert!(C::MAX as usize <= map::Plan::MAX.get()) };
        let layout = map::raw::Layout::try_plan(map::Plan {
            capacity: capacity.count(),
        })?;
        Ok(Self {
            table: map::raw::Table::try_new(layout)?,
            len: 0,
            capacity,
            thread: PhantomData,
        })
    }

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

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

    fn has_room(&self) -> bool {
        self.len < self.capacity.count().raw()
    }

    pub fn get(&self, hash: u64, matches: impl Fn(&V) -> bool) -> Option<&V> {
        map::raw::Query::find(self, hash, matches)
    }

    pub fn get_mut(&mut self, hash: u64, matches: impl Fn(&V) -> bool) -> Option<&mut V> {
        Some(self.occupied(hash, matches)?.into_mut())
    }

    pub fn occupied(
        &mut self,
        hash: u64,
        matches: impl Fn(&V) -> bool,
    ) -> Option<map::Found<&mut Self>> {
        map::raw::Query::find(self, hash, matches)
    }

    pub fn try_entry(
        &mut self,
        hash: u64,
        matches: impl Fn(&V) -> bool,
    ) -> Option<Entry<&mut Self>> {
        match map::raw::Insertion::entry(self, hash, matches) {
            map::Entry::Occupied(occupied) => Some(map::Entry::Occupied(occupied)),
            map::Entry::Vacant(vacant) => vacant.map(map::Entry::Vacant),
        }
    }

    pub fn try_insert(
        &mut self,
        hash: u64,
        value: V,
        matches: impl Fn(&V) -> bool,
    ) -> Result<(), Insert<V>> {
        match map::raw::Insertion::reserve(self, hash, matches) {
            map::Entry::Occupied(()) => Err(Insert::Occupied(value)),
            map::Entry::Vacant(None) => Err(Insert::Full(value)),
            map::Entry::Vacant(Some(vacant)) => {
                vacant.insert(value);
                Ok(())
            }
        }
    }

    /// Returns the minimum occupied entry when a new key exceeds logical capacity.
    pub fn entry_or_min<K: Ord + ?Sized>(
        &mut self,
        hash: u64,
        matches: impl Fn(&V) -> bool,
    ) -> Result<Entry<&mut Self>, map::Found<&mut Self>>
    where
        V: Borrow<K>,
    {
        const { assert!(C::MIN != 0) };
        // SAFETY: positive logical capacity retains a nonempty directory with a spare bucket.
        match unsafe { map::raw::spare(self, hash, matches) } {
            map::Entry::Occupied(found) => Ok(map::Entry::Occupied(found)),
            map::Entry::Vacant(vacant) if vacant.owner.has_room() => {
                Ok(map::Entry::Vacant(vacant.with_phase(hash)))
            }
            map::Entry::Vacant(vacant) => {
                let owner = vacant.owner;
                // SAFETY: this full table of positive capacity has a live minimum.
                let bucket = unsafe { owner.table.minimum::<K>() };
                Err(map::Found { owner, bucket })
            }
        }
    }

    /// # Safety
    /// This owner retains one unused logical entry.
    unsafe fn insert_new(&mut self, hash: u64, value: V) -> &mut V {
        let bucket = unsafe { self.table.directory.vacant(hash) };
        map::Vacancy {
            owner: self,
            bucket,
            phase: hash,
        }
        .insert(value)
    }

    pub fn remove(&mut self, hash: u64, matches: impl Fn(&V) -> bool) -> Option<V> {
        Some(self.occupied(hash, matches)?.remove())
    }

    pub fn values(&self) -> impl Iterator<Item = &V> + '_ {
        self.table.values()
    }

    pub fn clear(&mut self) {
        if !self.is_empty() {
            self.table.clear();
            self.len = 0;
        }
    }
}

impl<V, C: depot::raw::Count> Drop for Flat<V, C> {
    fn drop(&mut self) {
        if mem::needs_drop::<V>() && !self.is_empty() {
            self.table.clear();
        }
        // SAFETY: the exact payload recipe and count originally created this allocation.
        unsafe {
            let layout = map::raw::Layout::<V>::restore(map::Plan {
                capacity: self.capacity.count(),
            });
            layout.bundle().deallocate(self.table.base());
        }
    }
}

impl<'a, V, C: depot::raw::Count, D> depot::raw::Proof<(&'a mut Flat<V, C>, D), flat::Available> {
    /// Consumes logical capacity retained by the original caller.
    pub fn insert(self, hash: u64, value: V) -> (&'a mut V, D) {
        let (owner, context) = self.into_inner();
        // SAFETY: the consumed admission retains one unused logical entry.
        (unsafe { owner.insert_new(hash, value) }, context)
    }

    pub fn admit(self, hash: u64, matches: impl Fn(&V) -> bool) -> (Entry<&'a mut Flat<V, C>>, D) {
        let (owner, context) = self.into_inner();
        // SAFETY: the admitted owner retains a spare physical bucket throughout the probe.
        let entry = match unsafe { map::raw::spare(owner, hash, matches) } {
            map::Entry::Occupied(found) => map::Entry::Occupied(found),
            map::Entry::Vacant(vacant) => map::Entry::Vacant(vacant.with_phase(hash)),
        };
        (entry, context)
    }
}

impl<'a, V, C: depot::raw::Count, D, F: Fn(&V) -> bool>
    depot::raw::Proof<(&'a mut Flat<V, C>, D, u64, F), flat::Member>
{
    pub fn member(self) -> (map::Found<&'a mut Flat<V, C>>, D) {
        let (owner, context, hash, matches) = self.into_inner();
        // SAFETY: the consumed proof binds a matching live payload to this directory and hash.
        let bucket = unsafe {
            map::raw::member(&owner.table.directory, hash, |bucket| {
                matches(owner.table.payload(&bucket))
            })
        };
        (map::Found { owner, bucket }, context)
    }
}

impl<'a, V, C: depot::raw::Count> map::Found<&'a mut Flat<V, C>> {
    pub fn get(&self) -> &V {
        self.read().payload()
    }

    pub fn get_mut(&mut self) -> &mut V {
        self.reborrow().into_mut()
    }

    pub fn into_mut(self) -> &'a mut V {
        // SAFETY: this exclusive entry owns its initialized payload.
        unsafe { self.owner.table.payload_mut(&self.bucket) }
    }

    pub fn remove(self) -> V {
        self.owner.len -= 1;
        // SAFETY: the consumed capability binds its bucket to the exclusive owner through backshift.
        unsafe { map::raw::Hole::remove(self.owner, self.bucket) }
    }

    pub fn discard(self) {
        drop(self.remove());
    }

    pub fn replace(self, hash: u64, value: V) -> &'a mut V {
        let (owner, bucket) = self.into_parts();
        drop(
            map::Found {
                owner: &mut *owner,
                bucket,
            }
            .remove(),
        );
        // SAFETY: the completed removal left a logical and physical vacancy in this owner.
        unsafe { owner.insert_new(hash, value) }
    }
}

impl<'a, V, C: depot::raw::Count> map::Vacancy<&'a mut Flat<V, C>, u64> {
    pub fn insert(self, value: V) -> &'a mut V {
        // SAFETY: this admission retains the hash, bucket, exclusive owner and logical capacity.
        let value = unsafe { self.owner.table.insert(self.bucket, self.phase, value) };
        self.owner.len += 1;
        value
    }
}

const _: () = {
    assert!(mem::size_of::<Flat<()>>() == 5 * mem::size_of::<usize>());
    assert!(mem::align_of::<Flat<()>>() == mem::align_of::<usize>());
    assert!(mem::size_of::<Option<Flat<()>>>() == mem::size_of::<Flat<()>>());
    assert!(mem::size_of::<map::Found<&mut Flat<u64>>>() == 2 * mem::size_of::<usize>());
    assert!(mem::size_of::<map::Vacancy<&mut Flat<u64>, u64>>() == 3 * mem::size_of::<usize>());
};

// SAFETY: live payloads retain their original directory and a nonempty directory always has a spare bucket.
unsafe impl<'a, V, C: depot::raw::Count> map::raw::Query for &'a Flat<V, C> {
    const SPARE: bool = true;
    const NONEMPTY: bool = C::MIN != 0;
    type Payload = V;
    type Value = V;
    type Occupied = &'a V;

    fn table(&self) -> &map::raw::Table<V> {
        &self.table
    }

    fn value(entry: map::Found<&Self>) -> &V {
        entry.payload()
    }

    fn occupied(entry: map::Found<Self>) -> Self::Occupied {
        let (owner, bucket) = entry.into_parts();
        unsafe { owner.table.payload(&bucket) }
    }
}

// SAFETY: the exclusive loan retains the same bounds, payloads and vacancy guarantee.
unsafe impl<V, C: depot::raw::Count> map::raw::Query for &mut Flat<V, C> {
    const SPARE: bool = true;
    const NONEMPTY: bool = C::MIN != 0;
    type Payload = V;
    type Value = V;
    type Occupied = map::Found<Self>;

    fn table(&self) -> &map::raw::Table<V> {
        &self.table
    }

    fn value(entry: map::Found<&Self>) -> &V {
        entry.payload()
    }

    fn occupied(entry: map::Found<Self>) -> Self::Occupied {
        entry
    }
}

// SAFETY: a physical vacancy gains insertion authority only while logical room remains.
unsafe impl<V, C: depot::raw::Count> map::raw::Insertion for &mut Flat<V, C> {
    type Vacant = map::Vacancy<Self, u64>;

    fn vacant(entry: map::Vacancy<Self>, hash: u64) -> Option<Self::Vacant> {
        if entry.source().has_room() {
            Some(entry.with_phase(hash))
        } else {
            None
        }
    }
}

// SAFETY: the exclusive flat owner has no external reverse index to repair during backshift.
unsafe impl<V, C: depot::raw::Count> map::raw::Mutation for &mut Flat<V, C> {
    unsafe fn table_mut(&mut self) -> &mut map::raw::Table<V> {
        &mut self.table
    }

    unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64) {
        unsafe { self.table.shift(hole, next, hash) };
    }
}