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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use crate::future::poll_fn;
use crate::sync::task::AtomicWaker;
use fnv::FnvHashSet;
use std::ops;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::{Relaxed, SeqCst};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, Weak};
use std::task::Poll::{Pending, Ready};
use std::task::{Context, Poll};
#[derive(Debug)]
pub struct Receiver<T> {
shared: Arc<Shared<T>>,
inner: Watcher,
}
#[derive(Debug)]
pub struct Sender<T> {
shared: Weak<Shared<T>>,
}
#[derive(Debug)]
pub struct Ref<'a, T> {
inner: RwLockReadGuard<'a, T>,
}
pub mod error {
use std::fmt;
#[derive(Debug)]
pub struct SendError<T> {
pub(crate) inner: T,
}
impl<T: fmt::Debug> fmt::Display for SendError<T> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "channel closed")
}
}
impl<T: fmt::Debug> std::error::Error for SendError<T> {}
}
#[derive(Debug)]
struct Shared<T> {
value: RwLock<T>,
version: AtomicUsize,
watchers: Mutex<Watchers>,
cancel: AtomicWaker,
}
type Watchers = FnvHashSet<Watcher>;
#[derive(Clone, Debug)]
struct Watcher(Arc<WatchInner>);
#[derive(Debug)]
struct WatchInner {
version: AtomicUsize,
waker: AtomicWaker,
}
const CLOSED: usize = 1;
pub fn channel<T: Clone>(init: T) -> (Sender<T>, Receiver<T>) {
const VERSION_0: usize = 0;
const VERSION_1: usize = 2;
let inner = Watcher::new_version(VERSION_0);
let mut watchers = FnvHashSet::with_capacity_and_hasher(0, Default::default());
watchers.insert(inner.clone());
let shared = Arc::new(Shared {
value: RwLock::new(init),
version: AtomicUsize::new(VERSION_1),
watchers: Mutex::new(watchers),
cancel: AtomicWaker::new(),
});
let tx = Sender {
shared: Arc::downgrade(&shared),
};
let rx = Receiver { shared, inner };
(tx, rx)
}
impl<T> Receiver<T> {
pub fn borrow(&self) -> Ref<'_, T> {
let inner = self.shared.value.read().unwrap();
Ref { inner }
}
#[doc(hidden)]
pub fn poll_recv_ref<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll<Option<Ref<'a, T>>> {
self.inner.waker.register_by_ref(cx.waker());
let state = self.shared.version.load(SeqCst);
let version = state & !CLOSED;
if self.inner.version.swap(version, Relaxed) != version {
let inner = self.shared.value.read().unwrap();
return Ready(Some(Ref { inner }));
}
if CLOSED == state & CLOSED {
return Ready(None);
}
Pending
}
}
impl<T: Clone> Receiver<T> {
pub async fn recv(&mut self) -> Option<T> {
poll_fn(|cx| {
let v_ref = ready!(self.poll_recv_ref(cx));
Poll::Ready(v_ref.map(|v_ref| (*v_ref).clone()))
})
.await
}
}
#[cfg(feature = "stream")]
impl<T: Clone> crate::stream::Stream for Receiver<T> {
type Item = T;
fn poll_next(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
let v_ref = ready!(self.poll_recv_ref(cx));
Poll::Ready(v_ref.map(|v_ref| (*v_ref).clone()))
}
}
impl<T> Clone for Receiver<T> {
fn clone(&self) -> Self {
let ver = self.inner.version.load(Relaxed);
let inner = Watcher::new_version(ver);
let shared = self.shared.clone();
shared.watchers.lock().unwrap().insert(inner.clone());
Receiver { shared, inner }
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
self.shared.watchers.lock().unwrap().remove(&self.inner);
}
}
impl<T> Sender<T> {
pub fn broadcast(&self, value: T) -> Result<(), error::SendError<T>> {
let shared = match self.shared.upgrade() {
Some(shared) => shared,
None => return Err(error::SendError { inner: value }),
};
{
let mut lock = shared.value.write().unwrap();
*lock = value;
}
shared.version.fetch_add(2, SeqCst);
notify_all(&*shared);
Ok(())
}
pub async fn closed(&mut self) {
poll_fn(|cx| self.poll_close(cx)).await
}
fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll<()> {
match self.shared.upgrade() {
Some(shared) => {
shared.cancel.register_by_ref(cx.waker());
Pending
}
None => Ready(()),
}
}
}
fn notify_all<T>(shared: &Shared<T>) {
let watchers = shared.watchers.lock().unwrap();
for watcher in watchers.iter() {
watcher.waker.wake();
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
if let Some(shared) = self.shared.upgrade() {
shared.version.fetch_or(CLOSED, SeqCst);
notify_all(&*shared);
}
}
}
impl<T> ops::Deref for Ref<'_, T> {
type Target = T;
fn deref(&self) -> &T {
self.inner.deref()
}
}
impl<T> Drop for Shared<T> {
fn drop(&mut self) {
self.cancel.wake();
}
}
impl Watcher {
fn new_version(version: usize) -> Self {
Watcher(Arc::new(WatchInner {
version: AtomicUsize::new(version),
waker: AtomicWaker::new(),
}))
}
}
impl std::cmp::PartialEq for Watcher {
fn eq(&self, other: &Watcher) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl std::cmp::Eq for Watcher {}
impl std::hash::Hash for Watcher {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(&*self.0 as *const WatchInner).hash(state)
}
}
impl std::ops::Deref for Watcher {
type Target = WatchInner;
fn deref(&self) -> &Self::Target {
&self.0
}
}