On Tue Aug 5, 2025 at 3:13 PM CEST, Alexandre Courbot wrote: > On Mon Aug 4, 2025 at 11:17 PM JST, Miguel Ojeda wrote: >> On Mon, Aug 4, 2025 at 1:45 PM Alexandre Courbot <[email protected]> wrote: >>> + pub const fn mask(self) -> usize { >>> + // INVARIANT: `self.as_usize()` is guaranteed to be a power of two >>> (i.e. non-zero), thus >>> + // `1` can safely be substracted from it. >>> + self.as_usize() - 1 >>> + } >> >> I am not sure why there is `// INVARIANT` here, since we are not >> creating a new `Self`. > >> >> I guess by "safely" you are trying to say there is no overflow risk -- >> I would be explicit and avoid "safe", since it is safe to overflow. > > I just wanted to justify that we cannot substract from 0. Maybe an > `unchecked_sub` would be better here? The `unsafe` block would also > justify the safety comment. > > ... mmm actually that would be `checked_sub().unwrap_unchecked()`, since > `unchecked_sub` appeared in Rust 1.79.
No need to do that, the compiler already knows that there won't be underflow and optimizes it accordingly (since self.as_usize() converts a `NonZero<usize>`). [1] (it also works when removing the `is_power_of_two` check, but if we only stored a `usize`, I bet the compiler would also optimize this given that check) I'd just add a normal comment that mentions no underflow can occur. This shouldn't need unsafe. [1]: https://godbolt.org/z/M5x1W49nn --- Cheers, Benno
