o3 0.62.0

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

use crate::{alloc, depot::map};

const EMPTY: u8 = 1 << 7;

pub(in crate::depot::map) struct Buckets {
    controls: ptr::NonNull<[u8]>,
    hashes: ptr::NonNull<mem::MaybeUninit<u64>>,
}

impl Buckets {
    const fn tag(hash: u64) -> u8 {
        (hash >> 57) as u8
    }

    unsafe fn control(&self, index: usize) -> ptr::NonNull<u8> {
        unsafe { self.controls.cast::<u8>().add(index) }
    }

    unsafe fn is_occupied(&self, index: usize) -> bool {
        unsafe { self.control(index).read() != EMPTY }
    }

    pub(in crate::depot::map) unsafe fn vacate(
        &mut self,
        bucket: map::raw::Occupied,
    ) -> map::raw::Vacant {
        let index = bucket.index();
        unsafe { self.control(index).write(EMPTY) };
        unsafe { map::raw::Vacant::new(index) }
    }

    unsafe fn publish(&mut self, index: usize, hash: u64) {
        unsafe {
            self.hashes.add(index).write(mem::MaybeUninit::new(hash));
            self.control(index).write(Self::tag(hash));
        }
    }

    fn reset(&mut self) {
        unsafe {
            self.controls
                .cast::<u8>()
                .write_bytes(EMPTY, self.controls.len())
        };
    }

    /// # Safety
    /// This nonempty directory retains a vacant bucket.
    pub(in crate::depot::map) unsafe fn vacant(&self, hash: u64) -> map::raw::Vacant {
        let mask = self.controls.len() - 1;
        let mut index = hash as usize & mask;
        while unsafe { self.is_occupied(index) } {
            index = (index + 1) & mask;
        }
        unsafe { map::raw::Vacant::new(index) }
    }
}

// SAFETY: a control is published only after its matching hash and payload.
unsafe impl map::raw::Directory for Buckets {
    type Occupied = map::raw::Occupied;

    fn buckets(&self) -> usize {
        self.controls.len()
    }

    unsafe fn hash(&self, index: usize) -> Option<u64> {
        if unsafe { self.is_occupied(index) } {
            Some(unsafe { self.hashes.add(index).read().assume_init() })
        } else {
            None
        }
    }

    unsafe fn candidate(&self, index: usize, hash: u64) -> map::raw::Candidate<Self::Occupied> {
        let control = unsafe { self.control(index).read() };
        if control == EMPTY {
            map::raw::Candidate::Vacant
        } else if control == Self::tag(hash)
            && unsafe { self.hashes.add(index).read().assume_init() } == hash
        {
            map::raw::Candidate::Occupied(unsafe { map::raw::Occupied::new(index) })
        } else {
            map::raw::Candidate::Skip
        }
    }
}

pub struct Table<P> {
    pub(in crate::depot::map) directory: Buckets,
    payloads: ptr::NonNull<mem::MaybeUninit<P>>,
}

impl<P> Table<P> {
    pub(crate) fn try_new(layout: map::raw::Layout<P>) -> Result<Self, alloc::Exhausted> {
        let fields = layout.bundle().try_allocate()?;
        // SAFETY: allocation binds these exact planes and bucket count to this layout.
        Ok(unsafe { Self::from_fields(fields, layout.buckets()) })
    }

    /// # Safety
    /// These exact planes and bucket count were admitted by one `Layout`: zero or a power of two, at most 2^31.
    /// All planes stay live, disjoint and exclusively owned through access and destruction; controls start uninitialized.
    pub unsafe fn from_fields(
        fields: alloc::raw::Fields<'_, <map::raw::Layout<P> as alloc::raw::Recipe>::Fields>,
        buckets: usize,
    ) -> Self {
        let mut entries = Buckets {
            controls: ptr::NonNull::slice_from_raw_parts(fields.prior().prior().root(), buckets),
            hashes: fields.prior().tail(),
        };
        if buckets != 0 {
            entries.reset();
        }
        Self {
            directory: entries,
            payloads: fields.tail(),
        }
    }

