Skip to content

Commit

Permalink
Rollup merge of rust-lang#47333 - arthurprs:iter-position-bounds-chec…
Browse files Browse the repository at this point in the history
…k, r=dtolnay

Optimize slice.{r}position result bounds check

Second attempt of rust-lang#45501
Fixes rust-lang#45964

Demo: https://godbolt.org/g/N4mBHp
  • Loading branch information
kennytm committed Jan 17, 2018
2 parents 283ee54 + 0b56ab0 commit 175dd84
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1237,6 +1237,43 @@ macro_rules! iterator {
}
accum
}

#[inline]
#[rustc_inherit_overflow_checks]
fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
Self: Sized,
P: FnMut(Self::Item) -> bool,
{
// The addition might panic on overflow
let n = self.len();
self.try_fold(0, move |i, x| {
if predicate(x) { Err(i) }
else { Ok(i + 1) }
}).err()
.map(|i| {
unsafe { assume(i < n) };
i
})
}

#[inline]
fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
P: FnMut(Self::Item) -> bool,
Self: Sized + ExactSizeIterator + DoubleEndedIterator
{
// No need for an overflow check here, because `ExactSizeIterator`
// implies that the number of elements fits into a `usize`.
let n = self.len();
self.try_rfold(n, move |i, x| {
let i = i - 1;
if predicate(x) { Err(i) }
else { Ok(i) }
}).err()
.map(|i| {
unsafe { assume(i < n) };
i
})
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
19 changes: 19 additions & 0 deletions src/libcore/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,25 @@

use core::result::Result::{Ok, Err};


#[test]
fn test_position() {
let b = [1, 2, 3, 5, 5];
assert!(b.iter().position(|&v| v == 9) == None);
assert!(b.iter().position(|&v| v == 5) == Some(3));
assert!(b.iter().position(|&v| v == 3) == Some(2));
assert!(b.iter().position(|&v| v == 0) == None);
}

#[test]
fn test_rposition() {
let b = [1, 2, 3, 5, 5];
assert!(b.iter().rposition(|&v| v == 9) == None);
assert!(b.iter().rposition(|&v| v == 5) == Some(4));
assert!(b.iter().rposition(|&v| v == 3) == Some(2));
assert!(b.iter().rposition(|&v| v == 0) == None);
}

#[test]
fn test_binary_search() {
let b: [i32; 0] = [];
Expand Down

0 comments on commit 175dd84

Please sign in to comment.