summaryrefslogtreecommitdiffstats
path: root/tokio/src/stream/mod.rs
diff options
context:
space:
mode:
authorArtem Vorotnikov <artem@vorotnikov.me>2020-01-23 18:03:10 +0100
committerCarl Lerche <me@carllerche.com>2020-01-23 09:03:10 -0800
commit0545b349e1fbf6663eb628cd4273c5baddf232fe (patch)
tree1c8cdd57ebbe5a0863e6c7808b0f125eb4a3072f /tokio/src/stream/mod.rs
parent8cf98d694663e8397bfc337e7a4676567287bfae (diff)
stream: add `StreamExt::fold()` (#2122)
Diffstat (limited to 'tokio/src/stream/mod.rs')
-rw-r--r--tokio/src/stream/mod.rs27
1 files changed, 27 insertions, 0 deletions
diff --git a/tokio/src/stream/mod.rs b/tokio/src/stream/mod.rs
index 081fe817..3c09b658 100644
--- a/tokio/src/stream/mod.rs
+++ b/tokio/src/stream/mod.rs
@@ -26,6 +26,9 @@ use filter::Filter;
mod filter_map;
use filter_map::FilterMap;
+mod fold;
+use fold::FoldFuture;
+
mod fuse;
use fuse::Fuse;
@@ -582,6 +585,30 @@ pub trait StreamExt: Stream {
Chain::new(self, other)
}
+ /// A combinator that applies a function to every element in a stream
+ /// producing a single, final value.
+ ///
+ /// # Examples
+ /// Basic usage:
+ /// ```
+ /// # #[tokio::main]
+ /// # async fn main() {
+ /// use tokio::stream::{self, *};
+ ///
+ /// let s = stream::iter(vec![1u8, 2, 3]);
+ /// let sum = s.fold(0, |acc, x| acc + x).await;
+ ///
+ /// assert_eq!(sum, 6);
+ /// # }
+ /// ```
+ fn fold<B, F>(self, init: B, f: F) -> FoldFuture<Self, B, F>
+ where
+ Self: Sized,
+ F: FnMut(B, Self::Item) -> B,
+ {
+ FoldFuture::new(self, init, f)
+ }
+
/// Drain stream pushing all emitted values into a collection.
///
/// `collect` streams all values, awaiting as needed. Values are pushed into