Skip to content

Commit

Permalink
Explicitly test Iterator::position overflows
Browse files Browse the repository at this point in the history
  • Loading branch information
cuviper committed Aug 12, 2019
1 parent af1bfbe commit 6a04c76
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/libcore/iter/traits/iterator.rs
Expand Up @@ -2069,15 +2069,14 @@ pub trait Iterator {
Self: Sized,
P: FnMut(Self::Item) -> bool,
{
// The addition might panic on overflow
#[inline]
#[rustc_inherit_overflow_checks]
fn check<T>(
mut predicate: impl FnMut(T) -> bool,
) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
// The addition might panic on overflow
move |i, x| {
if predicate(x) { LoopState::Break(i) }
else { LoopState::Continue(i + 1) }
else { LoopState::Continue(Add::add(i, 1)) }
}
}

Expand Down
22 changes: 22 additions & 0 deletions src/test/run-pass/iterators/iter-position-overflow-debug.rs
@@ -0,0 +1,22 @@
// run-pass
// only-32bit too impatient for 2⁶⁴ items
// ignore-wasm32-bare compiled with panic=abort by default
// compile-flags: -C debug_assertions=yes

use std::panic;
use std::usize::MAX;

fn main() {
let n = MAX as u64;
assert_eq!((0..).by_ref().position(|i| i >= n), Some(MAX));

let r = panic::catch_unwind(|| {
(0..).by_ref().position(|i| i > n)
});
assert!(r.is_err());

let r = panic::catch_unwind(|| {
(0..=n + 1).by_ref().position(|_| false)
});
assert!(r.is_err());
}
13 changes: 13 additions & 0 deletions src/test/run-pass/iterators/iter-position-overflow-ndebug.rs
@@ -0,0 +1,13 @@
// run-pass
// only-32bit too impatient for 2⁶⁴ items
// compile-flags: -C debug_assertions=no

use std::panic;
use std::usize::MAX;

fn main() {
let n = MAX as u64;
assert_eq!((0..).by_ref().position(|i| i >= n), Some(MAX));
assert_eq!((0..).by_ref().position(|i| i > n), Some(0));
assert_eq!((0..=n + 1).by_ref().position(|_| false), None);
}

0 comments on commit 6a04c76

Please sign in to comment.