o3 0.62.0

shared-nothing primitives
Documentation
mod capacity;
mod hole;
mod source;

pub use capacity::Capacity;
pub(in crate::depot) use hole::Hole;
pub use source::Source;

use std::{mem, ptr};

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

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

struct Row<V> {
    hook: links::Hook,
    value: mem::MaybeUninit<V>,
}

type Storage<P, V> = alloc::raw::Block<
    heap::raw::Capacity<(links::Index, P), u32, Row<V>>,
    u32,
    ptr::NonNull<Row<V>>,
>;

pub struct Entry<'a, P: Ord, V, const LIVE: bool> {
    owner: &'a mut Min<P, V>,
    index: links::Index,
    row: ptr::NonNull<Row<V>>,
}

#[repr(transparent)]
pub struct Minimum<'a, P: Ord, V> {
    owner: &'a mut Min<P, V>,
}

impl<P: Ord, V> Min<P, V> {
    pub fn try_new(capacity: Count) -> Result<Self, heap::Error> {
        let mut memory = heap::raw::Capacity::try_new(capacity)?.uninit()?;
        let count = capacity.get();
        let (_, _, rows, _) = memory.planes_mut();
        for (index, row) in rows.iter_mut().enumerate() {
            row.write(Row {
                hook: links::Hook::vacant(
                    index as u32,
                    if index + 1 == count {
                        links::Index::END
                    } else {
                        index as u32 + 1
                    },
                ),
                value: mem::MaybeUninit::uninit(),
            });
        }
        let rows = ptr::NonNull::from(rows).cast();
        // SAFETY: positions and row metadata are initialized; heap and V remain absent.
        let storage = unsafe { memory.finish(0, rows) };
        Ok(Self {
            storage,
            ready: links::raw::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 fn is_empty(&self) -> bool {
        Source::is_empty(&self.storage)
    }

    pub fn min(&self) -> Option<&P> {
        // SAFETY: this sole owner retains the initialized dense prefix.
        Some(&unsafe { self.storage.heap_first() }?.1)
    }

    pub fn front(&mut self) -> Option<Entry<'_, P, V, true>> {
        let index = self.ready.first()?;
        // SAFETY: this exclusive root loan retains the initialized ready head.
        Some(unsafe { self.entry(index) })
    }

    pub fn minimum(&mut self) -> Option<Minimum<'_, P, V>> {
        // SAFETY: this sole owner retains the initialized dense prefix.
        unsafe { self.storage.heap_first() }?;
        Some(Minimum { owner: self })
    }

    pub fn remove_min(&mut self, maximum: &P) -> Option<slot::Occupied<'_, V>> {
        // SAFETY: this sole owner retains the initialized dense prefix.
        let minimum = unsafe { self.storage.heap_first() }?;
        if minimum.1.cmp(maximum).is_gt() {
            return None;
        }
        let (index, _) = unsafe { heap::raw::Source::remove(&mut self.storage, 0) };
        let row = ptr::NonNull::from(unsafe { self.storage.resident_mut(index) });
        Some(unsafe { self.retire::<false>(index, row) })
    }

    pub fn vacant(&mut self) -> Option<Entry<'_, P, V, false>> {
        let index = self.free.front()?;
        // SAFETY: the retained free head admits this absent row and one spare heap slot.
        Some(unsafe { self.entry(index) })
    }

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

    // SAFETY: the selected index and LIVE classification remain valid under this root loan.
    unsafe fn entry<const LIVE: bool>(&mut self, index: links::Index) -> Entry<'_, P, V, LIVE> {
        let row = ptr::NonNull::from(unsafe { self.storage.resident_mut(index) });
        Entry {
            owner: self,
            index,
            row,
        }
    }

    // SAFETY: heap removal has transferred this row's V; FRONT also proves the ready head.
    unsafe fn retire<const FRONT: bool>(
        &mut self,
        index: links::Index,
        row: ptr::NonNull<Row<V>>,
    ) -> slot::Occupied<'_, V> {
        let hook = unsafe { &(*row.as_ptr()).hook };
        let detached = unsafe {
            self.ready
                .detach_hook::<FRONT, 0, _>(&self.storage, index, hook)
        }
        .0;
        self.free.recycle(detached);
        // SAFETY: only Hook changed. This root loan blocks claim and Drop until V is consumed.
        unsafe { slot::raw::Vacant::new(&mut (*row.as_ptr()).value).assume_init() }
    }
}

