mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-26 16:54:01 +00:00
str: Improve .chars().count()
Use a simpler loop to count the `char` of a string: count the number of non-continuation bytes. Use `count += <conditional>` which the compiler understands well and can apply loop optimizations to.
This commit is contained in:
parent
b1da18fe9b
commit
5a3aa2f73c
@ -767,6 +767,7 @@ fn test_iterator() {
|
||||
pos += 1;
|
||||
}
|
||||
assert_eq!(pos, v.len());
|
||||
assert_eq!(s.chars().count(), v.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -424,6 +424,17 @@ impl<'a> Iterator for Chars<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count(self) -> usize {
|
||||
// length in `char` is equal to the number of non-continuation bytes
|
||||
let bytes_len = self.iter.len();
|
||||
let mut cont_bytes = 0;
|
||||
for &byte in self.iter {
|
||||
cont_bytes += utf8_is_cont_byte(byte) as usize;
|
||||
}
|
||||
bytes_len - cont_bytes
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.iter.len();
|
||||
@ -501,6 +512,11 @@ impl<'a> Iterator for CharIndices<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count(self) -> usize {
|
||||
self.iter.count()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.iter.size_hint()
|
||||
|
Loading…
Reference in New Issue
Block a user