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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use std::cell::UnsafeCell;
use std::fmt::{self, Debug};
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::mem;
use std::ptr;
use std::sync::atomic::Ordering::{Relaxed, SeqCst, Acquire, Release, AcqRel};
use std::sync::atomic::{AtomicPtr, AtomicBool};
use std::sync::{Arc, Weak};
use std::usize;
use {task, Stream, Future, Poll, Async, IntoFuture};
use executor::{Notify, UnsafeNotify, NotifyHandle};
use task_impl::{self, AtomicTask};
#[must_use = "streams do nothing unless polled"]
pub struct FuturesUnordered<F> {
inner: Arc<Inner<F>>,
len: usize,
head_all: *const Node<F>,
}
unsafe impl<T: Send> Send for FuturesUnordered<T> {}
unsafe impl<T: Sync> Sync for FuturesUnordered<T> {}
pub fn futures_unordered<I>(futures: I) -> FuturesUnordered<<I::Item as IntoFuture>::Future>
where I: IntoIterator,
I::Item: IntoFuture
{
let mut set = FuturesUnordered::new();
for future in futures {
set.push(future.into_future());
}
return set
}
#[allow(missing_debug_implementations)]
struct Inner<T> {
parent: AtomicTask,
head_readiness: AtomicPtr<Node<T>>,
tail_readiness: UnsafeCell<*const Node<T>>,
stub: Arc<Node<T>>,
}
struct Node<T> {
future: UnsafeCell<Option<T>>,
next_all: UnsafeCell<*const Node<T>>,
prev_all: UnsafeCell<*const Node<T>>,
next_readiness: AtomicPtr<Node<T>>,
queue: Weak<Inner<T>>,
queued: AtomicBool,
}
enum Dequeue<T> {
Data(*const Node<T>),
Empty,
Inconsistent,
}
impl<T> FuturesUnordered<T>
where T: Future,
{
pub fn new() -> FuturesUnordered<T> {
let stub = Arc::new(Node {
future: UnsafeCell::new(None),
next_all: UnsafeCell::new(ptr::null()),
prev_all: UnsafeCell::new(ptr::null()),
next_readiness: AtomicPtr::new(ptr::null_mut()),
queued: AtomicBool::new(true),
queue: Weak::new(),
});
let stub_ptr = &*stub as *const Node<T>;
let inner = Arc::new(Inner {
parent: AtomicTask::new(),
head_readiness: AtomicPtr::new(stub_ptr as *mut _),
tail_readiness: UnsafeCell::new(stub_ptr),
stub: stub,
});
FuturesUnordered {
len: 0,
head_all: ptr::null_mut(),
inner: inner,
}
}
}
impl<T> FuturesUnordered<T> {
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn push(&mut self, future: T) {
let node = Arc::new(Node {
future: UnsafeCell::new(Some(future)),
next_all: UnsafeCell::new(ptr::null_mut()),
prev_all: UnsafeCell::new(ptr::null_mut()),
next_readiness: AtomicPtr::new(ptr::null_mut()),
queued: AtomicBool::new(true),
queue: Arc::downgrade(&self.inner),
});
let ptr = self.link(node);
self.inner.enqueue(ptr);
}
fn release_node(&mut self, node: Arc<Node<T>>) {
let prev = node.queued.swap(true, SeqCst);
unsafe {
drop((*node.future.get()).take());
}
if prev {
mem::forget(node);
}
}
fn link(&mut self, node: Arc<Node<T>>) -> *const Node<T> {
let ptr = arc2ptr(node);
unsafe {
*(*ptr).next_all.get() = self.head_all;
if !self.head_all.is_null() {
*(*self.head_all).prev_all.get() = ptr;
}
}
self.head_all = ptr;
self.len += 1;
return ptr
}
unsafe fn unlink(&mut self, node: *const Node<T>) -> Arc<Node<T>> {
let node = ptr2arc(node);
let next = *node.next_all.get();
let prev = *node.prev_all.get();
*node.next_all.get() = ptr::null_mut();
*node.prev_all.get() = ptr::null_mut();
if !next.is_null() {
*(*next).prev_all.get() = prev;
}
if !prev.is_null() {
*(*prev).next_all.get() = next;
} else {
self.head_all = next;
}
self.len -= 1;
return node
}
}
impl<T> Stream for FuturesUnordered<T>
where T: Future
{
type Item = T::Item;
type Error = T::Error;
fn poll(&mut self) -> Poll<Option<T::Item>, T::Error> {
self.inner.parent.register();
loop {
let node = match unsafe { self.inner.dequeue() } {
Dequeue::Empty => {
if self.is_empty() {
return Ok(Async::Ready(None));
} else {
return Ok(Async::NotReady)
}
}
Dequeue::Inconsistent => {
task::current().notify();
return Ok(Async::NotReady);
}
Dequeue::Data(node) => node,
};
debug_assert!(node != self.inner.stub());
unsafe {
let mut future = match (*(*node).future.get()).take() {
Some(future) => future,
None => {
let node = ptr2arc(node);
assert!((*node.next_all.get()).is_null());
assert!((*node.prev_all.get()).is_null());
continue
}
};
let prev = (*node).queued.swap(false, SeqCst);
assert!(prev);
struct Bomb<'a, T: 'a> {
queue: &'a mut FuturesUnordered<T>,
node: Option<Arc<Node<T>>>,
}
impl<'a, T> Drop for Bomb<'a, T> {
fn drop(&mut self) {
if let Some(node) = self.node.take() {
self.queue.release_node(node);
}
}
}
let mut bomb = Bomb {
node: Some(self.unlink(node)),
queue: self,
};
let res = {
let notify = NodeToHandle(bomb.node.as_ref().unwrap());
task_impl::with_notify(¬ify, 0, || {
future.poll()
})
};
let ret = match res {
Ok(Async::NotReady) => {
let node = bomb.node.take().unwrap();
*node.future.get() = Some(future);
bomb.queue.link(node);
continue
}
Ok(Async::Ready(e)) => Ok(Async::Ready(Some(e))),
Err(e) => Err(e),
};
return ret
}
}
}
}
impl<T: Debug> Debug for FuturesUnordered<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "FuturesUnordered {{ ... }}")
}
}
impl<T> Drop for FuturesUnordered<T> {
fn drop(&mut self) {
unsafe {
while !self.head_all.is_null() {
let head = self.head_all;
let node = self.unlink(head);
self.release_node(node);
}
}
}
}
impl<F: Future> FromIterator<F> for FuturesUnordered<F> {
fn from_iter<T>(iter: T) -> Self
where T: IntoIterator<Item = F>
{
let mut new = FuturesUnordered::new();
for future in iter.into_iter() {
new.push(future);
}
new
}
}
impl<T> Inner<T> {
fn enqueue(&self, node: *const Node<T>) {
unsafe {
debug_assert!((*node).queued.load(Relaxed));
(*node).next_readiness.store(ptr::null_mut(), Relaxed);
let node = node as *mut _;
let prev = self.head_readiness.swap(node, AcqRel);
(*prev).next_readiness.store(node, Release);
}
}
unsafe fn dequeue(&self) -> Dequeue<T> {
let mut tail = *self.tail_readiness.get();
let mut next = (*tail).next_readiness.load(Acquire);
if tail == self.stub() {
if next.is_null() {
return Dequeue::Empty;
}
*self.tail_readiness.get() = next;
tail = next;
next = (*next).next_readiness.load(Acquire);
}
if !next.is_null() {
*self.tail_readiness.get() = next;
debug_assert!(tail != self.stub());
return Dequeue::Data(tail);
}
if self.head_readiness.load(Acquire) as *const _ != tail {
return Dequeue::Inconsistent;
}
self.enqueue(self.stub());
next = (*tail).next_readiness.load(Acquire);
if !next.is_null() {
*self.tail_readiness.get() = next;
return Dequeue::Data(tail);
}
Dequeue::Inconsistent
}
fn stub(&self) -> *const Node<T> {
&*self.stub
}
}
impl<T> Drop for Inner<T> {
fn drop(&mut self) {
unsafe {
loop {
match self.dequeue() {
Dequeue::Empty => break,
Dequeue::Inconsistent => abort("inconsistent in drop"),
Dequeue::Data(ptr) => drop(ptr2arc(ptr)),
}
}
}
}
}
#[allow(missing_debug_implementations)]
struct NodeToHandle<'a, T: 'a>(&'a Arc<Node<T>>);
impl<'a, T> Clone for NodeToHandle<'a, T> {
fn clone(&self) -> Self {
NodeToHandle(self.0)
}
}
impl<'a, T> From<NodeToHandle<'a, T>> for NotifyHandle {
fn from(handle: NodeToHandle<'a, T>) -> NotifyHandle {
unsafe {
let ptr = handle.0.clone();
let ptr = mem::transmute::<Arc<Node<T>>, *mut ArcNode<T>>(ptr);
NotifyHandle::new(hide_lt(ptr))
}
}
}
struct ArcNode<T>(PhantomData<T>);
unsafe impl<T> Send for ArcNode<T> {}
unsafe impl<T> Sync for ArcNode<T> {}
impl<T> Notify for ArcNode<T> {
fn notify(&self, _id: usize) {
unsafe {
let me: *const ArcNode<T> = self;
let me: *const *const ArcNode<T> = &me;
let me = me as *const Arc<Node<T>>;
Node::notify(&*me)
}
}
}
unsafe impl<T> UnsafeNotify for ArcNode<T> {
unsafe fn clone_raw(&self) -> NotifyHandle {
let me: *const ArcNode<T> = self;
let me: *const *const ArcNode<T> = &me;
let me = &*(me as *const Arc<Node<T>>);
NodeToHandle(me).into()
}
unsafe fn drop_raw(&self) {
let mut me: *const ArcNode<T> = self;
let me = &mut me as *mut *const ArcNode<T> as *mut Arc<Node<T>>;
ptr::drop_in_place(me);
}
}
unsafe fn hide_lt<T>(p: *mut ArcNode<T>) -> *mut UnsafeNotify {
mem::transmute(p as *mut UnsafeNotify)
}
impl<T> Node<T> {
fn notify(me: &Arc<Node<T>>) {
let inner = match me.queue.upgrade() {
Some(inner) => inner,
None => return,
};
let prev = me.queued.swap(true, SeqCst);
if !prev {
inner.enqueue(&**me);
inner.parent.notify();
}
}
}
impl<T> Drop for Node<T> {
fn drop(&mut self) {
unsafe {
if (*self.future.get()).is_some() {
abort("future still here when dropping");
}
}
}
}
fn arc2ptr<T>(ptr: Arc<T>) -> *const T {
let addr = &*ptr as *const T;
mem::forget(ptr);
return addr
}
unsafe fn ptr2arc<T>(ptr: *const T) -> Arc<T> {
let anchor = mem::transmute::<usize, Arc<T>>(0x10);
let addr = &*anchor as *const T;
mem::forget(anchor);
let offset = addr as isize - 0x10;
mem::transmute::<isize, Arc<T>>(ptr as isize - offset)
}
fn abort(s: &str) -> ! {
struct DoublePanic;
impl Drop for DoublePanic {
fn drop(&mut self) {
panic!("panicking twice to abort the program");
}
}
let _bomb = DoublePanic;
panic!("{}", s);
}