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
85
86
87
88
89
90
91
92
93
94
95
96
97
use super::subscriber::*;
use futures::future::{BoxFuture};
pub struct MessageSender<Message> {
send_message: Option<Box<dyn FnOnce(Message) -> ()+Send>>,
cancel_send: Option<Box<dyn FnOnce() -> ()+Send>>,
sent: bool
}
pub trait MessagePublisher
where Self: Send {
type Message: 'static+Send;
fn subscribe(&mut self) -> Subscriber<Self::Message>;
fn when_ready(&mut self) -> BoxFuture<'static, MessageSender<Self::Message>>;
fn when_empty(&mut self) -> BoxFuture<'static, ()>;
fn is_closed(&self) -> bool;
fn when_closed(&self) -> BoxFuture<'static, ()>;
fn publish(&mut self, message: Self::Message) -> BoxFuture<'static, ()> {
let when_ready = self.when_ready();
Box::pin(async move {
let sender = when_ready.await;
sender.send(message);
})
}
}
impl<Message> MessageSender<Message> {
pub fn new<TSendMsg, TCancelSend>(send_msg: TSendMsg, cancel_send: TCancelSend) -> MessageSender<Message>
where TSendMsg: 'static+Send+FnOnce(Message) -> (),
TCancelSend: 'static+Send+FnOnce() -> () {
MessageSender {
send_message: Some(Box::new(send_msg)),
cancel_send: Some(Box::new(cancel_send)),
sent: false
}
}
#[inline]
pub fn send(mut self, message: Message) {
self.sent = true;
self.send_message.take().map(move |send_message| send_message(message));
}
}
impl<Message> Drop for MessageSender<Message> {
fn drop(&mut self) {
if !self.sent {
self.cancel_send.take().map(move |cancel_send| cancel_send());
}
}
}