Skip to content

Commit

Permalink
Test and benchmark Chars::advance_by for counting chars
Browse files Browse the repository at this point in the history
  • Loading branch information
thaliaarchi committed Mar 9, 2025
1 parent 60acbd3 commit 2c5a5cd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
18 changes: 17 additions & 1 deletion library/alloc/tests/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2357,10 +2357,26 @@ fn utf8_char_counts() {

assert!(!target.starts_with(" ") && !target.ends_with(" "));
let expected_count = tmpl_char_count * repeat;

assert_eq!(
expected_count,
target.chars().count(),
"wrong count for `{:?}.repeat({})` (padding: `{:?}`)",
"wrong count for `{:?}.repeat({}).count()` (padding: `{:?}`)",
tmpl_str,
repeat,
(pad_start.len(), pad_end.len()),
);

// `.advance_by(n)` can also be used to count chars.
let mut iter = target.chars();
let remaining = match iter.advance_by(usize::MAX) {
Ok(()) => 0,
Err(remaining) => remaining.get(),
};
assert_eq!(
expected_count,
usize::MAX - remaining,
"wrong count for `{:?}.repeat({}).advance_by(usize::MAX)` (padding: `{:?}`)",
tmpl_str,
repeat,
(pad_start.len(), pad_end.len()),
Expand Down
29 changes: 21 additions & 8 deletions library/coretests/benches/str/char_count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,27 +48,40 @@ macro_rules! define_benches {
}

define_benches! {
fn case00_libcore(s: &str) {
libcore(s)
fn case00_chars_count(s: &str) {
chars_count(s)
}

fn case01_filter_count_cont_bytes(s: &str) {
fn case01_chars_advance_by(s: &str) {
chars_advance_by(s)
}

fn case02_filter_count_cont_bytes(s: &str) {
filter_count_cont_bytes(s)
}

fn case02_iter_increment(s: &str) {
iterator_increment(s)
fn case03_iter_chars_increment(s: &str) {
iter_chars_increment(s)
}

fn case03_manual_char_len(s: &str) {
fn case04_manual_char_len(s: &str) {
manual_char_len(s)
}
}

fn libcore(s: &str) -> usize {
fn chars_count(s: &str) -> usize {
s.chars().count()
}

fn chars_advance_by(s: &str) -> usize {
let mut iter = s.chars();
let remaining = match iter.advance_by(usize::MAX) {
Ok(()) => 0,
Err(remaining) => remaining.get(),
};
usize::MAX - remaining
}

#[inline]
fn utf8_is_cont_byte(byte: u8) -> bool {
(byte as i8) < -64
Expand All @@ -78,7 +91,7 @@ fn filter_count_cont_bytes(s: &str) -> usize {
s.as_bytes().iter().filter(|&&byte| !utf8_is_cont_byte(byte)).count()
}

fn iterator_increment(s: &str) -> usize {
fn iter_chars_increment(s: &str) -> usize {
let mut c = 0;
for _ in s.chars() {
c += 1;
Expand Down

0 comments on commit 2c5a5cd

Please sign in to comment.