Skip to content

Commit af1bfbe

Browse files
committed
Explicitly test Iterator::count overflows
1 parent 95e2a4f commit af1bfbe

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

src/libcore/iter/traits/iterator.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::cmp::Ordering;
2-
use crate::ops::Try;
2+
use crate::ops::{Add, Try};
33

44
use super::super::LoopState;
55
use super::super::{Chain, Cycle, Copied, Cloned, Enumerate, Filter, FilterMap, Fuse};
@@ -236,11 +236,10 @@ pub trait Iterator {
236236
#[inline]
237237
#[stable(feature = "rust1", since = "1.0.0")]
238238
fn count(self) -> usize where Self: Sized {
239-
// Might overflow.
240239
#[inline]
241-
#[rustc_inherit_overflow_checks]
242240
fn add1<T>(count: usize, _: T) -> usize {
243-
count + 1
241+
// Might overflow.
242+
Add::add(count, 1)
244243
}
245244

246245
self.fold(0, add1)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// run-pass
2+
// only-32bit too impatient for 2⁶⁴ items
3+
// ignore-wasm32-bare compiled with panic=abort by default
4+
// compile-flags: -C debug_assertions=yes
5+
6+
use std::panic;
7+
use std::usize::MAX;
8+
9+
fn main() {
10+
assert_eq!((0..MAX).by_ref().count(), MAX);
11+
12+
let r = panic::catch_unwind(|| {
13+
(0..=MAX).by_ref().count()
14+
});
15+
assert!(r.is_err());
16+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// run-pass
2+
// only-32bit too impatient for 2⁶⁴ items
3+
// compile-flags: -C debug_assertions=no
4+
5+
use std::panic;
6+
use std::usize::MAX;
7+
8+
fn main() {
9+
assert_eq!((0..MAX).by_ref().count(), MAX);
10+
assert_eq!((0..=MAX).by_ref().count(), 0);
11+
}

0 commit comments

Comments
 (0)