dope-core 0.77.0

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

use crate::{
    driver::schedule::clock,
    executor::drive::{self, regress::Regression},
};

pub(crate) struct Elapsed;

#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct Range {
    origin: time::Instant,
    duration: time::Duration,
}

impl Range {
    pub fn try_add(origin: time::Instant, duration: time::Duration) -> Result<time::Instant, Self> {
        match origin.checked_add(duration) {
            Some(deadline) => Ok(deadline),
            None => Err(Self { origin, duration }),
        }
    }

    pub const fn origin(self) -> time::Instant {
        self.origin
    }

    pub const fn duration(self) -> time::Duration {
        self.duration
    }
}

pub trait Input<'d> {
    type Source: Time;
    type Error: Into<drive::Error>;

    fn admit(self, current: clock::Clock<'_, 'd>) -> Result<Self::Source, Self::Error>;
}

impl Input<'_> for () {
    type Source = Wall;
    type Error = Infallible;

    fn admit(self, _current: clock::Clock<'_, '_>) -> Result<Wall, Self::Error> {
        Ok(Wall)
    }
}

impl Input<'_> for time::Duration {
    type Source = Bound<End>;
    type Error = Range;

    fn admit(self, _current: clock::Clock<'_, '_>) -> Result<Self::Source, Range> {
        Bound::until(Wall, self)
    }
}

impl<'d> Input<'d> for clock::Deadline<'d> {
    type Source = Self;
    type Error = Regression;

    fn admit(self, current: clock::Clock<'_, 'd>) -> Result<Self, Self::Error> {
        check(self.into_raw(), current)?;
        Ok(self)
    }
}

impl<'d> Input<'d> for (clock::Deadline<'d>, time::Duration) {
    type Source = Bound<End, clock::Deadline<'d>>;
    type Error = drive::Error;

    fn admit(self, current: clock::Clock<'_, 'd>) -> Result<Self::Source, drive::Error> {
        let source = self.0.admit(current).map_err(drive::Error::from)?;
        Bound::until(source, self.1).map_err(drive::Error::from)
    }
}

impl Input<'_> for Bound<Span> {
    type Source = Self;
    type Error = Infallible;

    fn admit(self, _current: clock::Clock<'_, '_>) -> Result<Self, Self::Error> {
        Ok(self)
    }
}

pub(crate) fn sample<'d>(
    current: clock::Clock<'_, 'd>,
    start: Option<clock::Deadline<'d>>,
) -> Result<clock::Sample, drive::Error> {
    let now = start.map_or_else(time::Instant::now, clock::Deadline::into_raw);
    check(now, current)?;
    Ok(clock::Sample::new(now))
}

pub(crate) fn check(now: time::Instant, current: clock::Clock<'_, '_>) -> Result<(), Regression> {
    let current = current.now().into_raw();
    if now < current {
        Err(Regression::new(now, current))
    } else {
        Ok(())
    }
}

pub trait Time: Copy {
    const FIXED: bool = false;

    fn sample_at(self, wall: time::Instant) -> clock::Sample {
        clock::Sample::new(wall)
    }

    fn start(self) -> clock::Sample {
        self.sample_at(time::Instant::now())
    }

    fn tick(self) -> Result<clock::Sample, drive::Error> {
        Ok(self.start())
    }

    fn quiesce(self) -> Result<clock::Sample, drive::Error> {
        Ok(self.start())
    }

    fn timeout(self, deadline: clock::Deadline<'_>) -> time::Duration {
        deadline
            .into_raw()
            .saturating_duration_since(time::Instant::now())
    }

    fn limit(self, timeout: Option<time::Duration>) -> Option<time::Duration>;
}

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

impl Time for Wall {
    fn limit(self, timeout: Option<time::Duration>) -> Option<time::Duration> {
        timeout
    }
}

pub(crate) fn wall() -> Wall {
    Wall
}

