Skip to main content

radiate_utils/primitives/
integer.rs

1use crate::{DataType, Primitive};
2
3pub trait Integer: Primitive + num_traits::PrimInt {
4    const DTYPE: DataType;
5
6    fn safe_clamp(self, min: Self, max: Self) -> Self {
7        if self < min {
8            min
9        } else if self > max {
10            max
11        } else {
12            self
13        }
14    }
15}
16
17#[macro_export]
18macro_rules! impl_integer {
19    ($t:ty, $dtype:ident) => {
20        impl Primitive for $t {
21            const HALF: Self = 0.5 as Self;
22            const MIN: Self = <$t>::MIN;
23            const MAX: Self = <$t>::MAX;
24            const ZERO: Self = 0;
25            const ONE: Self = 1;
26            const TWO: Self = 2;
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            #[inline]
58            fn is_equal(self, rhs: Self) -> bool {
59                self == rhs
60            }
61        }
62
63        impl Integer for $t {
64            const DTYPE: DataType = DataType::$dtype;
65
66            fn safe_clamp(self, min: Self, max: Self) -> Self {
67                if self < min {
68                    min
69                } else if self > max {
70                    max
71                } else {
72                    self
73                }
74            }
75        }
76    };
77}
78
79impl_integer!(i8, Int8);
80impl_integer!(i16, Int16);
81impl_integer!(i32, Int32);
82impl_integer!(i64, Int64);
83impl_integer!(i128, Int128);
84impl_integer!(u8, UInt8);
85impl_integer!(u16, UInt16);
86impl_integer!(u32, UInt32);
87impl_integer!(u64, UInt64);
88impl_integer!(u128, UInt128);