Skip to main content

kal_mux/
lib.rs

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    // This code is never called by the heap, but we need to implement
51    // it to satisfy the trait.
52    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        // Poll each stream to fill the heap with the next item if it's empty.
91        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                        // Stream is exhausted
104                        this.done[idx] = true;
105                    }
106                    Poll::Pending => {} // Stream is not ready
107                }
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        // Each source individually descending; overall merge should be descending.
166        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)); // desc
170        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        // Same values across streams ⇒ order is deterministic by source index (lower src first).
202        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        // With the current implementation, ties prefer lower `src` first.
209        // This yields all s0 1s before s1 1s.
210        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        // Two controllable streams
223        let (tx_a, rx_a) = mpsc::unbounded::<i32>();
224        let (tx_b, rx_b) = mpsc::unbounded::<i32>();
225
226        // Build mux (ascending)
227        let mut mux = mux_by(vec![rx_a, rx_b], |a, b| a.cmp(b));
228
229        // Manual polling setup
230        let waker = noop_waker();
231        let mut cx = Context::from_waker(&waker);
232        let mut mux = Pin::new(&mut mux);
233
234        // Make A ready, B empty  → must NOT yield yet (Pending)
235        tx_a.unbounded_send(1).unwrap();
236        assert!(matches!(
237            Stream::poll_next(mux.as_mut(), &mut cx),
238            Poll::Pending
239        ));
240
241        // Unlock B with a smaller head (0)  → now it should yield 0
242        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        // After popping 0, B has no head → must block again (Pending)
249        assert!(matches!(
250            Stream::poll_next(mux.as_mut(), &mut cx),
251            Poll::Pending
252        ));
253
254        // Provide B's next head 3 (so A's 1 should come next)
255        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        // Provide A's next head 2 → next yield is 2 (since 2 < 3)
262        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        // Both streams yield equal keys (1), but we tag items with their src.
274        // Expectation: lower src (0) should come before higher src (1) on ties.
275        let s0 = stream::iter(vec![(1, 10usize), (1, 11usize)]); // src 0 tags
276        let s1 = stream::iter(vec![(1, 20usize), (1, 21usize)]); // src 1 tags
277
278        let merged = mux_by(vec![s0, s1], |a, b| a.0.cmp(&b.0)); // compare by key only
279        let tags: Vec<usize> = merged.map(|(_, tag)| tag).collect().await;
280
281        // With correct tie-break (reverse also on src), this passes:
282        assert_eq!(tags, vec![10, 11, 20, 21]);
283
284        // With the old Ord (primary reversed but tie-break not reversed),
285        // this would come out as [20, 21, 10, 11] and the test fails.
286    }
287}