dope-core 0.75.0

Owned native I/O and completion driver for dope
Documentation
use std::{cell, mem, time};

use o3::{alloc, base::cell::region, mem::quota};
use state::{lanes, scope};

use crate::{
    driver,
    driver::{
        receive::{credit, credit::storage},
        route::table::conn,
        settings,
    },
};

pub mod clock;
pub mod timing;

pub mod app;
pub mod maint;
pub mod ready;
pub mod sequence;
#[doc(hidden)]
pub mod state;

pub const LIMIT: usize = 256;

/// Exact result of acquiring scheduler capacity from a non-empty source.
#[must_use = "capacity reports whether the scheduler granted the operation"]
pub enum Capacity<T> {
    Available(T),
    Exhausted,
}

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Turn<'turn, 'd> {
    state: &'turn state::Core<'d>,
}

impl<'turn, 'd> Turn<'turn, 'd> {
    pub(in crate::driver::schedule) const fn new(state: &'turn state::Core<'d>) -> Self {
        Self { state }
    }

    pub fn reborrow(&self) -> Turn<'_, 'd> {
        Turn::new(self.state)
    }

    pub fn clock(self) -> clock::Clock<'turn, 'd> {
        self.state.driver.scheduler().clock()
    }

    pub fn app(self) -> app::Work<'turn, 'd> {
        app::Work { state: self.state }
    }

    pub fn maint(self) -> maint::Work<'turn, 'd> {
        maint::Work { state: self.state }
    }

    pub fn next_step<'step>(
        self,
        driver: &'step mut driver::Local<'d>,
    ) -> Option<crate::control::Step<'step, 'd>> {
        self.coord().take()?;
        Some(crate::control::Step::new(driver))
    }

    #[doc(hidden)]
    pub fn coord(self) -> scope::Coord<'turn, 'd> {
        scope::Coord::new(self.state)
    }
}

impl<'driver, 'turn, 'd: 'driver + 'turn, Report: crate::io::Report>
    crate::executor::raw::Sweep<'driver, 'turn, 'd, Report>
{
    pub(crate) unsafe fn leaf<A: crate::executor::raw::App<'d>>(
        &mut self,
        app: std::pin::Pin<&mut A>,
    ) {
        let peers = self.parks;
        let ahead = self.ahead;
        self.parks = peers.saturating_sub(1);
        self.ahead = [ahead[0].saturating_sub(1), ahead[1].saturating_sub(1)];
        let turn = self.turn;
        let ledgers = &turn.state.lanes;
        let _app = lanes::split(&ledgers.app, peers, ahead[0]);
        let _maint = lanes::split(&ledgers.maint, peers, ahead[1]);
        let _coord = if A::COORDS != 0 {
            let peers = self.groups as usize;
            let ahead = self.coord as usize;
            self.groups = self.groups.saturating_sub(1);
            self.coord = self.coord.saturating_sub(1);
            Some(lanes::split(&ledgers.coord, peers, ahead))
        } else {
            None
        };
        // SAFETY: this is the next admitted pinned leaf in the root census.
        unsafe { A::park(app, turn, &mut *self.driver) };
    }

    /// # Safety
    /// Consume the next admitted coordinator in the root's census order.
    pub unsafe fn coordinate<A: crate::executor::raw::App<'d>>(
        &mut self,
        app: std::pin::Pin<&mut A>,
    ) {
        let peers = self.groups as usize;
        let ahead = self.coord as usize;
        self.groups = self.groups.saturating_sub(1);
        self.coord = self.coord.saturating_sub(1);
        let turn = self.turn;
        let _quota = lanes::split(&turn.state.lanes.coord, peers, ahead);
        // SAFETY: this is the admitted root's own coordinator and same turn.
        unsafe { A::park(app, turn, &mut *self.driver) };
    }
}

const _: () = {
    let word = mem::size_of::<usize>();
    assert!(mem::size_of::<Turn<'static, 'static>>() == word);
    assert!(mem::size_of::<quota::Admission<usize>>() == 2 * word);
    assert!(mem::size_of::<Capacity<&'static u8>>() == word);
};

/// Aggregate liveness of retained work owned by one driver.
#[must_use]
pub struct Waits<'d>(Option<Wait<'d>>);

impl<'d> Waits<'d> {
    pub fn new() -> Self {
        Self(None)
    }

    pub fn as_ref(&self) -> Option<&Wait<'d>> {
        self.0.as_ref()
    }

    pub fn event(&mut self, proof: region::Identity<'d>) {
        if self.0.is_none() {
            self.0 = Some(Wait::Event(proof));
        }
    }

    pub fn until(&mut self, deadline: clock::Deadline<'d>) {
        match &mut self.0 {
            Some(Wait::Until(prior)) => {
                if deadline < *prior {
                    *prior = deadline;
                }
            }
            wait => *wait = Some(Wait::Until(deadline)),
        }
    }
}

const _: () = assert!(mem::size_of::<Waits<'static>>() <= 24);

pub(in crate::driver) struct State {
    pub(in crate::driver) owner: storage::Owner<ready::Stored, credit::Wake, ready::Arena>,
    clock: cell::Cell<time::Instant>,
}

impl State {
    pub(in crate::driver) fn try_new(plan: settings::Plan<'_>) -> Result<Self, alloc::Error> {
        Ok(Self {
            owner: storage::Owner::try_new(plan)?,
            clock: cell::Cell::new(time::Instant::now()),
        })
    }
}

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Context<'d>(driver::Reference<'d>);

impl<'d> Context<'d> {
    pub(in crate::driver) const fn new(driver: driver::Reference<'d>) -> Self {
        Self(driver)
    }

    pub(in crate::driver) fn clock(self) -> clock::Clock<'d, 'd> {
        clock::Clock::new(&self.0.shared.context().schedule.clock, self.0.brand)
    }

    pub(in crate::driver) fn set_turn_now(self, now: time::Instant) {
        self.0.shared.context().schedule.clock.set(now);
    }

    /// Allocates fixed retained-credit storage in this driver generation.
    pub fn try_storage(
        self,
        capacity: conn::Capacity,
    ) -> Result<credit::Storage<'d>, alloc::Error> {
        let shared: &'d driver::Shared = self.0.shared.context();
        let owner = &shared.schedule.owner;
        owner.try_storage(capacity, self.0.brand)
    }
}

const _: () = assert!(
    std::mem::size_of::<Context<'static>>() == std::mem::size_of::<driver::Reference<'static>>()
);

/// Driver-scoped evidence that a retained owner is waiting for an external
/// wake or a monotonic deadline.
#[must_use]
pub enum Wait<'d> {
    Event(region::Identity<'d>),
    Until(clock::Deadline<'d>),
}

const _: () = {
    assert!(mem::size_of::<Wait<'static>>() == mem::size_of::<Option<clock::Deadline<'static>>>());
    assert!(
        mem::align_of::<Wait<'static>>() == mem::align_of::<Option<clock::Deadline<'static>>>()
    );
    assert!(mem::size_of::<Option<Wait<'static>>>() == mem::size_of::<Wait<'static>>());
    assert!(!mem::needs_drop::<Wait<'static>>());
};