1use std::{
4 cmp::Ordering,
5 fmt,
6 hash::{Hash, Hasher},
7};
8
9macro_rules! finite_float {
11 ($name:ident, $float:ty, $bits:ty, $width:literal) => {
12 #[doc = concat!("Finite canonical `", stringify!($float), "`. Construction normalizes negative zero; NaN and infinities refuse.")]
13 #[derive(Clone, Copy, Debug, Default, PartialEq)]
14 pub struct $name($float);
15 impl $name {
16 #[must_use]
18 pub fn try_new(value: $float) -> Option<Self> {
19 value.is_finite().then(|| Self(if value == 0.0 { 0.0 } else { value }))
20 }
21 #[must_use]
23 pub const fn get(self) -> $float { self.0 }
24
25 pub(crate) fn from_canonical_bits(bits: $bits) -> Option<Self> {
28 let value = Self::try_new(<$float>::from_bits(bits))?;
29 (value.0.to_bits() == bits).then_some(value)
30 }
31
32 pub(crate) fn ordered_bytes(self) -> [u8; $width] {
33 let bits = self.0.to_bits();
34 let sign = 1 << (<$bits>::BITS - 1);
35 (if bits & sign != 0 { !bits } else { bits ^ sign }).to_be_bytes()
36 }
37
38 pub(crate) fn from_ordered_bytes(bytes: [u8; $width]) -> Option<Self> {
39 let bits = <$bits>::from_be_bytes(bytes);
40 let sign = 1 << (<$bits>::BITS - 1);
41 Self::from_canonical_bits(if bits & sign != 0 { bits ^ sign } else { !bits })
42 }
43 }
44 impl Eq for $name {}
45 impl Ord for $name {
46 fn cmp(&self, other: &Self) -> Ordering { self.0.total_cmp(&other.0) }
47 }
48 impl PartialOrd for $name {
49 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
50 }
51 impl Hash for $name {
52 fn hash<H: Hasher>(&self, state: &mut H) { self.0.to_bits().hash(state); }
53 }
54 impl fmt::Display for $name {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
56 }
57 impl From<$name> for $float {
58 fn from(value: $name) -> Self { value.get() }
59 }
60 };
61}
62finite_float!(Float32, f32, u32, 4);
63finite_float!(Float64, f64, u64, 8);