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:
Ulrik Sverdrup 2016-11-19 23:18:43 +01:00
parent b1da18fe9b
commit 5a3aa2f73c
2 changed files with 17 additions and 0 deletions

View File

@ -767,6 +767,7 @@ fn test_iterator() {
pos += 1;
}
assert_eq!(pos, v.len());
assert_eq!(s.chars().count(), v.len());
}
#[test]

View File

@ -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()