async_std/stream/double_ended_stream/
rfold.rs

1use core::future::Future;
2use core::pin::Pin;
3use core::task::{Context, Poll};
4
5use pin_project_lite::pin_project;
6
7use crate::stream::DoubleEndedStream;
8
9pin_project! {
10    #[doc(hidden)]
11    #[allow(missing_debug_implementations)]
12    pub struct RFoldFuture<S, F, B> {
13        #[pin]
14        stream: S,
15        f: F,
16        acc: Option<B>,
17    }
18}
19
20impl<S, F, B> RFoldFuture<S, F, B> {
21    pub(super) fn new(stream: S, init: B, f: F) -> Self {
22        RFoldFuture {
23            stream,
24            f,
25            acc: Some(init),
26        }
27    }
28}
29
30impl<S, F, B> Future for RFoldFuture<S, F, B>
31where
32    S: DoubleEndedStream + Sized,
33    F: FnMut(B, S::Item) -> B,
34{
35    type Output = B;
36
37    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
38        let mut this = self.project();
39        loop {
40            let next = futures_core::ready!(this.stream.as_mut().poll_next_back(cx));
41
42            match next {
43                Some(v) => {
44                    let old = this.acc.take().unwrap();
45                    let new = (this.f)(old, v);
46                    *this.acc = Some(new);
47                }
48                None => return Poll::Ready(this.acc.take().unwrap()),
49            }
50        }
51    }
52}