dope-core 0.76.0

Owned native I/O and completion driver for dope
Documentation
use std::{cell, cmp, marker, mem, num::NonZero, ptr};

use o3::{
    alloc,
    base::marker::ThreadBound,
    depot::{capacity, heap},
};

use crate::driver::schedule::clock::timer::heap::{FIRED, FREE, IDLE, Min, Slot, State};

/// Persistent branded heap with non-Copy residents and their Drop obligations.
/// Preserves the four-plane layout, six-word owner, and 128-byte resident alignment.
/// Loans are allocation-free and exclusively borrow this store's retained state.
#[repr(transparent)]
pub struct Store<P: Ord, R, Tag = ()> {
    inner: cell::UnsafeCell<Core<P, R>>,
    tag: marker::PhantomData<cell::Cell<Tag>>,
}

impl<P: Ord, R, Tag> Store<P, R, Tag> {
    /// Allocates the fixed-capacity store inside its persistent owner cell.
    pub fn try_new(cap: usize) -> Result<Self, alloc::Error> {
        use alloc::raw::Rows;

        if cap > (u32::MAX - 2) as usize || cap > Capacity::<P, R>::EXTRA_MAX {
            return Err(alloc::Overflow.into());
        }
        let extent = Capacity {
            count: capacity::Count::new(cap as u32),
            ownership: marker::PhantomData,
        };
        let counts = Counts {
            len: 0,
            free: if cap == 0 { FREE } else { 0 },
        };
        let storage = alloc::raw::Uninit::try_parts(extent, counts, |index| {
            let next = if index + 1 == cap {
                FREE
            } else {
                (index + 1) as u32
            };
            (FREE, Resident { next })
        })?;
        Ok(Self {
            inner: cell::UnsafeCell::new(Core {
                storage,
                thread: marker::PhantomData,
            }),
            tag: marker::PhantomData,
        })
    }

    /// Runs `op` with one non-escaping exclusive loan.
    ///
    /// # Safety
    /// Every lease used by `op` must originate from `self`, and no other loan may overlap `op`.
    pub unsafe fn loan<'id, T>(
        &'id self,
        op: impl for<'a> FnOnce(Min<'a, 'id, P, R, Tag>) -> T,
    ) -> T {
        // SAFETY: the caller excludes overlapping loans. The higher-ranked
        // callback cannot return this exclusive core borrow.
        op(Min::new(unsafe { &mut *self.inner.get() }))
    }
}

#[repr(transparent)]
struct Capacity<P, R> {
    count: capacity::Count,
    ownership: marker::PhantomData<(P, R)>,
}

// SAFETY: construction proves the slot domain and all four immutable planes.
unsafe impl<P, R> alloc::raw::Shape for Capacity<P, R> {
    type Root = Slot;
    type Tail = mem::MaybeUninit<P>;
    type Extra = u32;
    type Last = Resident<R>;

    fn len(&self) -> usize {
        self.count.get()
    }
}

// SAFETY: Shape retains one count for all four planes and uses its default
// tail_len; construction admits that count against the complete EXTRA_MAX.
unsafe impl<P, R> alloc::raw::Rows for Capacity<P, R> {}

type Storage<P, R> =
    alloc::raw::Block<Capacity<P, R>, Counts, (ptr::NonNull<u32>, ptr::NonNull<Resident<R>>)>;

union Resident<R> {
    next: u32,
    value: mem::ManuallyDrop<R>,
}

pub(super) struct Core<P: Ord, R> {
    storage: Storage<P, R>,
    thread: marker::PhantomData<ThreadBound>,
}

struct Counts {
    len: u32,
    free: u32,
}

#[derive(Clone, Copy)]
pub(super) struct Free(());

#[derive(Clone, Copy)]
pub(super) struct Root(());

#[derive(Clone, Copy)]
#[repr(transparent)]
pub(super) struct Position(usize);

impl<P: Ord, R> Core<P, R> {
    pub(super) fn free(&self) -> Option<Free> {
        (self.storage.state.free != FREE).then_some(Free(()))
    }

