]> git.lizzy.rs Git - rust.git/commitdiff
Optimise CharIndices::last()
authorOliver Middleton <olliemail27@gmail.com>
Sun, 20 Nov 2016 00:37:48 +0000 (00:37 +0000)
committerOliver Middleton <olliemail27@gmail.com>
Sun, 20 Nov 2016 00:37:48 +0000 (00:37 +0000)
The default implementation of last() goes through the entire iterator
but that's not needed here.

src/libcollectionstest/str.rs
src/libcore/str/mod.rs

index a13e1fb33d159ca6d4226fba443a26c4e520d2df..ebbfbefc21b66709d532fa0d03d8ddf2b4e1571e 100644 (file)
@@ -919,6 +919,14 @@ fn test_char_indices_revator() {
     assert_eq!(pos, p.len());
 }
 
+#[test]
+fn test_char_indices_last() {
+    let s = "ศไทย中华Việt Nam";
+    let mut it = s.char_indices();
+    it.next();
+    assert_eq!(it.last(), Some((27, 'm')));
+}
+
 #[test]
 fn test_splitn_char_iterator() {
     let data = "\nMäry häd ä little lämb\nLittle lämb\n";
index 1dfd00e11aa967e83400807f896741d9a281a9be..1bd6188f4875a9bce726f13dd2f9c6fd5b4eefe7 100644 (file)
@@ -511,6 +511,12 @@ fn next(&mut self) -> Option<(usize, char)> {
     fn size_hint(&self) -> (usize, Option<usize>) {
         self.iter.size_hint()
     }
+
+    #[inline]
+    fn last(mut self) -> Option<(usize, char)> {
+        // No need to go through the entire string.
+        self.next_back()
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]