use crate::event::park;
use crate::scheduler::{self, TaskId};
use core::future::Future;
use core::pin::pin;
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
static VTABLE: RawWakerVTable = RawWakerVTable::new(clone_fn, wake_fn, wake_by_ref_fn, drop_fn);
unsafe fn clone_fn(p: *const ()) -> RawWaker {
RawWaker::new(p, &VTABLE)
}
unsafe fn wake_fn(p: *const ()) {
scheduler::wake_task(p as usize as u32);
}
unsafe fn wake_by_ref_fn(p: *const ()) {
scheduler::wake_task(p as usize as u32);
}
unsafe fn drop_fn(_: *const ()) {}
pub fn task_waker(id: TaskId) -> Waker {
unsafe { Waker::from_raw(RawWaker::new(id.raw() as usize as *const (), &VTABLE)) }
}
pub fn current_waker() -> Waker {
task_waker(scheduler::current_id())
}
pub fn block_on<F: Future>(fut: F) -> F::Output {
let me = scheduler::current_id();
let waker = task_waker(me);
let mut cx = Context::from_waker(&waker);
let mut fut = pin!(fut);
loop {
scheduler::clear_wake_flag();
scheduler::clear_timer_deadline();
if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
return v;
}
let d = scheduler::task_timer_deadline();
let _ = park(if d == 0 { None } else { Some(d) });
}
}
pub fn spawn_async<F>(f: F) -> Result<(), crate::SpawnError>
where
F: Future<Output = ()> + Send + 'static,
{
crate::thread::try_spawn(move || {
block_on(f);
})
}
pub struct Sleep {
deadline_tick: u64,
}
impl Sleep {
pub const fn until_tick(deadline_tick: u64) -> Self {
Sleep { deadline_tick }
}
pub const fn deadline_tick(&self) -> u64 {
self.deadline_tick
}
}
impl Future for Sleep {
type Output = ();
fn poll(self: core::pin::Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
if scheduler::tick_count() >= self.deadline_tick {
return Poll::Ready(());
}
scheduler::set_timer_deadline(self.deadline_tick);
Poll::Pending
}
}
pub fn sleep(d: core::time::Duration) -> Sleep {
Sleep::until_tick(scheduler::deadline_after_ticks(crate::time::ticks_for(d)))
}
pub const fn sleep_until_tick(deadline_tick: u64) -> Sleep {
Sleep::until_tick(deadline_tick)
}
pub struct SignalWait<'a> {
signal: &'a crate::event::Signal,
deadline_tick: u64,
}
impl<'a> SignalWait<'a> {
pub const fn new(signal: &'a crate::event::Signal, deadline_tick: u64) -> Self {
SignalWait {
signal,
deadline_tick,
}
}
}
impl Future for SignalWait<'_> {
type Output = Result<(), crate::event::Timeout>;
fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.signal.try_take() {
return Poll::Ready(Ok(()));
}
if self.deadline_tick != 0 && scheduler::tick_count() >= self.deadline_tick {
return Poll::Ready(Err(crate::event::Timeout));
}
scheduler::set_timer_deadline(if self.deadline_tick == 0 {
scheduler::tick_count().wrapping_add(1)
} else {
self.deadline_tick
});
let _ = cx;
Poll::Pending
}
}