Skip to content

Commit b8ea7ff

Browse files
committed
Add stream::fold implementation
1 parent 19f7fdb commit b8ea7ff

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/stream.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,20 @@ pub fn skip_while<St, F, Fut>(stream: St, f: F) -> impl Stream<Item = St::Item>
291291
})
292292
}
293293

294+
pub async fn fold<St, T, F, Fut>(stream: St, init: T, f: F) -> T
295+
where St: Stream,
296+
F: FnMut(T, St::Item) -> Fut,
297+
Fut: Future<Output = T>,
298+
{
299+
pin_mut!(stream);
300+
let mut f = f;
301+
let mut acc = init;
302+
while let Some(item) = await!(next(&mut stream)) {
303+
acc = await!(f(acc, item));
304+
}
305+
acc
306+
}
307+
294308
#[cfg(test)]
295309
mod tests {
296310
use futures::executor;
@@ -465,4 +479,12 @@ mod tests {
465479

466480
assert_eq!(vec![6, 7, 8, 9, 10], executor::block_on(collect::<_, Vec<_>>(stream)));
467481
}
482+
483+
#[test]
484+
fn test_fold() {
485+
let stream = iter(0..6);
486+
let sum = fold(stream, 0, |acc, x| ready(acc + x));
487+
488+
assert_eq!(15, executor::block_on(sum));
489+
}
468490
}

0 commit comments

Comments
 (0)