Skip to content

Commit 13e380d

Browse files
author
Thom Chiovoloni
committed
Benchmark the unaligned case for is_ascii, and add missing SAFETY
1 parent e1d4db6 commit 13e380d

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/libcore/benches/ascii.rs

+21-3
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,23 @@ macro_rules! benches {
6565
benches!(@ro mod short_readonly SHORT $($name $arg $body)+);
6666
benches!(@ro mod medium_readonly MEDIUM $($name $arg $body)+);
6767
benches!(@ro mod long_readonly LONG $($name $arg $body)+);
68+
// Add another `MEDIUM` bench, but trim the ends so that we can (try to)
69+
// benchmark a case where the function has to handle misalignment.
70+
mod medium_unaligned {
71+
use super::*;
72+
$(
73+
#[bench]
74+
fn $name(bencher: &mut Bencher) {
75+
bencher.bytes = MEDIUM.len() as u64 - 2;
76+
let mut vec = MEDIUM.as_bytes().to_vec();
77+
bencher.iter(|| {
78+
black_box(&mut vec);
79+
let $arg = black_box(&vec[1..(vec.len() - 1)]);
80+
black_box($body)
81+
})
82+
}
83+
)+
84+
}
6885
};
6986
(@ro mod $mod_name: ident $input: ident $($name: ident $arg: ident $body: block)+) => {
7087
mod $mod_name {
@@ -291,10 +308,11 @@ fn is_ascii_align_to_impl(bytes: &[u8]) -> bool {
291308
if bytes.len() < core::mem::size_of::<usize>() {
292309
return bytes.iter().all(|b| b.is_ascii());
293310
}
311+
// SAFETY: transmuting a sequence of `u8` to `usize` is always fine
294312
let (head, body, tail) = unsafe { bytes.align_to::<usize>() };
295-
head.iter().all(|b| b.is_ascii()) &&
296-
body.iter().all(|w| !contains_nonascii(*w)) &&
297-
tail.iter().all(|b| b.is_ascii())
313+
head.iter().all(|b| b.is_ascii())
314+
&& body.iter().all(|w| !contains_nonascii(*w))
315+
&& tail.iter().all(|b| b.is_ascii())
298316
}
299317

300318
#[inline]

0 commit comments

Comments
 (0)