[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <DBUMQBY9W4GY.K4659O5ONHDQ@kernel.org>
Date: Tue, 05 Aug 2025 18:20:19 +0200
From: "Benno Lossin" <lossin@...nel.org>
To: "Alexandre Courbot" <acourbot@...dia.com>, "Miguel Ojeda"
<miguel.ojeda.sandonis@...il.com>
Cc: "Miguel Ojeda" <ojeda@...nel.org>, "Alex Gaynor"
<alex.gaynor@...il.com>, "Boqun Feng" <boqun.feng@...il.com>, "Gary Guo"
<gary@...yguo.net>, Björn Roy Baron
<bjorn3_gh@...tonmail.com>, "Andreas Hindborg" <a.hindborg@...nel.org>,
"Alice Ryhl" <aliceryhl@...gle.com>, "Trevor Gross" <tmgross@...ch.edu>,
"Danilo Krummrich" <dakr@...nel.org>, <linux-kernel@...r.kernel.org>,
<rust-for-linux@...r.kernel.org>, <nouveau@...ts.freedesktop.org>
Subject: Re: [PATCH v2 2/4] rust: add `Alignment` type
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 <acourbot@...dia.com> 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
Powered by blists - more mailing lists