Skip to content

Commit 70cb75c

Browse files
committed
make memrchr use align_offset
1 parent 0fc4501 commit 70cb75c

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/libcore/slice/memchr.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,24 @@ pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
102102
let ptr = text.as_ptr();
103103
let usize_bytes = mem::size_of::<usize>();
104104

105+
// a version of align_offset that says how much must be *subtracted*
106+
// from a pointer to be aligned.
107+
#[inline(always)]
108+
fn align_offset_down(ptr: *const u8, align: usize) -> usize {
109+
let align_offset = ptr.align_offset(align);
110+
if align_offset > align {
111+
// Not possible to align
112+
usize::max_value()
113+
} else if align_offset == 0 {
114+
0
115+
} else {
116+
// E.g. if align=8 and we have to add 1, then we can also subtract 7.
117+
align - align_offset
118+
}
119+
}
120+
105121
// search to an aligned boundary
106-
let end_align = (ptr as usize + len) & (usize_bytes - 1);
122+
let end_align = align_offset_down(unsafe { ptr.offset(len as isize) }, usize_bytes);
107123
let mut offset;
108124
if end_align > 0 {
109125
offset = if end_align >= len { 0 } else { len - end_align };

0 commit comments

Comments
 (0)