Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specialize Interleave[Shortest]::fold #849

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,30 @@ where
fn size_hint(&self) -> (usize, Option<usize>) {
size_hint::add(self.a.size_hint(), self.b.size_hint())
}

fn fold<B, F>(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<I, J> FusedIterator for Interleave<I, J>
Expand Down Expand Up @@ -171,6 +195,34 @@ where
};
(lower, upper)
}

fn fold<B, F>(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<I, J> FusedIterator for InterleaveShortest<I, J>
Expand Down