ordered_float/
lib.rs

1#![no_std]
2#![cfg_attr(test, deny(warnings))]
3#![deny(missing_docs)]
4#![allow(clippy::derive_partial_eq_without_eq)]
5
6//! Wrappers for total order on Floats.  See the [`OrderedFloat`] and [`NotNan`] docs for details.
7
8#[cfg(feature = "std")]
9extern crate std;
10#[cfg(feature = "std")]
11use std::error::Error;
12
13use core::borrow::Borrow;
14use core::cmp::Ordering;
15use core::convert::TryFrom;
16use core::fmt;
17use core::hash::{Hash, Hasher};
18use core::iter::{Product, Sum};
19use core::num::FpCategory;
20use core::ops::{
21    Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub,
22    SubAssign,
23};
24use core::str::FromStr;
25
26pub use num_traits::float::FloatCore;
27#[cfg(any(feature = "std", feature = "libm"))]
28use num_traits::real::Real;
29use num_traits::{
30    AsPrimitive, Bounded, FloatConst, FromPrimitive, Num, NumCast, One, Signed, ToPrimitive, Zero,
31};
32#[cfg(any(feature = "std", feature = "libm"))]
33pub use num_traits::{Float, Pow};
34
35#[cfg(feature = "rand")]
36pub use impl_rand::{UniformNotNan, UniformOrdered};
37
38/// A wrapper around floats providing implementations of `Eq`, `Ord`, and `Hash`.
39///
40/// NaN is sorted as *greater* than all other values and *equal*
41/// to itself, in contradiction with the IEEE standard.
42///
43/// ```
44/// use ordered_float::OrderedFloat;
45/// use std::f32::NAN;
46///
47/// let mut v = [OrderedFloat(NAN), OrderedFloat(2.0), OrderedFloat(1.0)];
48/// v.sort();
49/// assert_eq!(v, [OrderedFloat(1.0), OrderedFloat(2.0), OrderedFloat(NAN)]);
50/// ```
51///
52/// Because `OrderedFloat` implements `Ord` and `Eq`, it can be used as a key in a `HashSet`,
53/// `HashMap`, `BTreeMap`, or `BTreeSet` (unlike the primitive `f32` or `f64` types):
54///
55/// ```
56/// # use ordered_float::OrderedFloat;
57/// # use std::collections::HashSet;
58/// # use std::f32::NAN;
59/// let mut s: HashSet<OrderedFloat<f32>> = HashSet::new();
60/// s.insert(OrderedFloat(NAN));
61/// assert!(s.contains(&OrderedFloat(NAN)));
62/// ```
63///
64/// Some non-identical values are still considered equal by the [`PartialEq`] implementation,
65/// and will therefore also be considered equal by maps, sets, and the `==` operator:
66///
67/// * `-0.0` and `+0.0` are considered equal.
68///   This different sign may show up in printing, or when dividing by zero (the sign of the zero
69///   becomes the sign of the resulting infinity).
70/// * All NaN values are considered equal, even though they may have different
71///   [bits](https://doc.rust-lang.org/std/primitive.f64.html#method.to_bits), and therefore
72///   different [sign](https://doc.rust-lang.org/std/primitive.f64.html#method.is_sign_positive),
73///   signaling/quiet status, and NaN payload bits.
74///   
75/// Therefore, `OrderedFloat` may be unsuitable for use as a key in interning and memoization
76/// applications which require equal results from equal inputs, unless these cases make no
77/// difference or are canonicalized before insertion.
78///
79/// # Representation
80///
81/// `OrderedFloat` has `#[repr(transparent)]` and permits any value, so it is sound to use
82/// [transmute](core::mem::transmute) or pointer casts to convert between any type `T` and
83/// `OrderedFloat<T>`.
84/// However, consider using [`bytemuck`] as a safe alternative if possible.
85///
86#[cfg_attr(
87    not(feature = "bytemuck"),
88    doc = "[`bytemuck`]: https://docs.rs/bytemuck/1/"
89)]
90#[derive(Default, Clone, Copy)]
91#[repr(transparent)]
92pub struct OrderedFloat<T>(pub T);
93
94#[cfg(feature = "derive-visitor")]
95mod impl_derive_visitor {
96    use crate::OrderedFloat;
97    use derive_visitor::{Drive, DriveMut, Event, Visitor, VisitorMut};
98
99    impl<T: 'static> Drive for OrderedFloat<T> {
100        fn drive<V: Visitor>(&self, visitor: &mut V) {
101            visitor.visit(self, Event::Enter);
102            visitor.visit(self, Event::Exit);
103        }
104    }
105
106    impl<T: 'static> DriveMut for OrderedFloat<T> {
107        fn drive_mut<V: VisitorMut>(&mut self, visitor: &mut V) {
108            visitor.visit(self, Event::Enter);
109            visitor.visit(self, Event::Exit);
110        }
111    }
112
113    #[test]
114    pub fn test_derive_visitor() {
115        #[derive(Debug, Clone, PartialEq, Eq, Drive, DriveMut)]
116        pub enum Literal {
117            Null,
118            Float(OrderedFloat<f64>),
119        }
120
121        #[derive(Visitor, VisitorMut)]
122        #[visitor(Literal(enter))]
123        struct FloatExpr(bool);
124
125        impl FloatExpr {
126            fn enter_literal(&mut self, lit: &Literal) {
127                if let Literal::Float(_) = lit {
128                    self.0 = true;
129                }
130            }
131        }
132
133        assert!({
134            let mut visitor = FloatExpr(false);
135            Literal::Null.drive(&mut visitor);
136            !visitor.0
137        });
138
139        assert!({
140            let mut visitor = FloatExpr(false);
141            Literal::Null.drive_mut(&mut visitor);
142            !visitor.0
143        });
144
145        assert!({
146            let mut visitor = FloatExpr(false);
147            Literal::Float(OrderedFloat(0.0)).drive(&mut visitor);
148            visitor.0
149        });
150
151        assert!({
152            let mut visitor = FloatExpr(false);
153            Literal::Float(OrderedFloat(0.0)).drive_mut(&mut visitor);
154            visitor.0
155        });
156    }
157}
158
159#[cfg(feature = "num-cmp")]
160mod impl_num_cmp {
161    use super::OrderedFloat;
162    use core::cmp::Ordering;
163    use num_cmp::NumCmp;
164    use num_traits::float::FloatCore;
165
166    impl<T, U> NumCmp<U> for OrderedFloat<T>
167    where
168        T: FloatCore + NumCmp<U>,
169        U: Copy,
170    {
171        fn num_cmp(self, other: U) -> Option<Ordering> {
172            NumCmp::num_cmp(self.0, other)
173        }
174
175        fn num_eq(self, other: U) -> bool {
176            NumCmp::num_eq(self.0, other)
177        }
178
179        fn num_ne(self, other: U) -> bool {
180            NumCmp::num_ne(self.0, other)
181        }
182
183        fn num_lt(self, other: U) -> bool {
184            NumCmp::num_lt(self.0, other)
185        }
186
187        fn num_gt(self, other: U) -> bool {
188            NumCmp::num_gt(self.0, other)
189        }
190
191        fn num_le(self, other: U) -> bool {
192            NumCmp::num_le(self.0, other)
193        }
194
195        fn num_ge(self, other: U) -> bool {
196            NumCmp::num_ge(self.0, other)
197        }
198    }
199
200    #[test]
201    pub fn test_num_cmp() {
202        let f = OrderedFloat(1.0);
203
204        assert_eq!(NumCmp::num_cmp(f, 1.0), Some(Ordering::Equal));
205        assert_eq!(NumCmp::num_cmp(f, -1.0), Some(Ordering::Greater));
206        assert_eq!(NumCmp::num_cmp(f, 2.0), Some(Ordering::Less));
207
208        assert!(NumCmp::num_eq(f, 1));
209        assert!(NumCmp::num_ne(f, -1));
210        assert!(NumCmp::num_lt(f, 100));
211        assert!(NumCmp::num_gt(f, 0));
212        assert!(NumCmp::num_le(f, 1));
213        assert!(NumCmp::num_le(f, 2));
214        assert!(NumCmp::num_ge(f, 1));
215        assert!(NumCmp::num_ge(f, -1));
216    }
217}
218
219impl<T: FloatCore> OrderedFloat<T> {
220    /// Get the value out.
221    #[inline]
222    pub fn into_inner(self) -> T {
223        self.0
224    }
225}
226
227impl<T: FloatCore> AsRef<T> for OrderedFloat<T> {
228    #[inline]
229    fn as_ref(&self) -> &T {
230        &self.0
231    }
232}
233
234impl<T: FloatCore> AsMut<T> for OrderedFloat<T> {
235    #[inline]
236    fn as_mut(&mut self) -> &mut T {
237        &mut self.0
238    }
239}
240
241impl<'a, T: FloatCore> From<&'a T> for &'a OrderedFloat<T> {
242    #[inline]
243    fn from(t: &'a T) -> &'a OrderedFloat<T> {
244        // Safety: OrderedFloat is #[repr(transparent)] and has no invalid values.
245        unsafe { &*(t as *const T as *const OrderedFloat<T>) }
246    }
247}
248
249impl<'a, T: FloatCore> From<&'a mut T> for &'a mut OrderedFloat<T> {
250    #[inline]
251    fn from(t: &'a mut T) -> &'a mut OrderedFloat<T> {
252        // Safety: OrderedFloat is #[repr(transparent)] and has no invalid values.
253        unsafe { &mut *(t as *mut T as *mut OrderedFloat<T>) }
254    }
255}
256
257impl<T: FloatCore> PartialOrd for OrderedFloat<T> {
258    #[inline]
259    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
260        Some(self.cmp(other))
261    }
262
263    #[inline]
264    fn lt(&self, other: &Self) -> bool {
265        !self.ge(other)
266    }
267
268    #[inline]
269    fn le(&self, other: &Self) -> bool {
270        other.ge(self)
271    }
272
273    #[inline]
274    fn gt(&self, other: &Self) -> bool {
275        !other.ge(self)
276    }
277
278    #[inline]
279    fn ge(&self, other: &Self) -> bool {
280        // We consider all NaNs equal, and NaN is the largest possible
281        // value. Thus if self is NaN we always return true. Otherwise
282        // self >= other is correct. If other is also not NaN it is trivially
283        // correct, and if it is we note that nothing can be greater or
284        // equal to NaN except NaN itself, which we already handled earlier.
285        self.0.is_nan() | (self.0 >= other.0)
286    }
287}
288
289impl<T: FloatCore> Ord for OrderedFloat<T> {
290    #[inline]
291    fn cmp(&self, other: &Self) -> Ordering {
292        #[allow(clippy::comparison_chain)]
293        if self < other {
294            Ordering::Less
295        } else if self > other {
296            Ordering::Greater
297        } else {
298            Ordering::Equal
299        }
300    }
301}
302
303impl<T: FloatCore> PartialEq for OrderedFloat<T> {
304    #[inline]
305    fn eq(&self, other: &OrderedFloat<T>) -> bool {
306        if self.0.is_nan() {
307            other.0.is_nan()
308        } else {
309            self.0 == other.0
310        }
311    }
312}
313
314impl<T: FloatCore> PartialEq<T> for OrderedFloat<T> {
315    #[inline]
316    fn eq(&self, other: &T) -> bool {
317        self.0 == *other
318    }
319}
320
321impl<T: fmt::Debug> fmt::Debug for OrderedFloat<T> {
322    #[inline]
323    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
324        self.0.fmt(f)
325    }
326}
327
328impl<T: FloatCore + fmt::Display> fmt::Display for OrderedFloat<T> {
329    #[inline]
330    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
331        self.0.fmt(f)
332    }
333}
334
335impl<T: FloatCore + fmt::LowerExp> fmt::LowerExp for OrderedFloat<T> {
336    #[inline]
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        self.0.fmt(f)
339    }
340}
341
342impl<T: FloatCore + fmt::UpperExp> fmt::UpperExp for OrderedFloat<T> {
343    #[inline]
344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345        self.0.fmt(f)
346    }
347}
348
349impl From<OrderedFloat<f32>> for f32 {
350    #[inline]
351    fn from(f: OrderedFloat<f32>) -> f32 {
352        f.0
353    }
354}
355
356impl From<OrderedFloat<f64>> for f64 {
357    #[inline]
358    fn from(f: OrderedFloat<f64>) -> f64 {
359        f.0
360    }
361}
362
363impl<T: FloatCore> From<T> for OrderedFloat<T> {
364    #[inline]
365    fn from(val: T) -> Self {
366        OrderedFloat(val)
367    }
368}
369
370impl From<bool> for OrderedFloat<f32> {
371    fn from(val: bool) -> Self {
372        OrderedFloat(val as u8 as f32)
373    }
374}
375
376impl From<bool> for OrderedFloat<f64> {
377    fn from(val: bool) -> Self {
378        OrderedFloat(val as u8 as f64)
379    }
380}
381
382macro_rules! impl_ordered_float_from {
383    ($dst:ty, $src:ty) => {
384        impl From<$src> for OrderedFloat<$dst> {
385            fn from(val: $src) -> Self {
386                OrderedFloat(val.into())
387            }
388        }
389    };
390}
391impl_ordered_float_from! {f64, i8}
392impl_ordered_float_from! {f64, i16}
393impl_ordered_float_from! {f64, i32}
394impl_ordered_float_from! {f64, u8}
395impl_ordered_float_from! {f64, u16}
396impl_ordered_float_from! {f64, u32}
397impl_ordered_float_from! {f32, i8}
398impl_ordered_float_from! {f32, i16}
399impl_ordered_float_from! {f32, u8}
400impl_ordered_float_from! {f32, u16}
401
402impl<T: FloatCore> Deref for OrderedFloat<T> {
403    type Target = T;
404
405    #[inline]
406    fn deref(&self) -> &Self::Target {
407        &self.0
408    }
409}
410
411impl<T: FloatCore> DerefMut for OrderedFloat<T> {
412    #[inline]
413    fn deref_mut(&mut self) -> &mut Self::Target {
414        &mut self.0
415    }
416}
417
418impl<T: FloatCore> Eq for OrderedFloat<T> {}
419
420macro_rules! impl_ordered_float_binop {
421    ($imp:ident, $method:ident, $assign_imp:ident, $assign_method:ident) => {
422        impl<T: $imp> $imp for OrderedFloat<T> {
423            type Output = OrderedFloat<T::Output>;
424
425            #[inline]
426            fn $method(self, other: Self) -> Self::Output {
427                OrderedFloat((self.0).$method(other.0))
428            }
429        }
430
431        // Work around for: https://github.com/reem/rust-ordered-float/issues/91
432        impl<'a, T: $imp + Copy> $imp<Self> for &'a OrderedFloat<T> {
433            type Output = OrderedFloat<T::Output>;
434
435            #[inline]
436            fn $method(self, other: Self) -> Self::Output {
437                OrderedFloat((self.0).$method(other.0))
438            }
439        }
440
441        impl<T: $imp> $imp<T> for OrderedFloat<T> {
442            type Output = OrderedFloat<T::Output>;
443
444            #[inline]
445            fn $method(self, other: T) -> Self::Output {
446                OrderedFloat((self.0).$method(other))
447            }
448        }
449
450        impl<'a, T> $imp<&'a T> for OrderedFloat<T>
451        where
452            T: $imp<&'a T>,
453        {
454            type Output = OrderedFloat<<T as $imp<&'a T>>::Output>;
455
456            #[inline]
457            fn $method(self, other: &'a T) -> Self::Output {
458                OrderedFloat((self.0).$method(other))
459            }
460        }
461
462        impl<'a, T> $imp<&'a Self> for OrderedFloat<T>
463        where
464            T: $imp<&'a T>,
465        {
466            type Output = OrderedFloat<<T as $imp<&'a T>>::Output>;
467
468            #[inline]
469            fn $method(self, other: &'a Self) -> Self::Output {
470                OrderedFloat((self.0).$method(&other.0))
471            }
472        }
473
474        impl<'a, T> $imp<OrderedFloat<T>> for &'a OrderedFloat<T>
475        where
476            &'a T: $imp<T>,
477        {
478            type Output = OrderedFloat<<&'a T as $imp<T>>::Output>;
479
480            #[inline]
481            fn $method(self, other: OrderedFloat<T>) -> Self::Output {
482                OrderedFloat((self.0).$method(other.0))
483            }
484        }
485
486        impl<'a, T> $imp<T> for &'a OrderedFloat<T>
487        where
488            &'a T: $imp<T>,
489        {
490            type Output = OrderedFloat<<&'a T as $imp<T>>::Output>;
491
492            #[inline]
493            fn $method(self, other: T) -> Self::Output {
494                OrderedFloat((self.0).$method(other))
495            }
496        }
497
498        impl<'a, T> $imp<&'a T> for &'a OrderedFloat<T>
499        where
500            &'a T: $imp,
501        {
502            type Output = OrderedFloat<<&'a T as $imp>::Output>;
503
504            #[inline]
505            fn $method(self, other: &'a T) -> Self::Output {
506                OrderedFloat((self.0).$method(other))
507            }
508        }
509
510        impl<T: $assign_imp> $assign_imp<T> for OrderedFloat<T> {
511            #[inline]
512            fn $assign_method(&mut self, other: T) {
513                (self.0).$assign_method(other);
514            }
515        }
516
517        impl<'a, T: $assign_imp<&'a T>> $assign_imp<&'a T> for OrderedFloat<T> {
518            #[inline]
519            fn $assign_method(&mut self, other: &'a T) {
520                (self.0).$assign_method(other);
521            }
522        }
523
524        impl<T: $assign_imp> $assign_imp for OrderedFloat<T> {
525            #[inline]
526            fn $assign_method(&mut self, other: Self) {
527                (self.0).$assign_method(other.0);
528            }
529        }
530
531        impl<'a, T: $assign_imp<&'a T>> $assign_imp<&'a Self> for OrderedFloat<T> {
532            #[inline]
533            fn $assign_method(&mut self, other: &'a Self) {
534                (self.0).$assign_method(&other.0);
535            }
536        }
537    };
538}
539
540impl_ordered_float_binop! {Add, add, AddAssign, add_assign}
541impl_ordered_float_binop! {Sub, sub, SubAssign, sub_assign}
542impl_ordered_float_binop! {Mul, mul, MulAssign, mul_assign}
543impl_ordered_float_binop! {Div, div, DivAssign, div_assign}
544impl_ordered_float_binop! {Rem, rem, RemAssign, rem_assign}
545
546macro_rules! impl_ordered_float_pow {
547    ($inner:ty, $rhs:ty) => {
548        #[cfg(any(feature = "std", feature = "libm"))]
549        impl Pow<$rhs> for OrderedFloat<$inner> {
550            type Output = OrderedFloat<$inner>;
551            #[inline]
552            fn pow(self, rhs: $rhs) -> OrderedFloat<$inner> {
553                OrderedFloat(<$inner>::pow(self.0, rhs))
554            }
555        }
556
557        #[cfg(any(feature = "std", feature = "libm"))]
558        impl<'a> Pow<&'a $rhs> for OrderedFloat<$inner> {
559            type Output = OrderedFloat<$inner>;
560            #[inline]
561            fn pow(self, rhs: &'a $rhs) -> OrderedFloat<$inner> {
562                OrderedFloat(<$inner>::pow(self.0, *rhs))
563            }
564        }
565
566        #[cfg(any(feature = "std", feature = "libm"))]
567        impl<'a> Pow<$rhs> for &'a OrderedFloat<$inner> {
568            type Output = OrderedFloat<$inner>;
569            #[inline]
570            fn pow(self, rhs: $rhs) -> OrderedFloat<$inner> {
571                OrderedFloat(<$inner>::pow(self.0, rhs))
572            }
573        }
574
575        #[cfg(any(feature = "std", feature = "libm"))]
576        impl<'a, 'b> Pow<&'a $rhs> for &'b OrderedFloat<$inner> {
577            type Output = OrderedFloat<$inner>;
578            #[inline]
579            fn pow(self, rhs: &'a $rhs) -> OrderedFloat<$inner> {
580                OrderedFloat(<$inner>::pow(self.0, *rhs))
581            }
582        }
583    };
584}
585
586impl_ordered_float_pow! {f32, i8}
587impl_ordered_float_pow! {f32, i16}
588impl_ordered_float_pow! {f32, u8}
589impl_ordered_float_pow! {f32, u16}
590impl_ordered_float_pow! {f32, i32}
591impl_ordered_float_pow! {f64, i8}
592impl_ordered_float_pow! {f64, i16}
593impl_ordered_float_pow! {f64, u8}
594impl_ordered_float_pow! {f64, u16}
595impl_ordered_float_pow! {f64, i32}
596impl_ordered_float_pow! {f32, f32}
597impl_ordered_float_pow! {f64, f32}
598impl_ordered_float_pow! {f64, f64}
599
600macro_rules! impl_ordered_float_self_pow {
601    ($base:ty, $exp:ty) => {
602        #[cfg(any(feature = "std", feature = "libm"))]
603        impl Pow<OrderedFloat<$exp>> for OrderedFloat<$base> {
604            type Output = OrderedFloat<$base>;
605            #[inline]
606            fn pow(self, rhs: OrderedFloat<$exp>) -> OrderedFloat<$base> {
607                OrderedFloat(<$base>::pow(self.0, rhs.0))
608            }
609        }
610
611        #[cfg(any(feature = "std", feature = "libm"))]
612        impl<'a> Pow<&'a OrderedFloat<$exp>> for OrderedFloat<$base> {
613            type Output = OrderedFloat<$base>;
614            #[inline]
615            fn pow(self, rhs: &'a OrderedFloat<$exp>) -> OrderedFloat<$base> {
616                OrderedFloat(<$base>::pow(self.0, rhs.0))
617            }
618        }
619
620        #[cfg(any(feature = "std", feature = "libm"))]
621        impl<'a> Pow<OrderedFloat<$exp>> for &'a OrderedFloat<$base> {
622            type Output = OrderedFloat<$base>;
623            #[inline]
624            fn pow(self, rhs: OrderedFloat<$exp>) -> OrderedFloat<$base> {
625                OrderedFloat(<$base>::pow(self.0, rhs.0))
626            }
627        }
628
629        #[cfg(any(feature = "std", feature = "libm"))]
630        impl<'a, 'b> Pow<&'a OrderedFloat<$exp>> for &'b OrderedFloat<$base> {
631            type Output = OrderedFloat<$base>;
632            #[inline]
633            fn pow(self, rhs: &'a OrderedFloat<$exp>) -> OrderedFloat<$base> {
634                OrderedFloat(<$base>::pow(self.0, rhs.0))
635            }
636        }
637    };
638}
639
640impl_ordered_float_self_pow! {f32, f32}
641impl_ordered_float_self_pow! {f64, f32}
642impl_ordered_float_self_pow! {f64, f64}
643
644/// Adds a float directly.
645impl<T: FloatCore + Sum> Sum for OrderedFloat<T> {
646    fn sum<I: Iterator<Item = OrderedFloat<T>>>(iter: I) -> Self {
647        OrderedFloat(iter.map(|v| v.0).sum())
648    }
649}
650
651impl<'a, T: FloatCore + Sum + 'a> Sum<&'a OrderedFloat<T>> for OrderedFloat<T> {
652    #[inline]
653    fn sum<I: Iterator<Item = &'a OrderedFloat<T>>>(iter: I) -> Self {
654        iter.cloned().sum()
655    }
656}
657
658impl<T: FloatCore + Product> Product for OrderedFloat<T> {
659    fn product<I: Iterator<Item = OrderedFloat<T>>>(iter: I) -> Self {
660        OrderedFloat(iter.map(|v| v.0).product())
661    }
662}
663
664impl<'a, T: FloatCore + Product + 'a> Product<&'a OrderedFloat<T>> for OrderedFloat<T> {
665    #[inline]
666    fn product<I: Iterator<Item = &'a OrderedFloat<T>>>(iter: I) -> Self {
667        iter.cloned().product()
668    }
669}
670
671impl<T: FloatCore + Signed> Signed for OrderedFloat<T> {
672    #[inline]
673    fn abs(&self) -> Self {
674        OrderedFloat(self.0.abs())
675    }
676
677    fn abs_sub(&self, other: &Self) -> Self {
678        OrderedFloat(Signed::abs_sub(&self.0, &other.0))
679    }
680
681    #[inline]
682    fn signum(&self) -> Self {
683        OrderedFloat(self.0.signum())
684    }
685    #[inline]
686    fn is_positive(&self) -> bool {
687        self.0.is_positive()
688    }
689    #[inline]
690    fn is_negative(&self) -> bool {
691        self.0.is_negative()
692    }
693}
694
695impl<T: Bounded> Bounded for OrderedFloat<T> {
696    #[inline]
697    fn min_value() -> Self {
698        OrderedFloat(T::min_value())
699    }
700
701    #[inline]
702    fn max_value() -> Self {
703        OrderedFloat(T::max_value())
704    }
705}
706
707impl<T: FromStr> FromStr for OrderedFloat<T> {
708    type Err = T::Err;
709
710    /// Convert a &str to `OrderedFloat`. Returns an error if the string fails to parse.
711    ///
712    /// ```
713    /// use ordered_float::OrderedFloat;
714    ///
715    /// assert!("-10".parse::<OrderedFloat<f32>>().is_ok());
716    /// assert!("abc".parse::<OrderedFloat<f32>>().is_err());
717    /// assert!("NaN".parse::<OrderedFloat<f32>>().is_ok());
718    /// ```
719    fn from_str(s: &str) -> Result<Self, Self::Err> {
720        T::from_str(s).map(OrderedFloat)
721    }
722}
723
724impl<T: Neg> Neg for OrderedFloat<T> {
725    type Output = OrderedFloat<T::Output>;
726
727    #[inline]
728    fn neg(self) -> Self::Output {
729        OrderedFloat(-self.0)
730    }
731}
732
733impl<'a, T> Neg for &'a OrderedFloat<T>
734where
735    &'a T: Neg,
736{
737    type Output = OrderedFloat<<&'a T as Neg>::Output>;
738
739    #[inline]
740    fn neg(self) -> Self::Output {
741        OrderedFloat(-(&self.0))
742    }
743}
744
745impl<T: Zero> Zero for OrderedFloat<T> {
746    #[inline]
747    fn zero() -> Self {
748        OrderedFloat(T::zero())
749    }
750
751    #[inline]
752    fn is_zero(&self) -> bool {
753        self.0.is_zero()
754    }
755}
756
757impl<T: One> One for OrderedFloat<T> {
758    #[inline]
759    fn one() -> Self {
760        OrderedFloat(T::one())
761    }
762}
763
764impl<T: NumCast> NumCast for OrderedFloat<T> {
765    #[inline]
766    fn from<F: ToPrimitive>(n: F) -> Option<Self> {
767        T::from(n).map(OrderedFloat)
768    }
769}
770
771macro_rules! impl_as_primitive {
772    (@ (NotNan<$T: ty>) => $(#[$cfg:meta])* impl (NotNan<$U: ty>) ) => {
773        $(#[$cfg])*
774        impl AsPrimitive<NotNan<$U>> for NotNan<$T> {
775            #[inline] fn as_(self) -> NotNan<$U> {
776                // Safety: `NotNan` guarantees that the value is not NaN.
777                unsafe {NotNan::new_unchecked(self.0 as $U) }
778            }
779        }
780    };
781    (@ ($T: ty) => $(#[$cfg:meta])* impl (NotNan<$U: ty>) ) => {
782        $(#[$cfg])*
783        impl AsPrimitive<NotNan<$U>> for $T {
784            #[inline] fn as_(self) -> NotNan<$U> { NotNan(self as $U) }
785        }
786    };
787    (@ (NotNan<$T: ty>) => $(#[$cfg:meta])* impl ($U: ty) ) => {
788        $(#[$cfg])*
789        impl AsPrimitive<$U> for NotNan<$T> {
790            #[inline] fn as_(self) -> $U { self.0 as $U }
791        }
792    };
793    (@ (OrderedFloat<$T: ty>) => $(#[$cfg:meta])* impl (OrderedFloat<$U: ty>) ) => {
794        $(#[$cfg])*
795        impl AsPrimitive<OrderedFloat<$U>> for OrderedFloat<$T> {
796            #[inline] fn as_(self) -> OrderedFloat<$U> { OrderedFloat(self.0 as $U) }
797        }
798    };
799    (@ ($T: ty) => $(#[$cfg:meta])* impl (OrderedFloat<$U: ty>) ) => {
800        $(#[$cfg])*
801        impl AsPrimitive<OrderedFloat<$U>> for $T {
802            #[inline] fn as_(self) -> OrderedFloat<$U> { OrderedFloat(self as $U) }
803        }
804    };
805    (@ (OrderedFloat<$T: ty>) => $(#[$cfg:meta])* impl ($U: ty) ) => {
806        $(#[$cfg])*
807        impl AsPrimitive<$U> for OrderedFloat<$T> {
808            #[inline] fn as_(self) -> $U { self.0 as $U }
809        }
810    };
811    ($T: tt => { $( $U: tt ),* } ) => {$(
812        impl_as_primitive!(@ $T => impl $U);
813    )*};
814}
815
816impl_as_primitive!((OrderedFloat<f32>) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
817impl_as_primitive!((OrderedFloat<f64>) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
818
819impl_as_primitive!((NotNan<f32>) => { (NotNan<f32>), (NotNan<f64>) });
820impl_as_primitive!((NotNan<f64>) => { (NotNan<f32>), (NotNan<f64>) });
821
822impl_as_primitive!((u8) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
823impl_as_primitive!((i8) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
824impl_as_primitive!((u16) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
825impl_as_primitive!((i16) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
826impl_as_primitive!((u32) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
827impl_as_primitive!((i32) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
828impl_as_primitive!((u64) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
829impl_as_primitive!((i64) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
830impl_as_primitive!((usize) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
831impl_as_primitive!((isize) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
832impl_as_primitive!((f32) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
833impl_as_primitive!((f64) => { (OrderedFloat<f32>), (OrderedFloat<f64>) });
834
835impl_as_primitive!((u8) => { (NotNan<f32>), (NotNan<f64>) });
836impl_as_primitive!((i8) => { (NotNan<f32>), (NotNan<f64>) });
837impl_as_primitive!((u16) => { (NotNan<f32>), (NotNan<f64>) });
838impl_as_primitive!((i16) => { (NotNan<f32>), (NotNan<f64>) });
839impl_as_primitive!((u32) => { (NotNan<f32>), (NotNan<f64>) });
840impl_as_primitive!((i32) => { (NotNan<f32>), (NotNan<f64>) });
841impl_as_primitive!((u64) => { (NotNan<f32>), (NotNan<f64>) });
842impl_as_primitive!((i64) => { (NotNan<f32>), (NotNan<f64>) });
843impl_as_primitive!((usize) => { (NotNan<f32>), (NotNan<f64>) });
844impl_as_primitive!((isize) => { (NotNan<f32>), (NotNan<f64>) });
845
846impl_as_primitive!((OrderedFloat<f32>) => { (u8), (u16), (u32), (u64), (usize), (i8), (i16), (i32), (i64), (isize), (f32), (f64) });
847impl_as_primitive!((OrderedFloat<f64>) => { (u8), (u16), (u32), (u64), (usize), (i8), (i16), (i32), (i64), (isize), (f32), (f64) });
848
849impl_as_primitive!((NotNan<f32>) => { (u8), (u16), (u32), (u64), (usize), (i8), (i16), (i32), (i64), (isize), (f32), (f64) });
850impl_as_primitive!((NotNan<f64>) => { (u8), (u16), (u32), (u64), (usize), (i8), (i16), (i32), (i64), (isize), (f32), (f64) });
851
852impl<T: FromPrimitive> FromPrimitive for OrderedFloat<T> {
853    fn from_i64(n: i64) -> Option<Self> {
854        T::from_i64(n).map(OrderedFloat)
855    }
856    fn from_u64(n: u64) -> Option<Self> {
857        T::from_u64(n).map(OrderedFloat)
858    }
859    fn from_isize(n: isize) -> Option<Self> {
860        T::from_isize(n).map(OrderedFloat)
861    }
862    fn from_i8(n: i8) -> Option<Self> {
863        T::from_i8(n).map(OrderedFloat)
864    }
865    fn from_i16(n: i16) -> Option<Self> {
866        T::from_i16(n).map(OrderedFloat)
867    }
868    fn from_i32(n: i32) -> Option<Self> {
869        T::from_i32(n).map(OrderedFloat)
870    }
871    fn from_usize(n: usize) -> Option<Self> {
872        T::from_usize(n).map(OrderedFloat)
873    }
874    fn from_u8(n: u8) -> Option<Self> {
875        T::from_u8(n).map(OrderedFloat)
876    }
877    fn from_u16(n: u16) -> Option<Self> {
878        T::from_u16(n).map(OrderedFloat)
879    }
880    fn from_u32(n: u32) -> Option<Self> {
881        T::from_u32(n).map(OrderedFloat)
882    }
883    fn from_f32(n: f32) -> Option<Self> {
884        T::from_f32(n).map(OrderedFloat)
885    }
886    fn from_f64(n: f64) -> Option<Self> {
887        T::from_f64(n).map(OrderedFloat)
888    }
889}
890
891impl<T: ToPrimitive> ToPrimitive for OrderedFloat<T> {
892    fn to_i64(&self) -> Option<i64> {
893        self.0.to_i64()
894    }
895    fn to_u64(&self) -> Option<u64> {
896        self.0.to_u64()
897    }
898    fn to_isize(&self) -> Option<isize> {
899        self.0.to_isize()
900    }
901    fn to_i8(&self) -> Option<i8> {
902        self.0.to_i8()
903    }
904    fn to_i16(&self) -> Option<i16> {
905        self.0.to_i16()
906    }
907    fn to_i32(&self) -> Option<i32> {
908        self.0.to_i32()
909    }
910    fn to_usize(&self) -> Option<usize> {
911        self.0.to_usize()
912    }
913    fn to_u8(&self) -> Option<u8> {
914        self.0.to_u8()
915    }
916    fn to_u16(&self) -> Option<u16> {
917        self.0.to_u16()
918    }
919    fn to_u32(&self) -> Option<u32> {
920        self.0.to_u32()
921    }
922    fn to_f32(&self) -> Option<f32> {
923        self.0.to_f32()
924    }
925    fn to_f64(&self) -> Option<f64> {
926        self.0.to_f64()
927    }
928}
929
930impl<T: FloatCore> FloatCore for OrderedFloat<T> {
931    fn nan() -> Self {
932        OrderedFloat(T::nan())
933    }
934    fn infinity() -> Self {
935        OrderedFloat(T::infinity())
936    }
937    fn neg_infinity() -> Self {
938        OrderedFloat(T::neg_infinity())
939    }
940    fn neg_zero() -> Self {
941        OrderedFloat(T::neg_zero())
942    }
943    fn min_value() -> Self {
944        OrderedFloat(T::min_value())
945    }
946    fn min_positive_value() -> Self {
947        OrderedFloat(T::min_positive_value())
948    }
949    fn max_value() -> Self {
950        OrderedFloat(T::max_value())
951    }
952    fn is_nan(self) -> bool {
953        self.0.is_nan()
954    }
955    fn is_infinite(self) -> bool {
956        self.0.is_infinite()
957    }
958    fn is_finite(self) -> bool {
959        self.0.is_finite()
960    }
961    fn is_normal(self) -> bool {
962        self.0.is_normal()
963    }
964    fn classify(self) -> FpCategory {
965        self.0.classify()
966    }
967    fn floor(self) -> Self {
968        OrderedFloat(self.0.floor())
969    }
970    fn ceil(self) -> Self {
971        OrderedFloat(self.0.ceil())
972    }
973    fn round(self) -> Self {
974        OrderedFloat(self.0.round())
975    }
976    fn trunc(self) -> Self {
977        OrderedFloat(self.0.trunc())
978    }
979    fn fract(self) -> Self {
980        OrderedFloat(self.0.fract())
981    }
982    fn abs(self) -> Self {
983        OrderedFloat(self.0.abs())
984    }
985    fn signum(self) -> Self {
986        OrderedFloat(self.0.signum())
987    }
988    fn is_sign_positive(self) -> bool {
989        self.0.is_sign_positive()
990    }
991    fn is_sign_negative(self) -> bool {
992        self.0.is_sign_negative()
993    }
994    fn recip(self) -> Self {
995        OrderedFloat(self.0.recip())
996    }
997    fn powi(self, n: i32) -> Self {
998        OrderedFloat(self.0.powi(n))
999    }
1000    fn integer_decode(self) -> (u64, i16, i8) {
1001        self.0.integer_decode()
1002    }
1003    fn epsilon() -> Self {
1004        OrderedFloat(T::epsilon())
1005    }
1006    fn to_degrees(self) -> Self {
1007        OrderedFloat(self.0.to_degrees())
1008    }
1009    fn to_radians(self) -> Self {
1010        OrderedFloat(self.0.to_radians())
1011    }
1012}
1013
1014#[cfg(any(feature = "std", feature = "libm"))]
1015impl<T: Float + FloatCore> Float for OrderedFloat<T> {
1016    fn nan() -> Self {
1017        OrderedFloat(<T as Float>::nan())
1018    }
1019    fn infinity() -> Self {
1020        OrderedFloat(<T as Float>::infinity())
1021    }
1022    fn neg_infinity() -> Self {
1023        OrderedFloat(<T as Float>::neg_infinity())
1024    }
1025    fn neg_zero() -> Self {
1026        OrderedFloat(<T as Float>::neg_zero())
1027    }
1028    fn min_value() -> Self {
1029        OrderedFloat(<T as Float>::min_value())
1030    }
1031    fn min_positive_value() -> Self {
1032        OrderedFloat(<T as Float>::min_positive_value())
1033    }
1034    fn max_value() -> Self {
1035        OrderedFloat(<T as Float>::max_value())
1036    }
1037    fn is_nan(self) -> bool {
1038        Float::is_nan(self.0)
1039    }
1040    fn is_infinite(self) -> bool {
1041        Float::is_infinite(self.0)
1042    }
1043    fn is_finite(self) -> bool {
1044        Float::is_finite(self.0)
1045    }
1046    fn is_normal(self) -> bool {
1047        Float::is_normal(self.0)
1048    }
1049    fn classify(self) -> FpCategory {
1050        Float::classify(self.0)
1051    }
1052    fn floor(self) -> Self {
1053        OrderedFloat(Float::floor(self.0))
1054    }
1055    fn ceil(self) -> Self {
1056        OrderedFloat(Float::ceil(self.0))
1057    }
1058    fn round(self) -> Self {
1059        OrderedFloat(Float::round(self.0))
1060    }
1061    fn trunc(self) -> Self {
1062        OrderedFloat(Float::trunc(self.0))
1063    }
1064    fn fract(self) -> Self {
1065        OrderedFloat(Float::fract(self.0))
1066    }
1067    fn abs(self) -> Self {
1068        OrderedFloat(Float::abs(self.0))
1069    }
1070    fn signum(self) -> Self {
1071        OrderedFloat(Float::signum(self.0))
1072    }
1073    fn is_sign_positive(self) -> bool {
1074        Float::is_sign_positive(self.0)
1075    }
1076    fn is_sign_negative(self) -> bool {
1077        Float::is_sign_negative(self.0)
1078    }
1079    fn mul_add(self, a: Self, b: Self) -> Self {
1080        OrderedFloat(self.0.mul_add(a.0, b.0))
1081    }
1082    fn recip(self) -> Self {
1083        OrderedFloat(Float::recip(self.0))
1084    }
1085    fn powi(self, n: i32) -> Self {
1086        OrderedFloat(Float::powi(self.0, n))
1087    }
1088    fn powf(self, n: Self) -> Self {
1089        OrderedFloat(self.0.powf(n.0))
1090    }
1091    fn sqrt(self) -> Self {
1092        OrderedFloat(self.0.sqrt())
1093    }
1094    fn exp(self) -> Self {
1095        OrderedFloat(self.0.exp())
1096    }
1097    fn exp2(self) -> Self {
1098        OrderedFloat(self.0.exp2())
1099    }
1100    fn ln(self) -> Self {
1101        OrderedFloat(self.0.ln())
1102    }
1103    fn log(self, base: Self) -> Self {
1104        OrderedFloat(self.0.log(base.0))
1105    }
1106    fn log2(self) -> Self {
1107        OrderedFloat(self.0.log2())
1108    }
1109    fn log10(self) -> Self {
1110        OrderedFloat(self.0.log10())
1111    }
1112    fn max(self, other: Self) -> Self {
1113        OrderedFloat(Float::max(self.0, other.0))
1114    }
1115    fn min(self, other: Self) -> Self {
1116        OrderedFloat(Float::min(self.0, other.0))
1117    }
1118    fn abs_sub(self, other: Self) -> Self {
1119        OrderedFloat(self.0.abs_sub(other.0))
1120    }
1121    fn cbrt(self) -> Self {
1122        OrderedFloat(self.0.cbrt())
1123    }
1124    fn hypot(self, other: Self) -> Self {
1125        OrderedFloat(self.0.hypot(other.0))
1126    }
1127    fn sin(self) -> Self {
1128        OrderedFloat(self.0.sin())
1129    }
1130    fn cos(self) -> Self {
1131        OrderedFloat(self.0.cos())
1132    }
1133    fn tan(self) -> Self {
1134        OrderedFloat(self.0.tan())
1135    }
1136    fn asin(self) -> Self {
1137        OrderedFloat(self.0.asin())
1138    }
1139    fn acos(self) -> Self {
1140        OrderedFloat(self.0.acos())
1141    }
1142    fn atan(self) -> Self {
1143        OrderedFloat(self.0.atan())
1144    }
1145    fn atan2(self, other: Self) -> Self {
1146        OrderedFloat(self.0.atan2(other.0))
1147    }
1148    fn sin_cos(self) -> (Self, Self) {
1149        let (a, b) = self.0.sin_cos();
1150        (OrderedFloat(a), OrderedFloat(b))
1151    }
1152    fn exp_m1(self) -> Self {
1153        OrderedFloat(self.0.exp_m1())
1154    }
1155    fn ln_1p(self) -> Self {
1156        OrderedFloat(self.0.ln_1p())
1157    }
1158    fn sinh(self) -> Self {
1159        OrderedFloat(self.0.sinh())
1160    }
1161    fn cosh(self) -> Self {
1162        OrderedFloat(self.0.cosh())
1163    }
1164    fn tanh(self) -> Self {
1165        OrderedFloat(self.0.tanh())
1166    }
1167    fn asinh(self) -> Self {
1168        OrderedFloat(self.0.asinh())
1169    }
1170    fn acosh(self) -> Self {
1171        OrderedFloat(self.0.acosh())
1172    }
1173    fn atanh(self) -> Self {
1174        OrderedFloat(self.0.atanh())
1175    }
1176    fn integer_decode(self) -> (u64, i16, i8) {
1177        Float::integer_decode(self.0)
1178    }
1179    fn epsilon() -> Self {
1180        OrderedFloat(<T as Float>::epsilon())
1181    }
1182    fn to_degrees(self) -> Self {
1183        OrderedFloat(Float::to_degrees(self.0))
1184    }
1185    fn to_radians(self) -> Self {
1186        OrderedFloat(Float::to_radians(self.0))
1187    }
1188}
1189
1190impl<T: FloatCore + Num> Num for OrderedFloat<T> {
1191    type FromStrRadixErr = T::FromStrRadixErr;
1192    fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
1193        T::from_str_radix(str, radix).map(OrderedFloat)
1194    }
1195}
1196
1197/// A wrapper around floats providing an implementation of `Eq`, `Ord` and `Hash`.
1198///
1199/// A NaN value cannot be stored in this type.
1200///
1201/// ```
1202/// use ordered_float::NotNan;
1203///
1204/// let mut v = [NotNan::new(2.0).unwrap(), NotNan::new(1.0).unwrap()];
1205/// v.sort();
1206/// assert_eq!(v, [1.0, 2.0]);
1207/// ```
1208///
1209/// Because `NotNan` implements `Ord` and `Eq`, it can be used as a key in a `HashSet`,
1210/// `HashMap`, `BTreeMap`, or `BTreeSet` (unlike the primitive `f32` or `f64` types):
1211///
1212/// ```
1213/// # use ordered_float::NotNan;
1214/// # use std::collections::HashSet;
1215/// let mut s: HashSet<NotNan<f32>> = HashSet::new();
1216/// let key = NotNan::new(1.0).unwrap();
1217/// s.insert(key);
1218/// assert!(s.contains(&key));
1219/// ```
1220///
1221/// `-0.0` and `+0.0` are still considered equal. This different sign may show up in printing,
1222/// or when dividing by zero (the sign of the zero becomes the sign of the resulting infinity).
1223/// Therefore, `NotNan` may be unsuitable for use as a key in interning and memoization
1224/// applications which require equal results from equal inputs, unless signed zeros make no
1225/// difference or are canonicalized before insertion.
1226///
1227/// Arithmetic on NotNan values will panic if it produces a NaN value:
1228///
1229/// ```should_panic
1230/// # use ordered_float::NotNan;
1231/// let a = NotNan::new(std::f32::INFINITY).unwrap();
1232/// let b = NotNan::new(std::f32::NEG_INFINITY).unwrap();
1233///
1234/// // This will panic:
1235/// let c = a + b;
1236/// ```
1237///
1238/// # Representation
1239///
1240/// `NotNan` has `#[repr(transparent)]`, so it is sound to use
1241/// [transmute](core::mem::transmute) or pointer casts to convert between any type `T` and
1242/// `NotNan<T>`, as long as this does not create a NaN value.
1243/// However, consider using [`bytemuck`] as a safe alternative if possible.
1244#[cfg_attr(
1245    not(feature = "bytemuck"),
1246    doc = "[`bytemuck`]: https://docs.rs/bytemuck/1/"
1247)]
1248#[derive(PartialOrd, PartialEq, Default, Clone, Copy)]
1249#[repr(transparent)]
1250pub struct NotNan<T>(T);
1251
1252impl<T: FloatCore> NotNan<T> {
1253    /// Create a `NotNan` value.
1254    ///
1255    /// Returns `Err` if `val` is NaN
1256    pub fn new(val: T) -> Result<Self, FloatIsNan> {
1257        match val {
1258            ref val if val.is_nan() => Err(FloatIsNan),
1259            val => Ok(NotNan(val)),
1260        }
1261    }
1262}
1263
1264impl<T> NotNan<T> {
1265    /// Get the value out.
1266    #[inline]
1267    pub fn into_inner(self) -> T {
1268        self.0
1269    }
1270
1271    /// Create a `NotNan` value from a value that is guaranteed to not be NaN
1272    ///
1273    /// # Safety
1274    ///
1275    /// Behaviour is undefined if `val` is NaN
1276    #[inline]
1277    pub const unsafe fn new_unchecked(val: T) -> Self {
1278        NotNan(val)
1279    }
1280
1281    /// Create a `NotNan` value from a value that is guaranteed to not be NaN
1282    ///
1283    /// # Safety
1284    ///
1285    /// Behaviour is undefined if `val` is NaN
1286    #[deprecated(
1287        since = "2.5.0",
1288        note = "Please use the new_unchecked function instead."
1289    )]
1290    #[inline]
1291    pub const unsafe fn unchecked_new(val: T) -> Self {
1292        Self::new_unchecked(val)
1293    }
1294}
1295
1296impl<T: FloatCore> AsRef<T> for NotNan<T> {
1297    #[inline]
1298    fn as_ref(&self) -> &T {
1299        &self.0
1300    }
1301}
1302
1303impl Borrow<f32> for NotNan<f32> {
1304    #[inline]
1305    fn borrow(&self) -> &f32 {
1306        &self.0
1307    }
1308}
1309
1310impl Borrow<f64> for NotNan<f64> {
1311    #[inline]
1312    fn borrow(&self) -> &f64 {
1313        &self.0
1314    }
1315}
1316
1317#[allow(clippy::derive_ord_xor_partial_ord)]
1318impl<T: FloatCore> Ord for NotNan<T> {
1319    fn cmp(&self, other: &NotNan<T>) -> Ordering {
1320        // Can't use unreachable_unchecked because unsafe code can't depend on FloatCore impl.
1321        // https://github.com/reem/rust-ordered-float/issues/150
1322        self.partial_cmp(other)
1323            .expect("partial_cmp failed for non-NaN value")
1324    }
1325}
1326
1327impl<T: fmt::Debug> fmt::Debug for NotNan<T> {
1328    #[inline]
1329    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1330        self.0.fmt(f)
1331    }
1332}
1333
1334impl<T: FloatCore + fmt::Display> fmt::Display for NotNan<T> {
1335    #[inline]
1336    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1337        self.0.fmt(f)
1338    }
1339}
1340
1341impl NotNan<f64> {
1342    /// Converts this [`NotNan`]`<`[`f64`]`>` to a [`NotNan`]`<`[`f32`]`>` while giving up on
1343    /// precision, [using `roundTiesToEven` as rounding mode, yielding `Infinity` on
1344    /// overflow](https://doc.rust-lang.org/reference/expressions/operator-expr.html#semantics).
1345    ///
1346    /// Note: For the reverse conversion (from `NotNan<f32>` to `NotNan<f64>`), you can use
1347    /// `.into()`.
1348    pub fn as_f32(self) -> NotNan<f32> {
1349        // This is not destroying invariants, as it is a pure rounding operation. The only two
1350        // special cases are where f32 would be overflowing, then the operation yields
1351        // Infinity, or where the input is already NaN, in which case the invariant is
1352        // already broken elsewhere.
1353        NotNan(self.0 as f32)
1354    }
1355}
1356
1357impl From<NotNan<f32>> for f32 {
1358    #[inline]
1359    fn from(value: NotNan<f32>) -> Self {
1360        value.0
1361    }
1362}
1363
1364impl From<NotNan<f64>> for f64 {
1365    #[inline]
1366    fn from(value: NotNan<f64>) -> Self {
1367        value.0
1368    }
1369}
1370
1371impl TryFrom<f32> for NotNan<f32> {
1372    type Error = FloatIsNan;
1373    #[inline]
1374    fn try_from(v: f32) -> Result<Self, Self::Error> {
1375        NotNan::new(v)
1376    }
1377}
1378
1379impl TryFrom<f64> for NotNan<f64> {
1380    type Error = FloatIsNan;
1381    #[inline]
1382    fn try_from(v: f64) -> Result<Self, Self::Error> {
1383        NotNan::new(v)
1384    }
1385}
1386
1387macro_rules! impl_from_int_primitive {
1388    ($primitive:ty, $inner:ty) => {
1389        impl From<$primitive> for NotNan<$inner> {
1390            fn from(source: $primitive) -> Self {
1391                // the primitives with which this macro will be called cannot hold a value that
1392                // f64::from would convert to NaN, so this does not hurt invariants
1393                NotNan(<$inner as From<$primitive>>::from(source))
1394            }
1395        }
1396    };
1397}
1398
1399impl_from_int_primitive!(i8, f64);
1400impl_from_int_primitive!(i16, f64);
1401impl_from_int_primitive!(i32, f64);
1402impl_from_int_primitive!(u8, f64);
1403impl_from_int_primitive!(u16, f64);
1404impl_from_int_primitive!(u32, f64);
1405
1406impl_from_int_primitive!(i8, f32);
1407impl_from_int_primitive!(i16, f32);
1408impl_from_int_primitive!(u8, f32);
1409impl_from_int_primitive!(u16, f32);
1410
1411impl From<NotNan<f32>> for NotNan<f64> {
1412    #[inline]
1413    fn from(v: NotNan<f32>) -> NotNan<f64> {
1414        unsafe { NotNan::new_unchecked(v.0 as f64) }
1415    }
1416}
1417
1418impl<T: FloatCore> Deref for NotNan<T> {
1419    type Target = T;
1420
1421    #[inline]
1422    fn deref(&self) -> &Self::Target {
1423        &self.0
1424    }
1425}
1426
1427impl<T: FloatCore + PartialEq> Eq for NotNan<T> {}
1428
1429impl<T: FloatCore> PartialEq<T> for NotNan<T> {
1430    #[inline]
1431    fn eq(&self, other: &T) -> bool {
1432        self.0 == *other
1433    }
1434}
1435
1436/// Adds a float directly.
1437///
1438/// This returns a `T` and not a `NotNan<T>` because if the added value is NaN, this will be NaN
1439impl<T: FloatCore> Add<T> for NotNan<T> {
1440    type Output = T;
1441
1442    #[inline]
1443    fn add(self, other: T) -> Self::Output {
1444        self.0 + other
1445    }
1446}
1447
1448/// Adds a float directly.
1449///
1450/// Panics if the provided value is NaN.
1451impl<T: FloatCore + Sum> Sum for NotNan<T> {
1452    fn sum<I: Iterator<Item = NotNan<T>>>(iter: I) -> Self {
1453        NotNan::new(iter.map(|v| v.0).sum()).expect("Sum resulted in NaN")
1454    }
1455}
1456
1457impl<'a, T: FloatCore + Sum + 'a> Sum<&'a NotNan<T>> for NotNan<T> {
1458    #[inline]
1459    fn sum<I: Iterator<Item = &'a NotNan<T>>>(iter: I) -> Self {
1460        iter.cloned().sum()
1461    }
1462}
1463
1464/// Subtracts a float directly.
1465///
1466/// This returns a `T` and not a `NotNan<T>` because if the substracted value is NaN, this will be
1467/// NaN
1468impl<T: FloatCore> Sub<T> for NotNan<T> {
1469    type Output = T;
1470
1471    #[inline]
1472    fn sub(self, other: T) -> Self::Output {
1473        self.0 - other
1474    }
1475}
1476
1477/// Multiplies a float directly.
1478///
1479/// This returns a `T` and not a `NotNan<T>` because if the multiplied value is NaN, this will be
1480/// NaN
1481impl<T: FloatCore> Mul<T> for NotNan<T> {
1482    type Output = T;
1483
1484    #[inline]
1485    fn mul(self, other: T) -> Self::Output {
1486        self.0 * other
1487    }
1488}
1489
1490impl<T: FloatCore + Product> Product for NotNan<T> {
1491    fn product<I: Iterator<Item = NotNan<T>>>(iter: I) -> Self {
1492        NotNan::new(iter.map(|v| v.0).product()).expect("Product resulted in NaN")
1493    }
1494}
1495
1496impl<'a, T: FloatCore + Product + 'a> Product<&'a NotNan<T>> for NotNan<T> {
1497    #[inline]
1498    fn product<I: Iterator<Item = &'a NotNan<T>>>(iter: I) -> Self {
1499        iter.cloned().product()
1500    }
1501}
1502
1503/// Divides a float directly.
1504///
1505/// This returns a `T` and not a `NotNan<T>` because if the divided-by value is NaN, this will be
1506/// NaN
1507impl<T: FloatCore> Div<T> for NotNan<T> {
1508    type Output = T;
1509
1510    #[inline]
1511    fn div(self, other: T) -> Self::Output {
1512        self.0 / other
1513    }
1514}
1515
1516/// Calculates `%` with a float directly.
1517///
1518/// This returns a `T` and not a `NotNan<T>` because if the RHS is NaN, this will be NaN
1519impl<T: FloatCore> Rem<T> for NotNan<T> {
1520    type Output = T;
1521
1522    #[inline]
1523    fn rem(self, other: T) -> Self::Output {
1524        self.0 % other
1525    }
1526}
1527
1528macro_rules! impl_not_nan_binop {
1529    ($imp:ident, $method:ident, $assign_imp:ident, $assign_method:ident) => {
1530        impl<T: FloatCore> $imp for NotNan<T> {
1531            type Output = Self;
1532
1533            #[inline]
1534            fn $method(self, other: Self) -> Self {
1535                NotNan::new(self.0.$method(other.0))
1536                    .expect("Operation on two NotNan resulted in NaN")
1537            }
1538        }
1539
1540        impl<T: FloatCore> $imp<&T> for NotNan<T> {
1541            type Output = T;
1542
1543            #[inline]
1544            fn $method(self, other: &T) -> Self::Output {
1545                self.$method(*other)
1546            }
1547        }
1548
1549        impl<T: FloatCore> $imp<&Self> for NotNan<T> {
1550            type Output = NotNan<T>;
1551
1552            #[inline]
1553            fn $method(self, other: &Self) -> Self::Output {
1554                self.$method(*other)
1555            }
1556        }
1557
1558        impl<T: FloatCore> $imp for &NotNan<T> {
1559            type Output = NotNan<T>;
1560
1561            #[inline]
1562            fn $method(self, other: Self) -> Self::Output {
1563                (*self).$method(*other)
1564            }
1565        }
1566
1567        impl<T: FloatCore> $imp<NotNan<T>> for &NotNan<T> {
1568            type Output = NotNan<T>;
1569
1570            #[inline]
1571            fn $method(self, other: NotNan<T>) -> Self::Output {
1572                (*self).$method(other)
1573            }
1574        }
1575
1576        impl<T: FloatCore> $imp<T> for &NotNan<T> {
1577            type Output = T;
1578
1579            #[inline]
1580            fn $method(self, other: T) -> Self::Output {
1581                (*self).$method(other)
1582            }
1583        }
1584
1585        impl<T: FloatCore> $imp<&T> for &NotNan<T> {
1586            type Output = T;
1587
1588            #[inline]
1589            fn $method(self, other: &T) -> Self::Output {
1590                (*self).$method(*other)
1591            }
1592        }
1593
1594        impl<T: FloatCore + $assign_imp> $assign_imp for NotNan<T> {
1595            #[inline]
1596            fn $assign_method(&mut self, other: Self) {
1597                *self = (*self).$method(other);
1598            }
1599        }
1600
1601        impl<T: FloatCore + $assign_imp> $assign_imp<&Self> for NotNan<T> {
1602            #[inline]
1603            fn $assign_method(&mut self, other: &Self) {
1604                *self = (*self).$method(*other);
1605            }
1606        }
1607    };
1608}
1609
1610impl_not_nan_binop! {Add, add, AddAssign, add_assign}
1611impl_not_nan_binop! {Sub, sub, SubAssign, sub_assign}
1612impl_not_nan_binop! {Mul, mul, MulAssign, mul_assign}
1613impl_not_nan_binop! {Div, div, DivAssign, div_assign}
1614impl_not_nan_binop! {Rem, rem, RemAssign, rem_assign}
1615
1616// Will panic if NaN value is return from the operation
1617macro_rules! impl_not_nan_pow {
1618    ($inner:ty, $rhs:ty) => {
1619        #[cfg(any(feature = "std", feature = "libm"))]
1620        impl Pow<$rhs> for NotNan<$inner> {
1621            type Output = NotNan<$inner>;
1622            #[inline]
1623            fn pow(self, rhs: $rhs) -> NotNan<$inner> {
1624                NotNan::new(<$inner>::pow(self.0, rhs)).expect("Pow resulted in NaN")
1625            }
1626        }
1627
1628        #[cfg(any(feature = "std", feature = "libm"))]
1629        impl<'a> Pow<&'a $rhs> for NotNan<$inner> {
1630            type Output = NotNan<$inner>;
1631            #[inline]
1632            fn pow(self, rhs: &'a $rhs) -> NotNan<$inner> {
1633                NotNan::new(<$inner>::pow(self.0, *rhs)).expect("Pow resulted in NaN")
1634            }
1635        }
1636
1637        #[cfg(any(feature = "std", feature = "libm"))]
1638        impl<'a> Pow<$rhs> for &'a NotNan<$inner> {
1639            type Output = NotNan<$inner>;
1640            #[inline]
1641            fn pow(self, rhs: $rhs) -> NotNan<$inner> {
1642                NotNan::new(<$inner>::pow(self.0, rhs)).expect("Pow resulted in NaN")
1643            }
1644        }
1645
1646        #[cfg(any(feature = "std", feature = "libm"))]
1647        impl<'a, 'b> Pow<&'a $rhs> for &'b NotNan<$inner> {
1648            type Output = NotNan<$inner>;
1649            #[inline]
1650            fn pow(self, rhs: &'a $rhs) -> NotNan<$inner> {
1651                NotNan::new(<$inner>::pow(self.0, *rhs)).expect("Pow resulted in NaN")
1652            }
1653        }
1654    };
1655}
1656
1657impl_not_nan_pow! {f32, i8}
1658impl_not_nan_pow! {f32, i16}
1659impl_not_nan_pow! {f32, u8}
1660impl_not_nan_pow! {f32, u16}
1661impl_not_nan_pow! {f32, i32}
1662impl_not_nan_pow! {f64, i8}
1663impl_not_nan_pow! {f64, i16}
1664impl_not_nan_pow! {f64, u8}
1665impl_not_nan_pow! {f64, u16}
1666impl_not_nan_pow! {f64, i32}
1667impl_not_nan_pow! {f32, f32}
1668impl_not_nan_pow! {f64, f32}
1669impl_not_nan_pow! {f64, f64}
1670
1671// This also should panic on NaN
1672macro_rules! impl_not_nan_self_pow {
1673    ($base:ty, $exp:ty) => {
1674        #[cfg(any(feature = "std", feature = "libm"))]
1675        impl Pow<NotNan<$exp>> for NotNan<$base> {
1676            type Output = NotNan<$base>;
1677            #[inline]
1678            fn pow(self, rhs: NotNan<$exp>) -> NotNan<$base> {
1679                NotNan::new(self.0.pow(rhs.0)).expect("Pow resulted in NaN")
1680            }
1681        }
1682
1683        #[cfg(any(feature = "std", feature = "libm"))]
1684        impl<'a> Pow<&'a NotNan<$exp>> for NotNan<$base> {
1685            type Output = NotNan<$base>;
1686            #[inline]
1687            fn pow(self, rhs: &'a NotNan<$exp>) -> NotNan<$base> {
1688                NotNan::new(self.0.pow(rhs.0)).expect("Pow resulted in NaN")
1689            }
1690        }
1691
1692        #[cfg(any(feature = "std", feature = "libm"))]
1693        impl<'a> Pow<NotNan<$exp>> for &'a NotNan<$base> {
1694            type Output = NotNan<$base>;
1695            #[inline]
1696            fn pow(self, rhs: NotNan<$exp>) -> NotNan<$base> {
1697                NotNan::new(self.0.pow(rhs.0)).expect("Pow resulted in NaN")
1698            }
1699        }
1700
1701        #[cfg(any(feature = "std", feature = "libm"))]
1702        impl<'a, 'b> Pow<&'a NotNan<$exp>> for &'b NotNan<$base> {
1703            type Output = NotNan<$base>;
1704            #[inline]
1705            fn pow(self, rhs: &'a NotNan<$exp>) -> NotNan<$base> {
1706                NotNan::new(self.0.pow(rhs.0)).expect("Pow resulted in NaN")
1707            }
1708        }
1709    };
1710}
1711
1712impl_not_nan_self_pow! {f32, f32}
1713impl_not_nan_self_pow! {f64, f32}
1714impl_not_nan_self_pow! {f64, f64}
1715
1716impl<T: FloatCore> Neg for NotNan<T> {
1717    type Output = Self;
1718
1719    #[inline]
1720    fn neg(self) -> Self {
1721        NotNan(-self.0)
1722    }
1723}
1724
1725impl<T: FloatCore> Neg for &NotNan<T> {
1726    type Output = NotNan<T>;
1727
1728    #[inline]
1729    fn neg(self) -> Self::Output {
1730        NotNan(-self.0)
1731    }
1732}
1733
1734/// An error indicating an attempt to construct NotNan from a NaN
1735#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1736pub struct FloatIsNan;
1737
1738#[cfg(feature = "std")]
1739impl Error for FloatIsNan {
1740    fn description(&self) -> &str {
1741        "NotNan constructed with NaN"
1742    }
1743}
1744
1745impl fmt::Display for FloatIsNan {
1746    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1747        write!(f, "NotNan constructed with NaN")
1748    }
1749}
1750
1751#[cfg(feature = "std")]
1752impl From<FloatIsNan> for std::io::Error {
1753    #[inline]
1754    fn from(e: FloatIsNan) -> std::io::Error {
1755        std::io::Error::new(std::io::ErrorKind::InvalidInput, e)
1756    }
1757}
1758
1759impl<T: FloatCore> Zero for NotNan<T> {
1760    #[inline]
1761    fn zero() -> Self {
1762        NotNan(T::zero())
1763    }
1764
1765    #[inline]
1766    fn is_zero(&self) -> bool {
1767        self.0.is_zero()
1768    }
1769}
1770
1771impl<T: FloatCore> One for NotNan<T> {
1772    #[inline]
1773    fn one() -> Self {
1774        NotNan(T::one())
1775    }
1776}
1777
1778impl<T: FloatCore> Bounded for NotNan<T> {
1779    #[inline]
1780    fn min_value() -> Self {
1781        NotNan(T::min_value())
1782    }
1783
1784    #[inline]
1785    fn max_value() -> Self {
1786        NotNan(T::max_value())
1787    }
1788}
1789
1790impl<T: FloatCore + FromStr> FromStr for NotNan<T> {
1791    type Err = ParseNotNanError<T::Err>;
1792
1793    /// Convert a &str to `NotNan`. Returns an error if the string fails to parse,
1794    /// or if the resulting value is NaN
1795    ///
1796    /// ```
1797    /// use ordered_float::NotNan;
1798    ///
1799    /// assert!("-10".parse::<NotNan<f32>>().is_ok());
1800    /// assert!("abc".parse::<NotNan<f32>>().is_err());
1801    /// assert!("NaN".parse::<NotNan<f32>>().is_err());
1802    /// ```
1803    fn from_str(src: &str) -> Result<Self, Self::Err> {
1804        src.parse()
1805            .map_err(ParseNotNanError::ParseFloatError)
1806            .and_then(|f| NotNan::new(f).map_err(|_| ParseNotNanError::IsNaN))
1807    }
1808}
1809
1810impl<T: FloatCore + FromPrimitive> FromPrimitive for NotNan<T> {
1811    fn from_i64(n: i64) -> Option<Self> {
1812        T::from_i64(n).and_then(|n| NotNan::new(n).ok())
1813    }
1814    fn from_u64(n: u64) -> Option<Self> {
1815        T::from_u64(n).and_then(|n| NotNan::new(n).ok())
1816    }
1817
1818    fn from_isize(n: isize) -> Option<Self> {
1819        T::from_isize(n).and_then(|n| NotNan::new(n).ok())
1820    }
1821    fn from_i8(n: i8) -> Option<Self> {
1822        T::from_i8(n).and_then(|n| NotNan::new(n).ok())
1823    }
1824    fn from_i16(n: i16) -> Option<Self> {
1825        T::from_i16(n).and_then(|n| NotNan::new(n).ok())
1826    }
1827    fn from_i32(n: i32) -> Option<Self> {
1828        T::from_i32(n).and_then(|n| NotNan::new(n).ok())
1829    }
1830    fn from_usize(n: usize) -> Option<Self> {
1831        T::from_usize(n).and_then(|n| NotNan::new(n).ok())
1832    }
1833    fn from_u8(n: u8) -> Option<Self> {
1834        T::from_u8(n).and_then(|n| NotNan::new(n).ok())
1835    }
1836    fn from_u16(n: u16) -> Option<Self> {
1837        T::from_u16(n).and_then(|n| NotNan::new(n).ok())
1838    }
1839    fn from_u32(n: u32) -> Option<Self> {
1840        T::from_u32(n).and_then(|n| NotNan::new(n).ok())
1841    }
1842    fn from_f32(n: f32) -> Option<Self> {
1843        T::from_f32(n).and_then(|n| NotNan::new(n).ok())
1844    }
1845    fn from_f64(n: f64) -> Option<Self> {
1846        T::from_f64(n).and_then(|n| NotNan::new(n).ok())
1847    }
1848}
1849
1850impl<T: FloatCore> ToPrimitive for NotNan<T> {
1851    fn to_i64(&self) -> Option<i64> {
1852        self.0.to_i64()
1853    }
1854    fn to_u64(&self) -> Option<u64> {
1855        self.0.to_u64()
1856    }
1857
1858    fn to_isize(&self) -> Option<isize> {
1859        self.0.to_isize()
1860    }
1861    fn to_i8(&self) -> Option<i8> {
1862        self.0.to_i8()
1863    }
1864    fn to_i16(&self) -> Option<i16> {
1865        self.0.to_i16()
1866    }
1867    fn to_i32(&self) -> Option<i32> {
1868        self.0.to_i32()
1869    }
1870    fn to_usize(&self) -> Option<usize> {
1871        self.0.to_usize()
1872    }
1873    fn to_u8(&self) -> Option<u8> {
1874        self.0.to_u8()
1875    }
1876    fn to_u16(&self) -> Option<u16> {
1877        self.0.to_u16()
1878    }
1879    fn to_u32(&self) -> Option<u32> {
1880        self.0.to_u32()
1881    }
1882    fn to_f32(&self) -> Option<f32> {
1883        self.0.to_f32()
1884    }
1885    fn to_f64(&self) -> Option<f64> {
1886        self.0.to_f64()
1887    }
1888}
1889
1890/// An error indicating a parse error from a string for `NotNan`.
1891#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1892pub enum ParseNotNanError<E> {
1893    /// A plain parse error from the underlying float type.
1894    ParseFloatError(E),
1895    /// The parsed float value resulted in a NaN.
1896    IsNaN,
1897}
1898
1899#[cfg(feature = "std")]
1900impl<E: fmt::Debug + Error + 'static> Error for ParseNotNanError<E> {
1901    fn description(&self) -> &str {
1902        "Error parsing a not-NaN floating point value"
1903    }
1904
1905    fn source(&self) -> Option<&(dyn Error + 'static)> {
1906        match self {
1907            ParseNotNanError::ParseFloatError(e) => Some(e),
1908            ParseNotNanError::IsNaN => None,
1909        }
1910    }
1911}
1912
1913impl<E: fmt::Display> fmt::Display for ParseNotNanError<E> {
1914    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1915        match self {
1916            ParseNotNanError::ParseFloatError(e) => write!(f, "Parse error: {e}"),
1917            ParseNotNanError::IsNaN => write!(f, "NotNan parser encounter a NaN"),
1918        }
1919    }
1920}
1921
1922impl<T: FloatCore> Num for NotNan<T> {
1923    type FromStrRadixErr = ParseNotNanError<T::FromStrRadixErr>;
1924
1925    fn from_str_radix(src: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
1926        T::from_str_radix(src, radix)
1927            .map_err(ParseNotNanError::ParseFloatError)
1928            .and_then(|n| NotNan::new(n).map_err(|_| ParseNotNanError::IsNaN))
1929    }
1930}
1931
1932impl<T: FloatCore + Signed> Signed for NotNan<T> {
1933    #[inline]
1934    fn abs(&self) -> Self {
1935        NotNan(self.0.abs())
1936    }
1937
1938    fn abs_sub(&self, other: &Self) -> Self {
1939        NotNan::new(Signed::abs_sub(&self.0, &other.0)).expect("Subtraction resulted in NaN")
1940    }
1941
1942    #[inline]
1943    fn signum(&self) -> Self {
1944        NotNan(self.0.signum())
1945    }
1946    #[inline]
1947    fn is_positive(&self) -> bool {
1948        self.0.is_positive()
1949    }
1950    #[inline]
1951    fn is_negative(&self) -> bool {
1952        self.0.is_negative()
1953    }
1954}
1955
1956impl<T: FloatCore> NumCast for NotNan<T> {
1957    fn from<F: ToPrimitive>(n: F) -> Option<Self> {
1958        T::from(n).and_then(|n| NotNan::new(n).ok())
1959    }
1960}
1961
1962#[cfg(any(feature = "std", feature = "libm"))]
1963impl<T: Real + FloatCore> Real for NotNan<T> {
1964    fn min_value() -> Self {
1965        NotNan(<T as Real>::min_value())
1966    }
1967    fn min_positive_value() -> Self {
1968        NotNan(<T as Real>::min_positive_value())
1969    }
1970    fn epsilon() -> Self {
1971        NotNan(Real::epsilon())
1972    }
1973    fn max_value() -> Self {
1974        NotNan(<T as Real>::max_value())
1975    }
1976    fn floor(self) -> Self {
1977        NotNan(Real::floor(self.0))
1978    }
1979    fn ceil(self) -> Self {
1980        NotNan(Real::ceil(self.0))
1981    }
1982    fn round(self) -> Self {
1983        NotNan(Real::round(self.0))
1984    }
1985    fn trunc(self) -> Self {
1986        NotNan(Real::trunc(self.0))
1987    }
1988    fn fract(self) -> Self {
1989        NotNan(Real::fract(self.0))
1990    }
1991    fn abs(self) -> Self {
1992        NotNan(Real::abs(self.0))
1993    }
1994    fn signum(self) -> Self {
1995        NotNan(Real::signum(self.0))
1996    }
1997    fn is_sign_positive(self) -> bool {
1998        Real::is_sign_positive(self.0)
1999    }
2000    fn is_sign_negative(self) -> bool {
2001        Real::is_sign_negative(self.0)
2002    }
2003    fn mul_add(self, a: Self, b: Self) -> Self {
2004        NotNan(self.0.mul_add(a.0, b.0))
2005    }
2006    fn recip(self) -> Self {
2007        NotNan(Real::recip(self.0))
2008    }
2009    fn powi(self, n: i32) -> Self {
2010        NotNan(Real::powi(self.0, n))
2011    }
2012    fn powf(self, n: Self) -> Self {
2013        // Panics if  self < 0 and n is not an integer
2014        NotNan::new(self.0.powf(n.0)).expect("Power resulted in NaN")
2015    }
2016    fn sqrt(self) -> Self {
2017        // Panics if self < 0
2018        NotNan::new(self.0.sqrt()).expect("Square root resulted in NaN")
2019    }
2020    fn exp(self) -> Self {
2021        NotNan(self.0.exp())
2022    }
2023    fn exp2(self) -> Self {
2024        NotNan(self.0.exp2())
2025    }
2026    fn ln(self) -> Self {
2027        // Panics if self <= 0
2028        NotNan::new(self.0.ln()).expect("Natural logarithm resulted in NaN")
2029    }
2030    fn log(self, base: Self) -> Self {
2031        // Panics if self <= 0 or base <= 0
2032        NotNan::new(self.0.log(base.0)).expect("Logarithm resulted in NaN")
2033    }
2034    fn log2(self) -> Self {
2035        // Panics if self <= 0
2036        NotNan::new(self.0.log2()).expect("Logarithm resulted in NaN")
2037    }
2038    fn log10(self) -> Self {
2039        // Panics if self <= 0
2040        NotNan::new(self.0.log10()).expect("Logarithm resulted in NaN")
2041    }
2042    fn to_degrees(self) -> Self {
2043        NotNan(Real::to_degrees(self.0))
2044    }
2045    fn to_radians(self) -> Self {
2046        NotNan(Real::to_radians(self.0))
2047    }
2048    fn max(self, other: Self) -> Self {
2049        NotNan(Real::max(self.0, other.0))
2050    }
2051    fn min(self, other: Self) -> Self {
2052        NotNan(Real::min(self.0, other.0))
2053    }
2054    fn abs_sub(self, other: Self) -> Self {
2055        NotNan(self.0.abs_sub(other.0))
2056    }
2057    fn cbrt(self) -> Self {
2058        NotNan(self.0.cbrt())
2059    }
2060    fn hypot(self, other: Self) -> Self {
2061        NotNan(self.0.hypot(other.0))
2062    }
2063    fn sin(self) -> Self {
2064        // Panics if self is +/-infinity
2065        NotNan::new(self.0.sin()).expect("Sine resulted in NaN")
2066    }
2067    fn cos(self) -> Self {
2068        // Panics if self is +/-infinity
2069        NotNan::new(self.0.cos()).expect("Cosine resulted in NaN")
2070    }
2071    fn tan(self) -> Self {
2072        // Panics if self is +/-infinity or self == pi/2 + k*pi
2073        NotNan::new(self.0.tan()).expect("Tangent resulted in NaN")
2074    }
2075    fn asin(self) -> Self {
2076        // Panics if self < -1.0 or self > 1.0
2077        NotNan::new(self.0.asin()).expect("Arcsine resulted in NaN")
2078    }
2079    fn acos(self) -> Self {
2080        // Panics if self < -1.0 or self > 1.0
2081        NotNan::new(self.0.acos()).expect("Arccosine resulted in NaN")
2082    }
2083    fn atan(self) -> Self {
2084        NotNan(self.0.atan())
2085    }
2086    fn atan2(self, other: Self) -> Self {
2087        NotNan(self.0.atan2(other.0))
2088    }
2089    fn sin_cos(self) -> (Self, Self) {
2090        // Panics if self is +/-infinity
2091        let (a, b) = self.0.sin_cos();
2092        (
2093            NotNan::new(a).expect("Sine resulted in NaN"),
2094            NotNan::new(b).expect("Cosine resulted in NaN"),
2095        )
2096    }
2097    fn exp_m1(self) -> Self {
2098        NotNan(self.0.exp_m1())
2099    }
2100    fn ln_1p(self) -> Self {
2101        // Panics if self <= -1.0
2102        NotNan::new(self.0.ln_1p()).expect("Natural logarithm resulted in NaN")
2103    }
2104    fn sinh(self) -> Self {
2105        NotNan(self.0.sinh())
2106    }
2107    fn cosh(self) -> Self {
2108        NotNan(self.0.cosh())
2109    }
2110    fn tanh(self) -> Self {
2111        NotNan(self.0.tanh())
2112    }
2113    fn asinh(self) -> Self {
2114        NotNan(self.0.asinh())
2115    }
2116    fn acosh(self) -> Self {
2117        // Panics if self < 1.0
2118        NotNan::new(self.0.acosh()).expect("Arccosh resulted in NaN")
2119    }
2120    fn atanh(self) -> Self {
2121        // Panics if self < -1.0 or self > 1.0
2122        NotNan::new(self.0.atanh()).expect("Arctanh resulted in NaN")
2123    }
2124}
2125
2126macro_rules! impl_float_const_method {
2127    ($wrapper:expr, $method:ident) => {
2128        #[allow(non_snake_case)]
2129        #[allow(clippy::redundant_closure_call)]
2130        fn $method() -> Self {
2131            $wrapper(T::$method())
2132        }
2133    };
2134}
2135
2136macro_rules! impl_float_const {
2137    ($type:ident, $wrapper:expr) => {
2138        impl<T: FloatConst> FloatConst for $type<T> {
2139            impl_float_const_method!($wrapper, E);
2140            impl_float_const_method!($wrapper, FRAC_1_PI);
2141            impl_float_const_method!($wrapper, FRAC_1_SQRT_2);
2142            impl_float_const_method!($wrapper, FRAC_2_PI);
2143            impl_float_const_method!($wrapper, FRAC_2_SQRT_PI);
2144            impl_float_const_method!($wrapper, FRAC_PI_2);
2145            impl_float_const_method!($wrapper, FRAC_PI_3);
2146            impl_float_const_method!($wrapper, FRAC_PI_4);
2147            impl_float_const_method!($wrapper, FRAC_PI_6);
2148            impl_float_const_method!($wrapper, FRAC_PI_8);
2149            impl_float_const_method!($wrapper, LN_10);
2150            impl_float_const_method!($wrapper, LN_2);
2151            impl_float_const_method!($wrapper, LOG10_E);
2152            impl_float_const_method!($wrapper, LOG2_E);
2153            impl_float_const_method!($wrapper, PI);
2154            impl_float_const_method!($wrapper, SQRT_2);
2155        }
2156    };
2157}
2158
2159impl_float_const!(OrderedFloat, OrderedFloat);
2160// Float constants are not NaN.
2161impl_float_const!(NotNan, |x| unsafe { NotNan::new_unchecked(x) });
2162
2163mod hash_internals {
2164    pub trait SealedTrait: Copy + num_traits::float::FloatCore {
2165        type Bits: core::hash::Hash;
2166
2167        const CANONICAL_NAN_BITS: Self::Bits;
2168
2169        fn canonical_bits(self) -> Self::Bits;
2170    }
2171
2172    impl SealedTrait for f32 {
2173        type Bits = u32;
2174
2175        const CANONICAL_NAN_BITS: u32 = 0x7fc00000;
2176
2177        fn canonical_bits(self) -> u32 {
2178            // -0.0 + 0.0 == +0.0 under IEEE754 roundTiesToEven rounding mode,
2179            // which Rust guarantees. Thus by adding a positive zero we
2180            // canonicalize signed zero without any branches in one instruction.
2181            (self + 0.0).to_bits()
2182        }
2183    }
2184
2185    impl SealedTrait for f64 {
2186        type Bits = u64;
2187
2188        const CANONICAL_NAN_BITS: u64 = 0x7ff8000000000000;
2189
2190        fn canonical_bits(self) -> u64 {
2191            (self + 0.0).to_bits()
2192        }
2193    }
2194}
2195
2196/// The built-in floating point types `f32` and `f64`.
2197///
2198/// This is a "sealed" trait that cannot be implemented for any other types.
2199pub trait PrimitiveFloat: hash_internals::SealedTrait {}
2200impl PrimitiveFloat for f32 {}
2201impl PrimitiveFloat for f64 {}
2202
2203impl<T: PrimitiveFloat> Hash for OrderedFloat<T> {
2204    fn hash<H: Hasher>(&self, hasher: &mut H) {
2205        let bits = if self.0.is_nan() {
2206            T::CANONICAL_NAN_BITS
2207        } else {
2208            self.0.canonical_bits()
2209        };
2210        bits.hash(hasher);
2211    }
2212}
2213
2214impl<T: PrimitiveFloat> Hash for NotNan<T> {
2215    fn hash<H: Hasher>(&self, hasher: &mut H) {
2216        self.0.canonical_bits().hash(hasher);
2217    }
2218}
2219
2220#[cfg(feature = "serde")]
2221mod impl_serde {
2222    extern crate serde;
2223    use self::serde::de::{Error, Unexpected};
2224    use self::serde::{Deserialize, Deserializer, Serialize, Serializer};
2225    use super::{NotNan, OrderedFloat};
2226    use core::f64;
2227    use num_traits::float::FloatCore;
2228
2229    #[cfg(test)]
2230    extern crate serde_test;
2231    #[cfg(test)]
2232    use self::serde_test::{assert_de_tokens_error, assert_tokens, Token};
2233
2234    impl<T: FloatCore + Serialize> Serialize for OrderedFloat<T> {
2235        #[inline]
2236        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2237            self.0.serialize(s)
2238        }
2239    }
2240
2241    impl<'de, T: FloatCore + Deserialize<'de>> Deserialize<'de> for OrderedFloat<T> {
2242        #[inline]
2243        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2244            T::deserialize(d).map(OrderedFloat)
2245        }
2246    }
2247
2248    impl<T: FloatCore + Serialize> Serialize for NotNan<T> {
2249        #[inline]
2250        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
2251            self.0.serialize(s)
2252        }
2253    }
2254
2255    impl<'de, T: FloatCore + Deserialize<'de>> Deserialize<'de> for NotNan<T> {
2256        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
2257            let float = T::deserialize(d)?;
2258            NotNan::new(float).map_err(|_| {
2259                Error::invalid_value(Unexpected::Float(f64::NAN), &"float (but not NaN)")
2260            })
2261        }
2262    }
2263
2264    #[test]
2265    fn test_ordered_float() {
2266        let float = OrderedFloat(1.0f64);
2267        assert_tokens(&float, &[Token::F64(1.0)]);
2268    }
2269
2270    #[test]
2271    fn test_not_nan() {
2272        let float = NotNan(1.0f64);
2273        assert_tokens(&float, &[Token::F64(1.0)]);
2274    }
2275
2276    #[test]
2277    fn test_fail_on_nan() {
2278        assert_de_tokens_error::<NotNan<f64>>(
2279            &[Token::F64(f64::NAN)],
2280            "invalid value: floating point `NaN`, expected float (but not NaN)",
2281        );
2282    }
2283}
2284
2285#[cfg(any(feature = "rkyv_16", feature = "rkyv_32", feature = "rkyv_64"))]
2286mod impl_rkyv {
2287    use super::{NotNan, OrderedFloat};
2288    use num_traits::float::FloatCore;
2289    #[cfg(test)]
2290    use rkyv::{archived_root, ser::Serializer};
2291    use rkyv::{Archive, Deserialize, Fallible, Serialize};
2292
2293    #[cfg(test)]
2294    type DefaultSerializer = rkyv::ser::serializers::CoreSerializer<16, 16>;
2295    #[cfg(test)]
2296    type DefaultDeserializer = rkyv::Infallible;
2297
2298    impl<T: FloatCore + Archive> Archive for OrderedFloat<T> {
2299        type Archived = OrderedFloat<T::Archived>;
2300
2301        type Resolver = T::Resolver;
2302
2303        unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
2304            self.0.resolve(pos, resolver, out.cast())
2305        }
2306    }
2307
2308    impl<T: FloatCore + Serialize<S>, S: Fallible + ?Sized> Serialize<S> for OrderedFloat<T> {
2309        fn serialize(&self, s: &mut S) -> Result<Self::Resolver, S::Error> {
2310            self.0.serialize(s)
2311        }
2312    }
2313
2314    impl<T: FloatCore, AT: Deserialize<T, D>, D: Fallible + ?Sized> Deserialize<OrderedFloat<T>, D>
2315        for OrderedFloat<AT>
2316    {
2317        fn deserialize(&self, d: &mut D) -> Result<OrderedFloat<T>, D::Error> {
2318            self.0.deserialize(d).map(OrderedFloat)
2319        }
2320    }
2321
2322    impl<T: FloatCore + Archive> Archive for NotNan<T> {
2323        type Archived = NotNan<T::Archived>;
2324
2325        type Resolver = T::Resolver;
2326
2327        unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
2328            self.0.resolve(pos, resolver, out.cast())
2329        }
2330    }
2331
2332    impl<T: FloatCore + Serialize<S>, S: Fallible + ?Sized> Serialize<S> for NotNan<T> {
2333        fn serialize(&self, s: &mut S) -> Result<Self::Resolver, S::Error> {
2334            self.0.serialize(s)
2335        }
2336    }
2337
2338    impl<T: FloatCore, AT: Deserialize<T, D>, D: Fallible + ?Sized> Deserialize<NotNan<T>, D>
2339        for NotNan<AT>
2340    {
2341        fn deserialize(&self, d: &mut D) -> Result<NotNan<T>, D::Error> {
2342            self.0.deserialize(d).map(NotNan)
2343        }
2344    }
2345
2346    macro_rules! rkyv_eq_ord {
2347        ($main:ident, $float:ty, $rend:ty) => {
2348            impl PartialEq<$main<$float>> for $main<$rend> {
2349                fn eq(&self, other: &$main<$float>) -> bool {
2350                    other.eq(&self.0.value())
2351                }
2352            }
2353            impl PartialEq<$main<$rend>> for $main<$float> {
2354                fn eq(&self, other: &$main<$rend>) -> bool {
2355                    self.eq(&other.0.value())
2356                }
2357            }
2358
2359            impl PartialOrd<$main<$float>> for $main<$rend> {
2360                fn partial_cmp(&self, other: &$main<$float>) -> Option<core::cmp::Ordering> {
2361                    self.0.value().partial_cmp(other)
2362                }
2363            }
2364
2365            impl PartialOrd<$main<$rend>> for $main<$float> {
2366                fn partial_cmp(&self, other: &$main<$rend>) -> Option<core::cmp::Ordering> {
2367                    other
2368                        .0
2369                        .value()
2370                        .partial_cmp(self)
2371                        .map(core::cmp::Ordering::reverse)
2372                }
2373            }
2374        };
2375    }
2376
2377    rkyv_eq_ord! { OrderedFloat, f32, rkyv::rend::f32_le }
2378    rkyv_eq_ord! { OrderedFloat, f32, rkyv::rend::f32_be }
2379    rkyv_eq_ord! { OrderedFloat, f64, rkyv::rend::f64_le }
2380    rkyv_eq_ord! { OrderedFloat, f64, rkyv::rend::f64_be }
2381    rkyv_eq_ord! { NotNan, f32, rkyv::rend::f32_le }
2382    rkyv_eq_ord! { NotNan, f32, rkyv::rend::f32_be }
2383    rkyv_eq_ord! { NotNan, f64, rkyv::rend::f64_le }
2384    rkyv_eq_ord! { NotNan, f64, rkyv::rend::f64_be }
2385
2386    #[cfg(feature = "rkyv_ck")]
2387    use super::FloatIsNan;
2388    #[cfg(feature = "rkyv_ck")]
2389    use core::convert::Infallible;
2390    #[cfg(feature = "rkyv_ck")]
2391    use rkyv::bytecheck::CheckBytes;
2392
2393    #[cfg(feature = "rkyv_ck")]
2394    impl<C: ?Sized, T: FloatCore + CheckBytes<C>> CheckBytes<C> for OrderedFloat<T> {
2395        type Error = Infallible;
2396
2397        #[inline]
2398        unsafe fn check_bytes<'a>(value: *const Self, _: &mut C) -> Result<&'a Self, Self::Error> {
2399            Ok(&*value)
2400        }
2401    }
2402
2403    #[cfg(feature = "rkyv_ck")]
2404    impl<C: ?Sized, T: FloatCore + CheckBytes<C>> CheckBytes<C> for NotNan<T> {
2405        type Error = FloatIsNan;
2406
2407        #[inline]
2408        unsafe fn check_bytes<'a>(value: *const Self, _: &mut C) -> Result<&'a Self, Self::Error> {
2409            Self::new(*(value as *const T)).map(|_| &*value)
2410        }
2411    }
2412
2413    #[test]
2414    fn test_ordered_float() {
2415        let float = OrderedFloat(1.0f64);
2416        let mut serializer = DefaultSerializer::default();
2417        serializer
2418            .serialize_value(&float)
2419            .expect("failed to archive value");
2420        let len = serializer.pos();
2421        let buffer = serializer.into_serializer().into_inner();
2422
2423        let archived_value = unsafe { archived_root::<OrderedFloat<f64>>(&buffer[0..len]) };
2424        assert_eq!(archived_value, &float);
2425        let mut deserializer = DefaultDeserializer::default();
2426        let deser_float: OrderedFloat<f64> = archived_value.deserialize(&mut deserializer).unwrap();
2427        assert_eq!(deser_float, float);
2428    }
2429
2430    #[test]
2431    fn test_not_nan() {
2432        let float = NotNan(1.0f64);
2433        let mut serializer = DefaultSerializer::default();
2434        serializer
2435            .serialize_value(&float)
2436            .expect("failed to archive value");
2437        let len = serializer.pos();
2438        let buffer = serializer.into_serializer().into_inner();
2439
2440        let archived_value = unsafe { archived_root::<NotNan<f64>>(&buffer[0..len]) };
2441        assert_eq!(archived_value, &float);
2442        let mut deserializer = DefaultDeserializer::default();
2443        let deser_float: NotNan<f64> = archived_value.deserialize(&mut deserializer).unwrap();
2444        assert_eq!(deser_float, float);
2445    }
2446}
2447
2448#[cfg(feature = "speedy")]
2449mod impl_speedy {
2450    use super::{NotNan, OrderedFloat};
2451    use num_traits::float::FloatCore;
2452    use speedy::{Context, Readable, Reader, Writable, Writer};
2453
2454    impl<C, T> Writable<C> for OrderedFloat<T>
2455    where
2456        C: Context,
2457        T: Writable<C>,
2458    {
2459        fn write_to<W: ?Sized + Writer<C>>(&self, writer: &mut W) -> Result<(), C::Error> {
2460            self.0.write_to(writer)
2461        }
2462
2463        fn bytes_needed(&self) -> Result<usize, C::Error> {
2464            self.0.bytes_needed()
2465        }
2466    }
2467
2468    impl<C, T> Writable<C> for NotNan<T>
2469    where
2470        C: Context,
2471        T: Writable<C>,
2472    {
2473        fn write_to<W: ?Sized + Writer<C>>(&self, writer: &mut W) -> Result<(), C::Error> {
2474            self.0.write_to(writer)
2475        }
2476
2477        fn bytes_needed(&self) -> Result<usize, C::Error> {
2478            self.0.bytes_needed()
2479        }
2480    }
2481
2482    impl<'a, T, C: Context> Readable<'a, C> for OrderedFloat<T>
2483    where
2484        T: Readable<'a, C>,
2485    {
2486        fn read_from<R: Reader<'a, C>>(reader: &mut R) -> Result<Self, C::Error> {
2487            T::read_from(reader).map(OrderedFloat)
2488        }
2489
2490        fn minimum_bytes_needed() -> usize {
2491            T::minimum_bytes_needed()
2492        }
2493    }
2494
2495    impl<'a, T: FloatCore, C: Context> Readable<'a, C> for NotNan<T>
2496    where
2497        T: Readable<'a, C>,
2498    {
2499        fn read_from<R: Reader<'a, C>>(reader: &mut R) -> Result<Self, C::Error> {
2500            let value: T = reader.read_value()?;
2501            Self::new(value).map_err(|error| {
2502                speedy::Error::custom(std::format!("failed to read NotNan: {error}")).into()
2503            })
2504        }
2505
2506        fn minimum_bytes_needed() -> usize {
2507            T::minimum_bytes_needed()
2508        }
2509    }
2510
2511    #[test]
2512    fn test_ordered_float() {
2513        let float = OrderedFloat(1.0f64);
2514        let buffer = float.write_to_vec().unwrap();
2515        let deser_float: OrderedFloat<f64> = OrderedFloat::read_from_buffer(&buffer).unwrap();
2516        assert_eq!(deser_float, float);
2517    }
2518
2519    #[test]
2520    fn test_not_nan() {
2521        let float = NotNan(1.0f64);
2522        let buffer = float.write_to_vec().unwrap();
2523        let deser_float: NotNan<f64> = NotNan::read_from_buffer(&buffer).unwrap();
2524        assert_eq!(deser_float, float);
2525    }
2526
2527    #[test]
2528    fn test_not_nan_with_nan() {
2529        let nan_buf = f64::nan().write_to_vec().unwrap();
2530        let nan_err: Result<NotNan<f64>, _> = NotNan::read_from_buffer(&nan_buf);
2531        assert!(nan_err.is_err());
2532    }
2533}
2534
2535#[cfg(feature = "borsh")]
2536mod impl_borsh {
2537    extern crate borsh;
2538    use super::{NotNan, OrderedFloat};
2539    use num_traits::float::FloatCore;
2540
2541    impl<T> borsh::BorshSerialize for OrderedFloat<T>
2542    where
2543        T: borsh::BorshSerialize,
2544    {
2545        #[inline]
2546        fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
2547            <T as borsh::BorshSerialize>::serialize(&self.0, writer)
2548        }
2549    }
2550
2551    impl<T> borsh::BorshDeserialize for OrderedFloat<T>
2552    where
2553        T: borsh::BorshDeserialize,
2554    {
2555        #[inline]
2556        fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
2557            <T as borsh::BorshDeserialize>::deserialize_reader(reader).map(Self)
2558        }
2559    }
2560
2561    impl<T> borsh::BorshSerialize for NotNan<T>
2562    where
2563        T: borsh::BorshSerialize,
2564    {
2565        #[inline]
2566        fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
2567            <T as borsh::BorshSerialize>::serialize(&self.0, writer)
2568        }
2569    }
2570
2571    impl<T> borsh::BorshDeserialize for NotNan<T>
2572    where
2573        T: FloatCore + borsh::BorshDeserialize,
2574    {
2575        #[inline]
2576        fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
2577            let float = <T as borsh::BorshDeserialize>::deserialize_reader(reader)?;
2578            NotNan::new(float).map_err(|_| {
2579                borsh::io::Error::new(
2580                    borsh::io::ErrorKind::InvalidData,
2581                    "expected a non-NaN float",
2582                )
2583            })
2584        }
2585    }
2586
2587    #[test]
2588    fn test_ordered_float() {
2589        let float = crate::OrderedFloat(1.0f64);
2590        let buffer = borsh::to_vec(&float).expect("failed to serialize value");
2591        let deser_float: crate::OrderedFloat<f64> =
2592            borsh::from_slice(&buffer).expect("failed to deserialize value");
2593        assert_eq!(deser_float, float);
2594    }
2595
2596    #[test]
2597    fn test_not_nan() {
2598        let float = crate::NotNan(1.0f64);
2599        let buffer = borsh::to_vec(&float).expect("failed to serialize value");
2600        let deser_float: crate::NotNan<f64> =
2601            borsh::from_slice(&buffer).expect("failed to deserialize value");
2602        assert_eq!(deser_float, float);
2603    }
2604}
2605
2606#[cfg(all(feature = "std", feature = "schemars"))]
2607mod impl_schemars {
2608    extern crate schemars;
2609    use self::schemars::gen::SchemaGenerator;
2610    use self::schemars::schema::{InstanceType, Schema, SchemaObject};
2611    use super::{NotNan, OrderedFloat};
2612
2613    macro_rules! primitive_float_impl {
2614        ($type:ty, $schema_name:literal) => {
2615            impl schemars::JsonSchema for $type {
2616                fn is_referenceable() -> bool {
2617                    false
2618                }
2619
2620                fn schema_name() -> std::string::String {
2621                    std::string::String::from($schema_name)
2622                }
2623
2624                fn json_schema(_: &mut SchemaGenerator) -> Schema {
2625                    SchemaObject {
2626                        instance_type: Some(InstanceType::Number.into()),
2627                        format: Some(std::string::String::from($schema_name)),
2628                        ..Default::default()
2629                    }
2630                    .into()
2631                }
2632            }
2633        };
2634    }
2635
2636    primitive_float_impl!(OrderedFloat<f32>, "float");
2637    primitive_float_impl!(OrderedFloat<f64>, "double");
2638    primitive_float_impl!(NotNan<f32>, "float");
2639    primitive_float_impl!(NotNan<f64>, "double");
2640
2641    #[test]
2642    fn schema_generation_does_not_panic_for_common_floats() {
2643        {
2644            let schema = schemars::gen::SchemaGenerator::default()
2645                .into_root_schema_for::<OrderedFloat<f32>>();
2646            assert_eq!(
2647                schema.schema.instance_type,
2648                Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new(
2649                    schemars::schema::InstanceType::Number
2650                )))
2651            );
2652            assert_eq!(
2653                schema.schema.metadata.unwrap().title.unwrap(),
2654                std::string::String::from("float")
2655            );
2656        }
2657        {
2658            let schema = schemars::gen::SchemaGenerator::default()
2659                .into_root_schema_for::<OrderedFloat<f64>>();
2660            assert_eq!(
2661                schema.schema.instance_type,
2662                Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new(
2663                    schemars::schema::InstanceType::Number
2664                )))
2665            );
2666            assert_eq!(
2667                schema.schema.metadata.unwrap().title.unwrap(),
2668                std::string::String::from("double")
2669            );
2670        }
2671        {
2672            let schema =
2673                schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f32>>();
2674            assert_eq!(
2675                schema.schema.instance_type,
2676                Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new(
2677                    schemars::schema::InstanceType::Number
2678                )))
2679            );
2680            assert_eq!(
2681                schema.schema.metadata.unwrap().title.unwrap(),
2682                std::string::String::from("float")
2683            );
2684        }
2685        {
2686            let schema =
2687                schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f64>>();
2688            assert_eq!(
2689                schema.schema.instance_type,
2690                Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new(
2691                    schemars::schema::InstanceType::Number
2692                )))
2693            );
2694            assert_eq!(
2695                schema.schema.metadata.unwrap().title.unwrap(),
2696                std::string::String::from("double")
2697            );
2698        }
2699    }
2700    #[test]
2701    fn ordered_float_schema_match_primitive_schema() {
2702        {
2703            let of_schema = schemars::gen::SchemaGenerator::default()
2704                .into_root_schema_for::<OrderedFloat<f32>>();
2705            let prim_schema =
2706                schemars::gen::SchemaGenerator::default().into_root_schema_for::<f32>();
2707            assert_eq!(of_schema, prim_schema);
2708        }
2709        {
2710            let of_schema = schemars::gen::SchemaGenerator::default()
2711                .into_root_schema_for::<OrderedFloat<f64>>();
2712            let prim_schema =
2713                schemars::gen::SchemaGenerator::default().into_root_schema_for::<f64>();
2714            assert_eq!(of_schema, prim_schema);
2715        }
2716        {
2717            let of_schema =
2718                schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f32>>();
2719            let prim_schema =
2720                schemars::gen::SchemaGenerator::default().into_root_schema_for::<f32>();
2721            assert_eq!(of_schema, prim_schema);
2722        }
2723        {
2724            let of_schema =
2725                schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f64>>();
2726            let prim_schema =
2727                schemars::gen::SchemaGenerator::default().into_root_schema_for::<f64>();
2728            assert_eq!(of_schema, prim_schema);
2729        }
2730    }
2731}
2732
2733#[cfg(feature = "rand")]
2734mod impl_rand {
2735    use super::{NotNan, OrderedFloat};
2736    use rand::distributions::uniform::*;
2737    use rand::distributions::{Distribution, Open01, OpenClosed01, Standard};
2738    use rand::Rng;
2739
2740    macro_rules! impl_distribution {
2741        ($dist:ident, $($f:ty),+) => {
2742            $(
2743            impl Distribution<NotNan<$f>> for $dist {
2744                fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> NotNan<$f> {
2745                    // 'rand' never generates NaN values in the Standard, Open01, or
2746                    // OpenClosed01 distributions. Using 'new_unchecked' is therefore
2747                    // safe.
2748                    unsafe { NotNan::new_unchecked(self.sample(rng)) }
2749                }
2750            }
2751
2752            impl Distribution<OrderedFloat<$f>> for $dist {
2753                fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> OrderedFloat<$f> {
2754                    OrderedFloat(self.sample(rng))
2755                }
2756            }
2757            )*
2758        }
2759    }
2760
2761    impl_distribution! { Standard, f32, f64 }
2762    impl_distribution! { Open01, f32, f64 }
2763    impl_distribution! { OpenClosed01, f32, f64 }
2764
2765    /// A sampler for a uniform distribution
2766    #[derive(Clone, Copy, Debug)]
2767    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2768    pub struct UniformNotNan<T>(UniformFloat<T>);
2769    impl SampleUniform for NotNan<f32> {
2770        type Sampler = UniformNotNan<f32>;
2771    }
2772    impl SampleUniform for NotNan<f64> {
2773        type Sampler = UniformNotNan<f64>;
2774    }
2775    impl<T> PartialEq for UniformNotNan<T>
2776    where
2777        UniformFloat<T>: PartialEq,
2778    {
2779        fn eq(&self, other: &Self) -> bool {
2780            self.0 == other.0
2781        }
2782    }
2783
2784    /// A sampler for a uniform distribution
2785    #[derive(Clone, Copy, Debug)]
2786    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2787    pub struct UniformOrdered<T>(UniformFloat<T>);
2788    impl SampleUniform for OrderedFloat<f32> {
2789        type Sampler = UniformOrdered<f32>;
2790    }
2791    impl SampleUniform for OrderedFloat<f64> {
2792        type Sampler = UniformOrdered<f64>;
2793    }
2794    impl<T> PartialEq for UniformOrdered<T>
2795    where
2796        UniformFloat<T>: PartialEq,
2797    {
2798        fn eq(&self, other: &Self) -> bool {
2799            self.0 == other.0
2800        }
2801    }
2802
2803    macro_rules! impl_uniform_sampler {
2804        ($f:ty) => {
2805            impl UniformSampler for UniformNotNan<$f> {
2806                type X = NotNan<$f>;
2807                fn new<B1, B2>(low: B1, high: B2) -> Self
2808                where
2809                    B1: SampleBorrow<Self::X> + Sized,
2810                    B2: SampleBorrow<Self::X> + Sized,
2811                {
2812                    UniformNotNan(UniformFloat::<$f>::new(low.borrow().0, high.borrow().0))
2813                }
2814                fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
2815                where
2816                    B1: SampleBorrow<Self::X> + Sized,
2817                    B2: SampleBorrow<Self::X> + Sized,
2818                {
2819                    UniformSampler::new(low, high)
2820                }
2821                fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
2822                    // UniformFloat.sample() will never return NaN.
2823                    unsafe { NotNan::new_unchecked(self.0.sample(rng)) }
2824                }
2825            }
2826
2827            impl UniformSampler for UniformOrdered<$f> {
2828                type X = OrderedFloat<$f>;
2829                fn new<B1, B2>(low: B1, high: B2) -> Self
2830                where
2831                    B1: SampleBorrow<Self::X> + Sized,
2832                    B2: SampleBorrow<Self::X> + Sized,
2833                {
2834                    UniformOrdered(UniformFloat::<$f>::new(low.borrow().0, high.borrow().0))
2835                }
2836                fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
2837                where
2838                    B1: SampleBorrow<Self::X> + Sized,
2839                    B2: SampleBorrow<Self::X> + Sized,
2840                {
2841                    UniformSampler::new(low, high)
2842                }
2843                fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
2844                    OrderedFloat(self.0.sample(rng))
2845                }
2846            }
2847        };
2848    }
2849
2850    impl_uniform_sampler! { f32 }
2851    impl_uniform_sampler! { f64 }
2852
2853    #[cfg(all(test, feature = "randtest"))]
2854    mod tests {
2855        use super::*;
2856
2857        fn sample_fuzz<T>()
2858        where
2859            Standard: Distribution<NotNan<T>>,
2860            Open01: Distribution<NotNan<T>>,
2861            OpenClosed01: Distribution<NotNan<T>>,
2862            Standard: Distribution<OrderedFloat<T>>,
2863            Open01: Distribution<OrderedFloat<T>>,
2864            OpenClosed01: Distribution<OrderedFloat<T>>,
2865            T: crate::Float,
2866        {
2867            let mut rng = rand::thread_rng();
2868            let f1: NotNan<T> = rng.sample(Standard);
2869            let f2: NotNan<T> = rng.sample(Open01);
2870            let f3: NotNan<T> = rng.sample(OpenClosed01);
2871            let _: OrderedFloat<T> = rng.sample(Standard);
2872            let _: OrderedFloat<T> = rng.sample(Open01);
2873            let _: OrderedFloat<T> = rng.sample(OpenClosed01);
2874            assert!(!f1.into_inner().is_nan());
2875            assert!(!f2.into_inner().is_nan());
2876            assert!(!f3.into_inner().is_nan());
2877        }
2878
2879        #[test]
2880        fn sampling_f32_does_not_panic() {
2881            sample_fuzz::<f32>();
2882        }
2883
2884        #[test]
2885        fn sampling_f64_does_not_panic() {
2886            sample_fuzz::<f64>();
2887        }
2888
2889        #[test]
2890        #[should_panic]
2891        fn uniform_sampling_panic_on_infinity_notnan() {
2892            let (low, high) = (
2893                NotNan::new(0f64).unwrap(),
2894                NotNan::new(f64::INFINITY).unwrap(),
2895            );
2896            let uniform = Uniform::new(low, high);
2897            let _ = uniform.sample(&mut rand::thread_rng());
2898        }
2899
2900        #[test]
2901        #[should_panic]
2902        fn uniform_sampling_panic_on_infinity_ordered() {
2903            let (low, high) = (OrderedFloat(0f64), OrderedFloat(f64::INFINITY));
2904            let uniform = Uniform::new(low, high);
2905            let _ = uniform.sample(&mut rand::thread_rng());
2906        }
2907
2908        #[test]
2909        #[should_panic]
2910        fn uniform_sampling_panic_on_nan_ordered() {
2911            let (low, high) = (OrderedFloat(0f64), OrderedFloat(f64::NAN));
2912            let uniform = Uniform::new(low, high);
2913            let _ = uniform.sample(&mut rand::thread_rng());
2914        }
2915    }
2916}
2917
2918#[cfg(feature = "proptest")]
2919mod impl_proptest {
2920    use super::{NotNan, OrderedFloat};
2921    use proptest::arbitrary::{Arbitrary, StrategyFor};
2922    use proptest::num::{f32, f64};
2923    use proptest::strategy::{FilterMap, Map, Strategy};
2924    use std::convert::TryFrom;
2925
2926    macro_rules! impl_arbitrary {
2927        ($($f:ident),+) => {
2928            $(
2929                impl Arbitrary for NotNan<$f> {
2930                    type Strategy = FilterMap<StrategyFor<$f>, fn(_: $f) -> Option<NotNan<$f>>>;
2931                    type Parameters = <$f as Arbitrary>::Parameters;
2932                    fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
2933                        <$f>::arbitrary_with(params)
2934                            .prop_filter_map("filter nan values", |f| NotNan::try_from(f).ok())
2935                    }
2936                }
2937
2938                impl Arbitrary for OrderedFloat<$f> {
2939                    type Strategy = Map<StrategyFor<$f>, fn(_: $f) -> OrderedFloat<$f>>;
2940                    type Parameters = <$f as Arbitrary>::Parameters;
2941                    fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
2942                        <$f>::arbitrary_with(params).prop_map(|f| OrderedFloat::from(f))
2943                    }
2944                }
2945            )*
2946        }
2947    }
2948    impl_arbitrary! { f32, f64 }
2949}
2950
2951#[cfg(feature = "arbitrary")]
2952mod impl_arbitrary {
2953    use super::{FloatIsNan, NotNan, OrderedFloat};
2954    use arbitrary::{Arbitrary, Unstructured};
2955    use num_traits::FromPrimitive;
2956
2957    macro_rules! impl_arbitrary {
2958        ($($f:ident),+) => {
2959            $(
2960                impl<'a> Arbitrary<'a> for NotNan<$f> {
2961                    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
2962                        let float: $f = u.arbitrary()?;
2963                        match NotNan::new(float) {
2964                            Ok(notnan_value) => Ok(notnan_value),
2965                            Err(FloatIsNan) => {
2966                                // If our arbitrary float input was a NaN (encoded by exponent = max
2967                                // value), then replace it with a finite float, reusing the mantissa
2968                                // bits.
2969                                //
2970                                // This means the output is not uniformly distributed among all
2971                                // possible float values, but Arbitrary makes no promise that that
2972                                // is true.
2973                                //
2974                                // An alternative implementation would be to return an
2975                                // `arbitrary::Error`, but that is not as useful since it forces the
2976                                // caller to retry with new random/fuzzed data; and the precendent of
2977                                // `arbitrary`'s built-in implementations is to prefer the approach of
2978                                // mangling the input bits to fit.
2979
2980                                let (mantissa, _exponent, sign) =
2981                                    num_traits::float::FloatCore::integer_decode(float);
2982                                let revised_float = <$f>::from_i64(
2983                                    i64::from(sign) * mantissa as i64
2984                                ).unwrap();
2985
2986                                // If this unwrap() fails, then there is a bug in the above code.
2987                                Ok(NotNan::new(revised_float).unwrap())
2988                            }
2989                        }
2990                    }
2991
2992                    fn size_hint(depth: usize) -> (usize, Option<usize>) {
2993                        <$f as Arbitrary>::size_hint(depth)
2994                    }
2995                }
2996
2997                impl<'a> Arbitrary<'a> for OrderedFloat<$f> {
2998                    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
2999                        let float: $f = u.arbitrary()?;
3000                        Ok(OrderedFloat::from(float))
3001                    }
3002
3003                    fn size_hint(depth: usize) -> (usize, Option<usize>) {
3004                        <$f as Arbitrary>::size_hint(depth)
3005                    }
3006                }
3007            )*
3008        }
3009    }
3010    impl_arbitrary! { f32, f64 }
3011}
3012
3013#[cfg(feature = "bytemuck")]
3014mod impl_bytemuck {
3015    use super::{FloatCore, NotNan, OrderedFloat};
3016    use bytemuck::{AnyBitPattern, CheckedBitPattern, NoUninit, Pod, TransparentWrapper, Zeroable};
3017
3018    unsafe impl<T: Zeroable> Zeroable for OrderedFloat<T> {}
3019
3020    // The zero bit pattern is indeed not a NaN bit pattern.
3021    unsafe impl<T: Zeroable> Zeroable for NotNan<T> {}
3022
3023    unsafe impl<T: Pod> Pod for OrderedFloat<T> {}
3024
3025    // `NotNan<T>` can only implement `NoUninit` and not `Pod`, since not every bit pattern is
3026    // valid (NaN bit patterns are invalid). `NoUninit` guarantees that we can read any bit pattern
3027    // from the value, which is fine in this case.
3028    unsafe impl<T: NoUninit> NoUninit for NotNan<T> {}
3029
3030    unsafe impl<T: FloatCore + AnyBitPattern> CheckedBitPattern for NotNan<T> {
3031        type Bits = T;
3032
3033        fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
3034            !bits.is_nan()
3035        }
3036    }
3037
3038    // OrderedFloat allows any value of the contained type, so it is a TransparentWrapper.
3039    // NotNan does not, so it is not.
3040    unsafe impl<T> TransparentWrapper<T> for OrderedFloat<T> {}
3041
3042    #[test]
3043    fn test_not_nan_bit_pattern() {
3044        use bytemuck::checked::{try_cast, CheckedCastError};
3045
3046        let nan = f64::NAN;
3047        assert_eq!(
3048            try_cast::<f64, NotNan<f64>>(nan),
3049            Err(CheckedCastError::InvalidBitPattern),
3050        );
3051
3052        let pi = core::f64::consts::PI;
3053        assert!(try_cast::<f64, NotNan<f64>>(pi).is_ok());
3054    }
3055}