merge_streams/merge/
vec.rs

1use crate::stream::IntoStream;
2use crate::utils::{self, Fuse};
3use crate::MergeStreams;
4
5use futures_core::Stream;
6use std::pin::Pin;
7use std::task::{Context, Poll};
8
9impl<S> MergeStreams for Vec<S>
10where
11    S: IntoStream,
12{
13    type Item = <Merge<S::IntoStream> as Stream>::Item;
14    type Stream = Merge<S::IntoStream>;
15
16    fn merge(self) -> Self::Stream {
17        Merge::new(self.into_iter().map(|i| i.into_stream()).collect())
18    }
19}
20
21/// A stream that merges multiple streams into a single stream.
22///
23/// This `struct` is created by the [`merge`] method on [`Stream`]. See its
24/// documentation for more.
25///
26/// [`merge`]: trait.Stream.html#method.merge
27/// [`Stream`]: trait.Stream.html
28#[derive(Debug)]
29#[pin_project::pin_project]
30pub struct Merge<S>
31where
32    S: Stream,
33{
34    #[pin]
35    streams: Vec<Fuse<S>>,
36}
37
38impl<S> Merge<S>
39where
40    S: Stream,
41{
42    pub(crate) fn new(streams: Vec<S>) -> Self {
43        Self {
44            streams: streams.into_iter().map(Fuse::new).collect(),
45        }
46    }
47}
48
49impl<S> Stream for Merge<S>
50where
51    S: Stream,
52{
53    type Item = S::Item;
54
55    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
56        let mut this = self.project();
57
58        // Randomize the indexes into our streams array. This ensures that when
59        // multiple streams are ready at the same time, we don't accidentally
60        // exhaust one stream before another.
61        // Randomize the indexes into our streams array. This ensures that when
62        // multiple streams are ready at the same time, we don't accidentally
63        // exhaust one stream before another.
64        let mut indexes: Vec<_> = (0..this.streams.len()).into_iter().collect();
65        indexes.sort_by_cached_key(|_| utils::random(1000));
66
67        // Iterate over our streams one-by-one. If a stream yields a value,
68        // we exit early. By default we'll return `Poll::Ready(None)`, but
69        // this changes if we encounter a `Poll::Pending`.
70        let mut res = Poll::Ready(None);
71        for index in indexes {
72            let stream = utils::get_pin_mut_from_vec(this.streams.as_mut(), index).unwrap();
73            match stream.poll_next(cx) {
74                Poll::Ready(Some(item)) => return Poll::Ready(Some(item)),
75                Poll::Ready(None) => continue,
76                Poll::Pending => res = Poll::Pending,
77            }
78        }
79        res
80    }
81}