dope-core 0.76.0

Owned native I/O and completion driver for dope
Documentation
use std::ptr;

use o3::{
    base::num::bounded,
    depot::queue::{links, resident},
};

use crate::driver::schedule::{
    app,
    ready::wake::{
        self,
        table::{Entry, Error, Registration, Table},
    },
};

/// A physical index admitted to this table's immutable extent.
#[derive(Clone, Copy)]
pub struct Slot<'target, 'd> {
    table: &'target Table<'d>,
    index: links::Index,
}

impl<'target, 'd> Slot<'target, 'd> {
    /// # Safety
    /// The position is below this exact table's capacity.
    pub unsafe fn new(table: &'target Table<'d>, position: usize) -> Self {
        // SAFETY: the table's count is at most u32::MAX, excluding the link sentinel.
        let index =
            unsafe { bounded::raw::U32::<0, { u32::MAX - 1 }>::from_proven(position as u32) };
        Self {
            table,
            index: index.into(),
        }
    }

    pub(super) fn try_new(
        table: &'target Table<'d>,
        position: usize,
    ) -> Result<Self, resident::Bounds<usize>> {
        if position >= table.entries.len() {
            return Err(resident::Bounds::new(position, table.entries.len()));
        }
        // SAFETY: the physical position was checked against this table.
        Ok(unsafe { Self::new(table, position) })
    }

    fn entry(self) -> &'target Entry<'d> {
        // SAFETY: this slot borrows the table that admitted its index.
        unsafe { self.table.entries.get_unchecked(self.index.get()) }
    }

    pub fn try_keep(
        self,
        wait: &mut Option<Registration<'target, 'd>>,
        wake: &wake::Waker<'d>,
    ) -> Result<(), Error> {
        let position = wake::Position::new(self.index.get());
        if self.table.draining.get() {
            return Err(Error::Draining { position });
        }
        let entry = self.entry();
        let linked = match wait {
            Some(Registration(active)) => {
                if !ptr::eq(active.table, self.table) || active.index != self.index {
                    return Err(Error::Active { position });
                }
                self.index.is_linked(entry.hook())
            }
            None => {
                if !entry.hook().is_vacant(self.index.get()) {
                    return Err(Error::Occupied { position });
                }
                *wait = Some(Registration(self));
                false
            }
        };
        entry.initialize(*wake.key());
        if !linked {
            // SAFETY: this registration owns the vacant or parked hook in the same store.
            unsafe {
                self.table
                    .links
                    .link_back::<0, _>(&*self.table.entries, self.index, entry.hook())
            };
        }
        Ok(())
    }

    pub fn wake(self) -> wake::Once {
        let entry = self.entry();
        if !self.index.is_linked(entry.hook()) {
            return wake::Once::Empty;
        }
        // SAFETY: this linked slot owns one initialized wake in this table's FIFO.
        unsafe { self.wake_linked::<false>(entry) };
        wake::Once::Woke
    }

    pub(super) fn drain_one(table: &'target Table<'d>, work: app::Work<'_, 'd>) -> wake::Drain {
        let Some(index) = table.links.first() else {
            table.draining.set(false);
            return wake::Drain::Empty;
        };
        let Some(_permit) = work.permit() else {
            work.defer();
            return wake::Drain::Exhausted;
        };
        let slot = Self { table, index };
        // SAFETY: taking a permit cannot reenter the table; this is its initialized FIFO front.
        unsafe { slot.wake_linked::<true>(slot.entry()) };
        wake::Drain::Woke
    }

    unsafe fn wake_linked<const FRONT: bool>(self, entry: &'target Entry<'d>) {
        // SAFETY: the caller owns this linked wake; FRONT identifies the actual head.
        unsafe { self.detach::<FRONT>(entry) }.park();
        unsafe { entry.take() }.wake(self.table.driver);
    }

    unsafe fn detach<const FRONT: bool>(
        self,
        entry: &'target Entry<'d>,
    ) -> links::Detached<'target> {
        // SAFETY: the caller identified this linked hook in this table and its head status.
        unsafe {
            self.table.links.detach_hook::<FRONT, 0, _>(
                &*self.table.entries,
                self.index,
                entry.hook(),
            )
        }
        .0
    }

    pub(super) fn cancel(wait: &Registration<'target, 'd>) {
        let slot = wait.0;
        let entry = slot.entry();
        if entry.hook().try_unpark(slot.index).is_none() {
            // SAFETY: this affine registration owns the linked hook whenever it is not parked.
            unsafe { slot.detach::<false>(entry) }.idle();
        }
    }
}