Skip to main content

sinktools/
demux_map_lazy.rs

1//! [`LazyDemuxSink`] and related items.
2use core::fmt::Debug;
3use core::hash::Hash;
4use core::pin::Pin;
5use core::task::{Context, Poll};
6use std::collections::HashMap;
7
8use crate::Sink;
9
10/// Sink which receives keys paired with items `(Key, Item)`, and lazily creates sinks on first use.
11pub struct LazyDemuxSink<Key, Si, Func> {
12    sinks: HashMap<Key, Si>,
13    func: Func,
14}
15
16impl<Key, Si, Func> LazyDemuxSink<Key, Si, Func> {
17    /// Create with the given initialization function.
18    pub fn new<Item>(func: Func) -> Self
19    where
20        Self: Sink<(Key, Item)>,
21    {
22        Self {
23            sinks: HashMap::new(),
24            func,
25        }
26    }
27}
28
29impl<Key, Si, Item, Func> Sink<(Key, Item)> for LazyDemuxSink<Key, Si, Func>
30where
31    Key: Eq + Hash + Debug + Unpin,
32    Si: Sink<Item> + Unpin,
33    Func: FnMut(&Key) -> Si + Unpin,
34{
35    type Error = Si::Error;
36
37    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
38        // Poll *every* sink, even after one returns `Pending`, so that all sinks can make progress
39        // and register wakers. Only errors short-circuit.
40        let mut any_pending = false;
41        #[expect(
42            clippy::disallowed_methods,
43            reason = "nondeterministic iteration order, but the loop is not order-dependent"
44        )]
45        for sink in self.get_mut().sinks.values_mut() {
46            any_pending |= Pin::new(sink).poll_ready(cx)?.is_pending();
47        }
48        if any_pending {
49            Poll::Pending
50        } else {
51            Poll::Ready(Ok(()))
52        }
53    }
54
55    fn start_send(self: Pin<&mut Self>, item: (Key, Item)) -> Result<(), Self::Error> {
56        let this = self.get_mut();
57        let sink = this
58            .sinks
59            .entry(item.0)
60            .or_insert_with_key(|k| (this.func)(k));
61        Pin::new(sink).start_send(item.1)
62    }
63
64    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
65        // Poll *every* sink, even after one returns `Pending`, so that all sinks can make progress
66        // and register wakers. Only errors short-circuit.
67        let mut any_pending = false;
68        #[expect(
69            clippy::disallowed_methods,
70            reason = "nondeterministic iteration order, but the loop is not order-dependent"
71        )]
72        for sink in self.get_mut().sinks.values_mut() {
73            any_pending |= Pin::new(sink).poll_flush(cx)?.is_pending();
74        }
75        if any_pending {
76            Poll::Pending
77        } else {
78            Poll::Ready(Ok(()))
79        }
80    }
81
82    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
83        // Poll *every* sink, even after one returns `Pending`, so that all sinks can make progress
84        // and register wakers. Only errors short-circuit.
85        let mut any_pending = false;
86        #[expect(
87            clippy::disallowed_methods,
88            reason = "nondeterministic iteration order, but the loop is not order-dependent"
89        )]
90        for sink in self.get_mut().sinks.values_mut() {
91            any_pending |= Pin::new(sink).poll_close(cx)?.is_pending();
92        }
93        if any_pending {
94            Poll::Pending
95        } else {
96            Poll::Ready(Ok(()))
97        }
98    }
99}
100
101/// Creates a `LazyDemuxSink` that lazily creates sinks on first use for each key.
102///
103/// This requires sinks `Si` to be `Unpin`. If your sinks are not `Unpin`, first wrap them in `Box::pin` to make them `Unpin`.
104pub fn demux_map_lazy<Key, Si, Item, Func>(func: Func) -> LazyDemuxSink<Key, Si, Func>
105where
106    Key: Eq + Hash + Debug + Unpin,
107    Si: Sink<Item> + Unpin,
108    Func: FnMut(&Key) -> Si + Unpin,
109{
110    LazyDemuxSink::new(func)
111}
112
113#[cfg(test)]
114mod test {
115    use core::cell::RefCell;
116    use core::pin::pin;
117    use std::collections::HashMap;
118    use std::rc::Rc;
119
120    use futures_util::SinkExt;
121
122    use super::*;
123    use crate::for_each::ForEach;
124
125    #[tokio::test]
126    async fn test_lazy_demux_sink() {
127        let outputs: Rc<RefCell<HashMap<String, Vec<u8>>>> = Rc::new(RefCell::new(HashMap::new()));
128        let outputs_clone = outputs.clone();
129
130        let mut sink = demux_map_lazy(move |key: &String| {
131            let key = key.clone();
132            let outputs = outputs_clone.clone();
133            ForEach::new(move |item: &[u8]| {
134                outputs
135                    .borrow_mut()
136                    .entry(key.clone())
137                    .or_default()
138                    .extend_from_slice(item);
139            })
140        });
141
142        sink.send(("a".to_owned(), b"test1".as_slice()))
143            .await
144            .unwrap();
145        sink.send(("b".to_owned(), b"test2".as_slice()))
146            .await
147            .unwrap();
148        sink.send(("a".to_owned(), b"test3".as_slice()))
149            .await
150            .unwrap();
151        sink.flush().await.unwrap();
152        sink.close().await.unwrap();
153
154        let outputs = outputs.borrow();
155        assert_eq!(outputs.get("a").unwrap().as_slice(), b"test1test3");
156        assert_eq!(outputs.get("b").unwrap().as_slice(), b"test2");
157    }
158
159    #[test]
160    fn test_lazy_demux_sink_good() {
161        use core::task::Context;
162
163        let outputs: Rc<RefCell<HashMap<String, Vec<u8>>>> = Rc::new(RefCell::new(HashMap::new()));
164        let outputs_clone = outputs.clone();
165
166        let mut sink = pin!(demux_map_lazy(move |key: &String| {
167            let outputs = outputs_clone.clone();
168            let key = key.clone();
169            ForEach::new(move |item: &[u8]| {
170                outputs
171                    .borrow_mut()
172                    .entry(key.clone())
173                    .or_default()
174                    .extend_from_slice(item);
175            })
176        }));
177
178        let cx = &mut Context::from_waker(futures_task::noop_waker_ref());
179
180        assert_eq!(Poll::Ready(Ok(())), sink.as_mut().poll_ready(cx));
181        assert_eq!(
182            Ok(()),
183            sink.as_mut()
184                .start_send(("a".to_owned(), b"test1".as_slice()))
185        );
186        assert_eq!(
187            Ok(()),
188            sink.as_mut()
189                .start_send(("b".to_owned(), b"test2".as_slice()))
190        );
191        assert_eq!(
192            Ok(()),
193            sink.as_mut()
194                .start_send(("a".to_owned(), b"test3".as_slice()))
195        );
196        assert_eq!(Poll::Ready(Ok(())), sink.as_mut().poll_flush(cx));
197        assert_eq!(Poll::Ready(Ok(())), sink.as_mut().poll_close(cx));
198
199        let outputs = outputs.borrow();
200        assert_eq!(outputs.get("a").unwrap().as_slice(), b"test1test3");
201        assert_eq!(outputs.get("b").unwrap().as_slice(), b"test2");
202    }
203}