impl Time for clock::Deadline<'_> {
    const FIXED: bool = true;

    fn sample_at(self, _wall: time::Instant) -> clock::Sample {
        clock::Sample::new(self.into_raw())
    }

    fn start(self) -> clock::Sample {
        clock::Sample::new(self.into_raw())
    }

    fn timeout(self, deadline: clock::Deadline<'_>) -> time::Duration {
        deadline
            .into_raw()
            .saturating_duration_since(self.into_raw())
    }

    fn limit(self, timeout: Option<time::Duration>) -> Option<time::Duration> {
        timeout.filter(time::Duration::is_zero)
    }
}

#[derive(Clone, Copy)]
pub struct Bound<L, S = Wall> {
    source: S,
    limit: L,
}

pub(crate) trait Limit: Copy {
    fn left(self, wall: time::Instant) -> time::Duration;
}

#[derive(Clone, Copy)]
pub struct Span {
    started: time::Instant,
    timeout: time::Duration,
}

impl Limit for Span {
    fn left(self, wall: time::Instant) -> time::Duration {
        self.timeout
            .saturating_sub(wall.saturating_duration_since(self.started))
    }
}

#[derive(Clone, Copy)]
pub struct End(time::Instant);

impl Limit for End {
    fn left(self, wall: time::Instant) -> time::Duration {
        self.0.saturating_duration_since(wall)
    }
}

impl<L, S: Time> Bound<L, S> {
    pub(crate) fn elapsed(self) -> Result<clock::Sample, Elapsed>
    where
        L: Limit,
    {
        let now = time::Instant::now();
        if self.limit.left(now).is_zero() {
            Err(Elapsed)
        } else {
            Ok(self.source.sample_at(now))
        }
    }
}

impl From<time::Duration> for Bound<Span> {
    fn from(timeout: time::Duration) -> Self {
        Self {
            source: Wall,
            limit: Span {
                started: time::Instant::now(),
                timeout,
            },
        }
    }
}

impl<'d> From<(clock::Clock<'_, 'd>, time::Duration)> for Bound<Span, clock::Deadline<'d>> {
    fn from((clock, timeout): (clock::Clock<'_, 'd>, time::Duration)) -> Self {
        Self {
            source: clock.now().into(),
            limit: Span {
                started: time::Instant::now(),
                timeout,
            },
        }
    }
}

impl<S: Time> Bound<End, S> {
    pub(crate) fn until(source: S, timeout: time::Duration) -> Result<Self, Range> {
        let origin = time::Instant::now();
        let end = Range::try_add(origin, timeout)?;
        Ok(Self {
            source,
            limit: End(end),
        })
    }
}

impl<L: Limit, S: Time> Time for Bound<L, S> {
    const FIXED: bool = S::FIXED;

    fn start(self) -> clock::Sample {
        self.source.start()
    }

    fn timeout(self, deadline: clock::Deadline<'_>) -> time::Duration {
        self.source.timeout(deadline)
    }

    fn quiesce(self) -> Result<clock::Sample, drive::Error> {
        self.elapsed().map_err(drive::Error::quiesce)
    }

    fn tick(self) -> Result<clock::Sample, drive::Error> {
        self.elapsed().map_err(drive::Error::timeout)
    }

    fn limit(self, timeout: Option<time::Duration>) -> Option<time::Duration> {
        let timeout = self.source.limit(timeout);
        if timeout.is_some_and(|wait| wait.is_zero()) {
            return timeout;
        }
        let left = self.limit.left(time::Instant::now());
        Some(timeout.map_or(left, |wait| wait.min(left)))
    }
}

const _: () = {
    assert!(std::mem::size_of::<Wall>() == 0);
    assert!(std::mem::size_of::<Range>() == std::mem::size_of::<(time::Instant, time::Duration)>());
    assert!(std::mem::size_of::<Bound<End>>() == std::mem::size_of::<time::Instant>());
    assert!(
        std::mem::size_of::<Bound<Span>>()
            == std::mem::size_of::<(time::Instant, time::Duration)>()
    );
};