From: Oliver Middleton Date: Sat, 19 Nov 2016 18:43:41 +0000 (+0000) Subject: Optimise Chars::last() X-Git-Url: https://git.lizzy.rs/?a=commitdiff_plain;h=de2f61740d4622f3938cb6ddb01854c80c1e9082;p=rust.git Optimise Chars::last() The default implementation of last() goes through the entire iterator but that's not needed here. --- diff --git a/src/libcollectionstest/str.rs b/src/libcollectionstest/str.rs index cc56bbf4890..a13e1fb33d1 100644 --- a/src/libcollectionstest/str.rs +++ b/src/libcollectionstest/str.rs @@ -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"; diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 196750254af..1dfd00e11aa 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -432,6 +432,12 @@ fn size_hint(&self) -> (usize, Option) { // `isize::MAX` (that's well below `usize::MAX`). ((len + 3) / 4, Some(len)) } + + #[inline] + fn last(mut self) -> Option { + // No need to go through the entire string. + self.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")]