Skip to content

Commit 7fdd900

Browse files
asonixspacejam
authored andcommitted
Store pending oneshot for subscriber future
1 parent 3bfd469 commit 7fdd900

File tree

1 file changed

+30
-17
lines changed

1 file changed

+30
-17
lines changed

src/subscriber.rs

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ type Senders = Map<usize, (Option<Waker>, SyncSender<OneShot<Option<Event>>>)>;
9292
pub struct Subscriber {
9393
id: usize,
9494
rx: Receiver<OneShot<Option<Event>>>,
95+
existing: Option<OneShot<Option<Event>>>,
9596
home: Arc<RwLock<Senders>>,
9697
}
9798

@@ -132,29 +133,41 @@ impl Subscriber {
132133
};
133134
}
134135
}
136+
137+
fn poll_oneshot(
138+
self: &mut Pin<&mut Self>,
139+
mut oneshot: OneShot<Option<Event>>,
140+
cx: &mut Context<'_>,
141+
) -> Option<Poll<Option<Event>>> {
142+
match Future::poll(Pin::new(&mut oneshot), cx) {
143+
Poll::Ready(Some(event)) => Some(Poll::Ready(event)),
144+
Poll::Ready(None) => None,
145+
Poll::Pending => {
146+
self.existing = Some(oneshot);
147+
Some(Poll::Pending)
148+
}
149+
}
150+
}
135151
}
136152

137153
impl Future for Subscriber {
138154
type Output = Option<Event>;
139155

140-
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
156+
fn poll(
157+
mut self: Pin<&mut Self>,
158+
cx: &mut Context<'_>,
159+
) -> Poll<Self::Output> {
141160
loop {
161+
if let Some(future_rx) = self.existing.take() {
162+
if let Some(poll) = self.poll_oneshot(future_rx, cx) {
163+
return poll;
164+
}
165+
}
166+
142167
match self.rx.try_recv() {
143-
Ok(mut future_rx) => {
144-
#[allow(unsafe_code)]
145-
let future_rx =
146-
unsafe { std::pin::Pin::new_unchecked(&mut future_rx) };
147-
148-
match Future::poll(future_rx, cx) {
149-
Poll::Ready(Some(event)) => {
150-
return Poll::Ready(event);
151-
}
152-
Poll::Ready(None) => {
153-
continue;
154-
}
155-
Poll::Pending => {
156-
return Poll::Pending;
157-
}
168+
Ok(future_rx) => {
169+
if let Some(poll) = self.poll_oneshot(future_rx, cx) {
170+
return poll;
158171
}
159172
}
160173
Err(TryRecvError::Empty) => break,
@@ -237,7 +250,7 @@ impl Subscribers {
237250

238251
w_senders.insert(id, (None, tx));
239252

240-
Subscriber { id, rx, home: arc_senders.clone() }
253+
Subscriber { id, rx, existing: None, home: arc_senders.clone() }
241254
}
242255

243256
pub(crate) fn reserve<R: AsRef<[u8]>>(

0 commit comments

Comments
 (0)