1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use crate::{client::utils, data::Response};
use std::{collections::HashMap, time::Duration};
use tokio::{io, sync::mpsc};
pub struct PostOffice {
mailboxes: HashMap<usize, mpsc::Sender<Response>>,
}
impl PostOffice {
pub fn new() -> Self {
Self {
mailboxes: HashMap::new(),
}
}
pub fn make_mailbox(&mut self, id: usize, buffer: usize) -> Mailbox {
let (tx, rx) = mpsc::channel(buffer);
self.mailboxes.insert(id, tx);
Mailbox { id, rx }
}
pub async fn deliver(&mut self, res: Response) -> bool {
let id = res.origin_id;
let success = if let Some(tx) = self.mailboxes.get_mut(&id) {
tx.send(res).await.is_ok()
} else {
false
};
if !success {
self.mailboxes.remove(&id);
}
success
}
pub fn prune_mailboxes(&mut self) {
self.mailboxes.retain(|_, tx| !tx.is_closed())
}
pub fn clear_mailboxes(&mut self) {
self.mailboxes.clear();
}
}
pub struct Mailbox {
id: usize,
rx: mpsc::Receiver<Response>,
}
impl Mailbox {
pub fn id(&self) -> usize {
self.id
}
pub async fn next(&mut self) -> Option<Response> {
self.rx.recv().await
}
pub async fn next_timeout(&mut self, duration: Duration) -> io::Result<Option<Response>> {
utils::timeout(duration, self.next()).await
}
pub async fn close(&mut self) {
self.rx.close()
}
}