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
use std::fmt::{self, Debug};
use std::pin::Pin;
use std::marker::Unpin;
use futures_core::{Poll, Stream, FusedStream};
use futures_core::task::LocalWaker;
use crate::stream::{StreamExt, StreamFuture, FuturesUnordered};
#[must_use = "streams do nothing unless polled"]
pub struct SelectAll<St> {
inner: FuturesUnordered<StreamFuture<St>>,
}
impl<St: Debug> Debug for SelectAll<St> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "SelectAll {{ ... }}")
}
}
impl<St: Stream + Unpin> SelectAll<St> {
#[allow(clippy::new_without_default_derive)]
pub fn new() -> SelectAll<St> {
SelectAll { inner: FuturesUnordered::new() }
}
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn push(&mut self, stream: St) {
self.inner.push(stream.into_future());
}
}
impl<St: Stream + Unpin> Stream for SelectAll<St> {
type Item = St::Item;
fn poll_next(
mut self: Pin<&mut Self>,
lw: &LocalWaker,
) -> Poll<Option<Self::Item>> {
match self.inner.poll_next_unpin(lw) {
Poll::Pending => Poll::Pending,
Poll::Ready(Some((Some(item), remaining))) => {
self.push(remaining);
Poll::Ready(Some(item))
}
Poll::Ready(Some((None, _))) => {
self.inner.poll_next_unpin(lw);
Poll::Ready(None)
}
Poll::Ready(_) => Poll::Ready(None),
}
}
}
impl<St: Stream + Unpin> FusedStream for SelectAll<St> {
fn is_terminated(&self) -> bool {
self.inner.is_terminated()
}
}
pub fn select_all<I>(streams: I) -> SelectAll<I::Item>
where I: IntoIterator,
I::Item: Stream + Unpin
{
let mut set = SelectAll::new();
for stream in streams {
set.push(stream);
}
set
}