mirror of
https://github.com/rust-lang/rust.git
synced 2026-05-01 07:13:24 +03:00
Rollup merge of #147686 - vrtgs:non-zero-isolate, r=joboet
update isolate_highest_one for NonZero<T> ## Rationale Let `x = self` and `m = (((1 as $Int) << (<$Int>::BITS - 1)).wrapping_shr(self.leading_zeros()))` Then the previous code computed `NonZero::new_unchecked(x & m)`. Since `m` has exactly one bit set (the most significant 1-bit of `x`), `(x & m) == m`. Therefore, the masking step was redundant. The shift is safe and does not need wrapping because: * `self.leading_zeros() < $Int::BITS` because `self` is non-zero. * The result of `unchecked_shr` is non-zero, satisfying the `NonZero` invariant. if wrapping happens we would be violating `NonZero` invariants. why this micro optimization? the old code was suboptimal it duplicated `$Int`’s isolate_highest_one logic instead of delegating to it. Since the type already wraps `$Int`, either delegation should be used for clarity or, if keeping a custom implementation, it should be optimized as above.
This commit is contained in:
@@ -660,12 +660,15 @@ pub const fn trailing_zeros(self) -> u32 {
|
||||
without modifying the original"]
|
||||
#[inline(always)]
|
||||
pub const fn isolate_highest_one(self) -> Self {
|
||||
let n = self.get() & (((1 as $Int) << (<$Int>::BITS - 1)).wrapping_shr(self.leading_zeros()));
|
||||
|
||||
// SAFETY:
|
||||
// `self` is non-zero, so masking to preserve only the most
|
||||
// significant set bit will result in a non-zero `n`.
|
||||
unsafe { NonZero::new_unchecked(n) }
|
||||
// and self.leading_zeros() is always < $INT::BITS since
|
||||
// at least one of the bits in the number is not zero
|
||||
unsafe {
|
||||
let bit = (((1 as $Uint) << (<$Uint>::BITS - 1)).unchecked_shr(self.leading_zeros()));
|
||||
NonZero::new_unchecked(bit as $Int)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `self` with only the least significant bit set.
|
||||
|
||||
Reference in New Issue
Block a user