Skip to main content

score_set/
float.rs

1use core::fmt::Debug;
2use core::ops::{Add, Div, Mul, Neg, 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        + Neg<Output = Self>
20        + 'static
21    {
22        fn zero() -> Self;
23        fn one() -> Self;
24        fn is_finite(self) -> bool;
25        fn from_f64(v: f64) -> Self;
26        fn abs(self) -> Self;
27        fn min(self, other: Self) -> Self;
28        fn max(self, other: Self) -> Self;
29        fn exp(self) -> Self;
30        fn ln(self) -> Self;
31        fn epsilon() -> Self;
32    }
33
34    impl SealedFloat for f32 {
35        #[inline]
36        fn zero() -> Self { 0.0 }
37        #[inline]
38        fn one() -> Self { 1.0 }
39        #[inline]
40        fn is_finite(self) -> bool { f32::is_finite(self) }
41        #[inline]
42        fn from_f64(v: f64) -> Self { v as f32 }
43        #[inline]
44        fn abs(self) -> Self { f32::abs(self) }
45        #[inline]
46        fn min(self, other: Self) -> Self { f32::min(self, other) }
47        #[inline]
48        fn max(self, other: Self) -> Self { f32::max(self, other) }
49        #[inline]
50        fn exp(self) -> Self { f32::exp(self) }
51        #[inline]
52        fn ln(self) -> Self { f32::ln(self) }
53        #[inline]
54        fn epsilon() -> Self { f32::EPSILON }
55    }
56
57    impl SealedFloat for f64 {
58        #[inline]
59        fn zero() -> Self { 0.0 }
60        #[inline]
61        fn one() -> Self { 1.0 }
62        #[inline]
63        fn is_finite(self) -> bool { f64::is_finite(self) }
64        #[inline]
65        fn from_f64(v: f64) -> Self { v }
66        #[inline]
67        fn abs(self) -> Self { f64::abs(self) }
68        #[inline]
69        fn min(self, other: Self) -> Self { f64::min(self, other) }
70        #[inline]
71        fn max(self, other: Self) -> Self { f64::max(self, other) }
72        #[inline]
73        fn exp(self) -> Self { f64::exp(self) }
74        #[inline]
75        fn ln(self) -> Self { f64::ln(self) }
76        #[inline]
77        fn epsilon() -> Self { f64::EPSILON }
78    }
79}
80
81/// Public trait bound for floating-point types used throughout `score-set`.
82///
83/// Blanket-implemented for `f32` and `f64`. Sealed so downstream cannot add new impls.
84pub trait Float: sealed::SealedFloat {}
85
86impl<T: sealed::SealedFloat> Float for T {}
87
88#[cfg(test)]
89mod tests_for_float;