Rollup merge of #138329 - scottmcm:assert-hint, r=Mark-Simulacrum

debug-assert that the size_hint is well-formed in `collect`

Closes #137919

In the hopes of helping to catch any future accidentally-incorrect rustc or stdlib iterators (like the ones #137908 accidentally found), this has `Iterator::collect` call `size_hint` and check its `low` doesn't exceed its `Some(high)`.

There's of course a bazillion more places this *could* be checked, but the hope is that this one is a good tradeoff of being likely to catch lots of things while having minimal maintenance cost (especially compared to putting it in *every* container's `from_iter`).
This commit is contained in:
许杰友 Jieyou Xu (Joe) 2025-03-16 09:40:07 +08:00 committed by GitHub
commit 01bc95417c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1977,6 +1977,15 @@ pub trait Iterator {
where
Self: Sized,
{
// This is too aggressive to turn on for everything all the time, but PR#137908
// accidentally noticed that some rustc iterators had malformed `size_hint`s,
// so this will help catch such things in debug-assertions-std runners,
// even if users won't actually ever see it.
if cfg!(debug_assertions) {
let hint = self.size_hint();
assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}");
}
FromIterator::from_iter(self)
}