    pub(super) fn lease(&mut self, item: R, free: Free) -> NonZero<u32> {
        let () = free.0;
        let raw = self.storage.state.free;
        // SAFETY: Vacancy retains the exclusive heap loan from free(), so this
        // unchanged free-list head is in capacity and contains its next link.
        let entry = unsafe { self.storage.extra_mut().1.get_unchecked_mut(raw as usize) };
        // SAFETY: the free-list head has not yet been changed to a live value.
        let next = unsafe { entry.next };
        entry.value = mem::ManuallyDrop::new(item);
        self.storage.state.free = next;
        // SAFETY: the admitted free head is below capacity, which excludes u32::MAX.
        let position = unsafe { NonZero::new_unchecked(raw + 1) };
        self.write_state(Slot::from_one(position), IDLE);
        position
    }

    pub(super) fn release(&mut self, slot: Slot) -> (R, Option<P>) {
        let priority = self.take_armed(slot);
        let free = self.storage.state.free;
        // SAFETY: the consumed branded lease names this live in-capacity slot.
        let entry = unsafe {
            self.storage
                .extra_mut()
                .1
                .get_unchecked_mut(slot.into_usize())
        };
        // SAFETY: the live slot contains one initialized value, moved once here.
        let item = unsafe { mem::ManuallyDrop::take(&mut entry.value) };
        entry.next = free;
        self.storage.state.free = slot.get();
        self.write_state(slot, FREE);
        (item, priority)
    }

    pub(super) fn resident(&self, slot: Slot) -> &R {
        // SAFETY: the branded lease proves this in-capacity slot contains a value;
        // the shared heap loan prevents release for the returned borrow.
        unsafe {
            &self
                .storage
                .extra()
                .1
                .get_unchecked(slot.into_usize())
                .value
        }
    }

    pub(super) fn set(&mut self, slot: Slot, prio: P) {
        match self.phase(slot) {
            State::Armed(position) => {
                // SAFETY: the armed resident proves this initialized position and unchanged slot identity.
                let _ = unsafe {
                    <Self as heap::raw::Source>::replace::<true>(self, position.0, (slot, prio))
                };
            }
            State::Idle | State::Fired => self.insert(slot, prio),
        }
    }

    pub(super) fn clear(&mut self, slot: Slot) {
        let priority = self.take_armed(slot);
        self.write_state(slot, IDLE);
        drop(priority);
    }

    fn take_armed(&mut self, slot: Slot) -> Option<P> {
        match self.phase(slot) {
            State::Armed(position) => Some(self.remove_at(position).1),
            State::Idle | State::Fired => None,
        }
    }

    pub(super) fn fire(&mut self, root: Root) -> &R {
        let (slot, priority) = self.remove_at(root.position());
        self.write_state(slot, FIRED);
        drop(priority);
        self.resident(slot)
    }

    pub(super) fn write_state(&mut self, slot: Slot, state: u32) {
        // SAFETY: slots originate from this heap's retained lease, free-list head
        // or minimum, all bounded by its unchanged allocation extent.
        unsafe {
            *self
                .storage
                .extra_mut()
                .0
                .get_unchecked_mut(slot.into_usize()) = state
        };
    }

    pub(super) fn phase(&self, slot: Slot) -> State<Position> {
        // SAFETY: the branded live slot is within this heap's initialized plane.
        match unsafe { *self.storage.extra().0.get_unchecked(slot.into_usize()) } {
            IDLE => State::Idle,
            FIRED => State::Fired,
            state => State::Armed(Position(state as usize)),
        }
    }

    pub(super) fn priority_at(&self, pos: Position) -> &P {
        // SAFETY: this position comes from an armed resident's reverse map, a
        // retained nonempty root, or an initialized o3 heap entry. Each names
        // this core's initialized prefix; the shared core loan retains P.
        unsafe { self.storage.tail().get_unchecked(pos.0).assume_init_ref() }
    }

    pub(super) fn root(&self) -> Option<Root> {
        (self.storage.state.len != 0).then_some(Root(()))
    }

    fn slot(&self, pos: Position) -> Slot {
        // SAFETY: the same initialized heap position proves both slot and
        // priority planes, whose equal extent is fixed by Capacity.
        unsafe { self.storage.as_ref().get_unchecked(pos.0).assume_init() }
    }

