Skip to content

Commit f0ff31f

Browse files
authored
Rollup merge of rust-lang#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]](rust-lang#95643 (comment))).
2 parents 1a96f31 + c195f7c commit f0ff31f

File tree

2 files changed

+2
-8
lines changed

2 files changed

+2
-8
lines changed

library/core/src/ptr/const_ptr.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -1336,11 +1336,8 @@ impl<T: ?Sized> *const T {
13361336
panic!("is_aligned_to: align is not a power-of-two");
13371337
}
13381338

1339-
// SAFETY: `is_power_of_two()` will return `false` for zero.
1340-
unsafe { core::intrinsics::assume(align != 0) };
1341-
13421339
// Cast is needed for `T: !Sized`
1343-
self.cast::<u8>().addr() % align == 0
1340+
self.cast::<u8>().addr() & align - 1 == 0
13441341
}
13451342
}
13461343

library/core/src/ptr/mut_ptr.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -1614,11 +1614,8 @@ impl<T: ?Sized> *mut T {
16141614
panic!("is_aligned_to: align is not a power-of-two");
16151615
}
16161616

1617-
// SAFETY: `is_power_of_two()` will return `false` for zero.
1618-
unsafe { core::intrinsics::assume(align != 0) };
1619-
16201617
// Cast is needed for `T: !Sized`
1621-
self.cast::<u8>().addr() % align == 0
1618+
self.cast::<u8>().addr() & align - 1 == 0
16221619
}
16231620
}
16241621

0 commit comments

Comments
 (0)