Skip to main content

ic_db/
float.rs

1//! Finite scalar boundary adapted from IcyDB's schema/atom at 6d421e3.
2//! One canonical zero makes equality, hashing, collections and keys agree.
3use std::{
4    cmp::Ordering,
5    fmt,
6    hash::{Hash, Hasher},
7};
8
9// The same invariant applies to both widths; no generic runtime numeric layer.
10macro_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, serde::Serialize)]
14        #[serde(transparent)]
15        pub struct $name($float);
16        impl $name {
17            /// Admit a finite primitive and normalize either signed zero to positive zero.
18            #[must_use]
19            pub fn try_new(value: $float) -> Option<Self> {
20                value.is_finite().then(|| Self(if value == 0.0 { 0.0 } else { value }))
21            }
22            /// Return the finite primitive value.
23            #[must_use]
24            pub const fn get(self) -> $float { self.0 }
25
26            // Stored data must already be canonical. Unlike input construction,
27            // decoding must not silently repair a negative-zero representation.
28            pub(crate) fn from_canonical_bits(bits: $bits) -> Option<Self> {
29                let value = Self::try_new(<$float>::from_bits(bits))?;
30                (value.0.to_bits() == bits).then_some(value)
31            }
32
33            pub(crate) fn ordered_bytes(self) -> [u8; $width] {
34                let bits = self.0.to_bits();
35                let sign = 1 << (<$bits>::BITS - 1);
36                (if bits & sign != 0 { !bits } else { bits ^ sign }).to_be_bytes()
37            }
38
39            pub(crate) fn from_ordered_bytes(bytes: [u8; $width]) -> Option<Self> {
40                let bits = <$bits>::from_be_bytes(bytes);
41                let sign = 1 << (<$bits>::BITS - 1);
42                Self::from_canonical_bits(if bits & sign != 0 { bits ^ sign } else { !bits })
43            }
44        }
45        impl<'de> serde::Deserialize<'de> for $name {
46            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
47                Self::try_new(<$float>::deserialize(deserializer)?)
48                    .ok_or_else(|| serde::de::Error::custom("expected a finite float"))
49            }
50        }
51        impl Eq for $name {}
52        impl Ord for $name {
53            fn cmp(&self, other: &Self) -> Ordering { self.0.total_cmp(&other.0) }
54        }
55        impl PartialOrd for $name {
56            fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
57        }
58        impl Hash for $name {
59            fn hash<H: Hasher>(&self, state: &mut H) { self.0.to_bits().hash(state); }
60        }
61        impl fmt::Display for $name {
62            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
63        }
64        impl From<$name> for $float {
65            fn from(value: $name) -> Self { value.get() }
66        }
67    };
68}
69finite_float!(Float32, f32, u32, 4);
70finite_float!(Float64, f64, u64, 8);