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