1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::marker::PhantomData;
use std::pin::Pin;

use crate::stream::Stream;
use crate::task::{Context, Poll};

/// A stream to filter elements of another stream with a predicate.
#[derive(Debug)]
pub struct Filter<S, P, T> {
    stream: S,
    predicate: P,
    __t: PhantomData<T>,
}

impl<S, P, T> Filter<S, P, T> {
    pin_utils::unsafe_pinned!(stream: S);
    pin_utils::unsafe_unpinned!(predicate: P);

    pub(super) fn new(stream: S, predicate: P) -> Self {
        Filter {
            stream,
            predicate,
            __t: PhantomData,
        }
    }
}

impl<S, P> Stream for Filter<S, P, S::Item>
where
    S: Stream,
    P: FnMut(&S::Item) -> bool,
{
    type Item = S::Item;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let next = futures_core::ready!(self.as_mut().stream().poll_next(cx));

        match next {
            Some(v) if (self.as_mut().predicate())(&v) => Poll::Ready(Some(v)),
            Some(_) => {
                cx.waker().wake_by_ref();
                Poll::Pending
            }
            None => Poll::Ready(None),
        }
    }
}