summaryrefslogtreecommitdiff
path: root/rust/kernel/num.rs
diff options
context:
space:
mode:
authorAlexandre Courbot <acourbot@nvidia.com>2025-11-08 11:23:47 +0900
committerMiguel Ojeda <ojeda@kernel.org>2025-11-17 22:56:23 +0100
commit90f3df4fdfb682e2394ee3f97dfe91a402d5c46a (patch)
tree6a04624bc5304c6661990eea1dfa8ae79e36ffa0 /rust/kernel/num.rs
parente5d330e13f67d574f683c052c9a342814fd8fa39 (diff)
rust: add num module and Integer trait
Introduce the `num` module, which will provide numerical extensions and utilities for the kernel. For now, introduce the `Integer` trait, which is implemented for all primitive integer types to provides their core properties to generic code. Signed-off-by: Alexandre Courbot <acourbot@nvidia.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://patch.msgid.link/20251108-bounded_ints-v4-1-c9342ac7ebd1@nvidia.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
Diffstat (limited to 'rust/kernel/num.rs')
-rw-r--r--rust/kernel/num.rs76
1 files changed, 76 insertions, 0 deletions
diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
new file mode 100644
index 000000000000..c8c91cb9e682
--- /dev/null
+++ b/rust/kernel/num.rs
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Additional numerical features for the kernel.
+
+use core::ops;
+
+/// Designates unsigned primitive types.
+pub enum Unsigned {}
+
+/// Designates signed primitive types.
+pub enum Signed {}
+
+/// Describes core properties of integer types.
+pub trait Integer:
+ Sized
+ + Copy
+ + Clone
+ + PartialEq
+ + Eq
+ + PartialOrd
+ + Ord
+ + ops::Add<Output = Self>
+ + ops::AddAssign
+ + ops::Sub<Output = Self>
+ + ops::SubAssign
+ + ops::Mul<Output = Self>
+ + ops::MulAssign
+ + ops::Div<Output = Self>
+ + ops::DivAssign
+ + ops::Rem<Output = Self>
+ + ops::RemAssign
+ + ops::BitAnd<Output = Self>
+ + ops::BitAndAssign
+ + ops::BitOr<Output = Self>
+ + ops::BitOrAssign
+ + ops::BitXor<Output = Self>
+ + ops::BitXorAssign
+ + ops::Shl<u32, Output = Self>
+ + ops::ShlAssign<u32>
+ + ops::Shr<u32, Output = Self>
+ + ops::ShrAssign<u32>
+ + ops::Not
+{
+ /// Whether this type is [`Signed`] or [`Unsigned`].
+ type Signedness;
+
+ /// Number of bits used for value representation.
+ const BITS: u32;
+}
+
+macro_rules! impl_integer {
+ ($($type:ty: $signedness:ty), *) => {
+ $(
+ impl Integer for $type {
+ type Signedness = $signedness;
+
+ const BITS: u32 = <$type>::BITS;
+ }
+ )*
+ };
+}
+
+impl_integer!(
+ u8: Unsigned,
+ u16: Unsigned,
+ u32: Unsigned,
+ u64: Unsigned,
+ u128: Unsigned,
+ usize: Unsigned,
+ i8: Signed,
+ i16: Signed,
+ i32: Signed,
+ i64: Signed,
+ i128: Signed,
+ isize: Signed
+);