simple_async/
futures.rs

1use std::{
2    future::Future,
3    task::Poll,
4    time::{Duration, Instant},
5};
6
7pub struct Timer {
8    end: Instant,
9}
10
11impl Future for Timer {
12    type Output = ();
13
14    fn poll(
15        self: std::pin::Pin<&mut Self>,
16        cx: &mut std::task::Context<'_>,
17    ) -> std::task::Poll<Self::Output> {
18        if Instant::now() < self.end {
19            let end = self.end;
20            let waker = cx.waker().clone();
21            std::thread::spawn(move || {
22                std::thread::sleep(end - Instant::now());
23                waker.wake();
24            });
25
26            Poll::Pending
27        } else {
28            Poll::Ready(())
29        }
30    }
31}
32
33pub fn sleep(dur: Duration) -> Timer {
34    Timer {
35        end: Instant::now() + dur,
36    }
37}