Skip to main content

radiate_utils/primitives/
float.rs

1use crate::primitives::Primitive;
2
3pub trait Float: Primitive + num_traits::Float {
4    const MIN: Self;
5    const MAX: Self;
6    const ZERO: Self;
7    const ONE: Self;
8    const TWO: Self;
9    const EPS: Self;
10
11    fn safe_clamp(self, min: Self, max: Self) -> Self {
12        if self.is_finite() {
13            self.clamp(min, max)
14        } else {
15            Self::EPS
16        }
17    }
18}
19
20#[macro_export]
21macro_rules! impl_float_scalar {
22    ($t:ty, $eps:expr) => {
23        impl Primitive for $t {
24            const HALF: Self = 0.5;
25
26            #[inline]
27            fn safe_add(self, rhs: Self) -> Self {
28                self + rhs
29            }
30
31            #[inline]
32            fn safe_sub(self, rhs: Self) -> Self {
33                self - rhs
34            }
35
36            #[inline]
37            fn safe_mul(self, rhs: Self) -> Self {
38                (self * rhs)
39            }
40
41            #[inline]
42            fn safe_div(self, rhs: Self) -> Self {
43                if rhs == Self::ZERO { self } else { self / rhs }
44            }
45
46            #[inline]
47            fn safe_mean(self, rhs: Self) -> Self {
48                (self + rhs) * Self::HALF
49            }
50        }
51
52        impl Float for $t {
53            const MIN: Self = <$t>::MIN;
54            const MAX: Self = <$t>::MAX;
55            const ZERO: Self = 0.0;
56            const ONE: Self = 1.0;
57            const TWO: Self = 2.0;
58            const EPS: Self = $eps;
59        }
60    };
61}
62
63impl_float_scalar!(f32, 1e-6_f32);
64impl_float_scalar!(f64, 1e-12_f64);