about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2022-08-07 01:19:34 +0200
committerGitHub <noreply@github.com>2022-08-07 01:19:34 +0200
commitf0ff31fa09a144b1c24099e7b93be87522200caf (patch)
treeb08e89a6fe55744e5b5046ee9ac2bdd8ce90730b
parent1a96f31f763142942adf7f15421b2d59494c2af4 (diff)
parentc195f7c0a432d1d77aed3c490509895add77f93f (diff)
downloadrust-f0ff31fa09a144b1c24099e7b93be87522200caf.tar.gz
rust-f0ff31fa09a144b1c24099e7b93be87522200caf.zip
Rollup merge of #100169 - WaffleLapkin:optimize_is_aligned_to, r=workingjubilee
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]](https://github.com/rust-lang/rust/pull/95643#discussion_r843326903)).
-rw-r--r--library/core/src/ptr/const_ptr.rs5
-rw-r--r--library/core/src/ptr/mut_ptr.rs5
2 files changed, 2 insertions, 8 deletions
diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs
index e0655d68d2c..2cd6e23c71a 100644
--- a/library/core/src/ptr/const_ptr.rs
+++ b/library/core/src/ptr/const_ptr.rs
@@ -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
     }
 }
 
diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs
index fc3dd2a9b25..56ad5f7658e 100644
--- a/library/core/src/ptr/mut_ptr.rs
+++ b/library/core/src/ptr/mut_ptr.rs
@@ -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
     }
 }