Skip to content

Implemented StreamExt::try_fold #344

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
2 commits merged into from
Oct 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/stream/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ mod skip_while;
mod step_by;
mod take;
mod take_while;
mod try_fold;
mod try_for_each;
mod zip;

Expand All @@ -59,6 +60,7 @@ use min_by::MinByFuture;
use next::NextFuture;
use nth::NthFuture;
use partial_cmp::PartialCmpFuture;
use try_fold::TryFoldFuture;
use try_for_each::TryForEeachFuture;

pub use chain::Chain;
Expand Down Expand Up @@ -1032,6 +1034,46 @@ extension_trait! {
Skip::new(self, n)
}

#[doc = r#"
A combinator that applies a function as long as it returns successfully, producing a single, final value.
Immediately returns the error when the function returns unsuccessfully.

# Examples

Basic usage:

```
# fn main() { async_std::task::block_on(async {
#
use async_std::prelude::*;
use std::collections::VecDeque;

let s: VecDeque<usize> = vec![1, 2, 3].into_iter().collect();
let sum = s.try_fold(0, |acc, v| {
if (acc+v) % 2 == 1 {
Ok(v+3)
} else {
Err("fail")
}
}).await;

assert_eq!(sum, Err("fail"));
#
# }) }
```
"#]
fn try_fold<B, F, T, E>(
self,
init: T,
f: F,
) -> impl Future<Output = Result<T, E>> [TryFoldFuture<Self, F, T>]
where
Self: Sized,
F: FnMut(B, Self::Item) -> Result<T, E>,
{
TryFoldFuture::new(self, init, f)
}

#[doc = r#"
Applies a falliable function to each element in a stream, stopping at first error and returning it.

Expand Down
59 changes: 59 additions & 0 deletions src/stream/stream/try_fold.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use std::marker::PhantomData;
use std::pin::Pin;

use crate::future::Future;
use crate::stream::Stream;
use crate::task::{Context, Poll};

#[doc(hidden)]
#[allow(missing_debug_implementations)]
pub struct TryFoldFuture<S, F, T> {
stream: S,
f: F,
acc: Option<T>,
__t: PhantomData<T>,
}

impl<S, F, T> TryFoldFuture<S, F, T> {
pin_utils::unsafe_pinned!(stream: S);
pin_utils::unsafe_unpinned!(f: F);
pin_utils::unsafe_unpinned!(acc: Option<T>);

pub(super) fn new(stream: S, init: T, f: F) -> Self {
TryFoldFuture {
stream,
f,
acc: Some(init),
__t: PhantomData,
}
}
}

impl<S, F, T, E> Future for TryFoldFuture<S, F, T>
where
S: Stream + Sized,
F: FnMut(T, S::Item) -> Result<T, E>,
{
type Output = Result<T, E>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let next = futures_core::ready!(self.as_mut().stream().poll_next(cx));

match next {
Some(v) => {
let old = self.as_mut().acc().take().unwrap();
let new = (self.as_mut().f())(old, v);

match new {
Ok(o) => {
*self.as_mut().acc() = Some(o);
}
Err(e) => return Poll::Ready(Err(e)),
}
}
None => return Poll::Ready(Ok(self.as_mut().acc().take().unwrap())),
}
}
}
}