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
use std::fmt;
use std::marker::PhantomData;
use std::marker::Unpin;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use futures::Stream;
use futures::task::AtomicWaker;
use pin_project_lite::pin_project;
use super::Waker;
pin_project! {
#[must_use = "streams do nothing unless polled"]
pub struct QueueStream<Q, Item, F> {
#[pin]
q: Q,
#[pin]
f: F,
recv_task: Arc<AtomicWaker>,
_item: PhantomData<Item>,
}
}
impl<Q, Item, F> Clone for QueueStream<Q, Item, F>
where
Q: Clone,
F: Clone,
{
#[inline]
fn clone(&self) -> Self {
Self {
q: self.q.clone(),
f: self.f.clone(),
recv_task: self.recv_task.clone(),
_item: PhantomData,
}
}
}
impl<Q, Item, F> fmt::Debug for QueueStream<Q, Item, F>
where
Q: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("QueueStream")
.field("queue", &self.q)
.finish()
}
}
impl<Q: Unpin, Item, F> QueueStream<Q, Item, F> {
#[inline]
pub(super) fn new(q: Q, f: F) -> Self {
Self {
q,
f,
recv_task: Arc::new(AtomicWaker::new()),
_item: PhantomData,
}
}
}
impl<Q, Item, F> Waker for QueueStream<Q, Item, F> {
#[inline]
fn wake(&self) {
self.recv_task.wake()
}
}
impl<Q, Item, F> Stream for QueueStream<Q, Item, F>
where
Q: Unpin,
F: Fn(Pin<&mut Q>, &mut Context<'_>) -> Poll<Option<Item>>,
{
type Item = Item;
fn poll_next(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
let f = this.f.as_mut();
match f(this.q.as_mut(), ctx) {
Poll::Ready(msg) => Poll::Ready(msg),
Poll::Pending => {
this.recv_task.register(ctx.waker());
f(this.q.as_mut(), ctx)
}
}
}
}
impl<Q, Item, F> Deref for QueueStream<Q, Item, F> {
type Target = Q;
#[inline]
fn deref(&self) -> &Self::Target {
&self.q
}
}
impl<Q, Item, F> DerefMut for QueueStream<Q, Item, F> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.q
}
}