Skip to content

Commit 2df66a8

Browse files
committed
iterator: add a position adaptor
1 parent eb5ac84 commit 2df66a8

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/libstd/iterator.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,9 @@ pub trait IteratorUtil<A> {
311311

312312
/// Return the first element satisfying the specified predicate
313313
fn find(&mut self, predicate: &fn(&A) -> bool) -> Option<A>;
314+
315+
/// Return the index of the first element satisfying the specified predicate
316+
fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint>;
314317
}
315318

316319
/// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
@@ -451,6 +454,19 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
451454
}
452455
None
453456
}
457+
458+
/// Return the index of the first element satisfying the specified predicate
459+
#[inline]
460+
fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint> {
461+
let mut i = 0;
462+
for self.advance |x| {
463+
if predicate(x) {
464+
return Some(i);
465+
}
466+
i += 1;
467+
}
468+
None
469+
}
454470
}
455471

456472
/// A trait for iterators over elements which can be added together
@@ -1075,4 +1091,12 @@ mod tests {
10751091
assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
10761092
assert!(v.iter().find(|x| *x % 12 == 0).is_none());
10771093
}
1094+
1095+
#[test]
1096+
fn test_position() {
1097+
let v = &[1, 3, 9, 27, 103, 14, 11];
1098+
assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
1099+
assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
1100+
assert!(v.iter().position(|x| *x % 12 == 0).is_none());
1101+
}
10781102
}

0 commit comments

Comments
 (0)