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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use super::subscriber::*;
use super::pubsub_core::*;
use super::message_publisher::*;
use futures::future;
use futures::future::{BoxFuture};
use std::sync::*;
use std::collections::{VecDeque};
pub struct WeakPublisher<Message> {
pub (super) core: Weak<Mutex<PubCore<Message>>>
}
impl<Message: Clone> WeakPublisher<Message> {
pub fn count_subscribers(&self) -> usize {
self.core.upgrade()
.map(|core| core.lock().unwrap().subscribers.len())
.unwrap_or(0)
}
pub fn republish(&self) -> Self {
WeakPublisher {
core: Weak::clone(&self.core)
}
}
}
impl<Message: 'static+Send+Clone> MessagePublisher for WeakPublisher<Message> {
type Message = Message;
fn subscribe(&mut self) -> Subscriber<Message> {
let core = self.core.upgrade();
if let Some(core) = core {
let subscriber_id = {
let mut core = core.lock().unwrap();
let id = core.next_subscriber_id;
core.next_subscriber_id += 1;
id
};
let sub_core = SubCore {
id: subscriber_id,
published: true,
waiting: VecDeque::new(),
reserved: 0,
notify_waiting: vec![],
notify_ready: vec![],
notify_complete: vec![]
};
let sub_core = Arc::new(Mutex::new(sub_core));
let pub_core = Arc::downgrade(&core);
{
let mut core = core.lock().unwrap();
core.subscribers.insert(subscriber_id, Arc::clone(&sub_core));
}
Subscriber::new(pub_core, sub_core)
} else {
let sub_core = SubCore {
id: 0,
published: true,
waiting: VecDeque::new(),
reserved: 0,
notify_waiting: vec![],
notify_ready: vec![],
notify_complete: vec![]
};
Subscriber::new(Weak::default(), Arc::new(Mutex::new(sub_core)))
}
}
fn when_ready(&mut self) -> BoxFuture<'static, MessageSender<Message>> {
let core = self.core.upgrade();
if let Some(core) = core {
let when_ready = PubCore::send_all_subscribers(&core);
Box::pin(when_ready)
} else {
Box::pin(future::ready(MessageSender::new(|_msg| {}, || {})))
}
}
fn when_empty(&mut self) -> BoxFuture<'static, ()> {
let core = self.core.upgrade();
if let Some(core) = core {
let when_empty = PubCore::when_empty(&core);
Box::pin(when_empty)
} else {
Box::pin(future::ready(()))
}
}
fn is_closed(&self) -> bool {
self.core.upgrade().is_none()
}
fn when_closed(&self) -> BoxFuture<'static, ()> {
if let Some(core) = self.core.upgrade() {
Box::pin(CoreClosedFuture::new(core))
} else {
Box::pin(future::ready(()))
}
}
}