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