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(size: usize) -> (Self, mpsc::Receiver<T>) {
10        let (sender, receiver) = mpsc::channel(size);
11        (Self(sender), receiver)
12    }
13}
14
15impl<T> Clone for Mailbox<T> {
16    fn clone(&self) -> Self {
17        Self(self.0.clone())
18    }
19}
20
21impl<T> Mailbox<T> {
22    /// Sends a message to the corresponding receiver.
23    pub async fn send(&mut self, message: T) -> Result<(), mpsc::SendError> {
24        self.0.send(message).await
25    }
26
27    /// Returns true if the mailbox is closed.
28    pub fn is_closed(&self) -> bool {
29        self.0.is_closed()
30    }
31}
32
33/// A mailbox wraps an unbounded sender for messages of type `T`.
34#[derive(Debug)]
35pub struct UnboundedMailbox<T>(mpsc::UnboundedSender<T>);
36
37impl<T> UnboundedMailbox<T> {
38    /// Returns a new mailbox with the given sender.
39    pub fn new() -> (Self, mpsc::UnboundedReceiver<T>) {
40        let (sender, receiver) = mpsc::unbounded();
41        (Self(sender), receiver)
42    }
43}
44
45impl<T> Clone for UnboundedMailbox<T> {
46    fn clone(&self) -> Self {
47        Self(self.0.clone())
48    }
49}
50
51impl<T> UnboundedMailbox<T> {
52    /// Sends a message to the corresponding receiver.
53    pub fn send(&mut self, message: T) -> Result<(), mpsc::TrySendError<T>> {
54        self.0.unbounded_send(message)
55    }
56}