about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorDaniel Micay <danielmicay@gmail.com>2013-06-15 17:56:26 -0400
committerDaniel Micay <danielmicay@gmail.com>2013-06-15 17:56:54 -0400
commit2df66a84cd64211c22e58c48df07ce63bf5469a3 (patch)
tree3ce3ea54a4d8c33aa7125cae52df62907e454f1f /src/libstd
parenteb5ac84c8e14184b9b76fe088b5f5120e887ee35 (diff)
downloadrust-2df66a84cd64211c22e58c48df07ce63bf5469a3.tar.gz
rust-2df66a84cd64211c22e58c48df07ce63bf5469a3.zip
iterator: add a `position` adaptor
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/iterator.rs24
1 files changed, 24 insertions, 0 deletions
diff --git a/src/libstd/iterator.rs b/src/libstd/iterator.rs
index 7aa273f7cd8..a8969f1da6e 100644
--- a/src/libstd/iterator.rs
+++ b/src/libstd/iterator.rs
@@ -311,6 +311,9 @@ pub trait IteratorUtil<A> {
 
     /// Return the first element satisfying the specified predicate
     fn find(&mut self, predicate: &fn(&A) -> bool) -> Option<A>;
+
+    /// Return the index of the first element satisfying the specified predicate
+    fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint>;
 }
 
 /// 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 {
         }
         None
     }
+
+    /// Return the index of the first element satisfying the specified predicate
+    #[inline]
+    fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint> {
+        let mut i = 0;
+        for self.advance |x| {
+            if predicate(x) {
+                return Some(i);
+            }
+            i += 1;
+        }
+        None
+    }
 }
 
 /// A trait for iterators over elements which can be added together
@@ -1075,4 +1091,12 @@ mod tests {
         assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
         assert!(v.iter().find(|x| *x % 12 == 0).is_none());
     }
+
+    #[test]
+    fn test_position() {
+        let v = &[1, 3, 9, 27, 103, 14, 11];
+        assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
+        assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
+        assert!(v.iter().position(|x| *x % 12 == 0).is_none());
+    }
 }