From 7c827ae9325400f05ec6703f86171c43497d02c5 Mon Sep 17 00:00:00 2001 From: Philippe-Cholet Date: Wed, 8 Nov 2023 12:09:17 +0100 Subject: [PATCH 1/2] `Interleave::fold` --- src/adaptors/mod.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/adaptors/mod.rs b/src/adaptors/mod.rs index 08d91e397..36ff1cde6 100644 --- a/src/adaptors/mod.rs +++ b/src/adaptors/mod.rs @@ -76,6 +76,30 @@ where fn size_hint(&self) -> (usize, Option) { size_hint::add(self.a.size_hint(), self.b.size_hint()) } + + fn fold(self, mut init: B, mut f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + let Self { mut a, mut b, flag } = self; + if flag { + match b.next() { + Some(y) => init = f(init, y), + None => return a.fold(init, f), + } + } + let res = a.try_fold(init, |mut acc, x| { + acc = f(acc, x); + match b.next() { + Some(y) => Ok(f(acc, y)), + None => Err(acc), + } + }); + match res { + Ok(acc) => b.fold(acc, f), + Err(acc) => a.fold(acc, f), + } + } } impl FusedIterator for Interleave From a4e74863c2b4e1a07edaa36aa389da4319766424 Mon Sep 17 00:00:00 2001 From: Philippe-Cholet Date: Wed, 8 Nov 2023 12:10:10 +0100 Subject: [PATCH 2/2] `InterleaveShortest::fold` --- src/adaptors/mod.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/adaptors/mod.rs b/src/adaptors/mod.rs index 36ff1cde6..a2bfb92ea 100644 --- a/src/adaptors/mod.rs +++ b/src/adaptors/mod.rs @@ -195,6 +195,34 @@ where }; (lower, upper) } + + fn fold(self, mut init: B, mut f: F) -> B + where + F: FnMut(B, Self::Item) -> B, + { + let Self { + mut it0, + mut it1, + phase, + } = self; + if phase { + match it1.next() { + Some(y) => init = f(init, y), + None => return init, + } + } + let res = it0.try_fold(init, |mut acc, x| { + acc = f(acc, x); + match it1.next() { + Some(y) => Ok(f(acc, y)), + None => Err(acc), + } + }); + match res { + Ok(val) => val, + Err(val) => val, + } + } } impl FusedIterator for InterleaveShortest