Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make memrchr use align_offset #52744

Merged
merged 2 commits into from
Jul 28, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/libcore/slice/memchr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,24 @@ pub fn memrchr(x: u8, text: &[u8]) -> Option<usize> {
let ptr = text.as_ptr();
let usize_bytes = mem::size_of::<usize>();

// a version of align_offset that says how much must be *subtracted*
// from a pointer to be aligned.
#[inline(always)]
fn align_offset_down(ptr: *const u8, align: usize) -> usize {
Copy link
Member

@nagisa nagisa Jul 26, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider slice::align_to::<usize>()? I believe that does exactly what a large part of this code does.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, plausible. Should I then also do that for memchr?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually it's not so easy, we want to do the main loop on a u8 slice, not usize (or actually pairs of usize, which is the steps that the loop is taking).

let align_offset = ptr.align_offset(align);
if align_offset > align {
// Not possible to align
usize::max_value()
} else if align_offset == 0 {
0
} else {
// E.g. if align=8 and we have to add 1, then we can also subtract 7.
align - align_offset
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You probably want (align - align_offset) & (align - 1) (or % align if you're sure it will optimize) instead of the last if/else. Not sure about the first one though, seems kinda fine as-is.

}
}

// search to an aligned boundary
let end_align = (ptr as usize + len) & (usize_bytes - 1);
let end_align = align_offset_down(unsafe { ptr.offset(len as isize) }, usize_bytes);
let mut offset;
if end_align > 0 {
offset = if end_align >= len { 0 } else { len - end_align };
Expand Down