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)]
14        pub struct $name($float);
15        impl $name {
16            /// Admit a finite primitive and normalize either signed zero to positive zero.
17            #[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            /// Return the finite primitive value.
22            #[must_use]
23            pub const fn get(self) -> $float { self.0 }
24
25            // Stored data must already be canonical. Unlike input construction,
26            // decoding must not silently repair a negative-zero representation.
27            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            pub(crate) fn ordered_bytes(self) -> [u8; $width] {
32                let bits = self.0.to_bits();
33                let sign = 1 << (<$bits>::BITS - 1);
34                (if bits & sign != 0 { !bits } else { bits ^ sign }).to_be_bytes()
35            }
36            pub(crate) fn from_ordered_bytes(bytes: [u8; $width]) -> Option<Self> {
37                let bits = <$bits>::from_be_bytes(bytes);
38                let sign = 1 << (<$bits>::BITS - 1);
39                Self::from_canonical_bits(if bits & sign != 0 { bits ^ sign } else { !bits })
40            }
41        }
42        impl Eq for $name {}
43        impl Ord for $name {
44            fn cmp(&self, other: &Self) -> Ordering { self.0.total_cmp(&other.0) }
45        }
46        impl PartialOrd for $name {
47            fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
48        }
49        impl Hash for $name {
50            fn hash<H: Hasher>(&self, state: &mut H) { self.0.to_bits().hash(state); }
51        }
52        impl fmt::Display for $name {
53            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
54        }
55        impl From<$name> for $float {
56            fn from(value: $name) -> Self { value.get() }
57        }
58    };
59}
60finite_float!(Float32, f32, u32, 4);
61finite_float!(Float64, f64, u64, 8);