Skip to content

Commit 90f3df4

Browse files
Gnurouojeda
authored andcommitted
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>
1 parent e5d330e commit 90f3df4

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ pub mod miscdevice;
109109
pub mod mm;
110110
#[cfg(CONFIG_NET)]
111111
pub mod net;
112+
pub mod num;
112113
pub mod of;
113114
#[cfg(CONFIG_PM_OPP)]
114115
pub mod opp;

rust/kernel/num.rs

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Additional numerical features for the kernel.
4+
5+
use core::ops;
6+
7+
/// Designates unsigned primitive types.
8+
pub enum Unsigned {}
9+
10+
/// Designates signed primitive types.
11+
pub enum Signed {}
12+
13+
/// Describes core properties of integer types.
14+
pub trait Integer:
15+
Sized
16+
+ Copy
17+
+ Clone
18+
+ PartialEq
19+
+ Eq
20+
+ PartialOrd
21+
+ Ord
22+
+ ops::Add<Output = Self>
23+
+ ops::AddAssign
24+
+ ops::Sub<Output = Self>
25+
+ ops::SubAssign
26+
+ ops::Mul<Output = Self>
27+
+ ops::MulAssign
28+
+ ops::Div<Output = Self>
29+
+ ops::DivAssign
30+
+ ops::Rem<Output = Self>
31+
+ ops::RemAssign
32+
+ ops::BitAnd<Output = Self>
33+
+ ops::BitAndAssign
34+
+ ops::BitOr<Output = Self>
35+
+ ops::BitOrAssign
36+
+ ops::BitXor<Output = Self>
37+
+ ops::BitXorAssign
38+
+ ops::Shl<u32, Output = Self>
39+
+ ops::ShlAssign<u32>
40+
+ ops::Shr<u32, Output = Self>
41+
+ ops::ShrAssign<u32>
42+
+ ops::Not
43+
{
44+
/// Whether this type is [`Signed`] or [`Unsigned`].
45+
type Signedness;
46+
47+
/// Number of bits used for value representation.
48+
const BITS: u32;
49+
}
50+
51+
macro_rules! impl_integer {
52+
($($type:ty: $signedness:ty), *) => {
53+
$(
54+
impl Integer for $type {
55+
type Signedness = $signedness;
56+
57+
const BITS: u32 = <$type>::BITS;
58+
}
59+
)*
60+
};
61+
}
62+
63+
impl_integer!(
64+
u8: Unsigned,
65+
u16: Unsigned,
66+
u32: Unsigned,
67+
u64: Unsigned,
68+
u128: Unsigned,
69+
usize: Unsigned,
70+
i8: Signed,
71+
i16: Signed,
72+
i32: Signed,
73+
i64: Signed,
74+
i128: Signed,
75+
isize: Signed
76+
);

0 commit comments

Comments
 (0)