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
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use async_task::Task;
use crate::core;
use crate::threadunsafe::{ThreadUnsafeCell, ThreadUnsafeFuture, ThreadUnsafeRefCell};
lazy_static! {
static ref TASKS: ThreadUnsafeRefCell<VecDeque<Task<()>>> = Default::default();
}
pub type JoinHandle<T> = async_task::JoinHandle<T, ()>;
#[inline(always)]
pub fn block_on<F, T>(future: F) -> T
where
F: Future<Output = T>,
{
block_on_boxed(Box::pin(future))
}
fn block_on_boxed<F, T>(mut future: Pin<Box<F>>) -> T
where
F: Future<Output = T>,
{
let rerun = Arc::new(ThreadUnsafeCell::new(false));
let wakerun = rerun.clone();
let waker = async_task::waker_fn(move || wakerun.set(true));
let cx = &mut Context::from_waker(&waker);
loop {
if let Poll::Ready(result) = future.as_mut().poll(cx) {
return result;
}
while let Some(task) = TASKS.borrow_mut().pop_front() {
task.run();
}
if !rerun.replace(false) {
core::io();
}
}
}
pub fn spawn<F, T>(future: F) -> JoinHandle<T>
where
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
let (task, handle) = async_task::spawn(future, |task| TASKS.borrow_mut().push_back(task), ());
task.schedule();
handle
}
#[inline(always)]
pub fn spawn_local<F, T>(future: F) -> JoinHandle<T>
where
F: Future<Output = T> + 'static,
T: Send + 'static,
{
spawn(ThreadUnsafeFuture(future))
}