use std::{pin, task::Poll};
use crate::executor::task::{self, context};
use crate::driver::{
self,
schedule::{app, ready},
};
pub struct Context<'poll, 'd: 'poll, R> {
root: pin::Pin<&'poll mut R>,
wake: ready::Target<'d>,
work: app::Work<'poll, 'd>,
driver: &'poll mut driver::Local<'d>,
}
#[derive(Clone, Copy)]
pub struct Budget<'poll, 'd> {
wake: ready::Target<'d>,
work: app::Work<'poll, 'd>,
}
impl<'poll, 'd, R> Context<'poll, 'd, R> {
pub(crate) fn new(
root: pin::Pin<&'poll mut R>,
wake: ready::Target<'d>,
work: app::Work<'poll, 'd>,
driver: &'poll mut driver::Local<'d>,
) -> Self {
Self {
root,
wake,
work,
driver,
}
}
pub fn into_parts(
self,
) -> (
pin::Pin<&'poll mut R>,
ready::Target<'d>,
app::Work<'poll, 'd>,
&'poll mut driver::Local<'d>,
) {
(self.root, self.wake, self.work, self.driver)
}
pub fn into_poll(
self,
) -> (
pin::Pin<&'poll mut R>,
Budget<'poll, 'd>,
&'poll mut driver::Local<'d>,
) {
(self.root, Budget::new(self.wake, self.work), self.driver)
}
}
impl<'poll, 'd> Budget<'poll, 'd> {
pub(crate) const fn new(wake: ready::Target<'d>, work: app::Work<'poll, 'd>) -> Self {
Self { wake, work }
}
pub fn target(self) -> ready::Target<'d> {
self.wake
}
pub fn try_continue(self) -> Option<app::Permit<'poll, 'd>> {
let permit = self.work.permit();
if permit.is_none() {
self.wake.wake();
}
permit
}
}
pub trait Root<'d>: Sized {
const ADMITTED: bool = false;
type Output;
fn poll(context: Context<'_, 'd, Self>) -> Poll<Self::Output>;
}
impl<'d, F: task::Fiber<'d>> Root<'d> for F {
type Output = F::Output;
const ADMITTED: bool = true;
fn poll(call: Context<'_, 'd, Self>) -> Poll<Self::Output> {
let (fiber, target, work, driver) = call.into_parts();
let mut context = context::Context::new(target, work, driver);
F::poll(context::PollCall::from_root(fiber, &mut context))
}
}