From 0545b349e1fbf6663eb628cd4273c5baddf232fe Mon Sep 17 00:00:00 2001 From: Artem Vorotnikov Date: Thu, 23 Jan 2020 18:03:10 +0100 Subject: stream: add `StreamExt::fold()` (#2122) --- tokio/src/stream/mod.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'tokio/src/stream/mod.rs') 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(self, init: B, f: F) -> FoldFuture + 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 -- cgit v1.2.3