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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use std::{
future::Future,
pin::Pin,
task::{Context, Poll, Waker},
any::Any,
ops::Deref,
};
use crate::*;
use futures_core::{stream::{Stream, FusedStream}, future::FusedFuture};
use futures_sink::Sink;
use pin_project::{pin_project, pinned_drop};
struct AsyncSignal {
waker: Spinlock<Waker>,
woken: AtomicBool,
stream: bool,
}
impl AsyncSignal {
fn new(cx: &Context, stream: bool) -> Self {
AsyncSignal {
waker: Spinlock::new(cx.waker().clone()),
woken: AtomicBool::new(false),
stream,
}
}
}
impl Signal for AsyncSignal {
fn fire(&self) -> bool {
self.woken.store(true, Ordering::SeqCst);
self.waker.lock().wake_by_ref();
self.stream
}
fn as_any(&self) -> &(dyn Any + 'static) { self }
fn as_ptr(&self) -> *const () { self as *const _ as *const () }
}
impl<T> Hook<T, AsyncSignal> {
fn update_waker(&self, cx_waker: &Waker) -> bool {
let mut waker = self.1.waker.lock();
let woken = self.1.woken.load(Ordering::SeqCst);
if !waker.will_wake(cx_waker) {
*waker = cx_waker.clone();
if woken {
cx_waker.wake_by_ref();
}
}
woken
}
}
#[derive(Clone)]
enum OwnedOrRef<'a, T> {
Owned(T),
Ref(&'a T),
}
impl<'a, T> Deref for OwnedOrRef<'a, T> {
type Target = T;
fn deref(&self) -> &T {
match self {
OwnedOrRef::Owned(arc) => &arc,
OwnedOrRef::Ref(r) => r,
}
}
}
impl<T> Sender<T> {
pub fn send_async(&self, item: T) -> SendFut<T> {
SendFut {
sender: OwnedOrRef::Ref(&self),
hook: Some(SendState::NotYetSent(item)),
}
}
pub fn into_send_async(self, item: T) -> SendFut<'static, T> {
SendFut {
sender: OwnedOrRef::Owned(self),
hook: Some(SendState::NotYetSent(item)),
}
}
pub fn sink(&self) -> SendSink<'_, T> {
SendSink(SendFut {
sender: OwnedOrRef::Ref(&self),
hook: None,
})
}
pub fn into_sink(self) -> SendSink<'static, T> {
SendSink(SendFut {
sender: OwnedOrRef::Owned(self),
hook: None,
})
}
}
enum SendState<T> {
NotYetSent(T),
QueuedItem(Arc<Hook<T, AsyncSignal>>),
}
#[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"]
#[pin_project(PinnedDrop)]
pub struct SendFut<'a, T> {
sender: OwnedOrRef<'a, Sender<T>>,
hook: Option<SendState<T>>,
}
impl<'a, T> SendFut<'a, T> {
fn reset_hook(&mut self) {
if let Some(SendState::QueuedItem(hook)) = self.hook.take() {
let hook: Arc<Hook<T, dyn Signal>> = hook;
wait_lock(&self.sender.shared.chan).sending
.as_mut()
.unwrap().1
.retain(|s| s.signal().as_ptr() != hook.signal().as_ptr());
}
}
pub fn is_disconnected(&self) -> bool {
self.sender.is_disconnected()
}
pub fn is_empty(&self) -> bool {
self.sender.is_empty()
}
pub fn is_full(&self) -> bool {
self.sender.is_full()
}
pub fn len(&self) -> usize {
self.sender.len()
}
pub fn capacity(&self) -> Option<usize> {
self.sender.capacity()
}
}
#[allow(clippy::needless_lifetimes)] #[pinned_drop]
impl<'a, T> PinnedDrop for SendFut<'a, T> {
fn drop(mut self: Pin<&mut Self>) {
self.reset_hook()
}
}
impl<'a, T> Future for SendFut<'a, T> {
type Output = Result<(), SendError<T>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(SendState::QueuedItem(hook)) = self.hook.as_ref() {
if hook.is_empty() {
Poll::Ready(Ok(()))
} else if self.sender.shared.is_disconnected() {
match self.hook.take().unwrap() {
SendState::NotYetSent(item) => Poll::Ready(Err(SendError(item))),
SendState::QueuedItem(hook) => match hook.try_take() {
Some(item) => Poll::Ready(Err(SendError(item))),
None => Poll::Ready(Ok(())),
},
}
} else {
hook.update_waker(cx.waker());
Poll::Pending
}
} else if let Some(SendState::NotYetSent(_)) = self.hook {
let mut mut_self = self.project();
let (shared, this_hook) = (&mut_self.sender.shared, &mut mut_self.hook);
shared.send(
match this_hook.take().unwrap() {
SendState::NotYetSent(item) => item,
SendState::QueuedItem(_) => return Poll::Ready(Ok(())),
},
true,
|msg| Hook::slot(Some(msg), AsyncSignal::new(cx, false)),
|hook| {
**this_hook = Some(SendState::QueuedItem(hook));
Poll::Pending
},
)
.map(|r| r.map_err(|err| match err {
TrySendTimeoutError::Disconnected(msg) => SendError(msg),
_ => unreachable!(),
}))
} else { Poll::Ready(Ok(()))
}
}
}
impl<'a, T> FusedFuture for SendFut<'a, T> {
fn is_terminated(&self) -> bool {
self.sender.shared.is_disconnected()
}
}
pub struct SendSink<'a, T>(SendFut<'a, T>);
impl<'a, T> SendSink<'a, T> {
pub fn sender(&self) -> &Sender<T> {
&self.0.sender
}
pub fn is_disconnected(&self) -> bool {
self.0.is_disconnected()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn is_full(&self) -> bool {
self.0.is_full()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn capacity(&self) -> Option<usize> {
self.0.capacity()
}
}
impl<'a, T> Sink<T> for SendSink<'a, T> {
type Error = SendError<T>;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.0).poll(cx)
}
fn start_send(mut self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
self.0.reset_hook();
self.0.hook = Some(SendState::NotYetSent(item));
Ok(())
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.0).poll(cx) }
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.0).poll(cx) }
}
impl<'a, T> Clone for SendSink<'a, T> {
fn clone(&self) -> SendSink<'a, T> {
SendSink(SendFut {
sender: self.0.sender.clone(),
hook: None,
})
}
}
impl<T> Receiver<T> {
pub fn recv_async(&self) -> RecvFut<'_, T> {
RecvFut::new(OwnedOrRef::Ref(self))
}
pub fn into_recv_async(self) -> RecvFut<'static, T> {
RecvFut::new(OwnedOrRef::Owned(self))
}
pub fn stream(&self) -> RecvStream<'_, T> {
RecvStream(RecvFut::new(OwnedOrRef::Ref(self)))
}
pub fn into_stream(self) -> RecvStream<'static, T> {
RecvStream(RecvFut::new(OwnedOrRef::Owned(self)))
}
}
#[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"]
pub struct RecvFut<'a, T> {
receiver: OwnedOrRef<'a, Receiver<T>>,
hook: Option<Arc<Hook<T, AsyncSignal>>>,
}
impl<'a, T> RecvFut<'a, T> {
fn new(receiver: OwnedOrRef<'a, Receiver<T>>) -> Self {
Self {
receiver,
hook: None,
}
}
fn reset_hook(&mut self) {
if let Some(hook) = self.hook.take() {
let hook: Arc<Hook<T, dyn Signal>> = hook;
let mut chan = wait_lock(&self.receiver.shared.chan);
chan.waiting.retain(|s| s.signal().as_ptr() != hook.signal().as_ptr());
if hook.signal().as_any().downcast_ref::<AsyncSignal>().unwrap().woken.load(Ordering::SeqCst) {
chan.try_wake_receiver_if_pending();
}
}
}
fn poll_inner(
self: Pin<&mut Self>,
cx: &mut Context,
stream: bool,
) -> Poll<Result<T, RecvError>> {
if self.hook.is_some() {
if let Ok(msg) = self.receiver.shared.recv_sync(None) {
Poll::Ready(Ok(msg))
} else if self.receiver.shared.is_disconnected() {
Poll::Ready(Err(RecvError::Disconnected))
} else {
let hook = self.hook.as_ref().map(Arc::clone).unwrap();
if hook.update_waker(cx.waker()) {
wait_lock(&self.receiver.shared.chan).waiting.push_back(hook);
}
if self.receiver.shared.is_disconnected() {
Poll::Ready(self.receiver.shared
.recv_sync(None)
.map(Ok)
.unwrap_or(Err(RecvError::Disconnected)))
} else {
Poll::Pending
}
}
} else {
let mut_self = self.get_mut();
let (shared, this_hook) = (&mut_self.receiver.shared, &mut mut_self.hook);
shared.recv(
true,
|| Hook::trigger(AsyncSignal::new(cx, stream)),
|hook| {
*this_hook = Some(hook);
Poll::Pending
},
)
.map(|r| r.map_err(|err| match err {
TryRecvTimeoutError::Disconnected => RecvError::Disconnected,
_ => unreachable!(),
}))
}
}
pub fn is_disconnected(&self) -> bool {
self.receiver.is_disconnected()
}
pub fn is_empty(&self) -> bool {
self.receiver.is_empty()
}
pub fn is_full(&self) -> bool {
self.receiver.is_full()
}
pub fn len(&self) -> usize {
self.receiver.len()
}
pub fn capacity(&self) -> Option<usize> {
self.receiver.capacity()
}
}
impl<'a, T> Drop for RecvFut<'a, T> {
fn drop(&mut self) {
self.reset_hook();
}
}
impl<'a, T> Future for RecvFut<'a, T> {
type Output = Result<T, RecvError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.poll_inner(cx, false) }
}
impl<'a, T> FusedFuture for RecvFut<'a, T> {
fn is_terminated(&self) -> bool {
self.receiver.shared.is_disconnected() && self.receiver.shared.is_empty()
}
}
pub struct RecvStream<'a, T>(RecvFut<'a, T>);
impl<'a, T> RecvStream<'a, T> {
pub fn is_disconnected(&self) -> bool {
self.0.is_disconnected()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn is_full(&self) -> bool {
self.0.is_full()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn capacity(&self) -> Option<usize> {
self.0.capacity()
}
}
impl<'a, T> Clone for RecvStream<'a, T> {
fn clone(&self) -> RecvStream<'a, T> {
RecvStream(RecvFut::new(self.0.receiver.clone()))
}
}
impl<'a, T> Stream for RecvStream<'a, T> {
type Item = T;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match Pin::new(&mut self.0).poll_inner(cx, true) { Poll::Pending => Poll::Pending,
Poll::Ready(item) => {
self.0.reset_hook();
Poll::Ready(item.ok())
}
}
}
}
impl<'a, T> FusedStream for RecvStream<'a, T> {
fn is_terminated(&self) -> bool {
self.0.is_terminated()
}
}