Implement more Iterator methods on core::iter::Repeat

`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.
This commit is contained in:
Ryan Lopopolo 2021-05-15 10:37:05 -07:00
parent 2a245f40a1
commit 963bd3b643
No known key found for this signature in database
GPG Key ID: 46047D739B6AE0B1

View File

@ -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")]
@ -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")]