diff options
| author | 许杰友 Jieyou Xu (Joe) <39484203+jieyouxu@users.noreply.github.com> | 2025-03-16 09:40:07 +0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-03-16 09:40:07 +0800 |
| commit | 01bc95417c8f9b4709af679b584e1670d9b956ad (patch) | |
| tree | 9bea51ee1e78a2ecd52fd1b149b038fd029b1856 | |
| parent | 5b9225070cee25f07086ff1db5b10abbae9a1918 (diff) | |
| parent | 3c74d02319ea8ebbfd16f70f3154ce0aef87ae5c (diff) | |
| download | rust-01bc95417c8f9b4709af679b584e1670d9b956ad.tar.gz rust-01bc95417c8f9b4709af679b584e1670d9b956ad.zip | |
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`).
| -rw-r--r-- | library/core/src/iter/traits/iterator.rs | 9 |
1 files changed, 9 insertions, 0 deletions
diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 5f157ff913b..075da022854 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -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) } |
