commonware_p2p/authenticated/
mailbox.rs

1use futures::{channel::mpsc, SinkExt as _};
2
3/// A mailbox wraps a sender for messages of type `T`.
4#[derive(Debug)]
5pub struct Mailbox<T>(mpsc::Sender<T>);
6
7impl<T> Mailbox<T> {
8    /// Returns a new mailbox with the given sender.
9    pub fn new(sender: mpsc::Sender<T>) -> Self {
10        Self(sender)
11    }
12
13    /// Returns a new mailbox and the corresponding receiver.
14    /// The capacity of the channel is 1.
15    #[cfg(test)]
16    pub fn test() -> (Self, mpsc::Receiver<T>) {
17        let (sender, receiver) = mpsc::channel(1);
18        (Self(sender), receiver)
19    }
20}
21
22impl<T> Clone for Mailbox<T> {
23    fn clone(&self) -> Self {
24        Self(self.0.clone())
25    }
26}
27
28impl<T> Mailbox<T> {
29    /// Sends a message to the corresponding receiver.
30    pub async fn send(&mut self, message: T) -> Result<(), mpsc::SendError> {
31        self.0.send(message).await
32    }
33
34    /// Returns true if the mailbox is closed.
35    pub fn is_closed(&self) -> bool {
36        self.0.is_closed()
37    }
38}