Skip to content

Commit

Permalink
Optimise Chars::last()
Browse files Browse the repository at this point in the history
The default implementation of last() goes through the entire iterator
but that's not needed here.
  • Loading branch information
ollie27 committed Nov 19, 2016
1 parent 5bd1e7f commit de2f617
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
8 changes: 8 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
6 changes: 6 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

0 comments on commit de2f617

Please sign in to comment.