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
#![warn(clippy::pedantic)]
use futures::lock::BiLock;
use std::future::Future;
use std::marker::Unpin;
use std::pin::Pin;
use std::task::Waker;
use std::task::{Context, Poll};
enum State<T> {
Incomplete,
Waiting(Waker),
Complete(Option<T>),
}
impl<T> State<T> {
fn new(value: Option<T>) -> Self {
match value {
None => Self::Incomplete,
v @ Some(_) => Self::Complete(v),
}
}
}
pub struct ManualFuture<T: Unpin> {
state: BiLock<State<T>>,
}
pub struct ManualFutureCompleter<T: Unpin> {
state: BiLock<State<T>>,
}
impl<T: Unpin> ManualFutureCompleter<T> {
pub async fn complete(self, value: T) {
let mut state = self.state.lock().await;
match std::mem::replace(&mut *state, State::Complete(Some(value))) {
State::Incomplete => {}
State::Waiting(w) => w.wake(),
_ => panic!("future already completed"),
}
}
}
impl<T: Unpin> ManualFuture<T> {
pub fn new() -> (Self, ManualFutureCompleter<T>) {
let (a, b) = BiLock::new(State::new(None));
(
Self { state: a },
ManualFutureCompleter { state: b },
)
}
pub fn new_completed(value: T) -> Self {
let (state, _) = BiLock::new(State::new(Some(value)));
Self { state }
}
}
impl<T: Unpin> Future for ManualFuture<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut state = match self.state.poll_lock(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(v) => v,
};
match &mut *state {
s @ State::Incomplete => *s = State::Waiting(cx.waker().clone()),
State::Waiting(w) if w.will_wake(cx.waker()) => {}
s @ State::Waiting(_) => *s = State::Waiting(cx.waker().clone()),
State::Complete(v) => match v.take() {
Some(v) => return Poll::Ready(v),
None => panic!("future already polled to completion"),
},
}
Poll::Pending
}
}
#[cfg(test)]
mod tests {
use super::*;
use async_std::future::timeout;
use futures::executor::block_on;
use futures::future::join;
use std::thread::sleep;
use std::thread::spawn;
use std::time::Duration;
#[async_std::test]
async fn test_not_completed() {
let (future, _) = ManualFuture::<()>::new();
timeout(Duration::from_millis(100), future)
.await
.expect_err("should not complete");
}
#[async_std::test]
async fn test_manual_completed() {
let (future, completer) = ManualFuture::<()>::new();
assert_eq!(join(future, completer.complete(())).await, ((), ()));
}
#[async_std::test]
async fn test_pre_completed() {
assert_eq!(ManualFuture::new_completed(()).await, ());
}
#[test]
fn test_threaded() {
let (future, completer) = ManualFuture::<()>::new();
let t1 = spawn(move || {
assert_eq!(block_on(future), ());
});
let t2 = spawn(move || {
sleep(Duration::from_millis(100));
block_on(async {
completer.complete(()).await;
});
});
t1.join().unwrap();
t2.join().unwrap();
}
}