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
//! Futures executor for cooperative multitasking

use {
    alloc::collections::VecDeque,
    core::{
        future::Future,
        task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
    },
    task::Task,
};

mod task;

/// Basic executor for async tasks
pub struct Executor {
    tasks: VecDeque<Task>,
}

impl Executor {
    /// Create new empty Executor
    pub fn new() -> Self {
        Self {
            tasks: VecDeque::new(),
        }
    }

    /// Spawn a new task on the executor
    pub fn spawn(&mut self, fut: impl Future<Output = ()> + 'static) {
        self.tasks.push_back(Task::new(fut))
    }

    /// Run the executor, polling tasks repeatedly
    pub fn run(&mut self) {
        while let Some(mut task) = self.tasks.pop_front() {
            let waker = new_waker();
            let mut context = Context::from_waker(&waker);
            match task.poll(&mut context) {
                Poll::Ready(()) => {}
                Poll::Pending => self.tasks.push_back(task),
            }
        }
    }
}

/// Create a new dummy RawWaker
fn new_raw_waker() -> RawWaker {
    fn no_op(_: *const ()) {}
    fn clone(_: *const ()) -> RawWaker {
        new_raw_waker()
    }

    let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op);
    RawWaker::new(0 as *const (), vtable)
}

/// Create a new dummy Waker
fn new_waker() -> Waker {
    unsafe { Waker::from_raw(new_raw_waker()) }
}