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