async_std/stream/stream/
try_fold.rs

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