Skip to main content

niche_value/
float.rs

1//! Float niche types.
2//!
3//! Two families:
4//! * **bit-exact** — [`NonValueF32`]/[`NonValueF64`], forbidding one bit pattern
5//!   (const generic `BITS`), plus the `NonMax*`/`NonMin*` aliases.
6//! * **class-based** — [`NonNanF32`], [`NonInfF32`], [`NonZeroF32`],
7//!   [`FiniteF32`], [`NonSubnormalF32`], … which reject a whole semantic class
8//!   at construction while anchoring their niche on one representative pattern.
9//!   [`NonNanF32`]/[`FiniteF32`] can never hold `NaN`, so they alone get a total
10//!   [`Ord`]/[`Eq`]/[`Hash`].
11//!
12//! # Anchors and the soundness rule
13//!
14//! Every type stores `value.to_bits() ^ ANCHOR` in a [`core::num::NonZero`], so
15//! the niche survives exactly as long as no *constructible* value can have
16//! `to_bits() == ANCHOR`. The two families guarantee that differently:
17//!
18//! * **bit-exact** types reject by **bit pattern** (`to_bits() == BITS`): the one
19//!   forbidden pattern is the anchor and nothing else is touched. A consequence
20//!   is that `+0.0` and `-0.0` are distinct patterns — forbidding one leaves the
21//!   other valid — and a bit-exact type forbids exactly one of them.
22//! * **class-based** types reject by **value / semantics** (`is_nan()`,
23//!   `== 0.0`, `is_subnormal()`, …) and anchor on one representative pattern
24//!   *drawn from the rejected class*, so the anchor is itself rejected and hence
25//!   never constructible.
26//!
27//! A value predicate is sound only when the anchor compares **equal to itself**.
28//! `+0.0 == +0.0`, so [`NonZeroF32`] may reject with `value == 0.0` (its anchor
29//! is `+0.0`). `NaN != NaN`, so a `value == NaN` check would let the anchor slip
30//! through and form an unsound `NonZero(0)`; [`NonNanF32`] must instead reject
31//! with `is_nan()`, which classifies *every* `NaN` pattern, the anchor included.
32//!
33//! # Serde
34//!
35//! Float (de)serialization uses the primitive's own representation, so a round
36//! trip reproduces the mathematical **value**, matching `f32`/`f64`. Exact bit
37//! identity — a specific `NaN` payload, or the sign of a zero — survives only on
38//! formats that preserve IEEE-754 bits (e.g. `bincode`). Under a format that
39//! canonicalizes `NaN` or flushes signed zero, a bit-exact `NonValueF*` whose
40//! forbidden pattern is such a value can even *fail* to deserialize, since the
41//! checked constructor rejects the mangled bits. Serialize `to_bits()` yourself
42//! if you need format-independent bit fidelity.
43
44use crate::error::{ParseFloatError, TryFromFloatError};
45
46// ============================ bit-exact family ============================
47
48macro_rules! niche_float {
49    ($nv:ident, $prim:ident, $bits:ident, $nonzero:ident, $nonmax:ident, $nonmin:ident) => {
50        #[doc = concat!("An [`", stringify!($prim), "`] whose bit pattern is known not to equal `BITS`.")]
51        ///
52        /// `Option<Self>` is niche-optimized to the size of the primitive.
53        /// Rejection is bit-exact (see the module docs). Because it can still
54        /// hold `NaN`, it implements only [`PartialEq`]/[`PartialOrd`] (by
55        /// value, matching the primitive) — not [`Eq`]/[`Ord`]/[`Hash`].
56        #[derive(Clone, Copy)]
57        #[repr(transparent)]
58        pub struct $nv<const BITS: $bits>(core::num::$nonzero);
59
60        impl<const BITS: $bits> $nv<BITS> {
61            /// Creates a value if `value.to_bits() != BITS`, otherwise `None`.
62            #[inline]
63            pub const fn new(value: $prim) -> Option<Self> {
64                match core::num::$nonzero::new(value.to_bits() ^ BITS) {
65                    None => None,
66                    Some(inner) => Some(Self(inner)),
67                }
68            }
69
70            /// Creates a value without checking its bit pattern.
71            ///
72            /// # Safety
73            ///
74            /// `value.to_bits()` must not equal `BITS`.
75            #[inline]
76            pub const unsafe fn new_unchecked(value: $prim) -> Self {
77                // SAFETY: caller guarantees `value.to_bits() != BITS`.
78                Self(unsafe { core::num::$nonzero::new_unchecked(value.to_bits() ^ BITS) })
79            }
80
81            /// Returns the value as a primitive.
82            #[inline]
83            pub const fn get(&self) -> $prim {
84                $prim::from_bits(self.0.get() ^ BITS)
85            }
86        }
87
88        impl<const BITS: $bits> PartialEq for $nv<BITS> {
89            #[inline]
90            fn eq(&self, other: &Self) -> bool {
91                self.get() == other.get()
92            }
93        }
94        impl<const BITS: $bits> PartialOrd for $nv<BITS> {
95            #[inline]
96            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
97                self.get().partial_cmp(&other.get())
98            }
99        }
100        impl<const BITS: $bits> From<$nv<BITS>> for $prim {
101            #[inline]
102            fn from(value: $nv<BITS>) -> Self {
103                value.get()
104            }
105        }
106        impl<const BITS: $bits> core::convert::TryFrom<$prim> for $nv<BITS> {
107            type Error = TryFromFloatError;
108            #[inline]
109            fn try_from(value: $prim) -> Result<Self, Self::Error> {
110                Self::new(value).ok_or(TryFromFloatError(()))
111            }
112        }
113        impl<const BITS: $bits> core::str::FromStr for $nv<BITS> {
114            type Err = ParseFloatError;
115            #[inline]
116            fn from_str(value: &str) -> Result<Self, Self::Err> {
117                Self::new(<$prim as core::str::FromStr>::from_str(value)?).ok_or(ParseFloatError(()))
118            }
119        }
120
121        impl<const BITS: $bits> core::fmt::Debug for $nv<BITS> {
122            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
123                core::fmt::Debug::fmt(&self.get(), f)
124            }
125        }
126        impl<const BITS: $bits> core::fmt::Display for $nv<BITS> {
127            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
128                core::fmt::Display::fmt(&self.get(), f)
129            }
130        }
131        impl<const BITS: $bits> core::fmt::LowerExp for $nv<BITS> {
132            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
133                core::fmt::LowerExp::fmt(&self.get(), f)
134            }
135        }
136        impl<const BITS: $bits> core::fmt::UpperExp for $nv<BITS> {
137            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
138                core::fmt::UpperExp::fmt(&self.get(), f)
139            }
140        }
141
142        #[cfg(feature = "serde")]
143        impl<const BITS: $bits> serde::Serialize for $nv<BITS> {
144            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
145                self.get().serialize(serializer)
146            }
147        }
148        #[cfg(feature = "serde")]
149        impl<'de, const BITS: $bits> serde::Deserialize<'de> for $nv<BITS> {
150            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
151                let value = <$prim as serde::Deserialize>::deserialize(deserializer)?;
152                Self::new(value).ok_or_else(|| serde::de::Error::custom("bit pattern is forbidden by niche type"))
153            }
154        }
155
156        #[doc = concat!("A [`", stringify!($prim), "`] known not to be `", stringify!($prim), "::MAX` (bit-exact).")]
157        pub type $nonmax = $nv<{ $prim::MAX.to_bits() }>;
158        #[doc = concat!("A [`", stringify!($prim), "`] known not to be `", stringify!($prim), "::MIN` (bit-exact).")]
159        pub type $nonmin = $nv<{ $prim::MIN.to_bits() }>;
160
161        const _: () = {
162            assert!(core::mem::size_of::<$nonmax>() == core::mem::size_of::<$prim>());
163            assert!(core::mem::size_of::<Option<$nonmax>>() == core::mem::size_of::<$prim>());
164        };
165    };
166}
167
168niche_float!(NonValueF32, f32, u32, NonZeroU32, NonMaxF32, NonMinF32);
169niche_float!(NonValueF64, f64, u64, NonZeroU64, NonMaxF64, NonMinF64);
170
171// ============================ class-based family ============================
172
173macro_rules! niche_float_class {
174    (
175        $ty:ident, $prim:ident, $bits:ident, $nonzero:ident,
176        anchor = $anchor:expr, reject = $reject:expr, what = $what:literal
177    ) => {
178        #[doc = concat!("An [`", stringify!($prim), "`] guaranteed not to be ", $what, ".")]
179        ///
180        /// `Option<Self>` is niche-optimized to the size of the primitive.
181        #[derive(Clone, Copy)]
182        #[repr(transparent)]
183        pub struct $ty(core::num::$nonzero);
184
185        impl $ty {
186            /// The niche anchor: a representative bit pattern from the forbidden
187            /// class. Never stored, so it is free to serve as `Option::None`.
188            const ANCHOR: $bits = $anchor;
189
190            #[doc = concat!("Creates a value if it is not ", $what, ", otherwise `None`.")]
191            #[inline]
192            pub fn new(value: $prim) -> Option<Self> {
193                #[allow(clippy::redundant_closure_call)]
194                if ($reject)(value) {
195                    return None;
196                }
197                // The predicate guarantees `value.to_bits() != ANCHOR` (the
198                // anchor is itself a member of the forbidden class), so the XOR
199                // is never zero and `NonZero::new` always returns `Some`.
200                core::num::$nonzero::new(value.to_bits() ^ Self::ANCHOR).map(Self)
201            }
202
203            #[doc = concat!("Creates a value without checking that it is not ", $what, ".")]
204            ///
205            /// # Safety
206            #[doc = concat!("`value` must not be ", $what, ".")]
207            #[inline]
208            pub unsafe fn new_unchecked(value: $prim) -> Self {
209                // SAFETY: caller guarantees the value is outside the forbidden
210                // class, hence `value.to_bits() != ANCHOR`.
211                Self(unsafe { core::num::$nonzero::new_unchecked(value.to_bits() ^ Self::ANCHOR) })
212            }
213
214            /// Returns the value as a primitive.
215            #[inline]
216            pub const fn get(&self) -> $prim {
217                $prim::from_bits(self.0.get() ^ Self::ANCHOR)
218            }
219        }
220
221        impl PartialEq for $ty {
222            #[inline]
223            fn eq(&self, other: &Self) -> bool {
224                self.get() == other.get()
225            }
226        }
227        impl From<$ty> for $prim {
228            #[inline]
229            fn from(value: $ty) -> Self {
230                value.get()
231            }
232        }
233        impl core::convert::TryFrom<$prim> for $ty {
234            type Error = TryFromFloatError;
235            #[inline]
236            fn try_from(value: $prim) -> Result<Self, Self::Error> {
237                Self::new(value).ok_or(TryFromFloatError(()))
238            }
239        }
240        impl core::str::FromStr for $ty {
241            type Err = ParseFloatError;
242            #[inline]
243            fn from_str(value: &str) -> Result<Self, Self::Err> {
244                Self::new(<$prim as core::str::FromStr>::from_str(value)?)
245                    .ok_or(ParseFloatError(()))
246            }
247        }
248        impl core::fmt::Debug for $ty {
249            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
250                core::fmt::Debug::fmt(&self.get(), f)
251            }
252        }
253        impl core::fmt::Display for $ty {
254            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
255                core::fmt::Display::fmt(&self.get(), f)
256            }
257        }
258        impl core::fmt::LowerExp for $ty {
259            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
260                core::fmt::LowerExp::fmt(&self.get(), f)
261            }
262        }
263        impl core::fmt::UpperExp for $ty {
264            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
265                core::fmt::UpperExp::fmt(&self.get(), f)
266            }
267        }
268
269        #[cfg(feature = "serde")]
270        impl serde::Serialize for $ty {
271            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
272                self.get().serialize(serializer)
273            }
274        }
275        #[cfg(feature = "serde")]
276        impl<'de> serde::Deserialize<'de> for $ty {
277            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
278                let value = <$prim as serde::Deserialize>::deserialize(deserializer)?;
279                Self::new(value)
280                    .ok_or_else(|| serde::de::Error::custom(concat!("value is ", $what)))
281            }
282        }
283
284        const _: () = {
285            assert!(core::mem::size_of::<$ty>() == core::mem::size_of::<$prim>());
286            assert!(core::mem::size_of::<Option<$ty>>() == core::mem::size_of::<$prim>());
287        };
288    };
289}
290
291/// `PartialOrd` for a class-based float that may still hold `NaN` (so no total
292/// order): comparison is by value and can be `None`.
293macro_rules! impl_partial_ord {
294    ($ty:ident) => {
295        impl PartialOrd for $ty {
296            #[inline]
297            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
298                self.get().partial_cmp(&other.get())
299            }
300        }
301    };
302}
303
304/// Adds total `Eq`/`Ord`/`Hash` (and a canonical `PartialOrd`) to a float type
305/// that can never hold `NaN`. `-0.0` is normalized to `+0.0` in `Hash` to stay
306/// consistent with `Eq` (`+0.0 == -0.0`), while `get()` round-trips the sign.
307macro_rules! impl_total_ord {
308    ($ty:ident, $prim:ident) => {
309        impl PartialOrd for $ty {
310            #[inline]
311            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
312                Some(self.cmp(other))
313            }
314        }
315        impl Eq for $ty {}
316        impl Ord for $ty {
317            #[inline]
318            fn cmp(&self, other: &Self) -> core::cmp::Ordering {
319                // SAFETY-of-logic: this type never holds NaN, so partial_cmp is total.
320                self.get()
321                    .partial_cmp(&other.get())
322                    .expect("type invariant guarantees no NaN")
323            }
324        }
325        impl core::hash::Hash for $ty {
326            #[inline]
327            fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
328                let value = self.get();
329                let normalized = if value == 0.0 { 0.0 } else { value };
330                normalized.to_bits().hash(state);
331            }
332        }
333    };
334}
335
336niche_float_class!(
337    NonNanF32,
338    f32,
339    u32,
340    NonZeroU32,
341    anchor = 0x7FC0_0000,
342    reject = |v: f32| v.is_nan(),
343    what = "`NaN`"
344);
345niche_float_class!(
346    NonNanF64,
347    f64,
348    u64,
349    NonZeroU64,
350    anchor = 0x7FF8_0000_0000_0000,
351    reject = |v: f64| v.is_nan(),
352    what = "`NaN`"
353);
354impl_total_ord!(NonNanF32, f32);
355impl_total_ord!(NonNanF64, f64);
356
357niche_float_class!(
358    NonInfF32,
359    f32,
360    u32,
361    NonZeroU32,
362    anchor = 0x7F80_0000,
363    reject = |v: f32| v.is_infinite(),
364    what = "infinite"
365);
366niche_float_class!(
367    NonInfF64,
368    f64,
369    u64,
370    NonZeroU64,
371    anchor = 0x7FF0_0000_0000_0000,
372    reject = |v: f64| v.is_infinite(),
373    what = "infinite"
374);
375impl_partial_ord!(NonInfF32);
376impl_partial_ord!(NonInfF64);
377
378niche_float_class!(
379    NonZeroF32,
380    f32,
381    u32,
382    NonZeroU32,
383    anchor = 0x0000_0000,
384    reject = |v: f32| v == 0.0,
385    what = "zero"
386);
387niche_float_class!(
388    NonZeroF64,
389    f64,
390    u64,
391    NonZeroU64,
392    anchor = 0x0000_0000_0000_0000,
393    reject = |v: f64| v == 0.0,
394    what = "zero"
395);
396impl_partial_ord!(NonZeroF32);
397impl_partial_ord!(NonZeroF64);
398
399niche_float_class!(
400    FiniteF32,
401    f32,
402    u32,
403    NonZeroU32,
404    anchor = 0x7FC0_0000,
405    reject = |v: f32| !v.is_finite(),
406    what = "non-finite (`NaN` or infinite)"
407);
408niche_float_class!(
409    FiniteF64,
410    f64,
411    u64,
412    NonZeroU64,
413    anchor = 0x7FF8_0000_0000_0000,
414    reject = |v: f64| !v.is_finite(),
415    what = "non-finite (`NaN` or infinite)"
416);
417impl_total_ord!(FiniteF32, f32);
418impl_total_ord!(FiniteF64, f64);
419
420niche_float_class!(
421    NonSubnormalF32,
422    f32,
423    u32,
424    NonZeroU32,
425    anchor = 0x0000_0001,
426    reject = |v: f32| v.is_subnormal(),
427    what = "subnormal"
428);
429niche_float_class!(
430    NonSubnormalF64,
431    f64,
432    u64,
433    NonZeroU64,
434    anchor = 0x0000_0000_0000_0001,
435    reject = |v: f64| v.is_subnormal(),
436    what = "subnormal"
437);
438impl_partial_ord!(NonSubnormalF32);
439impl_partial_ord!(NonSubnormalF64);
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    use core::mem::size_of;
445
446    // Shared contract checks for the NaN-free float types: a total `Ord` and the
447    // `-0.0`-normalized `Hash`. Both `NonNan*` and `Finite*` must satisfy them,
448    // so exercising them through one helper stops a future contract change from
449    // leaving either type under-tested.
450    #[cfg(feature = "std")]
451    fn assert_total_order_f64<T: Ord + Copy>(new: impl Fn(f64) -> T, get: impl Fn(&T) -> f64) {
452        use std::collections::BTreeSet;
453        let a = new(-1.0);
454        let b = new(0.0);
455        let c = new(2.5);
456        assert!(a < b && b < c);
457
458        let mut set: BTreeSet<T> = BTreeSet::new();
459        set.insert(c);
460        set.insert(a);
461        set.insert(b);
462        let sorted: Vec<f64> = set.iter().map(get).collect();
463        assert_eq!(sorted, vec![-1.0, 0.0, 2.5]);
464    }
465
466    #[cfg(feature = "std")]
467    fn assert_signed_zero_eq_hash_f32<T: Eq + core::hash::Hash + Copy + core::fmt::Debug>(
468        new: impl Fn(f32) -> T,
469    ) {
470        use std::collections::HashSet;
471        // +0.0 and -0.0 compare and hash equal, so -0.0 must collide in the set.
472        let mut hs: HashSet<T> = HashSet::new();
473        assert!(hs.insert(new(0.0)));
474        assert!(!hs.insert(new(-0.0)));
475        assert_eq!(new(0.0), new(-0.0));
476    }
477
478    #[test]
479    fn bit_exact_rejection_and_roundtrip() {
480        assert_eq!(NonMaxF32::new(1.5).unwrap().get(), 1.5);
481        assert!(NonMaxF32::new(f32::MAX).is_none());
482        assert!(NonMinF32::new(f32::MIN).is_none());
483        assert_eq!(NonMaxF32::new(f32::INFINITY).unwrap().get(), f32::INFINITY);
484    }
485
486    #[test]
487    fn signed_zero_is_bit_distinct() {
488        // Forbid +0.0's bit pattern; -0.0 is a *different* pattern and allowed.
489        type NoPosZero = NonValueF32<0x0000_0000>;
490        assert!(NoPosZero::new(0.0).is_none());
491        let neg = NoPosZero::new(-0.0).unwrap();
492        assert!(neg.get().is_sign_negative());
493        assert_eq!(neg.get(), 0.0); // value-equal to +0.0
494    }
495
496    #[test]
497    fn nonnan_rejects_every_nan_but_keeps_infinity() {
498        assert!(NonNanF32::new(f32::NAN).is_none());
499        // a different (signaling-ish) NaN bit pattern is also rejected
500        assert!(NonNanF32::new(f32::from_bits(0x7F80_0001)).is_none());
501        assert!(NonNanF32::new(f32::from_bits(0xFFFF_FFFF)).is_none());
502        // infinities are NOT NaN, so allowed
503        assert_eq!(NonNanF32::new(f32::INFINITY).unwrap().get(), f32::INFINITY);
504        assert_eq!(NonNanF32::new(-2.5).unwrap().get(), -2.5);
505    }
506
507    #[test]
508    fn noninf_rejects_both_infinities_but_keeps_nan() {
509        assert!(NonInfF32::new(f32::INFINITY).is_none());
510        assert!(NonInfF32::new(f32::NEG_INFINITY).is_none());
511        // NaN is not infinite, so allowed (and thus NonInf is NOT Eq/Ord)
512        assert!(NonInfF64::new(f64::NAN).unwrap().get().is_nan());
513        assert_eq!(NonInfF32::new(3.0).unwrap().get(), 3.0);
514    }
515
516    #[test]
517    #[cfg(feature = "std")] // ordered/hashed containers
518    fn nonnan_is_totally_ordered_and_hashable() {
519        assert_total_order_f64(|v| NonNanF64::new(v).unwrap(), |x| x.get());
520        assert_signed_zero_eq_hash_f32(|v| NonNanF32::new(v).unwrap());
521    }
522
523    #[test]
524    fn nonnan_signed_zero_roundtrips_but_compares_equal() {
525        let pos = NonNanF32::new(0.0).unwrap();
526        let neg = NonNanF32::new(-0.0).unwrap();
527        assert_eq!(pos, neg); // value equality
528        assert_eq!(pos.cmp(&neg), core::cmp::Ordering::Equal);
529        // but get() is lossless on the sign bit
530        assert!(pos.get().is_sign_positive());
531        assert!(neg.get().is_sign_negative());
532    }
533
534    #[test]
535    fn nonzero_rejects_both_signed_zeros_but_keeps_nan() {
536        // Both +0.0 and -0.0 are rejected as a *class* (unlike bit-exact
537        // NonValueF32<0x0000_0000>, which forbids only +0.0).
538        assert!(NonZeroF32::new(0.0).is_none());
539        assert!(NonZeroF32::new(-0.0).is_none());
540        assert!(NonZeroF64::new(0.0).is_none());
541        assert!(NonZeroF64::new(-0.0).is_none());
542        // nonzero values (including NaN and infinities) round-trip
543        assert_eq!(NonZeroF32::new(1.5).unwrap().get(), 1.5);
544        assert_eq!(NonZeroF32::new(-2.0).unwrap().get(), -2.0);
545        assert_eq!(
546            NonZeroF32::new(f32::MIN_POSITIVE).unwrap().get(),
547            f32::MIN_POSITIVE
548        );
549        assert!(NonZeroF64::new(f64::NAN).unwrap().get().is_nan());
550        assert_eq!(NonZeroF32::new(f32::INFINITY).unwrap().get(), f32::INFINITY);
551        assert_eq!(size_of::<Option<NonZeroF32>>(), size_of::<f32>());
552        assert_eq!(size_of::<Option<NonZeroF64>>(), size_of::<f64>());
553    }
554
555    #[test]
556    fn finite_rejects_nan_and_both_infinities() {
557        // Finite = NonNan ∩ NonInf: rejects the whole non-finite class.
558        assert!(FiniteF32::new(f32::NAN).is_none());
559        assert!(FiniteF32::new(f32::from_bits(0x7F80_0001)).is_none()); // another NaN
560        assert!(FiniteF32::new(f32::INFINITY).is_none());
561        assert!(FiniteF32::new(f32::NEG_INFINITY).is_none());
562        assert!(FiniteF64::new(f64::NAN).is_none());
563        assert!(FiniteF64::new(f64::INFINITY).is_none());
564        assert!(FiniteF64::new(f64::NEG_INFINITY).is_none());
565        // finite values (including subnormals and zeros) round-trip
566        assert_eq!(FiniteF32::new(1.5).unwrap().get(), 1.5);
567        assert_eq!(FiniteF64::new(-2.5).unwrap().get(), -2.5);
568        assert_eq!(FiniteF32::new(0.0).unwrap().get(), 0.0);
569        assert_eq!(size_of::<Option<FiniteF32>>(), size_of::<f32>());
570        assert_eq!(size_of::<Option<FiniteF64>>(), size_of::<f64>());
571    }
572
573    #[test]
574    #[cfg(feature = "std")] // ordered/hashed containers
575    fn finite_is_totally_ordered_and_hashable() {
576        assert_total_order_f64(|v| FiniteF64::new(v).unwrap(), |x| x.get());
577        assert_signed_zero_eq_hash_f32(|v| FiniteF32::new(v).unwrap());
578        // +0.0 and -0.0 compare and hash equal, but get() keeps the sign.
579        assert!(FiniteF32::new(-0.0).unwrap().get().is_sign_negative());
580    }
581
582    #[test]
583    fn nonsubnormal_rejects_subnormals_but_keeps_nan_zero_and_normals() {
584        // Smallest positive subnormal and a mid-range subnormal are rejected.
585        assert!(NonSubnormalF32::new(f32::from_bits(0x0000_0001)).is_none());
586        assert!(NonSubnormalF32::new(f32::from_bits(0x0040_0000)).is_none()); // larger subnormal
587        assert!(NonSubnormalF64::new(f64::from_bits(0x0000_0000_0000_0001)).is_none());
588        // Negative subnormals (sign bit set) are subnormal too, so also rejected.
589        assert!(NonSubnormalF32::new(f32::from_bits(0x8000_0001)).is_none());
590        assert!(NonSubnormalF64::new(f64::from_bits(0x8000_0000_0000_0001)).is_none());
591        // -0.0/+0.0 are NOT subnormal, so allowed; NaN allowed; normals allowed.
592        assert_eq!(NonSubnormalF32::new(0.0).unwrap().get(), 0.0);
593        assert!(NonSubnormalF32::new(-0.0).unwrap().get().is_sign_negative());
594        assert!(NonSubnormalF64::new(f64::NAN).unwrap().get().is_nan());
595        assert_eq!(
596            NonSubnormalF32::new(f32::MIN_POSITIVE).unwrap().get(),
597            f32::MIN_POSITIVE
598        );
599        assert_eq!(NonSubnormalF64::new(1.5).unwrap().get(), 1.5);
600        assert_eq!(size_of::<Option<NonSubnormalF32>>(), size_of::<f32>());
601        assert_eq!(size_of::<Option<NonSubnormalF64>>(), size_of::<f64>());
602    }
603
604    #[test]
605    fn sizes_niche_optimized() {
606        assert_eq!(size_of::<Option<NonValueF32<7>>>(), size_of::<f32>());
607        assert_eq!(size_of::<Option<NonMaxF64>>(), size_of::<f64>());
608        assert_eq!(size_of::<Option<NonNanF32>>(), size_of::<f32>());
609        assert_eq!(size_of::<Option<NonNanF64>>(), size_of::<f64>());
610        assert_eq!(size_of::<Option<NonInfF32>>(), size_of::<f32>());
611    }
612
613    #[test]
614    #[cfg(feature = "std")] // uses `format!`
615    fn fmt_and_parse() {
616        let v = NonNanF64::new(1.5).unwrap();
617        assert_eq!(format!("{v}"), "1.5");
618        assert_eq!(format!("{v:e}"), format!("{:e}", 1.5f64));
619        let p: NonNanF32 = "2.5".parse().unwrap();
620        assert_eq!(p.get(), 2.5);
621        assert!("NaN".parse::<NonNanF32>().is_err());
622    }
623
624    #[test]
625    #[cfg(feature = "serde")]
626    fn serde_roundtrip() {
627        let v = NonNanF64::new(1.25).unwrap();
628        let bytes = bincode::serialize(&v).unwrap();
629        let back: NonNanF64 = bincode::deserialize(&bytes).unwrap();
630        assert_eq!(v, back);
631    }
632
633    #[test]
634    #[cfg(feature = "serde")]
635    fn serde_signed_zero_and_nan_payload() {
636        // bincode preserves IEEE-754 bits, so the value-based serde impls keep
637        // signed zero and specific NaN payloads exact across a round trip.
638        let neg_zero = NonValueF32::<0x0000_0000>::new(-0.0).unwrap();
639        let bytes = bincode::serialize(&neg_zero).unwrap();
640        let back: NonValueF32<0x0000_0000> = bincode::deserialize(&bytes).unwrap();
641        assert_eq!(back.get().to_bits(), 0x8000_0000);
642        assert!(back.get().is_sign_negative());
643
644        // A payloaded NaN (not `f32::MAX`) survives a bit-preserving round trip.
645        let payload_nan = NonMaxF32::new(f32::from_bits(0x7F80_0001)).unwrap();
646        let bytes = bincode::serialize(&payload_nan).unwrap();
647        let back: NonMaxF32 = bincode::deserialize(&bytes).unwrap();
648        assert_eq!(back.get().to_bits(), 0x7F80_0001);
649    }
650}