35 lines
1.1 KiB
Rust
35 lines
1.1 KiB
Rust
|
// nice wrapper to have a Default impl for a (Sender, InactiveReceiver) pair
|
||
|
|
||
|
use async_broadcast::{broadcast, InactiveReceiver, Receiver, Sender, TrySendError};
|
||
|
|
||
|
pub struct Broadcast<const N: usize, T> {
|
||
|
pub sender: Sender<T>,
|
||
|
inactive_receiver: InactiveReceiver<T>,
|
||
|
}
|
||
|
|
||
|
impl<const N: usize, T> Default for Broadcast<N, T> {
|
||
|
fn default() -> Self {
|
||
|
let (sender, receiver) = broadcast(N);
|
||
|
Self {
|
||
|
sender,
|
||
|
inactive_receiver: receiver.deactivate(),
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<const N: usize, T> Broadcast<N, T> where T: Clone {
|
||
|
pub fn receiver(&self) -> Receiver<T> {
|
||
|
self.inactive_receiver.activate_cloned()
|
||
|
}
|
||
|
|
||
|
// like sender.try_broadcast, but ignores if there aren't any active listeners
|
||
|
pub fn try_broadcast(&self, msg: T) -> Result<(), TrySendError<T>> {
|
||
|
match self.sender.try_broadcast(msg) {
|
||
|
Err(TrySendError::Inactive(_)) => Ok(()), // ignore
|
||
|
Err(err) => Err(err),
|
||
|
Ok(Some(_)) => unreachable!("we do not enable overflow mode"),
|
||
|
Ok(None) => Ok(()),
|
||
|
}
|
||
|
}
|
||
|
}
|