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 std::pin::Pin;
use std::task::{Context, Poll};
use futures_core::ready;
use pin_project_lite::pin_project;
use crate::actor::Actor;
use crate::fut::{ActorFuture, ActorStream};
pin_project! {
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Fold<S, F, Fut, T> {
#[pin]
stream: S,
f: F,
accum: Option<T>,
#[pin]
future: Option<Fut>,
}
}
pub(super) fn new<S, A, F, Fut>(stream: S, f: F, t: Fut::Output) -> Fold<S, F, Fut, Fut::Output>
where
S: ActorStream<A>,
A: Actor,
F: FnMut(Fut::Output, S::Item, &mut A, &mut A::Context) -> Fut,
Fut: ActorFuture<A>,
{
Fold {
stream,
f,
accum: Some(t),
future: None,
}
}
impl<S, A, F, Fut> ActorFuture<A> for Fold<S, F, Fut, Fut::Output>
where
S: ActorStream<A>,
A: Actor,
F: FnMut(Fut::Output, S::Item, &mut A, &mut A::Context) -> Fut,
Fut: ActorFuture<A>,
{
type Output = Fut::Output;
fn poll(
self: Pin<&mut Self>,
act: &mut A,
ctx: &mut A::Context,
task: &mut Context<'_>,
) -> Poll<Self::Output> {
let mut this = self.project();
Poll::Ready(loop {
if let Some(fut) = this.future.as_mut().as_pin_mut() {
*this.accum = Some(ready!(fut.poll(act, ctx, task)));
this.future.set(None);
} else if this.accum.is_some() {
let res = ready!(this.stream.as_mut().poll_next(act, ctx, task));
let a = this.accum.take().unwrap();
if let Some(item) = res {
this.future.set(Some((this.f)(a, item, act, ctx)));
} else {
break a;
}
} else {
panic!("Fold polled after completion")
}
})
}
}