Rollup merge of #146410 - hkBst:repeat-1, r=jhpratt

Iterator repeat: no infinite loop for `last` and `count`

This removes two cases of infinite looping from [`Repeat`](https://doc.rust-lang.org/nightly/std/iter/struct.Repeat.html):
- [`last`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.last): By viewing the iterator as returning None after [omega](https://en.wikipedia.org/wiki/Ordinal_number) calls to `next`, this method can simply return the repeated element.

- [`count`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.count): From its docs: """The method does no guarding against overflows, so counting elements of an iterator with more than [usize::MAX](https://doc.rust-lang.org/nightly/std/primitive.usize.html#associatedconstant.MAX) elements either produces the wrong result or panics. If overflow checks are enabled, a panic is guaranteed.""", so a panic'ing impl is allowed by the docs, and is more honest than an infinite loop.
This commit is contained in:
Stuart Cook 2025-09-17 14:56:46 +10:00 committed by GitHub
commit cefd932520
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -9,7 +9,7 @@ use crate::num::NonZero;
/// [`Iterator::take()`], in order to make them finite.
///
/// Use [`str::repeat()`] instead of this function if you just want to repeat
/// a char/string `n`th times.
/// a char/string `n` times.
///
/// If the element type of the iterator you need does not implement `Clone`,
/// or if you do not want to keep the repeated element in memory, you can
@ -98,11 +98,12 @@ impl<A: Clone> Iterator for Repeat<A> {
}
fn last(self) -> Option<A> {
loop {}
Some(self.element)
}
#[track_caller]
fn count(self) -> usize {
loop {}
panic!("iterator is infinite");
}
}