1#![doc = include_str!(concat!(env!("OUT_DIR"), "/README.md"))]
2
3use futures::Stream;
4use std::cmp::Ordering;
5use std::collections::BinaryHeap;
6use std::pin::Pin;
7use std::sync::Arc;
8use std::task::{Context, Poll};
9
10pub fn mux_by<S, T, F>(streams: Vec<S>, cmp: F) -> MuxBy<S, T, F>
11where
12 S: Stream<Item = T> + Unpin,
13 F: Fn(&T, &T) -> Ordering + Unpin + Sync + 'static,
14{
15 let n = streams.len();
16 MuxBy {
17 streams,
18 cmp: Arc::new(cmp),
19 heap: BinaryHeap::new(),
20 in_heap: vec![false; n],
21 done: vec![false; n],
22 }
23}
24
25pub struct MuxBy<S, T, F>
26where
27 S: Stream<Item = T> + Unpin,
28 F: Fn(&T, &T) -> Ordering + Unpin + Sync + 'static,
29{
30 streams: Vec<S>,
31 cmp: Arc<F>,
32 heap: BinaryHeap<HeapItem<T, F>>,
33 in_heap: Vec<bool>,
34 done: Vec<bool>,
35}
36
37struct HeapItem<T, F>
38where
39 F: Fn(&T, &T) -> Ordering + Unpin + Sync + 'static,
40{
41 value: T,
42 src: usize,
43 cmp: Arc<F>,
44}
45
46impl<T, F> PartialEq for HeapItem<T, F>
47where
48 F: Fn(&T, &T) -> Ordering + Unpin + Sync + 'static,
49{
50 fn eq(&self, other: &Self) -> bool {
53 (self.cmp)(&self.value, &other.value) == Ordering::Equal && self.src == other.src
54 }
55}
56
57impl<T, F> Eq for HeapItem<T, F> where F: Fn(&T, &T) -> Ordering + Unpin + Sync + 'static {}
58
59impl<T, F> PartialOrd for HeapItem<T, F>
60where
61 F: Fn(&T, &T) -> Ordering + Unpin + Sync + 'static,
62{
63 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
64 Some(self.cmp(other))
65 }
66}
67
68impl<T, F> Ord for HeapItem<T, F>
69where
70 F: Fn(&T, &T) -> Ordering + Unpin + Sync + 'static,
71{
72 fn cmp(&self, other: &Self) -> Ordering {
73 (self.cmp)(&self.value, &other.value)
74 .reverse()
75 .then_with(|| self.src.cmp(&other.src).reverse())
76 }
77}
78
79impl<S, T, F> Stream for MuxBy<S, T, F>
80where
81 S: Stream<Item = T> + Unpin,
82 F: Fn(&T, &T) -> Ordering + Unpin + Sync + 'static,
83 T: Unpin,
84{
85 type Item = T;
86
87 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
88 let this = self.get_mut();
89
90 for (idx, stream) in this.streams.iter_mut().enumerate() {
92 if !this.in_heap[idx] && !this.done[idx] {
93 match Pin::new(stream).poll_next(cx) {
94 Poll::Ready(Some(item)) => {
95 this.heap.push(HeapItem {
96 value: item,
97 src: idx,
98 cmp: this.cmp.clone(),
99 });
100 this.in_heap[idx] = true;
101 }
102 Poll::Ready(None) => {
103 this.done[idx] = true;
105 }
106 Poll::Pending => {} }
108 }
109 }
110
111 let alive = this.done.iter().filter(|&&d| !d).count();
112 if alive == 0 {
113 return Poll::Ready(None);
114 }
115 let heads = this
116 .in_heap
117 .iter()
118 .zip(&this.done)
119 .filter(|&(&in_h, &d)| in_h && !d)
120 .count();
121 if heads < alive {
122 return Poll::Pending;
123 }
124
125 debug_assert_eq!(this.heap.len(), heads, "heap/in_heap mismatch");
126 if let Some(HeapItem { value, src, .. }) = this.heap.pop() {
127 this.in_heap[src] = false;
128 Poll::Ready(Some(value))
129 } else {
130 unreachable!("heap empty despite heads == alive > 0")
131 }
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138 use futures::{StreamExt, stream};
139
140 #[tokio::test(flavor = "current_thread")]
141 async fn merge_two_streams_ascending() {
142 let s1 = stream::iter(vec![1, 3, 5]);
143 let s2 = stream::iter(vec![2, 4, 6]);
144
145 let merged = mux_by(vec![s1, s2], |a: &i32, b: &i32| a.cmp(b));
146 let out: Vec<_> = merged.collect().await;
147
148 assert_eq!(out, vec![1, 2, 3, 4, 5, 6]);
149 }
150
151 #[tokio::test(flavor = "current_thread")]
152 async fn merge_three_streams_ascending() {
153 let s1 = stream::iter(vec![1, 10, 11]);
154 let s2 = stream::iter(vec![2, 3, 12]);
155 let s3 = stream::iter(vec![4, 5, 6, 13]);
156
157 let merged = mux_by(vec![s1, s2, s3], |a: &i32, b: &i32| a.cmp(b));
158 let out: Vec<_> = merged.collect().await;
159
160 assert_eq!(out, vec![1, 2, 3, 4, 5, 6, 10, 11, 12, 13]);
161 }
162
163 #[tokio::test(flavor = "current_thread")]
164 async fn merge_descending_order() {
165 let s1 = stream::iter(vec![9, 7, 5]);
167 let s2 = stream::iter(vec![8, 6, 0]);
168
169 let merged = mux_by(vec![s1, s2], |a: &i32, b: &i32| b.cmp(a)); let out: Vec<_> = merged.collect().await;
171
172 assert_eq!(out, vec![9, 8, 7, 6, 5, 0]);
173 }
174
175 #[tokio::test(flavor = "current_thread")]
176 async fn handles_empty_streams() {
177 let s1 = stream::iter(Vec::<i32>::new());
178 let s2 = stream::iter(vec![1, 2, 3]);
179 let s3 = stream::iter(Vec::<i32>::new());
180
181 let merged = mux_by(vec![s1, s2, s3], |a: &i32, b: &i32| a.cmp(b));
182 let out: Vec<_> = merged.collect().await;
183
184 assert_eq!(out, vec![1, 2, 3]);
185 }
186
187 #[tokio::test(flavor = "current_thread")]
188 async fn handles_all_empty() {
189 let merged = mux_by(vec![stream::empty::<i32>()], |a, b| a.cmp(b));
190 let out: Vec<_> = merged.collect().await;
191 assert!(out.is_empty());
192
193 let merged_none: Vec<stream::Iter<std::vec::IntoIter<i32>>> = Vec::new();
194 let merged = mux_by(merged_none, |a: &i32, b: &i32| a.cmp(b));
195 let out: Vec<_> = merged.collect().await;
196 assert!(out.is_empty());
197 }
198
199 #[tokio::test(flavor = "current_thread")]
200 async fn deterministic_tie_break_by_source_index() {
201 let s0 = stream::iter(vec![1, 1, 1]);
203 let s1 = stream::iter(vec![1, 1]);
204
205 let merged = mux_by(vec![s0, s1], |a: &i32, b: &i32| a.cmp(b));
206 let out: Vec<_> = merged.collect().await;
207
208 assert_eq!(out, vec![1, 1, 1, 1, 1]);
211 }
212
213 #[test]
214 fn waits_for_missing_head_then_unblocks_in_order() {
215 use futures::{
216 channel::mpsc,
217 stream::Stream,
218 task::{Context, noop_waker},
219 };
220 use std::{pin::Pin, task::Poll};
221
222 let (tx_a, rx_a) = mpsc::unbounded::<i32>();
224 let (tx_b, rx_b) = mpsc::unbounded::<i32>();
225
226 let mut mux = mux_by(vec![rx_a, rx_b], |a, b| a.cmp(b));
228
229 let waker = noop_waker();
231 let mut cx = Context::from_waker(&waker);
232 let mut mux = Pin::new(&mut mux);
233
234 tx_a.unbounded_send(1).unwrap();
236 assert!(matches!(
237 Stream::poll_next(mux.as_mut(), &mut cx),
238 Poll::Pending
239 ));
240
241 tx_b.unbounded_send(0).unwrap();
243 match Stream::poll_next(mux.as_mut(), &mut cx) {
244 Poll::Ready(Some(v)) => assert_eq!(v, 0),
245 other => panic!("expected Ready(Some(0)), got {:?}", other),
246 }
247
248 assert!(matches!(
250 Stream::poll_next(mux.as_mut(), &mut cx),
251 Poll::Pending
252 ));
253
254 tx_b.unbounded_send(3).unwrap();
256 match Stream::poll_next(mux.as_mut(), &mut cx) {
257 Poll::Ready(Some(v)) => assert_eq!(v, 1),
258 other => panic!("expected Ready(Some(1)), got {:?}", other),
259 }
260
261 tx_a.unbounded_send(2).unwrap();
263 match Stream::poll_next(mux.as_mut(), &mut cx) {
264 Poll::Ready(Some(v)) => assert_eq!(v, 2),
265 other => panic!("expected Ready(Some(2)), got {:?}", other),
266 }
267 }
268
269 #[tokio::test(flavor = "current_thread")]
270 async fn tie_break_prefers_lower_src_index() {
271 use futures::{StreamExt, stream};
272
273 let s0 = stream::iter(vec![(1, 10usize), (1, 11usize)]); let s1 = stream::iter(vec![(1, 20usize), (1, 21usize)]); let merged = mux_by(vec![s0, s1], |a, b| a.0.cmp(&b.0)); let tags: Vec<usize> = merged.map(|(_, tag)| tag).collect().await;
280
281 assert_eq!(tags, vec![10, 11, 20, 21]);
283
284 }
287}