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