Skip to content

Commit 1979fa8

Browse files
authored
Rollup merge of #74066 - thomcc:optimize-is-ascii, r=nagisa
Optimize is_ascii for str and [u8]. This optimizes the `is_ascii` function for `[u8]` and `str`. I've been surprised this wasn't done for a while, so I just did it. Benchmarks comparing before/after look like: ``` test ascii::long_readonly::is_ascii_slice_iter_all ... bench: 174 ns/iter (+/- 79) = 40172 MB/s test ascii::long_readonly::is_ascii_slice_libcore ... bench: 16 ns/iter (+/- 5) = 436875 MB/s test ascii::medium_readonly::is_ascii_slice_iter_all ... bench: 12 ns/iter (+/- 3) = 2666 MB/s test ascii::medium_readonly::is_ascii_slice_libcore ... bench: 2 ns/iter (+/- 0) = 16000 MB/s test ascii::short_readonly::is_ascii_slice_iter_all ... bench: 3 ns/iter (+/- 0) = 2333 MB/s test ascii::short_readonly::is_ascii_slice_libcore ... bench: 4 ns/iter (+/- 0) = 1750 MB/s ``` (Taken on a x86_64 macbook 2.9 GHz Intel Core i9 with 6 cores) Where `is_ascii_slice_iter_all` is the old version, and `is_ascii_slice_libcore` is the new. I tried to document the code well, so hopefully it's understandable. It has fairly exhaustive tests ensuring size/align doesn't get violated -- because `miri` doesn't really help a lot for this sort of code right now, I tried to `debug_assert` all the safety invariants I'm depending on. (Of course, none of them are required for correctness or soundness -- just allows us to test that this sort of pointer manipulation is sound and such). Anyway, thanks. Let me know if you have questions/desired changes.
2 parents 084ac77 + a150dcc commit 1979fa8

File tree

5 files changed

+242
-2
lines changed

5 files changed

+242
-2
lines changed

src/libcore/benches/ascii.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
mod is_ascii;
2+
13
// Lower-case ASCII 'a' is the first byte that has its highest bit set
24
// after wrap-adding 0x1F:
35
//

