Optimise CharIndices::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-20 00:37:48 +00:00
parent de2f61740d
commit 9e86e18092
2 changed files with 14 additions and 0 deletions

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

View 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")]