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
75
76
77
78
79
80
81
use std::pin::Pin;
use std::task::{self, Poll};

use futures_core::ready;
use pin_project_lite::pin_project;

use crate::actor::Actor;
use crate::fut::{ActorFuture, ActorStream};

pin_project! {
    /// Stream for the [`take_while`](super::ActorStreamExt::take_while) method.
    #[must_use = "streams do nothing unless polled"]
    #[derive(Debug)]
    pub struct TakeWhile<S, I, F, Fut> {
        #[pin]
        stream: S,
        f: F,
        #[pin]
        pending_fut: Option<Fut>,
        pending_item: Option<I>,
        done_taking: bool,
    }
}

pub(super) fn new<S, A, F, Fut>(stream: S, f: F) -> TakeWhile<S, S::Item, F, Fut>
where
    S: ActorStream<A>,
    A: Actor,
    F: FnMut(&S::Item, &mut A, &mut A::Context) -> Fut,
    Fut: ActorFuture<A, Output = bool>,
{
    TakeWhile {
        stream,
        f,
        pending_fut: None,
        pending_item: None,
        done_taking: false,
    }
}

impl<S, A, F, Fut> ActorStream<A> for TakeWhile<S, S::Item, F, Fut>
where
    S: ActorStream<A>,
    A: Actor,
    F: FnMut(&S::Item, &mut A, &mut A::Context) -> Fut,
    Fut: ActorFuture<A, Output = bool>,
{
    type Item = S::Item;

    fn poll_next(
        self: Pin<&mut Self>,
        act: &mut A,
        ctx: &mut A::Context,
        task: &mut task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        if self.done_taking {
            return Poll::Ready(None);
        }

        let mut this = self.project();

        Poll::Ready(loop {
            if let Some(fut) = this.pending_fut.as_mut().as_pin_mut() {
                let take = ready!(fut.poll(act, ctx, task));
                let item = this.pending_item.take();
                this.pending_fut.set(None);
                if take {
                    break item;
                } else {
                    *this.done_taking = true;
                    break None;
                }
            } else if let Some(item) = ready!(this.stream.as_mut().poll_next(act, ctx, task)) {
                this.pending_fut.set(Some((this.f)(&item, act, ctx)));
                *this.pending_item = Some(item);
            } else {
                break None;
            }
        })
    }
}