Skip to content

Commit 2c5a5cd

Browse files
committed
Test and benchmark Chars::advance_by for counting chars
1 parent 60acbd3 commit 2c5a5cd

File tree

2 files changed

+38
-9
lines changed

2 files changed

+38
-9
lines changed

library/alloc/tests/str.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -2357,10 +2357,26 @@ fn utf8_char_counts() {
23572357

23582358
assert!(!target.starts_with(" ") && !target.ends_with(" "));
23592359
let expected_count = tmpl_char_count * repeat;
2360+
23602361
assert_eq!(
23612362
expected_count,
23622363
target.chars().count(),
2363-
"wrong count for `{:?}.repeat({})` (padding: `{:?}`)",
2364+
"wrong count for `{:?}.repeat({}).count()` (padding: `{:?}`)",
2365+
tmpl_str,
2366+
repeat,
2367+
(pad_start.len(), pad_end.len()),
2368+
);
2369+
2370+
// `.advance_by(n)` can also be used to count chars.
2371+
let mut iter = target.chars();
2372+
let remaining = match iter.advance_by(usize::MAX) {
2373+
Ok(()) => 0,
2374+
Err(remaining) => remaining.get(),
2375+
};
2376+
assert_eq!(
2377+
expected_count,
2378+
usize::MAX - remaining,
2379+
"wrong count for `{:?}.repeat({}).advance_by(usize::MAX)` (padding: `{:?}`)",
23642380
tmpl_str,
23652381
repeat,
23662382
(pad_start.len(), pad_end.len()),

library/coretests/benches/str/char_count.rs

+21-8
Original file line numberDiff line numberDiff line change
@@ -48,27 +48,40 @@ macro_rules! define_benches {
4848
}
4949

5050
define_benches! {
51-
fn case00_libcore(s: &str) {
52-
libcore(s)
51+
fn case00_chars_count(s: &str) {
52+
chars_count(s)
5353
}
5454

55-
fn case01_filter_count_cont_bytes(s: &str) {
55+
fn case01_chars_advance_by(s: &str) {
56+
chars_advance_by(s)
57+
}
58+
59+
fn case02_filter_count_cont_bytes(s: &str) {
5660
filter_count_cont_bytes(s)
5761
}
5862

59-
fn case02_iter_increment(s: &str) {
60-
iterator_increment(s)
63+
fn case03_iter_chars_increment(s: &str) {
64+
iter_chars_increment(s)
6165
}
6266

63-
fn case03_manual_char_len(s: &str) {
67+
fn case04_manual_char_len(s: &str) {
6468
manual_char_len(s)
6569
}
6670
}
6771

68-
fn libcore(s: &str) -> usize {
72+
fn chars_count(s: &str) -> usize {
6973
s.chars().count()
7074
}
7175

76+
fn chars_advance_by(s: &str) -> usize {
77+
let mut iter = s.chars();
78+
let remaining = match iter.advance_by(usize::MAX) {
79+
Ok(()) => 0,
80+
Err(remaining) => remaining.get(),
81+
};
82+
usize::MAX - remaining
83+
}
84+
7285
#[inline]
7386
fn utf8_is_cont_byte(byte: u8) -> bool {
7487
(byte as i8) < -64
@@ -78,7 +91,7 @@ fn filter_count_cont_bytes(s: &str) -> usize {
7891
s.as_bytes().iter().filter(|&&byte| !utf8_is_cont_byte(byte)).count()
7992
}
8093

81-
fn iterator_increment(s: &str) -> usize {
94+
fn iter_chars_increment(s: &str) -> usize {
8295
let mut c = 0;
8396
for _ in s.chars() {
8497
c += 1;

0 commit comments

Comments
 (0)