Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream::ForEach can no longer block indefinitely #2224

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 24 additions & 19 deletions futures-util/src/stream/stream/for_each.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ where
}

impl<St, Fut, F> ForEach<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
where
St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
pub(super) fn new(stream: St, f: F) -> ForEach<St, Fut, F> {
ForEach {
Expand All @@ -44,34 +45,38 @@ where St: Stream,
}

impl<St, Fut, F> FusedFuture for ForEach<St, Fut, F>
where St: FusedStream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
where
St: FusedStream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
fn is_terminated(&self) -> bool {
self.future.is_none() && self.stream.is_terminated()
}
}

impl<St, Fut, F> Future for ForEach<St, Fut, F>
where St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
where
St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = ()>,
{
type Output = ();

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut this = self.project();
loop {
if let Some(fut) = this.future.as_mut().as_pin_mut() {
ready!(fut.poll(cx));
this.future.set(None);
} else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) {
this.future.set(Some((this.f)(item)));
} else {
break;
}

if let Some(fut) = this.future.as_mut().as_pin_mut() {
ready!(fut.poll(cx));
cx.waker().wake_by_ref();
this.future.set(None);
Poll::Pending
} else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) {
cx.waker().wake_by_ref();
this.future.set(Some((this.f)(item)));
Poll::Pending
} else {
Poll::Ready(())
}
Poll::Ready(())
}
}