Skip to main content

score_set/
float.rs

1use core::fmt::Debug;
2use core::ops::{Add, Div, Mul, Sub};
3
4/// Sealed trait for floating-point types supported by this crate.
5///
6/// Implemented for `f32` and `f64` only — downstream crates cannot add new impls.
7pub(crate) mod sealed {
8    use super::*;
9
10    pub trait SealedFloat:
11        Copy
12        + PartialOrd
13        + PartialEq
14        + Debug
15        + Add<Output = Self>
16        + Sub<Output = Self>
17        + Mul<Output = Self>
18        + Div<Output = Self>
19        + 'static
20    {
21        fn zero() -> Self;
22        fn one() -> Self;
23        fn is_finite(self) -> bool;
24        fn from_f64(v: f64) -> Self;
25        fn abs(self) -> Self;
26        fn min(self, other: Self) -> Self;
27        fn max(self, other: Self) -> Self;
28    }
29
30    impl SealedFloat for f32 {
31        #[inline]
32        fn zero() -> Self {
33            0.0
34        }
35        #[inline]
36        fn one() -> Self {
37            1.0
38        }
39        #[inline]
40        fn is_finite(self) -> bool {
41            f32::is_finite(self)
42        }
43        #[inline]
44        fn from_f64(v: f64) -> Self {
45            v as f32
46        }
47        #[inline]
48        fn abs(self) -> Self {
49            f32::abs(self)
50        }
51        #[inline]
52        fn min(self, other: Self) -> Self {
53            f32::min(self, other)
54        }
55        #[inline]
56        fn max(self, other: Self) -> Self {
57            f32::max(self, other)
58        }
59    }
60
61    impl SealedFloat for f64 {
62        #[inline]
63        fn zero() -> Self {
64            0.0
65        }
66        #[inline]
67        fn one() -> Self {
68            1.0
69        }
70        #[inline]
71        fn is_finite(self) -> bool {
72            f64::is_finite(self)
73        }
74        #[inline]
75        fn from_f64(v: f64) -> Self {
76            v
77        }
78        #[inline]
79        fn abs(self) -> Self {
80            f64::abs(self)
81        }
82        #[inline]
83        fn min(self, other: Self) -> Self {
84            f64::min(self, other)
85        }
86        #[inline]
87        fn max(self, other: Self) -> Self {
88            f64::max(self, other)
89        }
90    }
91}
92
93/// Public trait bound for floating-point types used throughout `score-set`.
94///
95/// Blanket-implemented for `f32` and `f64`. Sealed so downstream cannot add new impls.
96pub trait Float: sealed::SealedFloat {}
97
98impl<T: sealed::SealedFloat> Float for T {}
99
100#[cfg(test)]
101mod tests_for_float;