Skip to content

Commit e7752ae

Browse files
authored
Rollup merge of #68469 - ollie27:skip_count, r=sfackler
Avoid overflow in `std::iter::Skip::count` The call to `count` on the inner iterator can overflow even if `Skip` itself would return less that `usize::max_value()` items. Fixes #68139
2 parents 143059d + 9d3e844 commit e7752ae

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/libcore/iter/adapters/mod.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -1815,8 +1815,14 @@ where
18151815
}
18161816

18171817
#[inline]
1818-
fn count(self) -> usize {
1819-
self.iter.count().saturating_sub(self.n)
1818+
fn count(mut self) -> usize {
1819+
if self.n > 0 {
1820+
// nth(n) skips n+1
1821+
if self.iter.nth(self.n - 1).is_none() {
1822+
return 0;
1823+
}
1824+
}
1825+
self.iter.count()
18201826
}
18211827

18221828
#[inline]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// run-pass
2+
// only-32bit too impatient for 2⁶⁴ items
3+
// compile-flags: -C overflow-checks -C opt-level=3
4+
5+
fn main() {
6+
let i = (0..usize::max_value()).chain(0..10).skip(usize::max_value());
7+
assert_eq!(i.count(), 10);
8+
}

0 commit comments

Comments
 (0)