use futures::channel::mpsc; #[derive(Clone, Debug)] pub struct Relay { low: mpsc::Sender, high: mpsc::Sender, } impl Relay { pub const fn new(low: mpsc::Sender, high: mpsc::Sender) -> Self { Self { low, high } } /// Sends the given `message` to the appropriate channel based on `priority`. /// /// Uses non-blocking `try_send` to avoid blocking the caller when the /// channel buffer is full. Returns an error if the channel is full or /// disconnected. pub fn send(&mut self, message: T, priority: bool) -> Result<(), mpsc::TrySendError> { let sender = if priority { &mut self.high } else { &mut self.low }; sender.try_send(message) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_relay_content_priority() { let (low_sender, mut low_receiver) = mpsc::channel(1); let (high_sender, mut high_receiver) = mpsc::channel(1); let mut relay = Relay::new(low_sender, high_sender); // Send a high priority message let data = 123; relay.send(data, true).unwrap(); match high_receiver.try_next() { Ok(Some(received_data)) => { assert_eq!(data, received_data); } _ => panic!("Expected high priority message"), } assert!(low_receiver.try_next().is_err()); // Send a low priority message let data = 456; relay.send(data, false).unwrap(); match low_receiver.try_next() { Ok(Some(received_data)) => { assert_eq!(data, received_data); } _ => panic!("Expected low priority message"), } assert!(high_receiver.try_next().is_err()); } }