Skip to content

Commit ebbccaf

Browse files
committed
Respond to review feedback, and improve implementation somewhat
1 parent 002aaf2 commit ebbccaf

File tree

3 files changed

+59
-28
lines changed

3 files changed

+59
-28
lines changed

library/core/benches/str/char_count.rs

+12-6
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,25 @@ use test::{black_box, Bencher};
33

44
macro_rules! define_benches {
55
($( fn $name: ident($arg: ident: &str) $body: block )+) => {
6+
define_benches!(mod en_tiny, en::TINY, $($name $arg $body)+);
67
define_benches!(mod en_small, en::SMALL, $($name $arg $body)+);
78
define_benches!(mod en_medium, en::MEDIUM, $($name $arg $body)+);
89
define_benches!(mod en_large, en::LARGE, $($name $arg $body)+);
910
define_benches!(mod en_huge, en::HUGE, $($name $arg $body)+);
1011

12+
define_benches!(mod zh_tiny, zh::TINY, $($name $arg $body)+);
1113
define_benches!(mod zh_small, zh::SMALL, $($name $arg $body)+);
1214
define_benches!(mod zh_medium, zh::MEDIUM, $($name $arg $body)+);
1315
define_benches!(mod zh_large, zh::LARGE, $($name $arg $body)+);
1416
define_benches!(mod zh_huge, zh::HUGE, $($name $arg $body)+);
1517

18+
define_benches!(mod ru_tiny, ru::TINY, $($name $arg $body)+);
1619
define_benches!(mod ru_small, ru::SMALL, $($name $arg $body)+);
1720
define_benches!(mod ru_medium, ru::MEDIUM, $($name $arg $body)+);
1821
define_benches!(mod ru_large, ru::LARGE, $($name $arg $body)+);
1922
define_benches!(mod ru_huge, ru::HUGE, $($name $arg $body)+);
2023

24+
define_benches!(mod emoji_tiny, emoji::TINY, $($name $arg $body)+);
2125
define_benches!(mod emoji_small, emoji::SMALL, $($name $arg $body)+);
2226
define_benches!(mod emoji_medium, emoji::MEDIUM, $($name $arg $body)+);
2327
define_benches!(mod emoji_large, emoji::LARGE, $($name $arg $body)+);
@@ -43,12 +47,12 @@ macro_rules! define_benches {
4347
}
4448

4549
define_benches! {
46-
fn case00_cur_libcore(s: &str) {
47-
cur_libcore(s)
50+
fn case00_libcore(s: &str) {
51+
libcore(s)
4852
}
4953

50-
fn case01_old_libcore(s: &str) {
51-
old_libcore(s)
54+
fn case01_filter_count_cont_bytes(s: &str) {
55+
filter_count_cont_bytes(s)
5256
}
5357

5458
fn case02_iter_increment(s: &str) {
@@ -60,14 +64,16 @@ define_benches! {
6064
}
6165
}
6266

63-
fn cur_libcore(s: &str) -> usize {
67+
fn libcore(s: &str) -> usize {
6468
s.chars().count()
6569
}
70+
6671
#[inline]
6772
fn utf8_is_cont_byte(byte: u8) -> bool {
6873
(byte as i8) < -64
6974
}
70-
fn old_libcore(s: &str) -> usize {
75+
76+
fn filter_count_cont_bytes(s: &str) -> usize {
7177
s.as_bytes().iter().filter(|&&byte| !utf8_is_cont_byte(byte)).count()
7278
}
7379

library/core/benches/str/corpora.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
//! Exposes a number of modules with different kinds of strings.
22
//!
3-
//! Each module contains `&str` constants named `SMALL`, `MEDIUM`, `LARGE`, and
4-
//! `HUGE`.
3+
//! Each module contains `&str` constants named `TINY`, `SMALL`, `MEDIUM`,
4+
//! `LARGE`, and `HUGE`.
55
//!
6+
//! - The `TINY` string is generally around 8 bytes.
67
//! - The `SMALL` string is generally around 30-40 bytes.
78
//! - The `MEDIUM` string is generally around 600-700 bytes.
89
//! - The `LARGE` string is the `MEDIUM` string repeated 8x, and is around 5kb.
@@ -27,6 +28,7 @@ macro_rules! define_consts {
2728
}
2829

2930
pub mod en {
31+
pub const TINY: &str = "Mary had";
3032
pub const SMALL: &str = "Mary had a little lamb, Little lamb";
3133
define_consts! {
3234
"Rust is blazingly fast and memory-efficient: with no runtime or garbage
@@ -42,6 +44,7 @@ pub mod en {
4244
}
4345

4446
pub mod zh {
47+
pub const TINY: &str = "速度惊";
4548
pub const SMALL: &str = "速度惊人且内存利用率极高";
4649
define_consts! {
4750
"Rust 速度惊人且内存利用率极高。由于\
@@ -59,6 +62,7 @@ pub mod zh {
5962
}
6063

6164
pub mod ru {
65+
pub const TINY: &str = "Сотни";
6266
pub const SMALL: &str = "Сотни компаний по";
6367
define_consts! {
6468
"Сотни компаний по всему миру используют Rust в реальных\
@@ -72,6 +76,7 @@ pub mod ru {
7276
}
7377

7478
pub mod emoji {
79+
pub const TINY: &str = "😀😃";
7580
pub const SMALL: &str = "😀😃😄😁😆😅🤣😂🙂🙃😉😊😇🥰😍🤩😘";
7681
define_consts! {
7782
"😀😃😄😁😆😅🤣😂🙂🙃😉😊😇🥰😍🤩😘😗☺😚😙🥲😋😛😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐😑😶😶‍🌫️😏😒\

library/core/src/str/count.rs

+40-20
Original file line numberDiff line numberDiff line change
@@ -17,39 +17,66 @@
1717
//! Note: Because the term "leading byte" can sometimes be ambiguous (for
1818
//! example, it could also refer to the first byte of a slice), we'll often use
1919
//! the term "non-continuation byte" to refer to these bytes in the code.
20+
use core::intrinsics::unlikely;
2021

22+
const USIZE_SIZE: usize = core::mem::size_of::<usize>();
23+
const UNROLL_INNER: usize = 4;
24+
25+
#[inline]
2126
pub(super) fn count_chars(s: &str) -> usize {
27+
if s.len() < USIZE_SIZE * UNROLL_INNER {
28+
// Avoid entering the optimized implementation for strings where the
29+
// difference is not likely to matter, or where it might even be slower.
30+
// That said, a ton of thought was not spent on the particular threshold
31+
// here, beyond "this value seems to make sense".
32+
char_count_general_case(s.as_bytes())
33+
} else {
34+
do_count_chars(s)
35+
}
36+
}
37+
38+
fn do_count_chars(s: &str) -> usize {
2239
// For correctness, `CHUNK_SIZE` must be:
40+
//
2341
// - Less than or equal to 255, otherwise we'll overflow bytes in `counts`.
2442
// - A multiple of `UNROLL_INNER`, otherwise our `break` inside the
2543
// `body.chunks(CHUNK_SIZE)` loop.
2644
//
2745
// For performance, `CHUNK_SIZE` should be:
28-
// - Relatively cheap to `%` against.
46+
// - Relatively cheap to `/` against (so some simple sum of powers of two).
2947
// - Large enough to avoid paying for the cost of the `sum_bytes_in_usize`
3048
// too often.
3149
const CHUNK_SIZE: usize = 192;
32-
const UNROLL_INNER: usize = 4;
3350

34-
// Check the properties of `CHUNK_SIZE` / `UNROLL_INNER` that are required
51+
// Check the properties of `CHUNK_SIZE` and `UNROLL_INNER` that are required
3552
// for correctness.
36-
const _: [(); 1] = [(); (CHUNK_SIZE < 256 && (CHUNK_SIZE % UNROLL_INNER) == 0) as usize];
53+
const _: () = assert!(CHUNK_SIZE < 256);
54+
const _: () = assert!(CHUNK_SIZE % UNROLL_INNER == 0);
55+
3756
// SAFETY: transmuting `[u8]` to `[usize]` is safe except for size
3857
// differences which are handled by `align_to`.
3958
let (head, body, tail) = unsafe { s.as_bytes().align_to::<usize>() };
4059

60+
// This should be quite rare, and basically exists to handle the degenerate
61+
// cases where align_to fails (as well as miri under symbolic alignment
62+
// mode).
63+
//
64+
// The `unlikely` helps discourage LLVM from inlining the body, which is
65+
// nice, as we would rather not mark the `char_count_general_case` function
66+
// as cold.
67+
if unlikely(body.is_empty() || head.len() > USIZE_SIZE || tail.len() > USIZE_SIZE) {
68+
return char_count_general_case(s.as_bytes());
69+
}
70+
4171
let mut total = char_count_general_case(head) + char_count_general_case(tail);
4272
// Split `body` into `CHUNK_SIZE` chunks to reduce the frequency with which
4373
// we call `sum_bytes_in_usize`.
4474
for chunk in body.chunks(CHUNK_SIZE) {
4575
// We accumulate intermediate sums in `counts`, where each byte contains
4676
// a subset of the sum of this chunk, like a `[u8; size_of::<usize>()]`.
4777
let mut counts = 0;
48-
let unrolled_chunks = chunk.array_chunks::<UNROLL_INNER>();
49-
// If there's a remainder (know can only happen for the last item in
50-
// `chunks`, because `CHUNK_SIZE % UNROLL == 0`), then we need to
51-
// account for that (although we don't use it to later).
52-
let remainder = unrolled_chunks.remainder();
78+
79+
let (unrolled_chunks, remainder) = chunk.as_chunks::<UNROLL_INNER>();
5380
for unrolled in unrolled_chunks {
5481
for &word in unrolled {
5582
// Because `CHUNK_SIZE` is < 256, this addition can't cause the
@@ -85,8 +112,8 @@ pub(super) fn count_chars(s: &str) -> usize {
85112
// true)
86113
#[inline]
87114
fn contains_non_continuation_byte(w: usize) -> usize {
88-
let lsb = 0x0101_0101_0101_0101u64 as usize;
89-
((!w >> 7) | (w >> 6)) & lsb
115+
const LSB: usize = 0x0101_0101_0101_0101u64 as usize;
116+
((!w >> 7) | (w >> 6)) & LSB
90117
}
91118

92119
// Morally equivalent to `values.to_ne_bytes().into_iter().sum::<usize>()`, but
@@ -97,20 +124,13 @@ fn sum_bytes_in_usize(values: usize) -> usize {
97124
const SKIP_BYTES: usize = 0x00ff_00ff_00ff_00ff_u64 as usize;
98125

99126
let pair_sum: usize = (values & SKIP_BYTES) + ((values >> 8) & SKIP_BYTES);
100-
pair_sum.wrapping_mul(LSB_SHORTS) >> ((core::mem::size_of::<usize>() - 2) * 8)
127+
pair_sum.wrapping_mul(LSB_SHORTS) >> ((USIZE_SIZE - 2) * 8)
101128
}
102129

103130
// This is the most direct implementation of the concept of "count the number of
104131
// bytes in the string which are not continuation bytes", and is used for the
105132
// head and tail of the input string (the first and last item in the tuple
106133
// returned by `slice::align_to`).
107134
fn char_count_general_case(s: &[u8]) -> usize {
108-
const CONT_MASK_U8: u8 = 0b0011_1111;
109-
const TAG_CONT_U8: u8 = 0b1000_0000;
110-
let mut leads = 0;
111-
for &byte in s {
112-
let is_lead = (byte & !CONT_MASK_U8) != TAG_CONT_U8;
113-
leads += is_lead as usize;
114-
}
115-
leads
135+
s.iter().filter(|&&byte| !super::validations::utf8_is_cont_byte(byte)).count()
116136
}

0 commit comments

Comments
 (0)