Skip to main content

tokio_stream/stream_ext/
take_while.rs

1use crate::Stream;
2
3use core::fmt;
4use core::pin::Pin;
5use core::task::{Context, Poll};
6use futures_core::FusedStream;
7use pin_project_lite::pin_project;
8
9pin_project! {
10    /// Stream for the [`take_while`](super::StreamExt::take_while) method.
11    #[must_use = "streams do nothing unless polled"]
12    pub struct TakeWhile<St, F> {
13        #[pin]
14        stream: St,
15        predicate: F,
16        done: bool,
17    }
18}
19
20impl<St, F> fmt::Debug for TakeWhile<St, F>
21where
22    St: fmt::Debug,
23{
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        f.debug_struct("TakeWhile")
26            .field("stream", &self.stream)
27            .field("done", &self.done)
28            .finish()
29    }
30}
31
32impl<St, F> TakeWhile<St, F> {
33    pub(super) fn new(stream: St, predicate: F) -> Self {
34        Self {
35            stream,
36            predicate,
37            done: false,
38        }
39    }
40}
41
42impl<St, F> Stream for TakeWhile<St, F>
43where
44    St: Stream,
45    F: FnMut(&St::Item) -> bool,
46{
47    type Item = St::Item;
48
49    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
50        if !*self.as_mut().project().done {
51            self.as_mut().project().stream.poll_next(cx).map(|ready| {
52                let ready = ready.filter(self.as_mut().project().predicate);
53
54                if ready.is_none() {
55                    *self.as_mut().project().done = true;
56                }
57
58                ready
59            })
60        } else {
61            Poll::Ready(None)
62        }
63    }
64
65    fn size_hint(&self) -> (usize, Option<usize>) {
66        if self.done {
67            return (0, Some(0));
68        }
69
70        let (_, upper) = self.stream.size_hint();
71
72        (0, upper)
73    }
74}
75
76impl<St, F> FusedStream for TakeWhile<St, F>
77where
78    St: Stream,
79    F: FnMut(&St::Item) -> bool,
80{
81    fn is_terminated(&self) -> bool {
82        self.done
83    }
84}