use core::{pin, task};
use std::{mem, time};
use crate::{
driver::schedule::clock::{self, timer},
executor::task::{Fiber, context},
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Error {
Range(clock::Range),
Capacity(timer::Exhausted),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum Elapsed {
Budget,
Limit,
}
pub struct Budget<'d> {
deadline: clock::Deadline<'d>,
alarm: timer::Alarm<'d>,
}
pub struct Scope<'budget, 'd: 'budget> {
deadline: clock::Deadline<'d>,
alarm: &'budget mut timer::Alarm<'d>,
elapsed: Elapsed,
}
#[pin_project::pin_project(PinnedDrop)]
#[doc(hidden)]
#[must_use = "a fiber does nothing unless it is driven"]
pub struct Timeout<'scope, 'd, F> {
alarm: &'scope mut timer::Alarm<'d>,
deadline: clock::Deadline<'d>,
state: State,
limit: Option<time::Duration>,
#[pin]
fiber: F,
}
enum State {
Idle(Elapsed),
Armed(Elapsed),
Settled,
}
#[doc(hidden)]
#[must_use = "a fiber does nothing unless it is driven"]
pub struct Sleep<'scope, 'd> {
alarm: &'scope timer::Alarm<'d>,
deadline: clock::Deadline<'d>,
state: SleepState,
}
enum SleepState {
New(time::Duration, Elapsed),
Armed(Result<(), Elapsed>),
Settled,
}
impl Elapsed {
fn narrow<'d>(
self,
deadline: clock::Deadline<'d>,
now: clock::Moment<'d>,
duration: time::Duration,
) -> (clock::Deadline<'d>, Self) {
let limit = now.try_add(duration).unwrap_or(deadline);
if limit < deadline {
(limit, Self::Limit)
} else {
(deadline, self)
}
}
}
impl<'d> Budget<'d> {
pub fn try_new(
timer: timer::Timer<'d>,
started: clock::Moment<'d>,
duration: time::Duration,
) -> Result<Self, Error> {
let deadline = started.try_add(duration).map_err(Error::Range)?;
let alarm = timer.try_alarm().map_err(Error::Capacity)?;
Ok(Self { deadline, alarm })
}
pub fn scope(&mut self, sample: clock::Moment<'d>, duration: time::Duration) -> Scope<'_, 'd> {
if duration == time::Duration::MAX {
return Scope {
deadline: self.deadline,
alarm: &mut self.alarm,
elapsed: Elapsed::Budget,
};
}
self.limit(sample.moment_at(time::Instant::now()), duration)
}
pub fn limit(&mut self, now: clock::Moment<'d>, duration: time::Duration) -> Scope<'_, 'd> {
let (deadline, elapsed) = Elapsed::Budget.narrow(self.deadline, now, duration);
Scope {
deadline,
alarm: &mut self.alarm,
elapsed,
}
}
pub fn timeout<'scope, F>(&'scope mut self, fiber: F) -> Timeout<'scope, 'd, F>
where
F: Fiber<'d> + 'scope,
{
Timeout::new(&mut self.alarm, self.deadline, Elapsed::Budget, None, fiber)
}
pub fn timeout_for<'scope, F>(
&'scope mut self,
duration: time::Duration,
fiber: F,
) -> Timeout<'scope, 'd, F>
where
F: Fiber<'d> + 'scope,
{
Timeout::new(
&mut self.alarm,
self.deadline,
Elapsed::Budget,
Some(duration),
fiber,
)
}
pub fn sleep(&mut self, duration: time::Duration) -> Sleep<'_, 'd> {
Sleep::new(&mut self.alarm, self.deadline, Elapsed::Budget, duration)
}
}
impl<'d> Scope<'_, 'd> {
pub const fn checkpoint(&self) -> clock::Check<'d, Elapsed> {
clock::Check::new(self.deadline, self.elapsed)
}
pub fn timeout<'scope, F>(&'scope mut self, fiber: F) -> Timeout<'scope, 'd, F>
where
F: Fiber<'d> + 'scope,
{
Timeout::new(&mut *self.alarm, self.deadline, self.elapsed, None, fiber)
}
pub fn sleep(&mut self, duration: time::Duration) -> Sleep<'_, 'd> {
Sleep::new(&mut *self.alarm, self.deadline, self.elapsed, duration)
}
}
impl<'scope, 'd> Sleep<'scope, 'd> {
fn new(
alarm: &'scope mut timer::Alarm<'d>,
deadline: clock::Deadline<'d>,
elapsed: Elapsed,
duration: time::Duration,
) -> Self {
Self {
alarm,
deadline,
state: SleepState::New(duration, elapsed),
}
}
}
impl<'d> Fiber<'d> for Sleep<'_, 'd> {
type Output = Result<(), Elapsed>;
fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<Self::Output> {
let (this, context) = call.into_parts();
let this = this.get_mut();
let now = context.driver().driver_ref().clock().now();
let wake = context.completion();
let (outcome, polled) = match this.state {
SleepState::New(duration, elapsed) => {
let limited = now.try_add(duration).unwrap_or(this.deadline);
let (next, outcome) = if limited < this.deadline {
(limited, Ok(()))
} else {
(this.deadline, Err(elapsed))
};
this.state = SleepState::Armed(outcome);
(outcome, this.alarm.arm_and_poll(next, now, wake))
}
SleepState::Armed(outcome) => (outcome, this.alarm.poll(now, wake)),
SleepState::Settled => return task::Poll::Pending,
};
if polled.is_pending() {
task::Poll::Pending
} else {
this.state = SleepState::Settled;
task::Poll::Ready(outcome)
}
}
}
impl Drop for Sleep<'_, '_> {
fn drop(&mut self) {
if matches!(self.state, SleepState::Armed(_)) {
self.alarm.clear();
}
}
}
impl<'scope, 'd, F> Timeout<'scope, 'd, F> {
fn new(
alarm: &'scope mut timer::Alarm<'d>,
deadline: clock::Deadline<'d>,
elapsed: Elapsed,
limit: Option<time::Duration>,
fiber: F,
) -> Self {
Self {
alarm,
deadline,
state: State::Idle(elapsed),
limit,
fiber,
}
}
}
impl<'d, F> Fiber<'d> for Timeout<'_, 'd, F>
where
F: Fiber<'d>,
{
type Output = Result<F::Output, Elapsed>;
fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<Self::Output> {
use core::task::Poll;
let (this, context) = call.into_parts();
let this = this.project();
let now = context.driver().driver_ref().clock().now();
let wake = context.completion();
match *this.state {
State::Idle(elapsed) => {
let (due, elapsed) = match *this.limit {
Some(duration) => elapsed.narrow(*this.deadline, now, duration),
None => (*this.deadline, elapsed),
};
if this.alarm.arm_and_poll(due, now, wake).is_ready() {
*this.state = State::Settled;
return Poll::Ready(Err(elapsed));
}
*this.state = State::Armed(elapsed);
}
State::Armed(elapsed) => {
if this.alarm.poll(now, wake).is_ready() {
*this.state = State::Settled;
return Poll::Ready(Err(elapsed));
}
}
State::Settled => return Poll::Pending,
}
match F::poll(context::PollCall {
fiber: this.fiber,
context,
}) {
Poll::Ready(output) => {
this.alarm.clear();
*this.state = State::Settled;
Poll::Ready(Ok(output))
}
Poll::Pending => Poll::Pending,
}
}
}
#[pin_project::pinned_drop]
impl<F> PinnedDrop for Timeout<'_, '_, F> {
fn drop(self: pin::Pin<&mut Self>) {
let this = self.project();
if matches!(*this.state, State::Armed(_)) {
this.alarm.clear();
}
}
}
const _: () = {
assert!(mem::size_of::<Error>() <= mem::size_of::<clock::Range>() + mem::size_of::<usize>());
assert!(mem::size_of::<Elapsed>() == 1);
assert!(mem::size_of::<State>() <= 2);
assert!(
mem::size_of::<Budget<'static>>()
== mem::size_of::<time::Instant>() + mem::size_of::<timer::Alarm<'static>>()
);
assert!(mem::size_of::<Scope<'static, 'static>>() == 2 * mem::size_of::<time::Instant>());
};