    pub const fn base(&self) -> ptr::NonNull<u8> {
        self.directory.controls.cast()
    }

    /// # Safety
    /// The bucket identifies an initialized payload in this exact live directory.
    pub unsafe fn payload(&self, bucket: &map::raw::Occupied) -> &P {
        let index = bucket.index();
        unsafe { (&*self.payloads.as_ptr().add(index)).assume_init_ref() }
    }

    /// # Safety
    /// The unchanged directory retains at least one initialized payload.
    pub(in crate::depot::map) unsafe fn minimum<K: Ord + ?Sized>(&self) -> map::raw::Occupied
    where
        P: Borrow<K>,
    {
        let mut index = 0;
        // SAFETY: an occupied bucket exists before the retained directory ends.
        while !unsafe { self.directory.is_occupied(index) } {
            index += 1;
        }
        let mut selected = unsafe { map::raw::Occupied::new(index) };
        for index in index + 1..self.directory.controls.len() {
            if unsafe { self.directory.is_occupied(index) } {
                let bucket = unsafe { map::raw::Occupied::new(index) };
                let value = <P as Borrow<K>>::borrow(unsafe { self.payload(&bucket) });
                let minimum = <P as Borrow<K>>::borrow(unsafe { self.payload(&selected) });
                if value < minimum {
                    selected = bucket;
                }
            }
        }
        selected
    }

    pub(crate) fn values(&self) -> impl Iterator<Item = &P> {
        (0..self.directory.controls.len()).filter_map(|index| {
            if !unsafe { self.directory.is_occupied(index) } {
                return None;
            }
            Some(unsafe { self.payload(&map::raw::Occupied::new(index)) })
        })
    }

    /// # Safety
    /// The bucket is occupied and initialized in this live directory; mutation preserves its hash and ownership.
    pub unsafe fn payload_mut(&mut self, bucket: &map::raw::Occupied) -> &mut P {
        let index = bucket.index();
        unsafe { (&mut *self.payloads.as_ptr().add(index)).assume_init_mut() }
    }

    pub fn clear(&mut self) {
        if !mem::needs_drop::<P>() {
            // SAFETY: this exclusive owner retains the complete control plane;
            // P has no destruction obligation before its membership is cleared.
            self.directory.reset();
            return;
        }
        for index in 0..self.directory.controls.len() {
            if !unsafe { self.directory.is_occupied(index) } {
                continue;
            }
            unsafe {
                self.directory.control(index).write(EMPTY);
                (&mut *self.payloads.as_ptr().add(index)).assume_init_drop();
            }
        }
    }

    unsafe fn write(&mut self, bucket: &map::raw::Vacant, hash: u64, payload: P) -> &mut P {
        let index = bucket.index();
        let value = unsafe { (&mut *self.payloads.as_ptr().add(index)).write(payload) };
        unsafe { self.directory.publish(index, hash) };
        value
    }

    pub(super) unsafe fn take(&mut self, bucket: map::raw::Occupied) -> P {
        unsafe { self.payloads.add(bucket.index()).read().assume_init() }
    }

    /// Publishes one bucket and returns its initialized value under the original loan.
    /// # Safety
    /// The bucket is vacant in this directory and was probed for this exact hash.
    pub unsafe fn insert(&mut self, bucket: map::raw::Vacant, hash: u64, payload: P) -> &mut P {
        unsafe { self.write(&bucket, hash, payload) }
    }

    /// # Safety
    /// Both buckets belong to this directory; `next` is initialized with `hash`, and `hole` is vacant.
    pub unsafe fn shift(
        &mut self,
        hole: &map::raw::Vacant,
        next: &map::raw::Occupied,
        hash: u64,
    ) -> (map::raw::Occupied, &mut P) {
        let source = unsafe { self.directory.control(next.index()) };
        let payload = unsafe { self.take(*next) };
        let value = unsafe { self.write(hole, hash, payload) };
        // SAFETY: source is a distinct control byte in this retained allocation.
        unsafe { source.write(EMPTY) };
        (unsafe { map::raw::Occupied::new(hole.index()) }, value)
    }
}