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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// SPDX-License-Identifier: MIT
// Copyright 2023 IROX Contributors
//

use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};

use crate::{LocalCompletableTask, LocalFuture};

trait LocalFutureType<'a>: Future<Output = ()> + 'a + HasLocalWaker {}

///
/// An Executor that doesn't spawn new threads, just runs on the current thread.
#[derive(Default)]
pub struct CurrentThreadExecutor<'a> {
    processing_queue: VecDeque<Pin<Box<dyn LocalFutureType<'a, Output = ()>>>>,
}

impl<'a> CurrentThreadExecutor<'a> {
    /// Create a new [`CurrentThreadExecutor`]
    pub fn new() -> Self {
        CurrentThreadExecutor::default()
    }

    ///
    /// Submit a new task to this executor.  Note:  This does not immediately run the task, you
    /// still need to call either [`CurrentThreadExecutor::run_some`] or
    /// [`CurrentThreadExecutor::run_until_complete`]
    pub fn submit<T: 'a, F: Future<Output = T> + 'a>(&mut self, fut: F) -> LocalTaskHandle<T> {
        let task = LocalTask {
            future: Box::pin(fut),
            waker: Arc::new(LocalWaker::default()),
            complete: LocalCompletableTask::new(),
        };
        let handle = task.join_handle();
        self.processing_queue.push_back(Box::pin(task));
        handle
    }

    ///
    /// Runs a single loop through the processing queue, in order, letting each task attempt to do
    /// work.
    pub fn run_some(&mut self) {
        let mut pinned = Pin::new(self);
        let mut pending = VecDeque::new();
        while let Some(mut task) = pinned.processing_queue.pop_front() {
            if !task.needs_wake() {
                pending.push_back(task);
                continue;
            }
            let waker = Waker::from(task.get_waker());
            let mut context = Context::from_waker(&waker);

            match task.as_mut().poll(&mut context) {
                Poll::Ready(()) => {}
                Poll::Pending => {
                    // reschedule task again.
                    task.get_waker()
                        .needs_running
                        .store(false, Ordering::Relaxed);
                    pending.push_back(task);
                }
            }
        }
        pinned.processing_queue.append(&mut pending);
    }

    ///
    /// Runs this executor until all submitted tasks are complete.
    pub fn run_until_complete(&mut self) {
        while !self.processing_queue.is_empty() {
            self.run_some();
        }
    }
}

///
/// Local thread Waker struct
pub struct LocalWaker {
    needs_running: AtomicBool,
}

impl Default for LocalWaker {
    fn default() -> Self {
        LocalWaker {
            needs_running: AtomicBool::new(true),
        }
    }
}

impl Wake for LocalWaker {
    fn wake(self: Arc<Self>) {
        self.needs_running.store(true, Ordering::Relaxed);
    }
}

trait HasLocalWaker {
    fn needs_wake(&self) -> bool;
    fn clear_wake(&self);
    fn get_waker(&self) -> Arc<LocalWaker>;
}
///
/// A task that can be run on the current thread.
pub struct LocalTask<'a, T> {
    future: LocalFuture<'a, T>,
    waker: Arc<LocalWaker>,
    complete: LocalCompletableTask<T>,
}
impl<'a, T> HasLocalWaker for LocalTask<'a, T>
where
    T: 'a,
{
    fn needs_wake(&self) -> bool {
        self.waker.needs_running.load(Ordering::Relaxed)
    }

    fn clear_wake(&self) {
        self.waker.needs_running.store(false, Ordering::Relaxed);
    }

    fn get_waker(&self) -> Arc<LocalWaker> {
        self.waker.clone()
    }
}
impl<'a, T> LocalTask<'a, T>
where
    T: 'a,
{
    pub fn join_handle(&self) -> LocalTaskHandle<T> {
        LocalTaskHandle {
            result: self.complete.clone(),
        }
    }
}

impl<'a, T> Future for LocalTask<'a, T> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mself = self.get_mut();
        match mself.future.as_mut().poll(cx) {
            Poll::Ready(e) => {
                let _ign = mself.complete.try_complete(e);
                Poll::Ready(())
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl<'a, T: 'a> LocalFutureType<'a> for LocalTask<'a, T> {}

///
/// A handle to the submitted task, to retrieve the result of the operation
pub struct LocalTaskHandle<T> {
    result: LocalCompletableTask<T>,
}

impl<T> LocalTaskHandle<T> {
    ///
    /// Attempts to retrive the result of the operation.  If the operation isn't complete yet,
    /// returns [`None`]
    pub fn get(&mut self) -> Option<T> {
        match self.result.get() {
            Poll::Ready(e) => Some(e),
            Poll::Pending => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::CurrentThreadExecutor;

    #[test]
    pub fn test() {
        let mut executor = CurrentThreadExecutor::new();

        let mut handle = executor.submit(async { println!("Hello async") });
        let mut handle2 = executor.submit(async { println!("Hello async2") });

        assert_eq!(None, handle.get());
        assert_eq!(None, handle2.get());

        executor.run_until_complete();

        assert_ne!(None, handle.get());
        assert_ne!(None, handle2.get());
    }
}