Skip to content

Commit

Permalink
Rollup merge of #100169 - WaffleLapkin:optimize_is_aligned_to, r=work…
Browse files Browse the repository at this point in the history
…ingjubilee

Optimize `pointer::as_aligned_to`

This PR replaces `addr % align` with `addr & align - 1`, which is correct due to `align` being a power of two.

Here is a proof that this makes things better: [[godbolt]](https://godbolt.org/z/Wbq3hx6YG).

This PR also removes `assume(align != 0)`, with the new impl it does not improve anything anymore ([[godbolt]](https://rust.godbolt.org/z/zcnrG4777), [[original concern]](rust-lang/rust#95643 (comment))).
  • Loading branch information
matthiaskrgr authored Aug 6, 2022
2 parents a3d1a06 + fbcafb8 commit a6a26db
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 8 deletions.
5 changes: 1 addition & 4 deletions core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1336,11 +1336,8 @@ impl<T: ?Sized> *const T {
panic!("is_aligned_to: align is not a power-of-two");
}

// SAFETY: `is_power_of_two()` will return `false` for zero.
unsafe { core::intrinsics::assume(align != 0) };

// Cast is needed for `T: !Sized`
self.cast::<u8>().addr() % align == 0
self.cast::<u8>().addr() & align - 1 == 0
}
}

Expand Down
5 changes: 1 addition & 4 deletions core/src/ptr/mut_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1614,11 +1614,8 @@ impl<T: ?Sized> *mut T {
panic!("is_aligned_to: align is not a power-of-two");
}

// SAFETY: `is_power_of_two()` will return `false` for zero.
unsafe { core::intrinsics::assume(align != 0) };

// Cast is needed for `T: !Sized`
self.cast::<u8>().addr() % align == 0
self.cast::<u8>().addr() & align - 1 == 0
}
}

Expand Down

0 comments on commit a6a26db

Please sign in to comment.