diff --git a/benches/bench1.rs b/benches/bench1.rs index 4dd1395dc..8a384ee69 100644 --- a/benches/bench1.rs +++ b/benches/bench1.rs @@ -391,9 +391,11 @@ fn zip_unchecked_counted_loop3(c: &mut Criterion) { } fn ziplongest(c: &mut Criterion) { + let v1 = black_box((0..768).collect_vec()); + let v2 = black_box((0..1024).collect_vec()); c.bench_function("ziplongest", move |b| { b.iter(|| { - let zip = (0..768).zip_longest(0..1024); + let zip = v1.iter().zip_longest(v2.iter()); let sum = zip.fold(0u32, |mut acc, val| { match val { EitherOrBoth::Both(x, y) => acc += x * y, diff --git a/src/zip_longest.rs b/src/zip_longest.rs index d89e6edef..27d9f3ab6 100644 --- a/src/zip_longest.rs +++ b/src/zip_longest.rs @@ -54,29 +54,17 @@ where } #[inline] - fn fold(self, mut acc: B, mut f: F) -> B + fn fold(self, mut init: B, mut f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { - let ZipLongest { mut a, mut b } = self; - - loop { - match (a.next(), b.next()) { - (Some(x), Some(y)) => acc = f(acc, EitherOrBoth::Both(x, y)), - (Some(x), None) => { - acc = f(acc, EitherOrBoth::Left(x)); - // b is exhausted, so we can drain a. - return a.fold(acc, |acc, x| f(acc, EitherOrBoth::Left(x))); - } - (None, Some(y)) => { - acc = f(acc, EitherOrBoth::Right(y)); - // a is exhausted, so we can drain b. - return b.fold(acc, |acc, y| f(acc, EitherOrBoth::Right(y))); - } - (None, None) => return acc, // Both iterators are exhausted. - } - } + let ZipLongest { a, mut b } = self; + init = a.fold(init, |init, a| match b.next() { + Some(b) => f(init, EitherOrBoth::Both(a, b)), + None => f(init, EitherOrBoth::Left(a)), + }); + b.fold(init, |init, b| f(init, EitherOrBoth::Right(b))) } }