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