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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
use {Future, Poll, Async};
use task::{self, Task};
use executor::{self, Notify, Spawn};
use std::{error, fmt, mem, ops};
use std::cell::UnsafeCell;
use std::sync::{Arc, Mutex};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::collections::HashMap;
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F: Future> {
inner: Arc<Inner<F>>,
waiter: usize,
}
impl<F> fmt::Debug for Shared<F>
where F: Future + fmt::Debug,
F::Item: fmt::Debug,
F::Error: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Shared")
.field("inner", &self.inner)
.field("waiter", &self.waiter)
.finish()
}
}
struct Inner<F: Future> {
next_clone_id: AtomicUsize,
future: UnsafeCell<Option<Spawn<F>>>,
result: UnsafeCell<Option<Result<SharedItem<F::Item>, SharedError<F::Error>>>>,
notifier: Arc<Notifier>,
}
struct Notifier {
state: AtomicUsize,
waiters: Mutex<HashMap<usize, Task>>,
}
const IDLE: usize = 0;
const POLLING: usize = 1;
const REPOLL: usize = 2;
const COMPLETE: usize = 3;
const POISONED: usize = 4;
pub fn new<F: Future>(future: F) -> Shared<F> {
Shared {
inner: Arc::new(Inner {
next_clone_id: AtomicUsize::new(1),
notifier: Arc::new(Notifier {
state: AtomicUsize::new(IDLE),
waiters: Mutex::new(HashMap::new()),
}),
future: UnsafeCell::new(Some(executor::spawn(future))),
result: UnsafeCell::new(None),
}),
waiter: 0,
}
}
impl<F> Shared<F> where F: Future {
#[deprecated(since = "0.1.12", note = "use `Future::shared` instead")]
#[cfg(feature = "with-deprecated")]
#[doc(hidden)]
pub fn new(future: F) -> Self {
new(future)
}
pub fn peek(&self) -> Option<Result<SharedItem<F::Item>, SharedError<F::Error>>> {
match self.inner.notifier.state.load(SeqCst) {
COMPLETE => {
Some(unsafe { self.clone_result() })
}
POISONED => panic!("inner future panicked during poll"),
_ => None,
}
}
fn set_waiter(&mut self) {
let mut waiters = self.inner.notifier.waiters.lock().unwrap();
waiters.insert(self.waiter, task::current());
}
unsafe fn clone_result(&self) -> Result<SharedItem<F::Item>, SharedError<F::Error>> {
match *self.inner.result.get() {
Some(Ok(ref item)) => Ok(SharedItem { item: item.item.clone() }),
Some(Err(ref e)) => Err(SharedError { error: e.error.clone() }),
_ => unreachable!(),
}
}
fn complete(&self) {
unsafe { *self.inner.future.get() = None };
self.inner.notifier.state.store(COMPLETE, SeqCst);
self.inner.notifier.notify(0);
}
}
impl<F> Future for Shared<F>
where F: Future
{
type Item = SharedItem<F::Item>;
type Error = SharedError<F::Error>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.set_waiter();
match self.inner.notifier.state.compare_and_swap(IDLE, POLLING, SeqCst) {
IDLE => {
}
POLLING | REPOLL => {
return Ok(Async::NotReady);
}
COMPLETE => {
return unsafe { self.clone_result().map(Async::Ready) };
}
POISONED => panic!("inner future panicked during poll"),
_ => unreachable!(),
}
loop {
struct Reset<'a>(&'a AtomicUsize);
impl<'a> Drop for Reset<'a> {
fn drop(&mut self) {
use std::thread;
if thread::panicking() {
self.0.store(POISONED, SeqCst);
}
}
}
let _reset = Reset(&self.inner.notifier.state);
let res = unsafe {
(*self.inner.future.get()).as_mut().unwrap()
.poll_future_notify(&self.inner.notifier, 0)
};
match res {
Ok(Async::NotReady) => {
match self.inner.notifier.state.compare_and_swap(POLLING, IDLE, SeqCst) {
POLLING => {
return Ok(Async::NotReady);
}
REPOLL => {
let prev = self.inner.notifier.state.swap(POLLING, SeqCst);
assert_eq!(prev, REPOLL);
}
_ => unreachable!(),
}
}
Ok(Async::Ready(i)) => {
unsafe {
(*self.inner.result.get()) = Some(Ok(SharedItem { item: Arc::new(i) }));
}
break;
}
Err(e) => {
unsafe {
(*self.inner.result.get()) = Some(Err(SharedError { error: Arc::new(e) }));
}
break;
}
}
}
self.complete();
unsafe { self.clone_result().map(Async::Ready) }
}
}
impl<F> Clone for Shared<F> where F: Future {
fn clone(&self) -> Self {
let next_clone_id = self.inner.next_clone_id.fetch_add(1, SeqCst);
Shared {
inner: self.inner.clone(),
waiter: next_clone_id,
}
}
}
impl<F> Drop for Shared<F> where F: Future {
fn drop(&mut self) {
let mut waiters = self.inner.notifier.waiters.lock().unwrap();
waiters.remove(&self.waiter);
}
}
impl Notify for Notifier {
fn notify(&self, _id: usize) {
self.state.compare_and_swap(POLLING, REPOLL, SeqCst);
let waiters = mem::replace(&mut *self.waiters.lock().unwrap(), HashMap::new());
for (_, waiter) in waiters {
waiter.notify();
}
}
}
unsafe impl<F> Send for Inner<F>
where F: Future + Send,
F::Item: Send + Sync,
F::Error: Send + Sync,
{}
unsafe impl<F> Sync for Inner<F>
where F: Future + Send,
F::Item: Send + Sync,
F::Error: Send + Sync,
{}
impl<F> fmt::Debug for Inner<F>
where F: Future + fmt::Debug,
F::Item: fmt::Debug,
F::Error: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Inner")
.finish()
}
}
#[derive(Clone, Debug)]
pub struct SharedItem<T> {
item: Arc<T>,
}
impl<T> ops::Deref for SharedItem<T> {
type Target = T;
fn deref(&self) -> &T {
&self.item.as_ref()
}
}
#[derive(Clone, Debug)]
pub struct SharedError<E> {
error: Arc<E>,
}
impl<E> ops::Deref for SharedError<E> {
type Target = E;
fn deref(&self) -> &E {
&self.error.as_ref()
}
}
impl<E> fmt::Display for SharedError<E>
where E: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.error.fmt(f)
}
}
impl<E> error::Error for SharedError<E>
where E: error::Error,
{
fn description(&self) -> &str {
self.error.description()
}
#[allow(deprecated)]
fn cause(&self) -> Option<&error::Error> {
self.error.cause()
}
}