From 6c588cd4752059fb87a688a3ef3ae15af5aab007 Mon Sep 17 00:00:00 2001 From: Philippe-Cholet Date: Wed, 17 Jan 2024 09:13:35 +0100 Subject: [PATCH] `ZipLongest::fold`: use `try_fold` --- src/zip_longest.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/zip_longest.rs b/src/zip_longest.rs index f390edebd..6eb4bfbff 100644 --- a/src/zip_longest.rs +++ b/src/zip_longest.rs @@ -54,17 +54,20 @@ where } #[inline] - fn fold(self, mut init: B, mut f: F) -> B + fn fold(self, init: B, mut f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { - let Self { 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)), + let Self { mut a, mut b } = self; + let res = a.try_fold(init, |init, a| match b.next() { + Some(b) => Ok(f(init, EitherOrBoth::Both(a, b))), + None => Err(f(init, EitherOrBoth::Left(a))), }); - b.fold(init, |init, b| f(init, EitherOrBoth::Right(b))) + match res { + Ok(acc) => b.map(EitherOrBoth::Right).fold(acc, f), + Err(acc) => a.map(EitherOrBoth::Left).fold(acc, f), + } } }