Skip to content

Commit

Permalink
Hint slice.{r}position is within slice bounds
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurprs committed Oct 29, 2017
1 parent 690ff04 commit c8d3814
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1199,8 +1199,10 @@ macro_rules! iterator {
fn position<F>(&mut self, mut predicate: F) -> Option<usize>
where F: FnMut(Self::Item) -> bool,
{
let len = self.len();
let mut index = 0;
self.search_while(None, move |elt| {
unsafe { assume(index < len); }
if predicate(elt) {
SearchWhile::Done(Some(index))
} else {
Expand All @@ -1213,9 +1215,11 @@ macro_rules! iterator {
fn rposition<F>(&mut self, mut predicate: F) -> Option<usize>
where F: FnMut(Self::Item) -> bool,
{
let len = self.len();
let mut index = self.len();
self.rsearch_while(None, move |elt| {
index -= 1;
unsafe { assume(index < len); }
if predicate(elt) {
SearchWhile::Done(Some(index))
} else {
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 @@ -13,6 +13,25 @@ use core::slice::heapsort;
use core::result::Result::{Ok, Err};
use rand::{Rng, XorShiftRng};


#[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 = [1, 2, 4, 6, 8, 9];
Expand Down

0 comments on commit c8d3814

Please sign in to comment.