impl<P: Ord, V> Entry<'_, P, V, false> {
    pub fn slot(&mut self) -> slot::raw::Vacant<'_, V> {
        // SAFETY: this exclusive free row has no published V.
        slot::raw::Vacant::new(unsafe { &mut (*self.row.as_ptr()).value })
    }

    /// # Safety
    /// The exact slot is fully initialized, with its sole destruction transferred here.
    pub unsafe fn publish(self, priority: P) {
        let Self { owner, index, row } = self;
        unsafe { heap::raw::Source::append(&mut owner.storage, (index, priority)) };
        let hook = unsafe { &(*row.as_ptr()).hook };
        // SAFETY: no observer or fallible operation separates free removal and tail publication.
        unsafe {
            owner.free.acquire_hook(hook);
            owner.ready.link_back::<0, _>(&owner.storage, index, hook);
        }
    }
}

impl<'a, P: Ord, V> Entry<'a, P, V, true> {
    pub fn priority(&self) -> &P {
        // SAFETY: the retained live row and reverse map admit this initialized pair.
        let position = unsafe { self.owner.storage.position(self.index) } as usize;
        unsafe {
            &self
                .owner
                .storage
                .as_ref()
                .get_unchecked(position)
                .assume_init_ref()
                .1
        }
    }

    pub fn get_mut(&mut self) -> &mut V {
        unsafe { (*self.row.as_ptr()).value.assume_init_mut() }
    }

    pub fn rotate(self) {
        let hook = unsafe { &(*self.row.as_ptr()).hook };
        unsafe {
            self.owner
                .ready
                .rotate::<0, _>(&self.owner.storage, self.index, hook, true)
        };
    }

    pub fn take(self) -> (P, V) {
        let position = unsafe { self.owner.storage.position(self.index) } as usize;
        let (_, priority) = unsafe { heap::raw::Source::remove(&mut self.owner.storage, position) };
        let value = unsafe { self.owner.retire::<true>(self.index, self.row) }.into_inner();
        (priority, value)
    }

    pub fn remove(self) -> slot::Occupied<'a, V> {
        let position = unsafe { self.owner.storage.position(self.index) } as usize;
        unsafe { heap::raw::Source::remove(&mut self.owner.storage, position) };
        unsafe { self.owner.retire::<true>(self.index, self.row) }
    }
}

impl<P: Ord, V> Minimum<'_, P, V> {
    pub fn priority(&self) -> &P {
        // SAFETY: the private admission and exclusive root loan retain dense slot zero.
        unsafe {
            &self
                .owner
                .storage
                .as_ref()
                .get_unchecked(0)
                .assume_init_ref()
                .1
        }
    }

    pub fn take(self) -> (P, V) {
        // SAFETY: this same root has retained its admitted minimum without mutation.
        let (index, priority) = unsafe { heap::raw::Source::remove(&mut self.owner.storage, 0) };
        let row = ptr::NonNull::from(unsafe { self.owner.storage.resident_mut(index) });
        let value = unsafe { self.owner.retire::<false>(index, row) }.into_inner();
        (priority, value)
    }
}

impl<P: Ord, V> Sweep<'_, Min<P, V>> {
    pub fn next_entry(&mut self) -> Option<Entry<'_, P, V, true>> {
        let owner = self.take()?;
        // SAFETY: each prior loan removed at most its own head from the initial cardinality.
        let index = unsafe { owner.ready.front_key() };
        Some(unsafe { owner.entry(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() {
                let entry = unsafe { self.storage.as_mut().get_unchecked_mut(position) };
                let index = unsafe { entry.assume_init_ref() }.0;
                unsafe { entry.assume_init_drop() };
                unsafe {
                    self.storage.resident_mut(index).value.assume_init_drop();
                }
            }
        }
    }
}

unsafe impl<P: Ord, V> crate::depot::raw::Hooks for Storage<P, V> {
    unsafe fn hook_raw(&self, index: links::Index) -> &links::Hook {
        &unsafe { self.resident(index) }.hook
    }
}