    fn cmp(&self, priority: &P, slot: Slot, position: Position) -> cmp::Ordering {
        match priority.cmp(self.priority_at(position)) {
            cmp::Ordering::Equal => slot.get().cmp(&self.slot(position).get()),
            order => order,
        }
    }

    pub(super) fn remove_at(&mut self, position: Position) -> (Slot, P) {
        // SAFETY: the armed resident or minimum proves this initialized position.
        unsafe { <Self as heap::raw::Source>::remove(self, position.0) }
    }

    pub(super) fn insert(&mut self, slot: Slot, prio: P) {
        // SAFETY: the idle/fired leased slot is absent and reserves one spare heap position.
        unsafe { <Self as heap::raw::Source>::append(self, (slot, prio)) };
    }
}

impl<P: Ord, R> Drop for Core<P, R> {
    fn drop(&mut self) {
        if mem::needs_drop::<P>() {
            let (counts, _, values) = self.storage.parts_mut();
            for position in (0..counts.len as usize).rev() {
                // SAFETY: terminal ownership retains the initialized priority
                // prefix; reverse traversal preserves the prior removal order.
                unsafe { values.get_unchecked_mut(position).assume_init_drop() };
            }
        }
        if mem::needs_drop::<R>() {
            let (states, values) = self.storage.extra_mut();
            for (state, resident) in states.iter().zip(values) {
                if *state != FREE {
                    // SAFETY: the equal planes pair each non-free slot with its
                    // initialized resident, owned only by this terminal traversal.
                    unsafe { mem::ManuallyDrop::drop(&mut resident.value) };
                }
            }
        }
    }
}

impl Root {
    pub(super) const fn position(self) -> Position {
        Position(0)
    }
}

// SAFETY: this owner keeps all four planes and the initialized heap prefix
// together. The heap kernel uses only positions in that same exclusive loan.
unsafe impl<P: Ord, R> heap::raw::Source for Core<P, R> {
    type Value = (Slot, P);

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

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

    unsafe fn compare(&self, position: usize, (slot, priority): &Self::Value) -> cmp::Ordering {
        self.cmp(priority, *slot, Position(position))
    }

    unsafe fn direction(&self, position: usize, (_, priority): &Self::Value) -> cmp::Ordering {
        priority.cmp(self.priority_at(Position(position)))
    }

    unsafe fn compare_at(&self, left: usize, right: usize) -> cmp::Ordering {
        let left = Position(left);
        self.cmp(self.priority_at(left), self.slot(left), Position(right))
    }

    unsafe fn read<const REMOVE: bool>(&mut self, position: usize) -> Self::Value {
        let slot = self.slot(Position(position));
        // SAFETY: the heap kernel owns this initialized position and keeps the
        // exclusive core loan until this moved value is stored.
        let priority = unsafe {
            self.storage
                .tail()
                .get_unchecked(position)
                .assume_init_read()
        };
        (slot, priority)
    }

    unsafe fn shift(&mut self, source: usize, target: usize) {
        // SAFETY: the heap kernel retains this initialized source and vacant destination.
        let value = unsafe { self.read::<false>(source) };
        // SAFETY: the exclusive loan and unchanged extent retain the destination hole.
        unsafe { self.write::<true>(target, value) };
    }

    unsafe fn write<const PLACE: bool>(&mut self, position: usize, (slot, priority): Self::Value) {
        let (_, slots, values) = self.storage.parts_mut();
        // SAFETY: the heap kernel retains this hole in both same-extent planes.
        unsafe {
            if PLACE {
                slots.get_unchecked_mut(position).write(slot);
            }
            values.get_unchecked_mut(position).write(priority);
        }
        if PLACE {
            self.write_state(slot, position as u32);
        }
    }
}

const _: () = {
    assert!(mem::size_of::<Free>() == 0);
    assert!(mem::size_of::<Root>() == 0);
    assert!(mem::size_of::<Position>() == mem::size_of::<usize>());
    assert!(mem::size_of::<Counts>() == 2 * mem::size_of::<u32>());
    assert!(mem::size_of::<Slot>() == mem::size_of::<u32>());
    assert!(mem::size_of::<Store<u128, u64>>() == 6 * mem::size_of::<usize>());
    assert!(mem::align_of::<Store<u128, u64>>() == mem::align_of::<usize>());
};