Skip to content

Commit a181806

Browse files
Rollup merge of rust-lang#85338 - lopopolo:core-iter-repeat-rust-langgh-81292, r=joshtriplett
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 rust-lang#81292. rust-lang#81292 raises the question of whether these changes violate the contract of `core::iter::Repeat`, but as far as I can tell `core::iter::repeat` doesn't make any guarantees around how it calls `Clone::clone`.
2 parents d151ed8 + 963bd3b commit a181806

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

library/core/src/iter/sources/repeat.rs

+35
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,32 @@ impl<A: Clone> Iterator for Repeat<A> {
7272
fn next(&mut self) -> Option<A> {
7373
Some(self.element.clone())
7474
}
75+
7576
#[inline]
7677
fn size_hint(&self) -> (usize, Option<usize>) {
7778
(usize::MAX, None)
7879
}
80+
81+
#[inline]
82+
fn advance_by(&mut self, n: usize) -> Result<(), usize> {
83+
// Advancing an infinite iterator of a single element is a no-op.
84+
let _ = n;
85+
Ok(())
86+
}
87+
88+
#[inline]
89+
fn nth(&mut self, n: usize) -> Option<A> {
90+
let _ = n;
91+
Some(self.element.clone())
92+
}
93+
94+
fn last(self) -> Option<A> {
95+
loop {}
96+
}
97+
98+
fn count(self) -> usize {
99+
loop {}
100+
}
79101
}
80102

81103
#[stable(feature = "rust1", since = "1.0.0")]
@@ -84,6 +106,19 @@ impl<A: Clone> DoubleEndedIterator for Repeat<A> {
84106
fn next_back(&mut self) -> Option<A> {
85107
Some(self.element.clone())
86108
}
109+
110+
#[inline]
111+
fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
112+
// Advancing an infinite iterator of a single element is a no-op.
113+
let _ = n;
114+
Ok(())
115+
}
116+
117+
#[inline]
118+
fn nth_back(&mut self, n: usize) -> Option<A> {
119+
let _ = n;
120+
Some(self.element.clone())
121+
}
87122
}
88123

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

0 commit comments

Comments
 (0)