summaryrefslogtreecommitdiffstats
path: root/tokio/src/stream
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
parent8cf98d694663e8397bfc337e7a4676567287bfae (diff)
stream: add `StreamExt::fold()` (#2122)
Diffstat (limited to 'tokio/src/stream')
-rw-r--r--tokio/src/stream/fold.rs51
-rw-r--r--tokio/src/stream/mod.rs27
2 files changed, 78 insertions, 0 deletions
diff --git a/tokio/src/stream/fold.rs b/tokio/src/stream/fold.rs
new file mode 100644
index 00000000..7b9fead3
--- /dev/null
+++ b/tokio/src/stream/fold.rs
@@ -0,0 +1,51 @@
+use crate::stream::Stream;
+
+use core::future::Future;
+use core::pin::Pin;
+use core::task::{Context, Poll};
+use pin_project_lite::pin_project;
+
+pin_project! {
+ /// Future returned by the [`fold`](super::StreamExt::fold) method.
+ #[derive(Debug)]
+ pub struct FoldFuture<St, B, F> {
+ #[pin]
+ stream: St,
+ acc: Option<B>,
+ f: F,
+ }
+}
+
+impl<St, B, F> FoldFuture<St, B, F> {
+ pub(super) fn new(stream: St, init: B, f: F) -> Self {
+ Self {
+ stream,
+ acc: Some(init),
+ f,
+ }
+ }
+}
+
+impl<St, B, F> Future for FoldFuture<St, B, F>
+where
+ St: Stream,
+ F: FnMut(B, St::Item) -> B,
+{
+ type Output = B;
+
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ let mut me = self.project();
+ loop {
+ let next = ready!(me.stream.as_mut().poll_next(cx));
+
+ match next {
+ Some(v) => {
+ let old = me.acc.take().unwrap();
+ let new = (me.f)(old, v);
+ *me.acc = Some(new);
+ }
+ None => return Poll::Ready(me.acc.take().unwrap()),
+ }
+ }
+ }
+}
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