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
#![no_std]
extern crate alloc;
use once_cell::sync::OnceCell;
use {
core::{
future::Future,
task::{Context, Poll},
pin::Pin,
},
alloc::{
boxed::Box,
sync::Arc,
},
woke::{waker_ref, Woke},
spin::Mutex
};
pub struct Executor {
task: Option<Arc<Task>>,
}
struct Task {
pub future: Mutex<Option<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>>,
}
impl Woke for Task {
fn wake_by_ref(_: &Arc<Self>) {
Executor::run()
}
}
impl Executor {
pub fn spawn(future: impl Future<Output = ()> + 'static + Send) {
let task = Arc::new(Task {
future: Mutex::new(Some(Box::pin(future))),
});
let mut e = get_executor().lock();
e.task = Some(task);
core::mem::drop(e);
Executor::run();
}
fn run() {
let e = get_executor().lock();
if let Some(task) = &e.task {
let mut future_slot = task.future.lock();
if let Some(mut future) = future_slot.take() {
let waker = waker_ref(&task);
let context = &mut Context::from_waker(&*waker);
if let Poll::Pending = future.as_mut().poll(context) {
*future_slot = Some(future);
}
}
}
}
}
fn get_executor() -> &'static Mutex<Executor> {
static INSTANCE: OnceCell<Mutex<Executor>> = OnceCell::new();
INSTANCE.get_or_init(|| Mutex::new(Executor { task: None }))
}