about summary refs log tree commit diff
diff options
context:
space:
mode:
authorUlrik Sverdrup <bluss@users.noreply.github.com>2017-04-08 03:43:18 +0200
committerUlrik Sverdrup <bluss@users.noreply.github.com>2017-04-08 03:45:48 +0200
commit5d2f270395814564f674141a99ace77ea9a03352 (patch)
tree77f924c7b1488d285e000c2dafb298216310f4ea
parent53f4bc311b5ff11a16185dd40dc116cf6b8cc162 (diff)
downloadrust-5d2f270395814564f674141a99ace77ea9a03352.tar.gz
rust-5d2f270395814564f674141a99ace77ea9a03352.zip
slice: Implement .rfind() for slice iterators Iter and IterMut
Just like the forward case find, implement rfind explicitly
-rw-r--r--src/libcore/slice/mod.rs13
-rw-r--r--src/libcore/tests/lib.rs1
-rw-r--r--src/libcore/tests/slice.rs13
3 files changed, 27 insertions, 0 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs
index 6d598677c9b..87dfdfe57b6 100644
--- a/src/libcore/slice/mod.rs
+++ b/src/libcore/slice/mod.rs
@@ -1190,6 +1190,19 @@ macro_rules! iterator {
                     }
                 }
             }
+
+            fn rfind<F>(&mut self, mut predicate: F) -> Option<Self::Item>
+                where F: FnMut(&Self::Item) -> bool,
+            {
+                self.rsearch_while(None, move |elt| {
+                    if predicate(&elt) {
+                        SearchWhile::Done(Some(elt))
+                    } else {
+                        SearchWhile::Continue
+                    }
+                })
+            }
+
         }
 
         // search_while is a generalization of the internal iteration methods.
diff --git a/src/libcore/tests/lib.rs b/src/libcore/tests/lib.rs
index d92c378160d..528ab3bc845 100644
--- a/src/libcore/tests/lib.rs
+++ b/src/libcore/tests/lib.rs
@@ -20,6 +20,7 @@
 #![feature(fixed_size_array)]
 #![feature(flt2dec)]
 #![feature(fmt_internals)]
+#![feature(iter_rfind)]
 #![feature(libc)]
 #![feature(nonzero)]
 #![feature(rand)]
diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs
index ec38345030f..15047204e50 100644
--- a/src/libcore/tests/slice.rs
+++ b/src/libcore/tests/slice.rs
@@ -226,6 +226,19 @@ fn get_unchecked_mut_range() {
 }
 
 #[test]
+fn test_find_rfind() {
+    let v = [0, 1, 2, 3, 4, 5];
+    let mut iter = v.iter();
+    let mut i = v.len();
+    while let Some(&elt) = iter.rfind(|_| true) {
+        i -= 1;
+        assert_eq!(elt, v[i]);
+    }
+    assert_eq!(i, 0);
+    assert_eq!(v.iter().rfind(|&&x| x <= 3), Some(&3));
+}
+
+#[test]
 fn sort_unstable() {
     let mut v = [0; 600];
     let mut tmp = [0; 600];