Skip to main content

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