Commit b9a72b1
authored
Rollup merge of rust-lang#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.1 file changed
+6
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
660 | 660 | | |
661 | 661 | | |
662 | 662 | | |
663 | | - | |
664 | | - | |
665 | 663 | | |
666 | 664 | | |
667 | 665 | | |
668 | | - | |
| 666 | + | |
| 667 | + | |
| 668 | + | |
| 669 | + | |
| 670 | + | |
| 671 | + | |
669 | 672 | | |
670 | 673 | | |
671 | 674 | | |
| |||
0 commit comments