Skip to content

Commit

Permalink
Rollup merge of #37882 - ollie27:chars_last, r=bluss
Browse files Browse the repository at this point in the history
Optimise Chars::last()

The default implementation of last() goes through the entire iterator
but that's not needed here.
  • Loading branch information
GuillaumeGomez committed Nov 20, 2016
2 parents be2544c + 9e86e18 commit b0354fe
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/libcollectionstest/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -911,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";
Expand Down
12 changes: 12 additions & 0 deletions src/libcore/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -505,6 +511,12 @@ impl<'a> Iterator for CharIndices<'a> {
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")]
Expand Down

0 comments on commit b0354fe

Please sign in to comment.