mirror of
git://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs.git
synced 2026-10-28 12:53:14 +01:00
rust: num: add shr and shl methods to Bounded
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 <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Reviewed-by: Gary Guo <[email protected]> Reviewed-by: Daniel Almeida <[email protected]> Tested-by: Dirk Behme <[email protected]> Acked-by: Miguel Ojeda <[email protected]> Acked-by: Yury Norov <[email protected]> Signed-off-by: Alexandre Courbot <[email protected]> Link: https://patch.msgid.link/[email protected] Signed-off-by: Danilo Krummrich <[email protected]>
This commit is contained in:
1 parent
3cc319d5f4
commit
c59a2d14cd
1 file changed
+42
@@ -473,6 +473,48 @@ where
|
||||
// `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 + SHIFT >= N) }
|
||||
|
||||
// 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<_, RES>`, where `RES >=
|
||||
/// N + SHIFT`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use kernel::num::Bounded;
|
||||
///
|
||||
/// let v = Bounded::<u32, 8>::new::<0xff>();
|
||||
/// let v_shifted: Bounded::<u32, 16> = v.shl::<8, _>();
|
||||
///
|
||||
/// assert_eq!(v_shifted.get(), 0xff00);
|
||||
/// ```
|
||||
pub fn shl<const SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> {
|
||||
const { assert!(RES >= N + SHIFT) }
|
||||
|
||||
// SAFETY: We shift the value left by `SHIFT`, augmenting 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) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, const N: u32> Deref for Bounded<T, N>
|
||||
|
||||
Reference in new issue
Block a user