undeprecate and optimize `fold_while`
Prompted by
@@ -2099,19 +2099,26 @@ pub trait Itertools : Iterator {
/// The big difference between the computations of `result2` and `result3` is that while
/// `fold()` called the provided closure for every item of the callee iterator,
/// `fold_while()` actually stopped iterating as soon as it encountered `Fold::Done(_)`.
- #[deprecated(note="Use .try_fold() instead", since="0.8.0")]
fn fold_while<B, F>(&mut self, init: B, mut f: F) -> FoldWhile<B>
where Self: Sized,
F: FnMut(B, Self::Item) -> FoldWhile<B>
{
- let mut acc = init;
- for item in self {
- match f(acc, item) {
- FoldWhile::Continue(res) => acc = res,
- res @ FoldWhile::Done(_) => return res,
+ use Result::{
+ Ok as Continue,
+ Err as Break,
+ };
+
+ let result = self.try_fold(init, #[inline(always)] |acc, v|
+ match f(acc, v) {
+ FoldWhile::Continue(acc) => Continue(acc),
+ FoldWhile::Done(acc) => Break(acc),
}
+ );
+
+ match result {
+ Continue(acc) => FoldWhile::Continue(acc),
+ Break(acc) => FoldWhile::Done(acc),
}
- FoldWhile::Continue(acc)
}
/// Iterate over the entire iterator and add all the elements.
