Skip to content

Commit

Permalink
Implement more Iterator methods on core::iter::Repeat
Browse files Browse the repository at this point in the history
`core::iter::Repeat` always returns the same element, which means we can
do better than implementing most `Iterator` methods in terms of
`Iterator::next`.

Fixes #81292.
  • Loading branch information
lopopolo committed May 15, 2021
1 parent 2a245f4 commit 963bd3b
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions library/core/src/iter/sources/repeat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,32 @@ impl<A: Clone> Iterator for Repeat<A> {
fn next(&mut self) -> Option<A> {
Some(self.element.clone())
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(usize::MAX, None)
}

#[inline]
fn advance_by(&mut self, n: usize) -> Result<(), usize> {
// Advancing an infinite iterator of a single element is a no-op.
let _ = n;
Ok(())
}

#[inline]
fn nth(&mut self, n: usize) -> Option<A> {
let _ = n;
Some(self.element.clone())
}

fn last(self) -> Option<A> {
loop {}
}

fn count(self) -> usize {
loop {}
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand All @@ -84,6 +106,19 @@ impl<A: Clone> DoubleEndedIterator for Repeat<A> {
fn next_back(&mut self) -> Option<A> {
Some(self.element.clone())
}

#[inline]
fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
// Advancing an infinite iterator of a single element is a no-op.
let _ = n;
Ok(())
}

#[inline]
fn nth_back(&mut self, n: usize) -> Option<A> {
let _ = n;
Some(self.element.clone())
}
}

#[stable(feature = "fused", since = "1.26.0")]
Expand Down

0 comments on commit 963bd3b

Please sign in to comment.