src/libcore/benches/ascii/is_ascii.rs

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
use super::{LONG, MEDIUM, SHORT};
2+
use test::black_box;
3+
use test::Bencher;
4+
5+
macro_rules! benches {
6+
($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => {
7+
benches!(mod short SHORT[..] $($name $arg $body)+);
8+
benches!(mod medium MEDIUM[..] $($name $arg $body)+);
9+
benches!(mod long LONG[..] $($name $arg $body)+);
10+
// Ensure we benchmark cases where the functions are called with strings
11+
// that are not perfectly aligned or have a length which is not a
12+
// multiple of size_of::<usize>() (or both)
13+
benches!(mod unaligned_head MEDIUM[1..] $($name $arg $body)+);
14+
benches!(mod unaligned_tail MEDIUM[..(MEDIUM.len() - 1)] $($name $arg $body)+);
15+
benches!(mod unaligned_both MEDIUM[1..(MEDIUM.len() - 1)] $($name $arg $body)+);
16+
};
17+
18+
(mod $mod_name: ident $input: ident [$range: expr] $($name: ident $arg: ident $body: block)+) => {
19+
mod $mod_name {
20+
use super::*;
21+
$(
22+
#[bench]
23+
fn $name(bencher: &mut Bencher) {
24+
bencher.bytes = $input[$range].len() as u64;
25+
let mut vec = $input.as_bytes().to_vec();
26+
bencher.iter(|| {
27+
let $arg: &[u8] = &black_box(&mut vec)[$range];
28+
black_box($body)
29+
})
30+
}
31+
)+
32+
}
33+
};
34+
}
35+
36+
benches! {
37+
fn case00_libcore(bytes: &[u8]) {
38+
bytes.is_ascii()
39+
}
40+
41+
fn case01_iter_all(bytes: &[u8]) {
42+
bytes.iter().all(|b| b.is_ascii())
43+
}
44+
45+
fn case02_align_to(bytes: &[u8]) {
46+
is_ascii_align_to(bytes)
47+
}
48+
49+
fn case03_align_to_unrolled(bytes: &[u8]) {
50+
is_ascii_align_to_unrolled(bytes)
51+
}
52+
}
53+
54+
// These are separate since it's easier to debug errors if they don't go through
55+
// macro expansion first.
56+
fn is_ascii_align_to(bytes: &[u8]) -> bool {
57+
if bytes.len() < core::mem::size_of::<usize>() {
58+
return bytes.iter().all(|b| b.is_ascii());
59+
}
60+
// SAFETY: transmuting a sequence of `u8` to `usize` is always fine
61+
let (head, body, tail) = unsafe { bytes.align_to::<usize>() };
62+
head.iter().all(|b| b.is_ascii())
63+
&& body.iter().all(|w| !contains_nonascii(*w))
64+
&& tail.iter().all(|b| b.is_ascii())
65+
}
66+
67+
fn is_ascii_align_to_unrolled(bytes: &[u8]) -> bool {
68+
if bytes.len() < core::mem::size_of::<usize>() {
69+
return bytes.iter().all(|b| b.is_ascii());
70+
}
71+
// SAFETY: transmuting a sequence of `u8` to `[usize; 2]` is always fine
72+
let (head, body, tail) = unsafe { bytes.align_to::<[usize; 2]>() };
73+
head.iter().all(|b| b.is_ascii())
74+
&& body.iter().all(|w| !contains_nonascii(w[0] | w[1]))
75+
&& tail.iter().all(|b| b.is_ascii())
76+
}
77+
78+
#[inline]
79+
fn contains_nonascii(v: usize) -> bool {
80+
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
81+
(NONASCII_MASK & v) != 0
82+
}

src/libcore/slice/mod.rs

+101-1
Original file line numberDiff line numberDiff line change
@@ -2795,7 +2795,7 @@ impl [u8] {
27952795
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
27962796
#[inline]
27972797
pub fn is_ascii(&self) -> bool {
2798-
self.iter().all(|b| b.is_ascii())
2798+
is_ascii(self)
27992799
}
28002800

28012801
/// Checks that two slices are an ASCII case-insensitive match.
@@ -2843,6 +2843,106 @@ impl [u8] {
28432843
}
28442844
}
28452845

2846+
/// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
2847+
/// from `../str/mod.rs`, which does something similar for utf8 validation.
2848+
#[inline]
2849+
fn contains_nonascii(v: usize) -> bool {
2850+
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
2851+
(NONASCII_MASK & v) != 0
2852+
}
2853+
2854+
/// Optimized ASCII test that will use usize-at-a-time operations instead of
2855+
/// byte-at-a-time operations (when possible).
2856+
///
2857+
/// The algorithm we use here is pretty simple. If `s` is too short, we just
2858+
/// check each byte and be done with it. Otherwise:
2859+
///
2860+
/// - Read the first word with an unaligned load.
2861+
/// - Align the pointer, read subsequent words until end with aligned loads.
2862+
/// - If there's a tail, the last `usize` from `s` with an unaligned load.
2863+
///
2864+
/// If any of these loads produces something for which `contains_nonascii`
2865+
/// (above) returns true, then we know the answer is false.
2866+
#[inline]
2867+
fn is_ascii(s: &[u8]) -> bool {
2868+
const USIZE_SIZE: usize = mem::size_of::<usize>();
2869+
2870+
let len = s.len();
2871+
let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
2872+
2873+
// If we wouldn't gain anything from the word-at-a-time implementation, fall
2874+
// back to a scalar loop.
2875+
//
2876+
// We also do this for architectures where `size_of::<usize>()` isn't
2877+
// sufficient alignment for `usize`, because it's a weird edge case.
2878+
if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
2879+
return s.iter().all(|b| b.is_ascii());
2880+
}
2881+
2882+
// We always read the first word unaligned, which means `align_offset` is
2883+
// 0, we'd read the same value again for the aligned read.
2884+
let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
2885+
2886+
let start = s.as_ptr();
2887+
// SAFETY: We verify `len < USIZE_SIZE` above.
2888+
let first_word = unsafe { (start as *const usize).read_unaligned() };
2889+
2890+
if contains_nonascii(first_word) {
2891+
return false;
2892+
}
2893+
// We checked this above, somewhat implicitly. Note that `offset_to_aligned`
2894+
// is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
2895+
// above.
2896+
debug_assert!(offset_to_aligned <= len);
2897+
2898+
// word_ptr is the (properly aligned) usize ptr we use to read the middle chunk of the slice.
2899+
let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
2900+
2901+
// `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
2902+
let mut byte_pos = offset_to_aligned;
2903+
2904+
// Paranoia check about alignment, since we're about to do a bunch of
2905+
// unaligned loads. In practice this should be impossible barring a bug in
2906+
// `align_offset` though.
2907+
debug_assert_eq!((word_ptr as usize) % mem::align_of::<usize>(), 0);
2908+
2909+
while byte_pos <= len - USIZE_SIZE {
2910+
debug_assert!(
2911+
// Sanity check that the read is in bounds
2912+
(word_ptr as usize + USIZE_SIZE) <= (start.wrapping_add(len) as usize) &&
2913+
// And that our assumptions about `byte_pos` hold.
2914+
(word_ptr as usize) - (start as usize) == byte_pos
2915+
);
2916+
2917+
// Safety: We know `word_ptr` is properly aligned (because of
2918+
// `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
2919+
let word = unsafe { word_ptr.read() };
2920+
if contains_nonascii(word) {
2921+
return false;
2922+
}
2923+
2924+
byte_pos += USIZE_SIZE;
2925+
// SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
2926+
// after this `add`, `word_ptr` will be at most one-past-the-end.
2927+
word_ptr = unsafe { word_ptr.add(1) };
2928+
}
2929+
2930+
// If we have anything left over, it should be at-most 1 usize worth of bytes,
2931+
// which we check with a read_unaligned.
2932+
if byte_pos == len {
2933+
return true;
2934+
}
2935+
2936+
// Sanity check to ensure there really is only one `usize` left. This should
2937+
// be guaranteed by our loop condition.
2938+
debug_assert!(byte_pos < len && len - byte_pos < USIZE_SIZE);
2939+
2940+
// SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
2941+
let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
2942+
2943+
!contains_nonascii(last_word)
2944+
}
2945+
28462946
#[stable(feature = "rust1", since = "1.0.0")]
28472947
impl<T, I> ops::Index<I> for [T]
28482948
where

