Skip to content

Commit b0354fe

Browse files
Rollup merge of #37882 - ollie27:chars_last, r=bluss
Optimise Chars::last() The default implementation of last() goes through the entire iterator but that's not needed here.
2 parents be2544c + 9e86e18 commit b0354fe

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/libcollectionstest/str.rs

+16
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,14 @@ fn test_iterator_clone() {
814814
assert!(it.clone().zip(it).all(|(x,y)| x == y));
815815
}
816816

817+
#[test]
818+
fn test_iterator_last() {
819+
let s = "ศไทย中华Việt Nam";
820+
let mut it = s.chars();
821+
it.next();
822+
assert_eq!(it.last(), Some('m'));
823+
}
824+
817825
#[test]
818826
fn test_bytesator() {
819827
let s = "ศไทย中华Việt Nam";
@@ -911,6 +919,14 @@ fn test_char_indices_revator() {
911919
assert_eq!(pos, p.len());
912920
}
913921

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+
914930
#[test]
915931
fn test_splitn_char_iterator() {
916932
let data = "\nMäry häd ä little lämb\nLittle lämb\n";

src/libcore/str/mod.rs

+12
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,12 @@ impl<'a> Iterator for Chars<'a> {
432432
// `isize::MAX` (that's well below `usize::MAX`).
433433
((len + 3) / 4, Some(len))
434434
}
435+
436+
#[inline]
437+
fn last(mut self) -> Option<char> {
438+
// No need to go through the entire string.
439+
self.next_back()
440+
}
435441
}
436442

437443
#[stable(feature = "rust1", since = "1.0.0")]
@@ -505,6 +511,12 @@ impl<'a> Iterator for CharIndices<'a> {
505511
fn size_hint(&self) -> (usize, Option<usize>) {
506512
self.iter.size_hint()
507513
}
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+
}
508520
}
509521

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

0 commit comments

Comments
 (0)