Skip to content

Conversation

vrtgs
Copy link

@vrtgs vrtgs commented Oct 14, 2025

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.

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Oct 14, 2025
@rustbot
Copy link
Collaborator

rustbot commented Oct 14, 2025

r? @Mark-Simulacrum

rustbot has assigned @Mark-Simulacrum.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants