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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use futures_core::{ready, Stream};
use pin_project::{pin_project, project};
use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

/// A `ForEach`-like future.
#[must_use = "futures do nothing unless polled"]
#[pin_project]
pub struct StreamProcessor<S, P, F>
where
    F: Future,
{
    #[pin]
    receiver: S,
    processor: P,
    #[pin]
    state: State<F>,
}

impl<S, P, F> StreamProcessor<S, P, F>
where
    F: Future,
{
    pub fn new(receiver: S, processor: P) -> Self {
        StreamProcessor {
            receiver,
            processor,
            state: State::WaitingForItem,
        }
    }
}

#[pin_project]
enum State<F> {
    WaitingForItem,
    RunningProcessor(#[pin] F),
}

impl<S, P, F> Future for StreamProcessor<S, P, F>
where
    S: Stream,
    P: FnMut(S::Item) -> F,
    F: Future,
{
    type Output = ();

    #[project]
    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
        loop {
            let this = self.as_mut().project();

            #[project]
            let next = match this.state.project() {
                State::WaitingForItem => {
                    if let Some(item) = ready!(this.receiver.poll_next(ctx)) {
                        let fut = (this.processor)(item);
                        State::RunningProcessor(fut)
                    } else {
                        return Poll::Ready(());
                    }
                }
                State::RunningProcessor(fut) => {
                    ready!(fut.poll(ctx));
                    State::WaitingForItem
                }
            };

            self.as_mut().project().state.set(next);
        }
    }
}