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 RepeatN::[r]fold #821

Merged
merged 2 commits into from
Dec 15, 2023
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
22 changes: 22 additions & 0 deletions src/repeatn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ where
fn size_hint(&self) -> (usize, Option<usize>) {
(self.n, Some(self.n))
}

fn fold<B, F>(self, mut init: B, mut f: F) -> B
where
F: FnMut(B, Self::Item) -> B,
{
match self {
Self { elt: Some(elt), n } => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here, we take elt as reference if there's still work to do, whereas fn next uses self.n > 1. Should we canonicalize?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure there is a real benefit to win here. Feel free to investigate.

debug_assert!(n > 0);
init = (1..n).map(|_| elt.clone()).fold(init, &mut f);
f(init, elt)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoiding the clone. Nice.

}
_ => init,
}
}
}

impl<A> DoubleEndedIterator for RepeatN<A>
Expand All @@ -54,6 +68,14 @@ where
fn next_back(&mut self) -> Option<Self::Item> {
self.next()
}

#[inline]
fn rfold<B, F>(self, init: B, f: F) -> B
where
F: FnMut(B, Self::Item) -> B,
{
self.fold(init, f)
}
}

impl<A> ExactSizeIterator for RepeatN<A> where A: Clone {}
Expand Down