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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#![deny(missing_docs)]
extern crate crossbeam_channel;
extern crate snafu;
mod error;
use crossbeam_channel::{unbounded, Receiver, Sender};
use snafu::ensure;
use std::sync::{Arc, RwLock};
pub use error::Error;
#[derive(Clone)]
pub struct SubscriptionManager<T: Clone> {
sender: Sender<Sender<T>>,
}
#[derive(Clone)]
pub struct Broadcaster<T: Clone> {
senders: Arc<RwLock<Vec<Sender<T>>>>,
inbox: (Sender<Sender<T>>, Receiver<Sender<T>>),
}
impl<T: Clone> Default for Broadcaster<T> {
fn default() -> Self {
Broadcaster {
senders: Arc::new(RwLock::new(Vec::new())),
inbox: unbounded(),
}
}
}
impl<T: Clone> Broadcaster<T> {
pub fn process_pending_subscriptions(&mut self) {
self.process_pending_subscriptions_with(&mut |_| {})
}
pub fn process_pending_subscriptions_with<F: FnMut(&mut Sender<T>)>(
&mut self,
f: &mut F,
) {
let mut senders = self.senders.write().unwrap();
while let Ok(mut s) = self.inbox.1.try_recv() {
f(&mut s);
senders.push(s);
}
}
pub fn broadcast(&mut self, item: T) {
self.process_pending_subscriptions();
let mut senders = self.senders.write().unwrap();
senders.retain(|sender| sender.send(item.clone()).is_ok());
}
pub fn subscription_manager(&self) -> SubscriptionManager<T> {
SubscriptionManager {
sender: self.inbox.0.clone(),
}
}
}
impl<T: Clone> SubscriptionRegistration<T> for SubscriptionManager<T> {
fn subscribe_with<F: FnMut(&mut Sender<T>)>(
&self,
f: &mut F,
) -> Result<Receiver<T>, Error> {
self.sender.subscribe_with(f)
}
}
impl<T: Clone> SubscriptionRegistration<T> for Sender<Sender<T>> {
fn subscribe_with<F: FnMut(&mut Sender<T>)>(
&self,
f: &mut F,
) -> Result<Receiver<T>, Error> {
let (mut sender, receiver) = unbounded();
ensure!(
self.send(sender.clone()).is_ok(),
error::BroadcasterNoLongerExists
);
f(&mut sender);
Ok(receiver)
}
}
impl<T: Clone> SubscriptionRegistration<T> for Broadcaster<T> {
fn subscribe_with<F: FnMut(&mut Sender<T>)>(
&self,
f: &mut F,
) -> Result<Receiver<T>, Error> {
self.inbox.0.subscribe_with(f)
}
}
pub trait SubscriptionRegistration<T: Clone> {
fn subscribe(&self) -> Result<Receiver<T>, Error> {
self.subscribe_with(&mut |_| {})
}
fn subscribe_with<F: FnMut(&mut Sender<T>)>(
&self,
f: &mut F,
) -> Result<Receiver<T>, Error>;
}