Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions benches/bench1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,21 @@ fn permutations_slice(c: &mut Criterion) {
});
}

fn take_while_ref(c: &mut Criterion) {
c.bench_function("take_while_ref", |b| {
b.iter(|| {
let mut data = black_box("0123456789abcdef".chars());
let result =
data.take_while_ref(|c| c.is_numeric())
.fold(String::new(), |mut acc, ch| {
acc.push(ch);
acc
});
assert_eq!(result.as_str(), "0123456789");
});
});
}

criterion_group!(
benches,
slice_iter,
Expand Down Expand Up @@ -837,5 +852,6 @@ criterion_group!(
permutations_iter,
permutations_range,
permutations_slice,
take_while_ref
);
criterion_main!(benches);
26 changes: 26 additions & 0 deletions src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub use self::map::{map_into, map_ok, MapInto, MapOk};
pub use self::multi_product::*;

use crate::size_hint::{self, SizeHint};
use crate::FoldWhile::{Continue, Done};
use crate::Itertools;
use std::fmt;
use std::iter::{Enumerate, FromIterator, Fuse, FusedIterator};
use std::marker::PhantomData;
Expand Down Expand Up @@ -555,6 +557,30 @@ where
fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.iter.size_hint().1)
}

fn fold<B, G>(mut self, init: B, mut g: G) -> B
where
G: FnMut(B, I::Item) -> B,
{
let acc = init;
let original_iter = self.iter.clone();

let result = self.iter.clone().fold_while(acc, |acc, x| {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not clone it a second time.

if (self.f)(&x) {
Continue(g(acc, x))
} else {
Done(acc)
}
});

match result {
Done(acc) => {
*self.iter = original_iter;
acc
}
Continue(acc) => acc,
}
}
}

/// An iterator adaptor that filters `Option<A>` iterator elements
Expand Down