use futures::{channel::mpsc, SinkExt as _}; /// A mailbox wraps a sender for messages of type `T`. #[derive(Debug)] pub struct Mailbox(mpsc::Sender); impl Mailbox { /// Returns a new mailbox with the given sender. pub fn new(size: usize) -> (Self, mpsc::Receiver) { let (sender, receiver) = mpsc::channel(size); (Self(sender), receiver) } } impl Clone for Mailbox { fn clone(&self) -> Self { Self(self.0.clone()) } } impl Mailbox { /// Sends a message to the corresponding receiver. pub async fn send(&mut self, message: T) -> Result<(), mpsc::SendError> { self.0.send(message).await } /// Returns true if the mailbox is closed. pub fn is_closed(&self) -> bool { self.0.is_closed() } } /// A mailbox wraps an unbounded sender for messages of type `T`. #[derive(Debug)] pub struct UnboundedMailbox(mpsc::UnboundedSender); impl UnboundedMailbox { /// Returns a new mailbox with the given sender. pub fn new() -> (Self, mpsc::UnboundedReceiver) { let (sender, receiver) = mpsc::unbounded(); (Self(sender), receiver) } } impl Clone for UnboundedMailbox { fn clone(&self) -> Self { Self(self.0.clone()) } } impl UnboundedMailbox { /// Sends a message to the corresponding receiver. pub fn send(&mut self, message: T) -> Result<(), mpsc::TrySendError> { self.0.unbounded_send(message) } }