src/libcore/str/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -4348,7 +4348,7 @@ impl str {
43484348
// We can treat each byte as character here: all multibyte characters
43494349
// start with a byte that is not in the ascii range, so we will stop
43504350
// there already.
4351-
self.bytes().all(|b| b.is_ascii())
4351+
self.as_bytes().is_ascii()
43524352
}
43534353

43544354
/// Checks that two strings are an ASCII case-insensitive match.

src/libcore/tests/ascii.rs

+56
Original file line numberDiff line numberDiff line change
@@ -343,3 +343,59 @@ fn test_is_ascii_control() {
343343
" ",
344344
);
345345
}
346+
347+
// `is_ascii` does a good amount of pointer manipulation and has
348+
// alignment-dependent computation. This is all sanity-checked via
349+
// `debug_assert!`s, so we test various sizes/alignments thoroughly versus an
350+
// "obviously correct" baseline function.
351+
#[test]
352+
fn test_is_ascii_align_size_thoroughly() {
353+
// The "obviously-correct" baseline mentioned above.
354+
fn is_ascii_baseline(s: &[u8]) -> bool {
355+
s.iter().all(|b| b.is_ascii())
356+
}
357+
358+
// Helper to repeat `l` copies of `b0` followed by `l` copies of `b1`.
359+
fn repeat_concat(b0: u8, b1: u8, l: usize) -> Vec<u8> {
360+
use core::iter::repeat;
361+
repeat(b0).take(l).chain(repeat(b1).take(l)).collect()
362+
}
363+
364+
// Miri is too slow for much of this, and in miri `align_offset` always
365+
// returns `usize::max_value()` anyway (at the moment), so we just test
366+
// lightly.
367+
let iter = if cfg!(miri) { 0..5 } else { 0..100 };
368+
369+
for i in iter {
370+
#[cfg(not(miri))]
371+
let cases = &[
372+
b"a".repeat(i),
373+
b"\0".repeat(i),
374+
b"\x7f".repeat(i),
375+
b"\x80".repeat(i),
376+
b"\xff".repeat(i),
377+
repeat_concat(b'a', 0x80u8, i),
378+
repeat_concat(0x80u8, b'a', i),
379+
];
380+
381+
#[cfg(miri)]
382+
let cases = &[repeat_concat(b'a', 0x80u8, i)];
383+
384+
for case in cases {
385+
for pos in 0..=case.len() {
386+
// Potentially misaligned head
387+
let prefix = &case[pos..];
388+
assert_eq!(is_ascii_baseline(prefix), prefix.is_ascii(),);
389+
390+
// Potentially misaligned tail
391+
let suffix = &case[..case.len() - pos];
392+
393+
assert_eq!(is_ascii_baseline(suffix), suffix.is_ascii(),);
394+
395+
// Both head and tail are potentially misaligned
396+
let mid = &case[(pos / 2)..(case.len() - (pos / 2))];
397+
assert_eq!(is_ascii_baseline(mid), mid.is_ascii(),);
398+
}
399+
}
400+
}
401+
}

0 commit comments

Comments
 (0)