]> git.lizzy.rs Git - rust.git/commitdiff
Optimise Chars::last()
authorOliver Middleton <olliemail27@gmail.com>
Sat, 19 Nov 2016 18:43:41 +0000 (18:43 +0000)
committerOliver Middleton <olliemail27@gmail.com>
Sat, 19 Nov 2016 18:43:41 +0000 (18:43 +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 cc56bbf4890aa46de435ab3048d1952aeaaa7e18..a13e1fb33d159ca6d4226fba443a26c4e520d2df 100644 (file)
@@ -814,6 +814,14 @@ fn test_iterator_clone() {
     assert!(it.clone().zip(it).all(|(x,y)| x == y));
 }
 
+#[test]
+fn test_iterator_last() {
+    let s = "ศไทย中华Việt Nam";
+    let mut it = s.chars();
+    it.next();
+    assert_eq!(it.last(), Some('m'));
+}
+
 #[test]
 fn test_bytesator() {
     let s = "ศไทย中华Việt Nam";
index 196750254af30eacadeb20f8594a0208dc319f92..1dfd00e11aa967e83400807f896741d9a281a9be 100644 (file)
@@ -432,6 +432,12 @@ fn size_hint(&self) -> (usize, Option<usize>) {
         // `isize::MAX` (that's well below `usize::MAX`).
         ((len + 3) / 4, Some(len))
     }
+
+    #[inline]
+    fn last(mut self) -> Option<char> {
+        // No need to go through the entire string.
+        self.next_back()
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]