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
#![deny(missing_docs)]
extern crate crossbeam_channel;
extern crate failure;
mod error;
use crossbeam_channel::{unbounded, Receiver, Sender};
use std::sync::{Arc, RwLock};
pub use error::{Error, ErrorKind};
#[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> Broadcaster<T> {
pub fn new() -> Self {
Broadcaster {
senders: Arc::new(RwLock::new(Vec::new())),
inbox: unbounded(),
}
}
fn process_pending(&mut self) {
let mut senders = self.senders.write().unwrap();
while let Ok(s) = self.inbox.1.try_recv() {
senders.push(s);
}
}
pub fn broadcast(&mut self, item: T) {
self.process_pending();
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();
self.send(sender.clone()).map_err(|_| {
Error::from(ErrorKind::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>;
}