Optimise Chars::last()

The default implementation of last() goes through the entire iterator
but that's not needed here.
This commit is contained in:
Oliver Middleton 2016-11-19 18:43:41 +00:00
parent 5bd1e7f59f
commit de2f61740d
2 changed files with 14 additions and 0 deletions

View 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";

View File

@ -432,6 +432,12 @@ impl<'a> Iterator for Chars<'a> {
// `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")]