Skip to content

Commit 9e86e18

Browse files
committed
Optimise CharIndices::last()
The default implementation of last() goes through the entire iterator but that's not needed here.
1 parent de2f617 commit 9e86e18

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

src/libcollectionstest/str.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,14 @@ fn test_char_indices_revator() {
919919
assert_eq!(pos, p.len());
920920
}
921921

922+
#[test]
923+
fn test_char_indices_last() {
924+
let s = "ศไทย中华Việt Nam";
925+
let mut it = s.char_indices();
926+
it.next();
927+
assert_eq!(it.last(), Some((27, 'm')));
928+
}
929+
922930
#[test]
923931
fn test_splitn_char_iterator() {
924932
let data = "\nMäry häd ä little lämb\nLittle lämb\n";

src/libcore/str/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,12 @@ impl<'a> Iterator for CharIndices<'a> {
511511
fn size_hint(&self) -> (usize, Option<usize>) {
512512
self.iter.size_hint()
513513
}
514+
515+
#[inline]
516+
fn last(mut self) -> Option<(usize, char)> {
517+
// No need to go through the entire string.
518+
self.next_back()
519+
}
514520
}
515521

516522
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)