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
use crate::alertable::Alertable;
use crate::event::EventRead;
use crate::ring_buffer::{EventWrapper, RingBuffer};
use crate::sequence::Sequence;
use crate::WaitStrategy;
use futures::task::{Context, Poll, Waker};
use futures::Stream;
use std::pin::Pin;
use std::sync::Arc;
impl Alertable for Waker {
fn alert(&self) {
self.wake_by_ref();
}
}
pub struct AsyncSubscriber<'a, T> {
ring: Arc<RingBuffer>,
sequence: Arc<Sequence>,
current_event: Option<EventWrapper>,
_marker: std::marker::PhantomData<&'a T>,
}
impl<'a, T> AsyncSubscriber<'a, T>
where
T: Send,
{
pub(crate) fn new(ring: Arc<RingBuffer>, sequence: Arc<Sequence>) -> Self {
Self {
ring,
sequence,
current_event: None,
_marker: std::marker::PhantomData,
}
}
pub fn sequence(&self) -> u64 {
self.sequence.get()
}
}
impl<'a, T: 'static> Stream for AsyncSubscriber<'a, T> {
type Item = EventRead<'a, T>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
let sequence = self.sequence.get();
let envelope = if let Some(envelope) = self.current_event.take() {
envelope
} else {
let envelope = self
.ring
.get_envelope(sequence)
.expect("ring buffer was not pre-populated with empty event envelopes")
.clone();
envelope.start_waiting();
envelope
};
let envelope_sequence = envelope.sequence();
if sequence == envelope_sequence {
let event_opt: Option<EventRead<T>> = unsafe { envelope.read() };
envelope.stop_waiting();
self.sequence.increment();
if let Some(event) = event_opt {
return Poll::Ready(Some(event));
}
} else if sequence > envelope_sequence {
envelope.add_subscriber(Box::new(cx.waker().clone()));
self.current_event.replace(envelope);
return Poll::Pending;
} else {
match self.ring.wait_strategy() {
WaitStrategy::AllSubscribers => unreachable!(),
_ => {
self.sequence.set(envelope_sequence);
}
}
}
}
}
}