Skip to content

Commit cd2ef4a

Browse files
committed
Use size_of::<usize>() instead of cfg constants
1 parent 442ae6b commit cd2ef4a

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

src/memrnchr.rs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,7 @@
33
// We use this mainly to skip repeated `/`. If there is only one slash, `memrnchr` performs the same
44
// as a naive version (e.g. `rposition`). However, it is much faster in pathological cases.
55

6-
#[cfg(target_pointer_width = "32")]
7-
const USIZE_BYTES: usize = 4;
8-
#[cfg(target_pointer_width = "64")]
9-
const USIZE_BYTES: usize = 8;
6+
use std::mem::size_of;
107

118
// Returns the byte offset of the last byte that is NOT equal to the given one.
129
#[inline(always)]
@@ -21,12 +18,11 @@ pub fn memrnchr(x: u8, text: &[u8]) -> Option<usize> {
2118
let ptr = text.as_ptr();
2219

2320
// search to an aligned boundary
24-
let end_align = (ptr as usize + len) & (USIZE_BYTES - 1);
21+
let end_align = (ptr as usize + len) & (size_of::<usize>() - 1);
2522
let mut offset;
2623
if end_align > 0 {
2724
offset = if end_align >= len { 0 } else { len - end_align };
28-
let pos = text[offset..].iter().rposition(|elt| *elt != x);
29-
if let Some(index) = pos {
25+
if let Some(index) = memrnchr_naive(x, &text[offset..]) {
3026
return Some(offset + index);
3127
}
3228
} else {
@@ -35,23 +31,25 @@ pub fn memrnchr(x: u8, text: &[u8]) -> Option<usize> {
3531

3632
// search the body of the text
3733
let repeated_x = repeat_byte(x);
38-
39-
while offset >= 2 * USIZE_BYTES {
40-
debug_assert_eq!((ptr as usize + offset) % USIZE_BYTES, 0);
34+
while offset >= 2 * size_of::<usize>() {
35+
debug_assert_eq!((ptr as usize + offset) % size_of::<usize>(), 0);
4136
unsafe {
42-
let u = *(ptr.offset(offset as isize - 2 * USIZE_BYTES as isize) as *const usize);
43-
let v = *(ptr.offset(offset as isize - USIZE_BYTES as isize) as *const usize);
44-
45-
// break if there is no matching byte
37+
let u = *(ptr.offset(offset as isize - 2 * size_of::<usize>() as isize) as *const usize);
38+
let v = *(ptr.offset(offset as isize - size_of::<usize>() as isize) as *const usize);
4639
if u & repeated_x != usize::max_value() || v & repeated_x != usize::max_value() {
4740
break;
4841
}
4942
}
50-
offset -= 2 * USIZE_BYTES;
43+
offset -= 2 * size_of::<usize>();
5144
}
5245

5346
// find the byte before the point the body loop stopped
54-
text[..offset].iter().rposition(|elt| *elt != x)
47+
memrnchr_naive(x, &text[..offset])
48+
}
49+
50+
#[inline(always)]
51+
fn memrnchr_naive(x: u8, text: &[u8]) -> Option<usize> {
52+
text.iter().rposition(|c| *c != x)
5553
}
5654

5755
#[cfg(target_pointer_width = "32")]

0 commit comments

Comments
 (0)