diff --git a/benches/bench1.rs b/benches/bench1.rs index fbcaa05a7..664191ab4 100644 --- a/benches/bench1.rs +++ b/benches/bench1.rs @@ -448,6 +448,25 @@ fn group_by_lazy_2(c: &mut Criterion) { }); } +fn while_some(c: &mut Criterion) { + c.bench_function("while_some", |b| { + b.iter(|| { + let data = black_box( + (0..) + .fuse() + .map(|i| std::char::from_digit(i, 16)) + .while_some(), + ); + // let result: String = data.fold(String::new(), |acc, ch| acc + &ch.to_string()); + let result = data.fold(String::new(), |mut acc, ch| { + acc.push(ch); + acc + }); + assert_eq!(result.as_str(), "0123456789abcdef"); + }); + }); +} + fn slice_chunks(c: &mut Criterion) { let data = vec![0; 1024]; @@ -884,5 +903,6 @@ criterion_group!( permutations_range, permutations_slice, with_position_fold, + while_some, ); criterion_main!(benches); diff --git a/src/adaptors/mod.rs b/src/adaptors/mod.rs index 90cf46eed..18c864ad1 100644 --- a/src/adaptors/mod.rs +++ b/src/adaptors/mod.rs @@ -581,6 +581,22 @@ where fn size_hint(&self) -> (usize, Option) { (0, self.iter.size_hint().1) } + + fn fold(mut self, acc: B, mut f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, + { + let res = self.iter.try_fold(acc, |acc, item| match item { + Some(item) => Ok(f(acc, item)), + None => Err(acc), + }); + let res = match res { + Ok(val) => val, + Err(val) => val, + }; + res + } } /// An iterator to iterate through all combinations in a `Clone`-able iterator that produces tuples