1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use crate::timer_now;
use alloc::boxed::Box;
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use core::time::Duration;
pub fn yield_now() -> impl Future<Output = ()> {
YieldFuture::default()
}
#[must_use = "yield_now does nothing unless polled/`await`-ed"]
#[derive(Default)]
struct YieldFuture {
flag: bool,
}
impl Future for YieldFuture {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
if self.flag {
Poll::Ready(())
} else {
self.flag = true;
cx.waker().clone().wake();
Poll::Pending
}
}
}
pub fn sleep_until(deadline: Duration) -> impl Future {
SleepFuture { deadline }
}
#[must_use = "sleep does nothing unless polled/`await`-ed"]
pub struct SleepFuture {
deadline: Duration,
}
impl Future for SleepFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
if timer_now() >= self.deadline {
return Poll::Ready(());
}
if self.deadline.as_nanos() < i64::max_value() as u128 {
let waker = cx.waker().clone();
crate::timer_set(self.deadline, Box::new(move |_| waker.wake()));
}
Poll::Pending
}
}
pub fn serial_getchar() -> impl Future<Output = u8> {
SerialFuture
}
#[must_use = "serial_getchar does nothing unless polled/`await`-ed"]
pub struct SerialFuture;
impl Future for SerialFuture {
type Output = u8;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut buf = [0u8];
if crate::serial_read(&mut buf) != 0 {
return Poll::Ready(buf[0]);
}
let waker = cx.waker().clone();
crate::serial_set_callback(Box::new({
move || {
waker.wake_by_ref();
true
}
}));
Poll::Pending
}
}