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
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use completion_core::{CompletionFuture, CompletionStream};
use futures_core::{ready, Stream};
use pin_project_lite::pin_project;
pin_project! {
#[derive(Debug)]
pub struct Fold<S, F, T> {
#[pin]
stream: S,
f: F,
accumulator: Option<T>,
}
}
impl<S, F, T> Fold<S, F, T> {
pub(crate) fn new(stream: S, init: T, f: F) -> Self {
Self {
stream,
f,
accumulator: Some(init),
}
}
}
impl<S, F, T> CompletionFuture for Fold<S, F, T>
where
S: CompletionStream,
F: FnMut(T, S::Item) -> T,
{
type Output = T;
unsafe fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
loop {
match ready!(this.stream.as_mut().poll_next(cx)) {
Some(item) => {
let accumulator = this.accumulator.take().expect("polled after completion");
*this.accumulator = Some((this.f)(accumulator, item));
}
None => {
break Poll::Ready(this.accumulator.take().expect("polled after completion"))
}
}
}
}
unsafe fn poll_cancel(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
self.project().stream.poll_cancel(cx)
}
}
impl<S, F, T> Future for Fold<S, F, T>
where
S: CompletionStream + Stream<Item = <S as CompletionStream>::Item>,
F: FnMut(T, <S as CompletionStream>::Item) -> T,
{
type Output = <Self as CompletionFuture>::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
unsafe { CompletionFuture::poll(self, cx) }
}
}