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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! A local executor, for running a single task with IO on the current thread.

use self::timer::Timer;
use crate::sys::local as sys;
use crate::timer::Instant;
use crate::timer::PollTimer;
use crate::timer::TimerDriver;
use crate::timer::TimerQueue;
use crate::timer::TimerResult;
use crate::waker::WakerList;
use futures::task::waker_ref;
use futures::task::ArcWake;
use parking_lot::Condvar;
use parking_lot::MappedMutexGuard;
use parking_lot::Mutex;
use parking_lot::MutexGuard;
use std::future::Future;
use std::pin::pin;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;

/// Polls a future that needs to issue IO until it completes.
pub fn block_with_io<F, Fut, R>(f: F) -> R
where
    F: FnOnce(LocalDriver) -> Fut,
    Fut: Future<Output = R>,
{
    let mut executor = LocalExecutor::new();
    let fut = f(executor.driver());
    executor.run_until(pin!(fut))
}

/// An executor that runs on a single thread and runs only one future.
struct LocalExecutor {
    inner: Arc<LocalInner>,
}

impl LocalExecutor {
    fn new() -> Self {
        Self {
            inner: Arc::new(LocalInner::default()),
        }
    }

    fn driver(&self) -> LocalDriver {
        LocalDriver {
            inner: self.inner.clone(),
        }
    }

    fn run_until<F: Future>(&mut self, mut fut: Pin<&mut F>) -> F::Output {
        let waker = waker_ref(&self.inner);
        let mut cx = Context::from_waker(&waker);
        loop {
            match fut.as_mut().poll(&mut cx) {
                Poll::Ready(r) => break r,
                Poll::Pending => self.inner.wait(),
            }
        }
    }
}

/// An IO driver for single-task use on a single thread.
#[derive(Debug, Clone)]
pub struct LocalDriver {
    pub(crate) inner: Arc<LocalInner>,
}

#[derive(Default, Debug)]
pub(crate) struct LocalInner {
    state: Mutex<LocalState>,
    wait_state: Mutex<sys::WaitState>,
    condvar: Condvar,
    wait_cancel: sys::WaitCancel,
}

#[derive(Debug, PartialEq, Eq)]
enum OpState {
    // The executor is running.
    Running,
    // The executor should poll its task again without waiting.
    RunAgain,
    // The executor is waiting on IO.
    Waiting,
    // The executor wait has been cancelled.
    Woken,
}

impl Default for OpState {
    fn default() -> Self {
        Self::Running
    }
}

#[derive(Debug, Default)]
struct LocalState {
    op_state: OpState,
    sys: sys::State,
    timers: TimerQueue,
}

impl LocalInner {
    pub fn lock_sys_state(&self) -> MappedMutexGuard<'_, sys::State> {
        MutexGuard::map(self.lock_state(), |x| &mut x.sys)
    }

    // Locks the state for mutation.
    //
    // If the executor is currently waiting, then wakes up the executor first to
    // ensure that the executor never sees state changes between pre_wait and
    // post_wait.
    fn lock_state(&self) -> MutexGuard<'_, LocalState> {
        let mut guard = self.state.lock();
        loop {
            match guard.op_state {
                OpState::Running | OpState::RunAgain => break,

                OpState::Waiting => {
                    guard.op_state = OpState::Woken;
                    // Although it would be better to call this outside the
                    // lock, doing so might result in live lock since the
                    // executor could loop around and take the lock again before
                    // we get a chance to. With this approach, the condition
                    // variable notify will put this thread directly on the
                    // mutex queue.
                    self.wait_cancel.cancel_wait();
                    self.condvar.wait(&mut guard);
                }
                OpState::Woken => {
                    self.condvar.wait(&mut guard);
                }
            }
        }
        guard
    }

    fn wait(&self) {
        let mut state = self.state.lock();
        if state.op_state != OpState::Running {
            assert_eq!(state.op_state, OpState::RunAgain);
            state.op_state = OpState::Running;
            return;
        }

        let mut wait_state = self
            .wait_state
            .try_lock()
            .expect("wait should not be called concurrently");

        state.sys.pre_wait(&mut wait_state, &self.wait_cancel);

        let timeout = state.timers.next_deadline().map(|deadline| {
            let now = Instant::now();
            deadline.max(now) - now
        });

        {
            state.op_state = OpState::Waiting;
            drop(state);
            wait_state.wait(&self.wait_cancel, timeout);
            state = self.state.lock();
            state.op_state = OpState::Running;
        }

        let mut wakers = WakerList::default();
        state.sys.post_wait(&mut wait_state, &mut wakers);
        state.timers.wake_expired(&mut wakers);
        drop(state);
        wakers.wake();
        // Notify mutators that the wait has finished.
        self.condvar.notify_all();
    }
}

impl ArcWake for LocalInner {
    fn wake_by_ref(arc_self: &Arc<Self>) {
        let mut state = arc_self.state.lock();
        match state.op_state {
            OpState::Running => state.op_state = OpState::RunAgain,
            OpState::RunAgain => {}
            OpState::Waiting => {
                state.op_state = OpState::Woken;
                drop(state);
                arc_self.wait_cancel.cancel_wait();
            }
            OpState::Woken => {}
        }
    }
}

// Use a separate module so that `Timer` is not visible.
mod timer {
    use super::LocalInner;
    use crate::timer::TimerQueueId;
    use std::sync::Arc;

    #[derive(Debug)]
    pub struct Timer {
        pub(super) inner: Arc<LocalInner>,
        pub(super) id: TimerQueueId,
    }
}

impl TimerDriver for LocalDriver {
    type Timer = Timer;

    fn new_timer(&self) -> Self::Timer {
        let id = self.inner.lock_state().timers.add();
        Timer {
            inner: self.inner.clone(),
            id,
        }
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        let _waker = self.inner.lock_state().timers.remove(self.id);
    }
}

impl PollTimer for Timer {
    fn poll_timer(&mut self, cx: &mut Context<'_>, deadline: Option<Instant>) -> Poll<Instant> {
        let mut state = self.inner.lock_state();
        if let Some(deadline) = deadline {
            state.timers.set_deadline(self.id, deadline);
        }
        match state.timers.poll_deadline(cx, self.id) {
            TimerResult::TimedOut(now) => Poll::Ready(now),
            TimerResult::Pending(_) => Poll::Pending,
        }
    }

    fn set_deadline(&mut self, deadline: Instant) {
        self.inner
            .lock_state()
            .timers
            .set_deadline(self.id, deadline);
    }
}

#[cfg(test)]
mod tests {
    use super::block_with_io;
    use crate::executor_tests;

    #[test]
    fn waker_works() {
        block_with_io(|_| executor_tests::waker_tests())
    }

    #[test]
    fn sleep_works() {
        block_with_io(executor_tests::sleep_tests)
    }

    #[test]
    fn wait_works() {
        block_with_io(executor_tests::wait_tests)
    }

    #[test]
    fn socket_works() {
        block_with_io(executor_tests::socket_tests)
    }

    #[cfg(windows)]
    #[test]
    fn overlapped_file_works() {
        block_with_io(executor_tests::windows::overlapped_file_tests)
    }
}