merge_streams/merge/
array.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, const N: usize> MergeStreams for [S; N]
10where
11    S: IntoStream,
12{
13    type Item = <Merge<S::IntoStream, N> as Stream>::Item;
14    type Stream = Merge<S::IntoStream, N>;
15
16    fn merge(self) -> Self::Stream {
17        Merge::new(self.map(|i| i.into_stream()))
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, const N: usize>
31where
32    S: Stream,
33{
34    #[pin]
35    streams: [Fuse<S>; N],
36}
37
38impl<S, const N: usize> Merge<S, N>
39where
40    S: Stream,
41{
42    pub(crate) fn new(streams: [S; N]) -> Self {
43        Self {
44            streams: streams.map(Fuse::new),
45        }
46    }
47}
48
49impl<S, const N: usize> Stream for Merge<S, N>
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        let mut arr: [usize; N] = {
62            // this is an inlined version of `core::array::from_fn`
63            // TODO: replace this with `core::array::from_fn` when it becomes stable
64            let cb = |n| n;
65            let mut idx = 0;
66            [(); N].map(|_| {
67                let res = cb(idx);
68                idx += 1;
69                res
70            })
71        };
72        arr.sort_by_cached_key(|_| utils::random(1000));
73
74        // Iterate over our streams one-by-one. If a stream yields a value,
75        // we exit early. By default we'll return `Poll::Ready(None)`, but
76        // this changes if we encounter a `Poll::Pending`.
77        let mut res = Poll::Ready(None);
78        for index in arr {
79            let stream = utils::get_pin_mut(this.streams.as_mut(), index).unwrap();
80            match stream.poll_next(cx) {
81                Poll::Ready(Some(item)) => return Poll::Ready(Some(item)),
82                Poll::Ready(None) => continue,
83                Poll::Pending => res = Poll::Pending,
84            }
85        }
86        res
87    }
88}