Skip to content

Commit

Permalink
turn the Option<St> into a St
Browse files Browse the repository at this point in the history
`MapWhile` doesn't need to remember whether it's done. As per the contract of the `Stream` trait:

> Once a stream has finished (returned Ready(None) from poll_next), calling its poll_next method again may panic, block forever, or cause other kinds of problems; the Stream trait places no requirements on the effects of such a call.

This allows us to save the space that may be needed by the boolean,
but also lets us simplify the implementation. People can use `fuse`
if they so need.
  • Loading branch information
BraulioVM committed Dec 30, 2021
1 parent cd834df commit cc2aac6
Showing 1 changed file with 6 additions and 24 deletions.
30 changes: 6 additions & 24 deletions tokio-stream/src/stream_ext/map_while.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pin_project! {
#[must_use = "streams do nothing unless polled"]
pub struct MapWhile<St, F> {
#[pin]
stream: Option<St>,
stream: St,
f: F,
}
}
Expand All @@ -28,10 +28,7 @@ where

impl<St, F> MapWhile<St, F> {
pub(super) fn new(stream: St, f: F) -> Self {
MapWhile {
stream: Some(stream),
f,
}
MapWhile { stream, f }
}
}

Expand All @@ -43,28 +40,13 @@ where
type Item = T;

fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
let mut me = self.project();
let me = self.project();
let f = me.f;
match me.stream.as_mut().as_pin_mut() {
Some(stream) => match stream.poll_next(cx).map(|opt| opt.and_then(f)) {
Poll::Ready(Some(item)) => Poll::Ready(Some(item)),
Poll::Ready(None) => {
me.stream.set(None);
Poll::Ready(None)
}
Poll::Pending => Poll::Pending,
},
None => Poll::Ready(None),
}
me.stream.poll_next(cx).map(|opt| opt.and_then(f))
}

fn size_hint(&self) -> (usize, Option<usize>) {
self.stream
.as_ref()
.map(|stream| {
let (_, upper) = stream.size_hint();
(0, upper)
})
.unwrap_or((0, Some(0)))
let (_, upper) = self.stream.size_hint();
(0, upper)
}
}

0 comments on commit cc2aac6

Please sign in to comment.