Skip to content

Commit 6c588cd

Browse files
ZipLongest::fold: use try_fold
1 parent 98344ad commit 6c588cd

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/zip_longest.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,20 @@ where
5454
}
5555

5656
#[inline]
57-
fn fold<B, F>(self, mut init: B, mut f: F) -> B
57+
fn fold<B, F>(self, init: B, mut f: F) -> B
5858
where
5959
Self: Sized,
6060
F: FnMut(B, Self::Item) -> B,
6161
{
62-
let Self { a, mut b } = self;
63-
init = a.fold(init, |init, a| match b.next() {
64-
Some(b) => f(init, EitherOrBoth::Both(a, b)),
65-
None => f(init, EitherOrBoth::Left(a)),
62+
let Self { mut a, mut b } = self;
63+
let res = a.try_fold(init, |init, a| match b.next() {
64+
Some(b) => Ok(f(init, EitherOrBoth::Both(a, b))),
65+
None => Err(f(init, EitherOrBoth::Left(a))),
6666
});
67-
b.fold(init, |init, b| f(init, EitherOrBoth::Right(b)))
67+
match res {
68+
Ok(acc) => b.map(EitherOrBoth::Right).fold(acc, f),
69+
Err(acc) => a.map(EitherOrBoth::Left).fold(acc, f),
70+
}
6871
}
6972
}
7073

0 commit comments

Comments
 (0)