Skip to content

Commit 13635c1

Browse files
committed
Implement custom fold for while some
Implement custom fold for while some
1 parent 0951795 commit 13635c1

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

benches/bench1.rs

+19
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,24 @@ fn group_by_lazy_2(c: &mut Criterion) {
448448
});
449449
}
450450

451+
fn while_some(c: &mut Criterion) {
452+
c.bench_function("while_some", |b| {
453+
b.iter(|| {
454+
let data = black_box(
455+
(0..)
456+
.fuse()
457+
.map(|i| std::char::from_digit(i, 16))
458+
.while_some(),
459+
);
460+
let result: String = data.fold(String::new(), |acc, ch| acc + &ch.to_string());
461+
assert_eq!(
462+
result.chars().collect::<Vec<_>>(),
463+
"0123456789abcdef".chars().collect::<Vec<_>>()
464+
);
465+
});
466+
});
467+
}
468+
451469
fn slice_chunks(c: &mut Criterion) {
452470
let data = vec![0; 1024];
453471

@@ -884,5 +902,6 @@ criterion_group!(
884902
permutations_range,
885903
permutations_slice,
886904
with_position_fold,
905+
while_some,
887906
);
888907
criterion_main!(benches);

src/adaptors/mod.rs

+11
Original file line numberDiff line numberDiff line change
@@ -581,6 +581,17 @@ where
581581
fn size_hint(&self) -> (usize, Option<usize>) {
582582
(0, self.iter.size_hint().1)
583583
}
584+
585+
fn fold<B, F>(self, acc: B, f: F) -> B
586+
where
587+
Self: Sized,
588+
F: FnMut(B, Self::Item) -> B,
589+
{
590+
self.iter
591+
.take_while(|opt| opt.is_some())
592+
.map(|item| item.unwrap())
593+
.fold(acc, f)
594+
}
584595
}
585596

586597
/// An iterator to iterate through all combinations in a `Clone`-able iterator that produces tuples

0 commit comments

Comments
 (0)