async_std/stream/stream/
skip_while.rs

1use core::pin::Pin;
2
3use pin_project_lite::pin_project;
4
5use crate::stream::Stream;
6use crate::task::{Context, Poll};
7
8pin_project! {
9    /// A stream to skip elements of another stream based on a predicate.
10    ///
11    /// This `struct` is created by the [`skip_while`] method on [`Stream`]. See its
12    /// documentation for more.
13    ///
14    /// [`skip_while`]: trait.Stream.html#method.skip_while
15    /// [`Stream`]: trait.Stream.html
16    #[derive(Debug)]
17    pub struct SkipWhile<S, P> {
18        #[pin]
19        stream: S,
20        predicate: Option<P>,
21    }
22}
23
24impl<S, P> SkipWhile<S, P> {
25    pub(crate) fn new(stream: S, predicate: P) -> Self {
26        Self {
27            stream,
28            predicate: Some(predicate),
29        }
30    }
31}
32
33impl<S, P> Stream for SkipWhile<S, P>
34where
35    S: Stream,
36    P: FnMut(&S::Item) -> bool,
37{
38    type Item = S::Item;
39
40    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
41        let mut this = self.project();
42        loop {
43            let next = futures_core::ready!(this.stream.as_mut().poll_next(cx));
44
45            match next {
46                Some(v) => match this.predicate {
47                    Some(p) => {
48                        if !p(&v) {
49                            *this.predicate = None;
50                            return Poll::Ready(Some(v));
51                        }
52                    }
53                    None => return Poll::Ready(Some(v)),
54                },
55                None => return Poll::Ready(None),
56            }
57        }
58    }
59}