o3 0.60.0

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

use crate::{
    alloc,
    depot::{
        capacity, heap,
        queue::{Sweep, links},
    },
};

pub struct Min<P: Ord, V> {
    storage: Storage<P, V>,
    ready: links::Chain<()>,
    free: links::Free,
}

pub type Vacant<'a, P, V> = heap::Vacancy<&'a mut Min<P, V>, heap::Direct>;
pub type Minimum<'a, P, V> = heap::Entry<&'a mut Min<P, V>, heap::indexed::Full>;

pub struct Front<'a, P: Ord, V> {
    owner: &'a mut Min<P, V>,
    index: links::Index,
}

pub(in crate::depot) struct Node<V> {
    hook: links::Hook,
    value: mem::MaybeUninit<V>,
}

type Storage<P, V> = alloc::raw::Block<
    heap::Capacity<heap::Stored<heap::Direct, P>, u32, Node<V>>,
    u32,
    ptr::NonNull<Node<V>>,
>;

impl<P: Ord, V> Min<P, V> {
    pub fn try_new(capacity: capacity::Count) -> Result<Self, heap::Error> {
        let count = capacity.get();
        let storage = heap::Capacity::try_new(capacity)?
            .allocate()?
            .enumerate(|index| Node {
                hook: links::Hook::vacant(
                    index as u32,
                    if index + 1 == count {
                        links::Index::END
                    } else {
                        (index + 1) as u32
                    },
                ),
                value: mem::MaybeUninit::uninit(),
            });
        Ok(Self {
            storage,
            ready: links::Chain::new(),
            free: links::Free::seeded(count),
        })
    }

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

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

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

    pub fn min(&self) -> Option<&P> {
        Some(heap::raw::Store::peek(self)?.1)
    }

    pub fn min_entry(&mut self) -> Option<Minimum<'_, P, V>> {
        Some(heap::Entry::first(self)?.with_key(heap::indexed::Full))
    }

    pub fn front(&mut self) -> Option<Front<'_, P, V>> {
        let index = self.ready.first()?;
        Some(Front { owner: self, index })
    }

    pub fn vacant(&mut self) -> Option<Vacant<'_, P, V>> {
        let index = self.free.front()?;
        // The retained free head proves spare capacity and this exact absent identity.
        let key = unsafe { heap::Direct::from_index(index.get()) };
        Some(unsafe { heap::Vacancy::new(self, key) })
    }

    pub fn sweep(&mut self) -> Sweep<'_, Self> {
        let remaining = self.len();
        Sweep {
            owner: self,
            remaining,
        }
    }

    // The private callers retain this exact live resident in the reverse map.
    unsafe fn position(&self, index: links::Index) -> usize {
        unsafe { *self.storage.tail().get_unchecked(index.get()) as usize }
    }

    fn remove<const FRONT: bool>(entry: heap::Entry<&mut Self>) -> (P, V) {
        let (vacant, priority) = entry.remove_slot();
        let owner = vacant.owner;
        // Heap removal returns the same admitted resident identity.
        let index = unsafe { links::Index::new_usize(vacant.value.get()) };
        let value = unsafe {
            owner
                .storage
                .values_mut()
                .get_unchecked_mut(index.get())
                .value
                .assume_init_read()
        };
        // Only Front::remove supplies FRONT; minimum removal may select any FIFO position.
        let vacant = unsafe {
            if FRONT {
                owner.ready.pop(&owner.storage, index).0
            } else {
                owner.ready.unlink(&owner.storage, index)
            }
        };
        owner.free.recycle(vacant);
        (priority, value)
    }
}

impl<P: Ord, V> Front<'_, P, V> {
    pub fn priority(&self) -> &P {
        // This front retains the initialized resident and its exact heap position.
        let position = unsafe { self.owner.position(self.index) };
        unsafe {
            &self
                .owner
                .storage
                .as_ref()
                .get_unchecked(position)
                .assume_init_ref()
                .priority
        }
    }

    pub fn get_mut(&mut self) -> &mut V {
        // This exact front owns the sole mutable payload loan.
        unsafe {
            self.owner
                .storage
                .values_mut()
                .get_unchecked_mut(self.index.get())
                .value
                .assume_init_mut()
        }
    }

    pub fn move_to_back(self) {
        // Every Front is the original ready head; rotation changes no priority.
        let hook = unsafe { crate::depot::raw::Hooks::hook_raw(&self.owner.storage, self.index) };
        unsafe {
            self.owner
                .ready
                .rotate(&self.owner.storage, self.index, hook, true)
        };
    }

    pub fn remove(self) -> (P, V) {
        let position = unsafe { self.owner.position(self.index) };
        // The reverse map and exclusive front loan retain this initialized heap slot.
        let entry = unsafe { heap::Entry::new(self.owner, position, ()) };
        Min::remove::<true>(entry)
    }
}

impl<P: Ord, V> Minimum<'_, P, V> {
    pub fn priority(&self) -> &P {
        &self.value().priority
    }

    pub fn pop(self) -> (P, V) {
        Min::remove::<false>(self.with_key(()))
    }
}

impl<P: Ord, V> Vacant<'_, P, V> {
    pub fn push_back(self, priority: P, value: V) {
        let (owner, key) = self.into_inner();
        let index = unsafe { links::Index::new_usize(key.get()) };
        // Complete ordering before consuming the free hook or publishing the payload.
        unsafe { heap::Vacancy::new(&mut *owner, key) }
            .prepare(priority)
            .store();
        unsafe { owner.free.acquire_at(&owner.storage, index) };
        unsafe {
            owner
                .storage
                .values_mut()
                .get_unchecked_mut(index.get())
                .value
                .write(value);
            owner.ready.link_back(&owner.storage, index);
        }
    }
}

impl<P: Ord, V> Sweep<'_, Min<P, V>> {
    pub fn next(&mut self) -> Option<Front<'_, P, V>> {
        let owner = self.take()?;
        // Initial cardinality survives: each previous loan can remove only its own head.
        let index = unsafe { owner.ready.front_key() };
        Some(Front { owner, index })
    }
}

impl<P: Ord, V> Drop for Min<P, V> {
    fn drop(&mut self) {
        if mem::needs_drop::<P>() || mem::needs_drop::<V>() {
            for position in 0..self.len() {
                // Terminal ownership retains the initialized prefix and resident bijection.
                let entry = unsafe { self.storage.as_mut().get_unchecked_mut(position) };
                let index = unsafe { entry.assume_init_ref().identity.get() };
                unsafe { entry.assume_init_drop() };
                unsafe {
                    self.storage
                        .values_mut()
                        .get_unchecked_mut(index)
                        .value
                        .assume_init_drop();
                }
            }
        }
    }
}

unsafe impl<P: Ord, V> heap::raw::Store for Min<P, V> {
    type Key = heap::Direct;
    type Priority = P;
    type Position = u32;
    type Storage = heap::Capacity<heap::Stored<heap::Direct, P>, u32, Node<V>>;
    type Extra = ptr::NonNull<Node<V>>;

    fn storage(&self) -> &alloc::raw::Block<Self::Storage, u32, Self::Extra> {
        &self.storage
    }

    fn storage_mut(&mut self) -> &mut alloc::raw::Block<Self::Storage, u32, Self::Extra> {
        &mut self.storage
    }
}

unsafe impl<P: Ord, V> crate::depot::raw::Hooks for Storage<P, V> {
    unsafe fn hook_raw(&self, index: links::Index) -> &links::Hook {
        // Every topology mutation retains this exact allocation's admitted index.
        &unsafe { self.values().get_unchecked(index.get()) }.hook
    }
}