Re: [PATCH v6 2/9] rust: num: add `shr` and `shl` methods to `Bounded`

From: Alice Ryhl

Date: Mon Feb 16 2026 - 03:55:26 EST


On Mon, Feb 16, 2026 at 05:04:38PM +0900, 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>
> Reviewed-by: Gary Guo <gary@xxxxxxxxxxx>
> Reviewed-by: Daniel Almeida <daniel.almeida@xxxxxxxxxxxxx>
> Tested-by: Dirk Behme <dirk.behme@xxxxxxxxxxxx>
> Acked-by: Miguel Ojeda <ojeda@xxxxxxxxxx>
> Signed-off-by: Alexandre Courbot <acourbot@xxxxxxxxxx>
> ---
> rust/kernel/num/bounded.rs | 42 ++++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 42 insertions(+)
>
> diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs
> index fa81acbdc8c2..7014b5be66db 100644
> --- a/rust/kernel/num/bounded.rs
> +++ b/rust/kernel/num/bounded.rs
> @@ -473,6 +473,48 @@ pub fn cast<U>(self) -> Bounded<U, N>
> // `N` bits, and with the same signedness.
> unsafe { Bounded::__new(value) }
> }
> +
> + /// Right-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >=
> + /// N - SHIFT`.
> + ///
> + /// # 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) }

Perhaps slightly better as:

const { assert!(RES + SHIFT >= N) }

Alice