Re: [PATCH v2 2/5] rust: num: add `shr` and `shl` methods to `Bounded`
From: Alexandre Courbot
Date: Sun Jan 25 2026 - 22:24:58 EST
On Wed Jan 21, 2026 at 11:12 PM JST, Gary Guo wrote:
> On Wed Jan 21, 2026 at 7:23 AM GMT, Alexandre Courbot wrote:
>> Shifting a `Bounded` left or right changes the number of bits required
>> to represent the value. Add methods that perform the shift and return a
>> `Bounded` with the appropriately adjusted bit width.
>>
>> These methods are particularly useful for bitfield extraction.
>>
>> Suggested-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
>> Reviewed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
>> Signed-off-by: Alexandre Courbot <acourbot@xxxxxxxxxx>
>> ---
>> rust/kernel/num/bounded.rs | 40 ++++++++++++++++++++++++++++++++++++++++
>> 1 file changed, 40 insertions(+)
>>
>> diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs
>> index f870080af8ac..8782535770f1 100644
>> --- a/rust/kernel/num/bounded.rs
>> +++ b/rust/kernel/num/bounded.rs
>> @@ -470,6 +470,46 @@ pub fn cast<U>(self) -> Bounded<U, N>
>> // `N` bits, and with the same signedness.
>> Bounded::__new(value)
>
> This patch doesn't apply cleanly. Looks like you send it from the wrong base
> commit.
>
> The __new call here is still safe while your code has `unsafe {}` in it.
The cover letter mentions that the base for this patchset is
`driver-core-next`, since `register!` lands in `kernel/rust/io` and we
need to rebase on top of Zhi's Io patchset, which will land there as
well.
This indeed creates a minor conflict with `rust-next` as it includes a
couple of patches for `bounded.rs`.
>
>> }
>> +
>> + /// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, { N - SHIFT }>`.
>
> The returned bound can be larger given the assert below?
Indeed, I forgot to update this comment - thanks!
>
>> + ///
>> + /// # Examples
>> + ///
>> + /// ```
>> + /// use kernel::num::Bounded;
>> + ///
>> + /// let v = Bounded::<u32, 16>::new::<0xff00>();
>> + /// let v_shifted: Bounded::<u32, 8> = v.shr::<8, _>();
>> + ///
>> + /// assert_eq!(v_shifted.get(), 0xff);
>> + /// ```
>> + pub fn shr<const SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> {
>> + const { assert!(RES >= N - SHIFT) }
>
> Quite surprised that rustfmt didn't ask for the block to be expanded into
> multiple lines.
>
> I think we probably want to create a new assert macro for this pattern
> (obviously this doesn't block this patch).
>
>> +
>> + // SAFETY: we shift the value right by `SHIFT`, reducing the number of bits needed to
>> + // represent the shifted value by as much, and just asserted that `RES == N - SHIFT`.
>> + unsafe { Bounded::__new(self.0 >> SHIFT) }
>> + }
>> +
>> + /// Left-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, { N + SHIFT }>`.
>
> Same, the bound can be actually larger.
Fixed, thanks.