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
use crate::*;
use core::ops::DerefMut;
use core::pin::Pin;
use core::task::{Context, Poll};
fn poll_multiple<I, P, S>(
streams: I,
cx: &mut Context<'_>,
before: Option<&S::Ordering>,
) -> Poll<PollResult<S::Ordering, S::Data>>
where
I: IntoIterator<Item = Pin<P>>,
P: DerefMut<Target = Peekable<S>>,
S: OrderedStream,
{
let mut best: Option<Pin<P>> = None;
let mut has_data = false;
let mut has_pending = true;
for mut stream in streams {
let best_before = best.as_ref().and_then(|p| p.item().map(|i| &i.0));
let before = match (before, best_before) {
(Some(a), Some(b)) if a < b => Some(a),
(_, Some(b)) => Some(b),
(a, None) => a,
};
match stream.as_mut().poll_peek_before(cx, before) {
Poll::Pending => {
has_pending = true;
}
Poll::Ready(PollResult::Terminated) => continue,
Poll::Ready(PollResult::NoneBefore) => {
has_data = true;
}
Poll::Ready(PollResult::Item { ordering, .. }) => {
match before {
_ if has_pending => continue,
Some(max) if max < ordering => continue,
_ => {
best = Some(stream);
}
}
}
}
}
match best {
_ if has_pending => Poll::Pending,
Some(mut stream) => stream.as_mut().poll_next_before(cx, before),
None if has_data => Poll::Ready(PollResult::NoneBefore),
None => Poll::Ready(PollResult::Terminated),
}
}
#[derive(Debug, Default, Clone)]
pub struct JoinMultiple<C>(pub C);
impl<C> Unpin for JoinMultiple<C> {}
impl<C, S> OrderedStream for JoinMultiple<C>
where
for<'a> &'a mut C: IntoIterator<Item = &'a mut Peekable<S>>,
S: OrderedStream + Unpin,
{
type Ordering = S::Ordering;
type Data = S::Data;
fn poll_next_before(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
before: Option<&S::Ordering>,
) -> Poll<PollResult<S::Ordering, S::Data>> {
poll_multiple(self.get_mut().0.into_iter().map(Pin::new), cx, before)
}
}
pin_project_lite::pin_project! {
#[derive(Debug,Default,Clone)]
pub struct JoinMultiplePin<C> {
#[pin]
pub streams: C,
}
}
impl<C> JoinMultiplePin<C> {
pub fn as_pin_mut(self: Pin<&mut Self>) -> Pin<&mut C> {
self.project().streams
}
}
impl<C, S> OrderedStream for JoinMultiplePin<C>
where
for<'a> Pin<&'a mut C>: IntoIterator<Item = Pin<&'a mut Peekable<S>>>,
S: OrderedStream,
{
type Ordering = S::Ordering;
type Data = S::Data;
fn poll_next_before(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
before: Option<&S::Ordering>,
) -> Poll<PollResult<S::Ordering, S::Data>> {
poll_multiple(self.as_pin_mut(), cx, before)
}
}