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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use crossbeam::channel;
use futures::future::BoxFuture;
use futures::task::{self, ArcWake};

use std::{
    cell::RefCell,
    future::Future,
    sync::{Arc, Mutex},
    task::Context,
};

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        future::Future,
        pin::Pin,
        sync::{Arc, Mutex},
        task::{Context, Poll, Waker},
        thread,
        time::{Duration, Instant},
    };

    #[test]
    fn test_runtime() {
        async fn delay(dur: Duration) {
            struct Delay {
                when: Instant,

                waker: Option<Arc<Mutex<Waker>>>,
            }

            impl Future for Delay {
                type Output = ();

                fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
                    if let Some(waker) = &self.waker {
                        let mut waker = waker.lock().unwrap();

                        if !waker.will_wake(cx.waker()) {
                            *waker = cx.waker().clone();
                        }
                    } else {
                        let when = self.when;
                        let waker = Arc::new(Mutex::new(cx.waker().clone()));
                        self.waker = Some(waker.clone());

                        thread::spawn(move || {
                            let now = Instant::now();

                            if now < when {
                                thread::sleep(when - now);
                            }

                            let waker = waker.lock().unwrap();
                            waker.wake_by_ref();
                        });
                    }

                    if Instant::now() >= self.when {
                        Poll::Ready(())
                    } else {
                        Poll::Pending
                    }
                }
            }

            let future = Delay {
                when: Instant::now() + dur,
                waker: None,
            };

            future.await;
        }

        let mini_tokio = MiniTokio::new();

        mini_tokio.spawn(async {
            spawn(async {
                delay(Duration::from_millis(100)).await;
                println!("world");
            });

            spawn(async {
                println!("hello");
            });

            delay(Duration::from_millis(200)).await;
            std::process::exit(0);
        });

        mini_tokio.run();
    }
}

pub struct MiniTokio {
    scheduled: channel::Receiver<Arc<Task>>,
    sender: channel::Sender<Arc<Task>>,
}

impl MiniTokio {
    pub fn new() -> MiniTokio {
        let (sender, scheduled) = channel::unbounded();

        MiniTokio { scheduled, sender }
    }

    pub fn spawn<F>(&self, future: F)
    where
        F: Future<Output = ()> + Send + 'static,
    {
        Task::spawn(future, &self.sender);
    }

    pub fn run(&self) {
        CURRENT.with(|cell| {
            *cell.borrow_mut() = Some(self.sender.clone());
        });

        while let Ok(task) = self.scheduled.recv() {
            task.poll();
        }
    }
}

pub fn spawn<F>(future: F)
where
    F: Future<Output = ()> + Send + 'static,
{
    CURRENT.with(|cell| {
        let borrow = cell.borrow();
        let sender = borrow.as_ref().unwrap();
        Task::spawn(future, sender);
    });
}

thread_local! {
    static CURRENT: RefCell<Option<channel::Sender<Arc<Task>>>> =
        RefCell::new(None);
}

struct Task {
    future: Mutex<BoxFuture<'static, ()>>,
    executor: channel::Sender<Arc<Task>>,
}

impl Task {
    fn spawn<F>(future: F, sender: &channel::Sender<Arc<Task>>)
    where
        F: Future<Output = ()> + Send + 'static,
    {
        let task = Arc::new(Task {
            future: Mutex::new(Box::pin(future)),
            executor: sender.clone(),
        });

        let _ = sender.send(task);
    }

    fn poll(self: Arc<Self>) {
        let waker = task::waker(self.clone());
        let mut cx = Context::from_waker(&waker);
        let mut future = self.future.try_lock().unwrap();
        let _ = future.as_mut().poll(&mut cx);
    }
}

impl ArcWake for Task {
    fn wake_by_ref(arc_self: &Arc<Self>) { let _ = arc_self.executor.send(arc_self.clone()); }
}