Skip to main content

kernel/
num.rs

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