Skip to main content

radiate_utils/primitives/
integer.rs

1use crate::Primitive;
2
3pub trait Integer: Primitive + num_traits::PrimInt {
4    const MIN: Self;
5    const MAX: Self;
6    const ZERO: Self;
7    const ONE: Self;
8    const TWO: Self;
9
10    fn safe_clamp(self, min: Self, max: Self) -> Self {
11        if self < min {
12            min
13        } else if self > max {
14            max
15        } else {
16            self
17        }
18    }
19}
20
21#[macro_export]
22macro_rules! impl_integer {
23    ($($t:ty),*) => {
24        $(
25            impl Primitive for $t {
26                const HALF: Self = 0.5 as Self;
27
28                #[inline]
29                fn safe_add(self, rhs: Self) -> Self {
30                    self.saturating_add(rhs)
31                }
32
33                #[inline]
34                fn safe_sub(self, rhs: Self) -> Self {
35                    self.saturating_sub(rhs)
36                }
37
38                #[inline]
39                fn safe_mul(self, rhs: Self) -> Self {
40                    self.saturating_mul(rhs)
41                }
42
43                #[inline]
44                fn safe_div(self, rhs: Self) -> Self {
45                    if rhs == Self::ZERO {
46                        self
47                    } else {
48                        self.saturating_div(rhs)
49                    }
50                }
51
52                #[inline]
53                fn safe_mean(self, rhs: Self) -> Self {
54                    self.safe_add(rhs).safe_div(Self::TWO)
55                }
56            }
57
58            impl Integer for $t {
59                const MIN: Self = <$t>::MIN;
60                const MAX: Self = <$t>::MAX;
61                const ZERO: Self = 0;
62                const ONE: Self = 1;
63                const TWO: Self = 2;
64
65                fn safe_clamp(self, min: Self, max: Self) -> Self {
66                    if self < min {
67                        min
68                    } else if self > max {
69                        max
70                    } else {
71                        self
72                    }
73                }
74            }
75        )*
76    };
77}
78
79impl_integer!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);