Skip to main content

core/str/
count.rs

1//! Code for efficiently counting the number of `char`s in a UTF-8 encoded
2//! string.
3//!
4//! Broadly, UTF-8 encodes `char`s as a "leading" byte which begins the `char`,
5//! followed by some number (possibly 0) of continuation bytes.
6//!
7//! The leading byte can have a number of bit-patterns (with the specific
8//! pattern indicating how many continuation bytes follow), but the continuation
9//! bytes are always in the format `0b10XX_XXXX` (where the `X`s can take any
10//! value). That is, the most significant bit is set, and the second most
11//! significant bit is unset.
12//!
13//! To count the number of characters, we can just count the number of bytes in
14//! the string which are not continuation bytes, which can be done many bytes at
15//! a time fairly easily.
16//!
17//! Note: Because the term "leading byte" can sometimes be ambiguous (for
18//! example, it could also refer to the first byte of a slice), we'll often use
19//! the term "non-continuation byte" to refer to these bytes in the code.
20
21use core::intrinsics::unlikely;
22
23const USIZE_SIZE: usize = size_of::<usize>();
24const UNROLL_INNER: usize = 4;
25
26#[inline]
27#[ferrocene::prevalidated]
28pub(super) fn count_chars(s: &str) -> usize {
29    if cfg!(feature = "optimize_for_size") || s.len() < USIZE_SIZE * UNROLL_INNER {
30        // Avoid entering the optimized implementation for strings where the
31        // difference is not likely to matter, or where it might even be slower.
32        // That said, a ton of thought was not spent on the particular threshold
33        // here, beyond "this value seems to make sense".
34        char_count_general_case(s.as_bytes())
35    } else {
36        do_count_chars(s)
37    }
38}
39
40#[ferrocene::prevalidated]
41fn do_count_chars(s: &str) -> usize {
42    // For correctness, `CHUNK_SIZE` must be:
43    //
44    // - Less than or equal to 255, otherwise we'll overflow bytes in `counts`.
45    // - A multiple of `UNROLL_INNER`, otherwise our `break` inside the
46    //   `body.chunks(CHUNK_SIZE)` loop is incorrect.
47    //
48    // For performance, `CHUNK_SIZE` should be:
49    // - Relatively cheap to `/` against (so some simple sum of powers of two).
50    // - Large enough to avoid paying for the cost of the `sum_bytes_in_usize`
51    //   too often.
52    const CHUNK_SIZE: usize = 192;
53
54    // Check the properties of `CHUNK_SIZE` and `UNROLL_INNER` that are required
55    // for correctness.
56    const _: () = assert!(CHUNK_SIZE < 256);
57    const _: () = assert!(CHUNK_SIZE.is_multiple_of(UNROLL_INNER));
58
59    // SAFETY: transmuting `[u8]` to `[usize]` is safe except for size
60    // differences which are handled by `align_to`.
61    let (head, body, tail) = unsafe { s.as_bytes().align_to::<usize>() };
62
63    // This should be quite rare, and basically exists to handle the degenerate
64    // cases where align_to fails (as well as miri under symbolic alignment
65    // mode).
66    //
67    // The `unlikely` helps discourage LLVM from inlining the body, which is
68    // nice, as we would rather not mark the `char_count_general_case` function
69    // as cold.
70    if unlikely(body.is_empty() || head.len() > USIZE_SIZE || tail.len() > USIZE_SIZE) {
71        return char_count_general_case(s.as_bytes());
72    }
73
74    let mut total = char_count_general_case(head) + char_count_general_case(tail);
75    // Split `body` into `CHUNK_SIZE` chunks to reduce the frequency with which
76    // we call `sum_bytes_in_usize`.
77    for chunk in body.chunks(CHUNK_SIZE) {
78        // We accumulate intermediate sums in `counts`, where each byte contains
79        // a subset of the sum of this chunk, like a `[u8; size_of::<usize>()]`.
80        let mut counts = 0;
81
82        let (unrolled_chunks, remainder) = chunk.as_chunks::<UNROLL_INNER>();
83        for unrolled in unrolled_chunks {
84            for &word in unrolled {
85                // Because `CHUNK_SIZE` is < 256, this addition can't cause the
86                // count in any of the bytes to overflow into a subsequent byte.
87                counts += contains_non_continuation_byte(word);
88            }
89        }
90
91        // Sum the values in `counts` (which, again, is conceptually a `[u8;
92        // size_of::<usize>()]`), and accumulate the result into `total`.
93        total += sum_bytes_in_usize(counts);
94
95        // If there's any data in `remainder`, then handle it. This will only
96        // happen for the last `chunk` in `body.chunks()` (because `CHUNK_SIZE`
97        // is divisible by `UNROLL_INNER`), so we explicitly break at the end
98        // (which seems to help LLVM out).
99        if !remainder.is_empty() {
100            // Accumulate all the data in the remainder.
101            let mut counts = 0;
102            for &word in remainder {
103                counts += contains_non_continuation_byte(word);
104            }
105            total += sum_bytes_in_usize(counts);
106            break;
107        }
108    }
109    total
110}
111
112// Checks each byte of `w` to see if it contains the first byte in a UTF-8
113// sequence. Bytes in `w` which are continuation bytes are left as `0x00` (e.g.
114// false), and bytes which are non-continuation bytes are left as `0x01` (e.g.
115// true)
116#[inline]
117#[ferrocene::prevalidated]
118fn contains_non_continuation_byte(w: usize) -> usize {
119    const LSB: usize = usize::repeat_u8(0x01);
120    ((!w >> 7) | (w >> 6)) & LSB
121}
122
123// Morally equivalent to `values.to_ne_bytes().into_iter().sum::<usize>()`, but
124// more efficient.
125#[inline]
126#[ferrocene::prevalidated]
127fn sum_bytes_in_usize(values: usize) -> usize {
128    const LSB_SHORTS: usize = usize::repeat_u16(0x0001);
129    const SKIP_BYTES: usize = usize::repeat_u16(0x00ff);
130
131    let pair_sum: usize = (values & SKIP_BYTES) + ((values >> 8) & SKIP_BYTES);
132    pair_sum.wrapping_mul(LSB_SHORTS) >> ((USIZE_SIZE - 2) * 8)
133}
134
135// This is the most direct implementation of the concept of "count the number of
136// bytes in the string which are not continuation bytes", and is used for the
137// head and tail of the input string (the first and last item in the tuple
138// returned by `slice::align_to`).
139#[ferrocene::prevalidated]
140fn char_count_general_case(s: &[u8]) -> usize {
141    s.iter().filter(|&&byte| !super::validations::utf8_is_cont_byte(byte)).count()
142}
143
144/// Ferrocene addition: Hidden module to test crate-internal functionality
145#[doc(hidden)]
146#[unstable(feature = "ferrocene_test", issue = "none")]
147pub(crate) mod ferrocene_test;