Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement custom fold for WhileSome #780

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions benches/bench1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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];

Expand Down Expand Up @@ -884,5 +903,6 @@ criterion_group!(
permutations_range,
permutations_slice,
with_position_fold,
while_some,
);
criterion_main!(benches);
16 changes: 16 additions & 0 deletions src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,22 @@ where
fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.iter.size_hint().1)
}

fn fold<B, F>(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
Expand Down