Skip to main content

sinktools/
demux_map.rs

1//! [`DemuxMap`] 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 pushes to the corresponding output sink in a [`HashMap`] of sinks.
11pub struct DemuxMap<Key, Si> {
12    sinks: HashMap<Key, Si>,
13}
14
15impl<Key, Si> DemuxMap<Key, Si> {
16    /// Create with the given next `sinks` map.
17    pub fn new<Item>(sinks: impl Into<HashMap<Key, Si>>) -> Self
18    where
19        Self: Sink<(Key, Item)>,
20    {
21        Self {
22            sinks: sinks.into(),
23        }
24    }
25}
26
27impl<Key, Si, Item> Sink<(Key, Item)> for DemuxMap<Key, Si>
28where
29    Key: Eq + Hash + Debug + Unpin,
30    Si: Sink<Item> + Unpin,
31{
32    type Error = Si::Error;
33
34    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
35        // Poll *every* sink, even after one returns `Pending`, so that all sinks can make progress
36        // and register wakers. Only errors short-circuit.
37        let mut any_pending = false;
38        #[expect(
39            clippy::disallowed_methods,
40            reason = "nondeterministic iteration order, but the loop is not order-dependent"
41        )]
42        for sink in self.get_mut().sinks.values_mut() {
43            any_pending |= Pin::new(sink).poll_ready(cx)?.is_pending();
44        }
45        if any_pending {
46            Poll::Pending
47        } else {
48            Poll::Ready(Ok(()))
49        }
50    }
51
52    fn start_send(self: Pin<&mut Self>, item: (Key, Item)) -> Result<(), Self::Error> {
53        let sink = self
54            .get_mut()
55            .sinks
56            .get_mut(&item.0)
57            .unwrap_or_else(|| panic!("`DemuxMap` missing key {:?}", item.0));
58        Pin::new(sink).start_send(item.1)
59    }
60
61    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
62        // Poll *every* sink, even after one returns `Pending`, so that all sinks can make progress
63        // and register wakers. Only errors short-circuit.
64        let mut any_pending = false;
65        #[expect(
66            clippy::disallowed_methods,
67            reason = "nondeterministic iteration order, but the loop is not order-dependent"
68        )]
69        for sink in self.get_mut().sinks.values_mut() {
70            any_pending |= Pin::new(sink).poll_flush(cx)?.is_pending();
71        }
72        if any_pending {
73            Poll::Pending
74        } else {
75            Poll::Ready(Ok(()))
76        }
77    }
78
79    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
80        // Poll *every* sink, even after one returns `Pending`, so that all sinks can make progress
81        // and register wakers. Only errors short-circuit.
82        let mut any_pending = false;
83        #[expect(
84            clippy::disallowed_methods,
85            reason = "nondeterministic iteration order, but the loop is not order-dependent"
86        )]
87        for sink in self.get_mut().sinks.values_mut() {
88            any_pending |= Pin::new(sink).poll_close(cx)?.is_pending();
89        }
90        if any_pending {
91            Poll::Pending
92        } else {
93            Poll::Ready(Ok(()))
94        }
95    }
96}
97
98/// Creates a `DemuxMap` sink that sends each item to one of many outputs, depending on the key.
99///
100/// This requires sinks `Si` to be `Unpin`. If your sinks are not `Unpin`, first wrap them in `Box::pin` to make them `Unpin`.
101pub fn demux_map<Key, Si, Item>(sinks: impl Into<HashMap<Key, Si>>) -> DemuxMap<Key, Si>
102where
103    Key: Eq + Hash + Debug + Unpin,
104    Si: Sink<Item> + Unpin,
105{
106    DemuxMap::new(sinks)
107}