ordered_float/
lib.rs

1#![no_std]
2#![cfg_attr(test, deny(warnings))]
3#![deny(missing_docs)]
4
5//! Wrappers for total order on Floats.  See the [`OrderedFloat`] and [`NotNan`] docs for details.
6
7#[cfg(feature = "std")]
8extern crate std;
9#[cfg(feature = "std")]
10use std::error::Error;
11
12use core::borrow::Borrow;
13use core::cmp::Ordering;
14use core::convert::TryFrom;
15use core::fmt;
16use core::hash::{Hash, Hasher};
17use core::hint::unreachable_unchecked;
18use core::iter::{Product, Sum};
19use core::num::FpCategory;
20use core::ops::{
21    Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub,
22    SubAssign,
23};
24use core::str::FromStr;
25
26#[cfg(not(feature = "std"))]
27use num_traits::float::FloatCore as Float;
28#[cfg(feature = "std")]
29pub use num_traits::Float;
30use num_traits::{Bounded, FromPrimitive, Num, NumCast, One, Signed, ToPrimitive, Zero};
31
32// masks for the parts of the IEEE 754 float
33const SIGN_MASK: u64 = 0x8000000000000000u64;
34const EXP_MASK: u64 = 0x7ff0000000000000u64;
35const MAN_MASK: u64 = 0x000fffffffffffffu64;
36
37// canonical raw bit patterns (for hashing)
38const CANONICAL_NAN_BITS: u64 = 0x7ff8000000000000u64;
39
40#[inline(always)]
41fn canonicalize_signed_zero<T: Float>(x: T) -> T {
42    // -0.0 + 0.0 == +0.0 under IEEE754 roundTiesToEven rounding mode,
43    // which Rust guarantees. Thus by adding a positive zero we
44    // canonicalize signed zero without any branches in one instruction.
45    x + T::zero()
46}
47
48/// A wrapper around floats providing implementations of `Eq`, `Ord`, and `Hash`.
49///
50/// NaN is sorted as *greater* than all other values and *equal*
51/// to itself, in contradiction with the IEEE standard.
52///
53/// ```
54/// use ordered_float::OrderedFloat;
55/// use std::f32::NAN;
56///
57/// let mut v = [OrderedFloat(NAN), OrderedFloat(2.0), OrderedFloat(1.0)];
58/// v.sort();
59/// assert_eq!(v, [OrderedFloat(1.0), OrderedFloat(2.0), OrderedFloat(NAN)]);
60/// ```
61///
62/// Because `OrderedFloat` implements `Ord` and `Eq`, it can be used as a key in a `HashSet`,
63/// `HashMap`, `BTreeMap`, or `BTreeSet` (unlike the primitive `f32` or `f64` types):
64///
65/// ```
66/// # use ordered_float::OrderedFloat;
67/// # use std::collections::HashSet;
68/// # use std::f32::NAN;
69///
70/// let mut s: HashSet<OrderedFloat<f32>> = HashSet::new();
71/// s.insert(OrderedFloat(NAN));
72/// assert!(s.contains(&OrderedFloat(NAN)));
73/// ```
74#[derive(Debug, Default, Clone, Copy)]
75#[repr(transparent)]
76pub struct OrderedFloat<T>(pub T);
77
78impl<T: Float> OrderedFloat<T> {
79    /// Get the value out.
80    #[inline]
81    pub fn into_inner(self) -> T {
82        self.0
83    }
84}
85
86impl<T: Float> AsRef<T> for OrderedFloat<T> {
87    #[inline]
88    fn as_ref(&self) -> &T {
89        &self.0
90    }
91}
92
93impl<T: Float> AsMut<T> for OrderedFloat<T> {
94    #[inline]
95    fn as_mut(&mut self) -> &mut T {
96        &mut self.0
97    }
98}
99
100impl<'a, T: Float> From<&'a T> for &'a OrderedFloat<T> {
101    #[inline]
102    fn from(t: &'a T) -> &'a OrderedFloat<T> {
103        // Safety: OrderedFloat is #[repr(transparent)] and has no invalid values.
104        unsafe { &*(t as *const T as *const OrderedFloat<T>) }
105    }
106}
107
108impl<'a, T: Float> From<&'a mut T> for &'a mut OrderedFloat<T> {
109    #[inline]
110    fn from(t: &'a mut T) -> &'a mut OrderedFloat<T> {
111        // Safety: OrderedFloat is #[repr(transparent)] and has no invalid values.
112        unsafe { &mut *(t as *mut T as *mut OrderedFloat<T>) }
113    }
114}
115
116impl<T: Float> PartialOrd for OrderedFloat<T> {
117    #[inline]
118    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
119        Some(self.cmp(other))
120    }
121
122    #[inline]
123    fn lt(&self, other: &Self) -> bool {
124        !self.ge(other)
125    }
126
127    #[inline]
128    fn le(&self, other: &Self) -> bool {
129        other.ge(self)
130    }
131
132    #[inline]
133    fn gt(&self, other: &Self) -> bool {
134        !other.ge(self)
135    }
136
137    #[inline]
138    fn ge(&self, other: &Self) -> bool {
139        // We consider all NaNs equal, and NaN is the largest possible
140        // value. Thus if self is NaN we always return true. Otherwise
141        // self >= other is correct. If other is also not NaN it is trivially
142        // correct, and if it is we note that nothing can be greater or
143        // equal to NaN except NaN itself, which we already handled earlier.
144        self.0.is_nan() | (self.0 >= other.0)
145    }
146}
147
148impl<T: Float> Ord for OrderedFloat<T> {
149    #[inline]
150    #[allow(clippy::comparison_chain)]
151    fn cmp(&self, other: &Self) -> Ordering {
152        if self < other {
153            Ordering::Less
154        } else if self > other {
155            Ordering::Greater
156        } else {
157            Ordering::Equal
158        }
159    }
160}
161
162impl<T: Float> PartialEq for OrderedFloat<T> {
163    #[inline]
164    fn eq(&self, other: &OrderedFloat<T>) -> bool {
165        if self.0.is_nan() {
166            other.0.is_nan()
167        } else {
168            self.0 == other.0
169        }
170    }
171}
172
173impl<T: Float> PartialEq<T> for OrderedFloat<T> {
174    #[inline]
175    fn eq(&self, other: &T) -> bool {
176        self.0 == *other
177    }
178}
179
180impl<T: Float> Hash for OrderedFloat<T> {
181    fn hash<H: Hasher>(&self, state: &mut H) {
182        let bits = if self.is_nan() {
183            CANONICAL_NAN_BITS
184        } else {
185            raw_double_bits(&canonicalize_signed_zero(self.0))
186        };
187
188        bits.hash(state)
189    }
190}
191
192impl<T: Float + fmt::Display> fmt::Display for OrderedFloat<T> {
193    #[inline]
194    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
195        self.0.fmt(f)
196    }
197}
198
199impl From<OrderedFloat<f32>> for f32 {
200    #[inline]
201    fn from(f: OrderedFloat<f32>) -> f32 {
202        f.0
203    }
204}
205
206impl From<OrderedFloat<f64>> for f64 {
207    #[inline]
208    fn from(f: OrderedFloat<f64>) -> f64 {
209        f.0
210    }
211}
212
213impl<T: Float> From<T> for OrderedFloat<T> {
214    #[inline]
215    fn from(val: T) -> Self {
216        OrderedFloat(val)
217    }
218}
219
220impl<T: Float> Deref for OrderedFloat<T> {
221    type Target = T;
222
223    #[inline]
224    fn deref(&self) -> &Self::Target {
225        &self.0
226    }
227}
228
229impl<T: Float> DerefMut for OrderedFloat<T> {
230    #[inline]
231    fn deref_mut(&mut self) -> &mut Self::Target {
232        &mut self.0
233    }
234}
235
236impl<T: Float> Eq for OrderedFloat<T> {}
237
238macro_rules! impl_ordered_float_binop {
239    ($imp:ident, $method:ident, $assign_imp:ident, $assign_method:ident) => {
240        impl<T: $imp> $imp for OrderedFloat<T> {
241            type Output = OrderedFloat<T::Output>;
242
243            #[inline]
244            fn $method(self, other: Self) -> Self::Output {
245                OrderedFloat((self.0).$method(other.0))
246            }
247        }
248
249        impl<T: $imp> $imp<T> for OrderedFloat<T> {
250            type Output = OrderedFloat<T::Output>;
251
252            #[inline]
253            fn $method(self, other: T) -> Self::Output {
254                OrderedFloat((self.0).$method(other))
255            }
256        }
257
258        impl<'a, T> $imp<&'a T> for OrderedFloat<T>
259        where
260            T: $imp<&'a T>,
261        {
262            type Output = OrderedFloat<<T as $imp<&'a T>>::Output>;
263
264            #[inline]
265            fn $method(self, other: &'a T) -> Self::Output {
266                OrderedFloat((self.0).$method(other))
267            }
268        }
269
270        impl<'a, T> $imp<&'a Self> for OrderedFloat<T>
271        where
272            T: $imp<&'a T>,
273        {
274            type Output = OrderedFloat<<T as $imp<&'a T>>::Output>;
275
276            #[inline]
277            fn $method(self, other: &'a Self) -> Self::Output {
278                OrderedFloat((self.0).$method(&other.0))
279            }
280        }
281
282        impl<'a, T> $imp for &'a OrderedFloat<T>
283        where
284            &'a T: $imp,
285        {
286            type Output = OrderedFloat<<&'a T as $imp>::Output>;
287
288            #[inline]
289            fn $method(self, other: Self) -> Self::Output {
290                OrderedFloat((self.0).$method(&other.0))
291            }
292        }
293
294        impl<'a, T> $imp<OrderedFloat<T>> for &'a OrderedFloat<T>
295        where
296            &'a T: $imp<T>,
297        {
298            type Output = OrderedFloat<<&'a T as $imp<T>>::Output>;
299
300            #[inline]
301            fn $method(self, other: OrderedFloat<T>) -> Self::Output {
302                OrderedFloat((self.0).$method(other.0))
303            }
304        }
305
306        impl<'a, T> $imp<T> for &'a OrderedFloat<T>
307        where
308            &'a T: $imp<T>,
309        {
310            type Output = OrderedFloat<<&'a T as $imp<T>>::Output>;
311
312            #[inline]
313            fn $method(self, other: T) -> Self::Output {
314                OrderedFloat((self.0).$method(other))
315            }
316        }
317
318        impl<'a, T> $imp<&'a T> for &'a OrderedFloat<T>
319        where
320            &'a T: $imp,
321        {
322            type Output = OrderedFloat<<&'a T as $imp>::Output>;
323
324            #[inline]
325            fn $method(self, other: &'a T) -> Self::Output {
326                OrderedFloat((self.0).$method(other))
327            }
328        }
329
330        #[doc(hidden)] // Added accidentally; remove in next major version
331        impl<'a, T> $imp<&'a Self> for &'a OrderedFloat<T>
332        where
333            &'a T: $imp,
334        {
335            type Output = OrderedFloat<<&'a T as $imp>::Output>;
336
337            #[inline]
338            fn $method(self, other: &'a Self) -> Self::Output {
339                OrderedFloat((self.0).$method(&other.0))
340            }
341        }
342
343        impl<T: $assign_imp> $assign_imp<T> for OrderedFloat<T> {
344            #[inline]
345            fn $assign_method(&mut self, other: T) {
346                (self.0).$assign_method(other);
347            }
348        }
349
350        impl<'a, T: $assign_imp<&'a T>> $assign_imp<&'a T> for OrderedFloat<T> {
351            #[inline]
352            fn $assign_method(&mut self, other: &'a T) {
353                (self.0).$assign_method(other);
354            }
355        }
356
357        impl<T: $assign_imp> $assign_imp for OrderedFloat<T> {
358            #[inline]
359            fn $assign_method(&mut self, other: Self) {
360                (self.0).$assign_method(other.0);
361            }
362        }
363
364        impl<'a, T: $assign_imp<&'a T>> $assign_imp<&'a Self> for OrderedFloat<T> {
365            #[inline]
366            fn $assign_method(&mut self, other: &'a Self) {
367                (self.0).$assign_method(&other.0);
368            }
369        }
370    };
371}
372
373impl_ordered_float_binop! {Add, add, AddAssign, add_assign}
374impl_ordered_float_binop! {Sub, sub, SubAssign, sub_assign}
375impl_ordered_float_binop! {Mul, mul, MulAssign, mul_assign}
376impl_ordered_float_binop! {Div, div, DivAssign, div_assign}
377impl_ordered_float_binop! {Rem, rem, RemAssign, rem_assign}
378
379/// Adds a float directly.
380impl<T: Float + Sum> Sum for OrderedFloat<T> {
381    fn sum<I: Iterator<Item = OrderedFloat<T>>>(iter: I) -> Self {
382        OrderedFloat(iter.map(|v| v.0).sum())
383    }
384}
385
386impl<'a, T: Float + Sum + 'a> Sum<&'a OrderedFloat<T>> for OrderedFloat<T> {
387    #[inline]
388    fn sum<I: Iterator<Item = &'a OrderedFloat<T>>>(iter: I) -> Self {
389        iter.cloned().sum()
390    }
391}
392
393impl<T: Float + Product> Product for OrderedFloat<T> {
394    fn product<I: Iterator<Item = OrderedFloat<T>>>(iter: I) -> Self {
395        OrderedFloat(iter.map(|v| v.0).product())
396    }
397}
398
399impl<'a, T: Float + Product + 'a> Product<&'a OrderedFloat<T>> for OrderedFloat<T> {
400    #[inline]
401    fn product<I: Iterator<Item = &'a OrderedFloat<T>>>(iter: I) -> Self {
402        iter.cloned().product()
403    }
404}
405
406impl<T: Float + Signed> Signed for OrderedFloat<T> {
407    #[inline]
408    fn abs(&self) -> Self {
409        OrderedFloat(self.0.abs())
410    }
411
412    fn abs_sub(&self, other: &Self) -> Self {
413        OrderedFloat(Signed::abs_sub(&self.0, &other.0))
414    }
415
416    #[inline]
417    fn signum(&self) -> Self {
418        OrderedFloat(self.0.signum())
419    }
420    #[inline]
421    fn is_positive(&self) -> bool {
422        self.0.is_positive()
423    }
424    #[inline]
425    fn is_negative(&self) -> bool {
426        self.0.is_negative()
427    }
428}
429
430impl<T: Bounded> Bounded for OrderedFloat<T> {
431    #[inline]
432    fn min_value() -> Self {
433        OrderedFloat(T::min_value())
434    }
435
436    #[inline]
437    fn max_value() -> Self {
438        OrderedFloat(T::max_value())
439    }
440}
441
442impl<T: FromStr> FromStr for OrderedFloat<T> {
443    type Err = T::Err;
444
445    /// Convert a &str to `OrderedFloat`. Returns an error if the string fails to parse.
446    ///
447    /// ```
448    /// use ordered_float::OrderedFloat;
449    ///
450    /// assert!("-10".parse::<OrderedFloat<f32>>().is_ok());
451    /// assert!("abc".parse::<OrderedFloat<f32>>().is_err());
452    /// assert!("NaN".parse::<OrderedFloat<f32>>().is_ok());
453    /// ```
454    fn from_str(s: &str) -> Result<Self, Self::Err> {
455        T::from_str(s).map(OrderedFloat)
456    }
457}
458
459impl<T: Neg> Neg for OrderedFloat<T> {
460    type Output = OrderedFloat<T::Output>;
461
462    #[inline]
463    fn neg(self) -> Self::Output {
464        OrderedFloat(-self.0)
465    }
466}
467
468impl<'a, T> Neg for &'a OrderedFloat<T>
469where
470    &'a T: Neg,
471{
472    type Output = OrderedFloat<<&'a T as Neg>::Output>;
473
474    #[inline]
475    fn neg(self) -> Self::Output {
476        OrderedFloat(-(&self.0))
477    }
478}
479
480impl<T: Zero> Zero for OrderedFloat<T> {
481    #[inline]
482    fn zero() -> Self {
483        OrderedFloat(T::zero())
484    }
485
486    #[inline]
487    fn is_zero(&self) -> bool {
488        self.0.is_zero()
489    }
490}
491
492impl<T: One> One for OrderedFloat<T> {
493    #[inline]
494    fn one() -> Self {
495        OrderedFloat(T::one())
496    }
497}
498
499impl<T: NumCast> NumCast for OrderedFloat<T> {
500    #[inline]
501    fn from<F: ToPrimitive>(n: F) -> Option<Self> {
502        T::from(n).map(OrderedFloat)
503    }
504}
505
506impl<T: FromPrimitive> FromPrimitive for OrderedFloat<T> {
507    fn from_i64(n: i64) -> Option<Self> {
508        T::from_i64(n).map(OrderedFloat)
509    }
510    fn from_u64(n: u64) -> Option<Self> {
511        T::from_u64(n).map(OrderedFloat)
512    }
513    fn from_isize(n: isize) -> Option<Self> {
514        T::from_isize(n).map(OrderedFloat)
515    }
516    fn from_i8(n: i8) -> Option<Self> {
517        T::from_i8(n).map(OrderedFloat)
518    }
519    fn from_i16(n: i16) -> Option<Self> {
520        T::from_i16(n).map(OrderedFloat)
521    }
522    fn from_i32(n: i32) -> Option<Self> {
523        T::from_i32(n).map(OrderedFloat)
524    }
525    fn from_usize(n: usize) -> Option<Self> {
526        T::from_usize(n).map(OrderedFloat)
527    }
528    fn from_u8(n: u8) -> Option<Self> {
529        T::from_u8(n).map(OrderedFloat)
530    }
531    fn from_u16(n: u16) -> Option<Self> {
532        T::from_u16(n).map(OrderedFloat)
533    }
534    fn from_u32(n: u32) -> Option<Self> {
535        T::from_u32(n).map(OrderedFloat)
536    }
537    fn from_f32(n: f32) -> Option<Self> {
538        T::from_f32(n).map(OrderedFloat)
539    }
540    fn from_f64(n: f64) -> Option<Self> {
541        T::from_f64(n).map(OrderedFloat)
542    }
543}
544
545impl<T: ToPrimitive> ToPrimitive for OrderedFloat<T> {
546    fn to_i64(&self) -> Option<i64> {
547        self.0.to_i64()
548    }
549    fn to_u64(&self) -> Option<u64> {
550        self.0.to_u64()
551    }
552    fn to_isize(&self) -> Option<isize> {
553        self.0.to_isize()
554    }
555    fn to_i8(&self) -> Option<i8> {
556        self.0.to_i8()
557    }
558    fn to_i16(&self) -> Option<i16> {
559        self.0.to_i16()
560    }
561    fn to_i32(&self) -> Option<i32> {
562        self.0.to_i32()
563    }
564    fn to_usize(&self) -> Option<usize> {
565        self.0.to_usize()
566    }
567    fn to_u8(&self) -> Option<u8> {
568        self.0.to_u8()
569    }
570    fn to_u16(&self) -> Option<u16> {
571        self.0.to_u16()
572    }
573    fn to_u32(&self) -> Option<u32> {
574        self.0.to_u32()
575    }
576    fn to_f32(&self) -> Option<f32> {
577        self.0.to_f32()
578    }
579    fn to_f64(&self) -> Option<f64> {
580        self.0.to_f64()
581    }
582}
583
584impl<T: Float> num_traits::float::FloatCore for OrderedFloat<T> {
585    fn nan() -> Self {
586        OrderedFloat(T::nan())
587    }
588    fn infinity() -> Self {
589        OrderedFloat(T::infinity())
590    }
591    fn neg_infinity() -> Self {
592        OrderedFloat(T::neg_infinity())
593    }
594    fn neg_zero() -> Self {
595        OrderedFloat(T::neg_zero())
596    }
597    fn min_value() -> Self {
598        OrderedFloat(T::min_value())
599    }
600    fn min_positive_value() -> Self {
601        OrderedFloat(T::min_positive_value())
602    }
603    fn max_value() -> Self {
604        OrderedFloat(T::max_value())
605    }
606    fn is_nan(self) -> bool {
607        self.0.is_nan()
608    }
609    fn is_infinite(self) -> bool {
610        self.0.is_infinite()
611    }
612    fn is_finite(self) -> bool {
613        self.0.is_finite()
614    }
615    fn is_normal(self) -> bool {
616        self.0.is_normal()
617    }
618    fn classify(self) -> FpCategory {
619        self.0.classify()
620    }
621    fn floor(self) -> Self {
622        OrderedFloat(self.0.floor())
623    }
624    fn ceil(self) -> Self {
625        OrderedFloat(self.0.ceil())
626    }
627    fn round(self) -> Self {
628        OrderedFloat(self.0.round())
629    }
630    fn trunc(self) -> Self {
631        OrderedFloat(self.0.trunc())
632    }
633    fn fract(self) -> Self {
634        OrderedFloat(self.0.fract())
635    }
636    fn abs(self) -> Self {
637        OrderedFloat(self.0.abs())
638    }
639    fn signum(self) -> Self {
640        OrderedFloat(self.0.signum())
641    }
642    fn is_sign_positive(self) -> bool {
643        self.0.is_sign_positive()
644    }
645    fn is_sign_negative(self) -> bool {
646        self.0.is_sign_negative()
647    }
648    fn recip(self) -> Self {
649        OrderedFloat(self.0.recip())
650    }
651    fn powi(self, n: i32) -> Self {
652        OrderedFloat(self.0.powi(n))
653    }
654    fn integer_decode(self) -> (u64, i16, i8) {
655        self.0.integer_decode()
656    }
657    fn epsilon() -> Self {
658        OrderedFloat(T::epsilon())
659    }
660    fn to_degrees(self) -> Self {
661        OrderedFloat(self.0.to_degrees())
662    }
663    fn to_radians(self) -> Self {
664        OrderedFloat(self.0.to_radians())
665    }
666}
667
668#[cfg(feature = "std")]
669impl<T: Float> Float for OrderedFloat<T> {
670    fn nan() -> Self {
671        OrderedFloat(T::nan())
672    }
673    fn infinity() -> Self {
674        OrderedFloat(T::infinity())
675    }
676    fn neg_infinity() -> Self {
677        OrderedFloat(T::neg_infinity())
678    }
679    fn neg_zero() -> Self {
680        OrderedFloat(T::neg_zero())
681    }
682    fn min_value() -> Self {
683        OrderedFloat(T::min_value())
684    }
685    fn min_positive_value() -> Self {
686        OrderedFloat(T::min_positive_value())
687    }
688    fn max_value() -> Self {
689        OrderedFloat(T::max_value())
690    }
691    fn is_nan(self) -> bool {
692        self.0.is_nan()
693    }
694    fn is_infinite(self) -> bool {
695        self.0.is_infinite()
696    }
697    fn is_finite(self) -> bool {
698        self.0.is_finite()
699    }
700    fn is_normal(self) -> bool {
701        self.0.is_normal()
702    }
703    fn classify(self) -> FpCategory {
704        self.0.classify()
705    }
706    fn floor(self) -> Self {
707        OrderedFloat(self.0.floor())
708    }
709    fn ceil(self) -> Self {
710        OrderedFloat(self.0.ceil())
711    }
712    fn round(self) -> Self {
713        OrderedFloat(self.0.round())
714    }
715    fn trunc(self) -> Self {
716        OrderedFloat(self.0.trunc())
717    }
718    fn fract(self) -> Self {
719        OrderedFloat(self.0.fract())
720    }
721    fn abs(self) -> Self {
722        OrderedFloat(self.0.abs())
723    }
724    fn signum(self) -> Self {
725        OrderedFloat(self.0.signum())
726    }
727    fn is_sign_positive(self) -> bool {
728        self.0.is_sign_positive()
729    }
730    fn is_sign_negative(self) -> bool {
731        self.0.is_sign_negative()
732    }
733    fn mul_add(self, a: Self, b: Self) -> Self {
734        OrderedFloat(self.0.mul_add(a.0, b.0))
735    }
736    fn recip(self) -> Self {
737        OrderedFloat(self.0.recip())
738    }
739    fn powi(self, n: i32) -> Self {
740        OrderedFloat(self.0.powi(n))
741    }
742    fn powf(self, n: Self) -> Self {
743        OrderedFloat(self.0.powf(n.0))
744    }
745    fn sqrt(self) -> Self {
746        OrderedFloat(self.0.sqrt())
747    }
748    fn exp(self) -> Self {
749        OrderedFloat(self.0.exp())
750    }
751    fn exp2(self) -> Self {
752        OrderedFloat(self.0.exp2())
753    }
754    fn ln(self) -> Self {
755        OrderedFloat(self.0.ln())
756    }
757    fn log(self, base: Self) -> Self {
758        OrderedFloat(self.0.log(base.0))
759    }
760    fn log2(self) -> Self {
761        OrderedFloat(self.0.log2())
762    }
763    fn log10(self) -> Self {
764        OrderedFloat(self.0.log10())
765    }
766    fn max(self, other: Self) -> Self {
767        OrderedFloat(self.0.max(other.0))
768    }
769    fn min(self, other: Self) -> Self {
770        OrderedFloat(self.0.min(other.0))
771    }
772    fn abs_sub(self, other: Self) -> Self {
773        OrderedFloat(self.0.abs_sub(other.0))
774    }
775    fn cbrt(self) -> Self {
776        OrderedFloat(self.0.cbrt())
777    }
778    fn hypot(self, other: Self) -> Self {
779        OrderedFloat(self.0.hypot(other.0))
780    }
781    fn sin(self) -> Self {
782        OrderedFloat(self.0.sin())
783    }
784    fn cos(self) -> Self {
785        OrderedFloat(self.0.cos())
786    }
787    fn tan(self) -> Self {
788        OrderedFloat(self.0.tan())
789    }
790    fn asin(self) -> Self {
791        OrderedFloat(self.0.asin())
792    }
793    fn acos(self) -> Self {
794        OrderedFloat(self.0.acos())
795    }
796    fn atan(self) -> Self {
797        OrderedFloat(self.0.atan())
798    }
799    fn atan2(self, other: Self) -> Self {
800        OrderedFloat(self.0.atan2(other.0))
801    }
802    fn sin_cos(self) -> (Self, Self) {
803        let (a, b) = self.0.sin_cos();
804        (OrderedFloat(a), OrderedFloat(b))
805    }
806    fn exp_m1(self) -> Self {
807        OrderedFloat(self.0.exp_m1())
808    }
809    fn ln_1p(self) -> Self {
810        OrderedFloat(self.0.ln_1p())
811    }
812    fn sinh(self) -> Self {
813        OrderedFloat(self.0.sinh())
814    }
815    fn cosh(self) -> Self {
816        OrderedFloat(self.0.cosh())
817    }
818    fn tanh(self) -> Self {
819        OrderedFloat(self.0.tanh())
820    }
821    fn asinh(self) -> Self {
822        OrderedFloat(self.0.asinh())
823    }
824    fn acosh(self) -> Self {
825        OrderedFloat(self.0.acosh())
826    }
827    fn atanh(self) -> Self {
828        OrderedFloat(self.0.atanh())
829    }
830    fn integer_decode(self) -> (u64, i16, i8) {
831        self.0.integer_decode()
832    }
833    fn epsilon() -> Self {
834        OrderedFloat(T::epsilon())
835    }
836    fn to_degrees(self) -> Self {
837        OrderedFloat(self.0.to_degrees())
838    }
839    fn to_radians(self) -> Self {
840        OrderedFloat(self.0.to_radians())
841    }
842}
843
844impl<T: Float + Num> Num for OrderedFloat<T> {
845    type FromStrRadixErr = T::FromStrRadixErr;
846    fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
847        T::from_str_radix(str, radix).map(OrderedFloat)
848    }
849}
850
851/// A wrapper around floats providing an implementation of `Eq`, `Ord` and `Hash`.
852///
853/// A NaN value cannot be stored in this type.
854///
855/// ```
856/// use ordered_float::NotNan;
857///
858/// let mut v = [
859///     NotNan::new(2.0).unwrap(),
860///     NotNan::new(1.0).unwrap(),
861/// ];
862/// v.sort();
863/// assert_eq!(v, [1.0, 2.0]);
864/// ```
865///
866/// Because `NotNan` implements `Ord` and `Eq`, it can be used as a key in a `HashSet`,
867/// `HashMap`, `BTreeMap`, or `BTreeSet` (unlike the primitive `f32` or `f64` types):
868///
869/// ```
870/// # use ordered_float::NotNan;
871/// # use std::collections::HashSet;
872///
873/// let mut s: HashSet<NotNan<f32>> = HashSet::new();
874/// let key = NotNan::new(1.0).unwrap();
875/// s.insert(key);
876/// assert!(s.contains(&key));
877/// ```
878///
879/// Arithmetic on NotNan values will panic if it produces a NaN value:
880///
881/// ```should_panic
882/// # use ordered_float::NotNan;
883/// let a = NotNan::new(std::f32::INFINITY).unwrap();
884/// let b = NotNan::new(std::f32::NEG_INFINITY).unwrap();
885///
886/// // This will panic:
887/// let c = a + b;
888/// ```
889#[derive(PartialOrd, PartialEq, Debug, Default, Clone, Copy)]
890#[repr(transparent)]
891pub struct NotNan<T>(T);
892
893impl<T: Float> NotNan<T> {
894    /// Create a `NotNan` value.
895    ///
896    /// Returns `Err` if `val` is NaN
897    pub fn new(val: T) -> Result<Self, FloatIsNan> {
898        match val {
899            ref val if val.is_nan() => Err(FloatIsNan),
900            val => Ok(NotNan(val)),
901        }
902    }
903}
904
905impl<T> NotNan<T> {
906    /// Get the value out.
907    #[inline]
908    pub fn into_inner(self) -> T {
909        self.0
910    }
911
912    /// Create a `NotNan` value from a value that is guaranteed to not be NaN
913    ///
914    /// # Safety
915    ///
916    /// Behaviour is undefined if `val` is NaN
917    #[inline]
918    pub const unsafe fn new_unchecked(val: T) -> Self {
919        NotNan(val)
920    }
921
922    /// Create a `NotNan` value from a value that is guaranteed to not be NaN
923    ///
924    /// # Safety
925    ///
926    /// Behaviour is undefined if `val` is NaN
927    #[deprecated(
928        since = "2.5.0",
929        note = "Please use the new_unchecked function instead."
930    )]
931    #[inline]
932    pub const unsafe fn unchecked_new(val: T) -> Self {
933        Self::new_unchecked(val)
934    }
935}
936
937impl<T: Float> AsRef<T> for NotNan<T> {
938    #[inline]
939    fn as_ref(&self) -> &T {
940        &self.0
941    }
942}
943
944impl Borrow<f32> for NotNan<f32> {
945    #[inline]
946    fn borrow(&self) -> &f32 {
947        &self.0
948    }
949}
950
951impl Borrow<f64> for NotNan<f64> {
952    #[inline]
953    fn borrow(&self) -> &f64 {
954        &self.0
955    }
956}
957
958#[allow(clippy::derive_ord_xor_partial_ord)]
959impl<T: Float> Ord for NotNan<T> {
960    fn cmp(&self, other: &NotNan<T>) -> Ordering {
961        match self.partial_cmp(&other) {
962            Some(ord) => ord,
963            None => unsafe { unreachable_unchecked() },
964        }
965    }
966}
967
968#[allow(clippy::derive_hash_xor_eq)]
969impl<T: Float> Hash for NotNan<T> {
970    #[inline]
971    fn hash<H: Hasher>(&self, state: &mut H) {
972        let bits = raw_double_bits(&canonicalize_signed_zero(self.0));
973        bits.hash(state)
974    }
975}
976
977impl<T: Float + fmt::Display> fmt::Display for NotNan<T> {
978    #[inline]
979    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
980        self.0.fmt(f)
981    }
982}
983
984impl From<NotNan<f32>> for f32 {
985    #[inline]
986    fn from(value: NotNan<f32>) -> Self {
987        value.0
988    }
989}
990
991impl From<NotNan<f64>> for f64 {
992    #[inline]
993    fn from(value: NotNan<f64>) -> Self {
994        value.0
995    }
996}
997
998impl TryFrom<f32> for NotNan<f32> {
999    type Error = FloatIsNan;
1000    #[inline]
1001    fn try_from(v: f32) -> Result<Self, Self::Error> {
1002        NotNan::new(v)
1003    }
1004}
1005
1006impl TryFrom<f64> for NotNan<f64> {
1007    type Error = FloatIsNan;
1008    #[inline]
1009    fn try_from(v: f64) -> Result<Self, Self::Error> {
1010        NotNan::new(v)
1011    }
1012}
1013
1014macro_rules! impl_from_int_primitive {
1015    ($primitive:ty, $inner:ty) => {
1016        impl From<$primitive> for NotNan<$inner> {
1017            fn from(source: $primitive) -> Self {
1018                // the primitives with which this macro will be called cannot hold a value that
1019                // f64::from would convert to NaN, so this does not hurt invariants
1020                NotNan(<$inner as From<$primitive>>::from(source))
1021            }
1022        }
1023    };
1024}
1025
1026impl_from_int_primitive!(i8, f64);
1027impl_from_int_primitive!(i16, f64);
1028impl_from_int_primitive!(i32, f64);
1029impl_from_int_primitive!(u8, f64);
1030impl_from_int_primitive!(u16, f64);
1031impl_from_int_primitive!(u32, f64);
1032
1033impl_from_int_primitive!(i8, f32);
1034impl_from_int_primitive!(i16, f32);
1035impl_from_int_primitive!(u8, f32);
1036impl_from_int_primitive!(u16, f32);
1037
1038impl From<NotNan<f32>> for NotNan<f64> {
1039    #[inline]
1040    fn from(v: NotNan<f32>) -> NotNan<f64> {
1041        unsafe { NotNan::new_unchecked(v.0 as f64) }
1042    }
1043}
1044
1045impl<T: Float> Deref for NotNan<T> {
1046    type Target = T;
1047
1048    #[inline]
1049    fn deref(&self) -> &Self::Target {
1050        &self.0
1051    }
1052}
1053
1054impl<T: Float + PartialEq> Eq for NotNan<T> {}
1055
1056impl<T: Float> PartialEq<T> for NotNan<T> {
1057    #[inline]
1058    fn eq(&self, other: &T) -> bool {
1059        self.0 == *other
1060    }
1061}
1062
1063/// Adds a float directly.
1064///
1065/// Panics if the provided value is NaN or the computation results in NaN
1066impl<T: Float> Add<T> for NotNan<T> {
1067    type Output = Self;
1068
1069    #[inline]
1070    fn add(self, other: T) -> Self {
1071        NotNan::new(self.0 + other).expect("Addition resulted in NaN")
1072    }
1073}
1074
1075/// Adds a float directly.
1076///
1077/// Panics if the provided value is NaN.
1078impl<T: Float + Sum> Sum for NotNan<T> {
1079    fn sum<I: Iterator<Item = NotNan<T>>>(iter: I) -> Self {
1080        NotNan::new(iter.map(|v| v.0).sum()).expect("Sum resulted in NaN")
1081    }
1082}
1083
1084impl<'a, T: Float + Sum + 'a> Sum<&'a NotNan<T>> for NotNan<T> {
1085    #[inline]
1086    fn sum<I: Iterator<Item = &'a NotNan<T>>>(iter: I) -> Self {
1087        iter.cloned().sum()
1088    }
1089}
1090
1091/// Subtracts a float directly.
1092///
1093/// Panics if the provided value is NaN or the computation results in NaN
1094impl<T: Float> Sub<T> for NotNan<T> {
1095    type Output = Self;
1096
1097    #[inline]
1098    fn sub(self, other: T) -> Self {
1099        NotNan::new(self.0 - other).expect("Subtraction resulted in NaN")
1100    }
1101}
1102
1103/// Multiplies a float directly.
1104///
1105/// Panics if the provided value is NaN or the computation results in NaN
1106impl<T: Float> Mul<T> for NotNan<T> {
1107    type Output = Self;
1108
1109    #[inline]
1110    fn mul(self, other: T) -> Self {
1111        NotNan::new(self.0 * other).expect("Multiplication resulted in NaN")
1112    }
1113}
1114
1115impl<T: Float + Product> Product for NotNan<T> {
1116    fn product<I: Iterator<Item = NotNan<T>>>(iter: I) -> Self {
1117        NotNan::new(iter.map(|v| v.0).product()).expect("Product resulted in NaN")
1118    }
1119}
1120
1121impl<'a, T: Float + Product + 'a> Product<&'a NotNan<T>> for NotNan<T> {
1122    #[inline]
1123    fn product<I: Iterator<Item = &'a NotNan<T>>>(iter: I) -> Self {
1124        iter.cloned().product()
1125    }
1126}
1127
1128/// Divides a float directly.
1129///
1130/// Panics if the provided value is NaN or the computation results in NaN
1131impl<T: Float> Div<T> for NotNan<T> {
1132    type Output = Self;
1133
1134    #[inline]
1135    fn div(self, other: T) -> Self {
1136        NotNan::new(self.0 / other).expect("Division resulted in NaN")
1137    }
1138}
1139
1140/// Calculates `%` with a float directly.
1141///
1142/// Panics if the provided value is NaN or the computation results in NaN
1143impl<T: Float> Rem<T> for NotNan<T> {
1144    type Output = Self;
1145
1146    #[inline]
1147    fn rem(self, other: T) -> Self {
1148        NotNan::new(self.0 % other).expect("Rem resulted in NaN")
1149    }
1150}
1151
1152macro_rules! impl_not_nan_binop {
1153    ($imp:ident, $method:ident, $assign_imp:ident, $assign_method:ident) => {
1154        impl<T: Float> $imp for NotNan<T> {
1155            type Output = Self;
1156
1157            #[inline]
1158            fn $method(self, other: Self) -> Self {
1159                self.$method(other.0)
1160            }
1161        }
1162
1163        impl<T: Float> $imp<&T> for NotNan<T> {
1164            type Output = NotNan<T>;
1165
1166            #[inline]
1167            fn $method(self, other: &T) -> Self::Output {
1168                self.$method(*other)
1169            }
1170        }
1171
1172        impl<T: Float> $imp<&Self> for NotNan<T> {
1173            type Output = NotNan<T>;
1174
1175            #[inline]
1176            fn $method(self, other: &Self) -> Self::Output {
1177                self.$method(other.0)
1178            }
1179        }
1180
1181        impl<T: Float> $imp for &NotNan<T> {
1182            type Output = NotNan<T>;
1183
1184            #[inline]
1185            fn $method(self, other: Self) -> Self::Output {
1186                (*self).$method(other.0)
1187            }
1188        }
1189
1190        impl<T: Float> $imp<NotNan<T>> for &NotNan<T> {
1191            type Output = NotNan<T>;
1192
1193            #[inline]
1194            fn $method(self, other: NotNan<T>) -> Self::Output {
1195                (*self).$method(other.0)
1196            }
1197        }
1198
1199        impl<T: Float> $imp<T> for &NotNan<T> {
1200            type Output = NotNan<T>;
1201
1202            #[inline]
1203            fn $method(self, other: T) -> Self::Output {
1204                (*self).$method(other)
1205            }
1206        }
1207
1208        impl<T: Float> $imp<&T> for &NotNan<T> {
1209            type Output = NotNan<T>;
1210
1211            #[inline]
1212            fn $method(self, other: &T) -> Self::Output {
1213                (*self).$method(*other)
1214            }
1215        }
1216
1217        impl<T: Float + $assign_imp> $assign_imp<T> for NotNan<T> {
1218            #[inline]
1219            fn $assign_method(&mut self, other: T) {
1220                *self = (*self).$method(other);
1221            }
1222        }
1223
1224        impl<T: Float + $assign_imp> $assign_imp<&T> for NotNan<T> {
1225            #[inline]
1226            fn $assign_method(&mut self, other: &T) {
1227                *self = (*self).$method(*other);
1228            }
1229        }
1230
1231        impl<T: Float + $assign_imp> $assign_imp for NotNan<T> {
1232            #[inline]
1233            fn $assign_method(&mut self, other: Self) {
1234                (*self).$assign_method(other.0);
1235            }
1236        }
1237
1238        impl<T: Float + $assign_imp> $assign_imp<&Self> for NotNan<T> {
1239            #[inline]
1240            fn $assign_method(&mut self, other: &Self) {
1241                (*self).$assign_method(other.0);
1242            }
1243        }
1244    };
1245}
1246
1247impl_not_nan_binop! {Add, add, AddAssign, add_assign}
1248impl_not_nan_binop! {Sub, sub, SubAssign, sub_assign}
1249impl_not_nan_binop! {Mul, mul, MulAssign, mul_assign}
1250impl_not_nan_binop! {Div, div, DivAssign, div_assign}
1251impl_not_nan_binop! {Rem, rem, RemAssign, rem_assign}
1252
1253impl<T: Float> Neg for NotNan<T> {
1254    type Output = Self;
1255
1256    #[inline]
1257    fn neg(self) -> Self {
1258        NotNan(-self.0)
1259    }
1260}
1261
1262impl<T: Float> Neg for &NotNan<T> {
1263    type Output = NotNan<T>;
1264
1265    #[inline]
1266    fn neg(self) -> Self::Output {
1267        NotNan(-self.0)
1268    }
1269}
1270
1271/// An error indicating an attempt to construct NotNan from a NaN
1272#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1273pub struct FloatIsNan;
1274
1275#[cfg(feature = "std")]
1276impl Error for FloatIsNan {
1277    fn description(&self) -> &str {
1278        "NotNan constructed with NaN"
1279    }
1280}
1281
1282impl fmt::Display for FloatIsNan {
1283    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1284        write!(f, "NotNan constructed with NaN")
1285    }
1286}
1287
1288#[cfg(feature = "std")]
1289impl From<FloatIsNan> for std::io::Error {
1290    #[inline]
1291    fn from(e: FloatIsNan) -> std::io::Error {
1292        std::io::Error::new(std::io::ErrorKind::InvalidInput, e)
1293    }
1294}
1295
1296#[inline]
1297fn raw_double_bits<F: Float>(f: &F) -> u64 {
1298    let (man, exp, sign) = f.integer_decode();
1299    let exp_u64 = exp as u16 as u64;
1300    let sign_u64 = if sign > 0 { 1u64 } else { 0u64 };
1301    (man & MAN_MASK) | ((exp_u64 << 52) & EXP_MASK) | ((sign_u64 << 63) & SIGN_MASK)
1302}
1303
1304impl<T: Float> Zero for NotNan<T> {
1305    #[inline]
1306    fn zero() -> Self {
1307        NotNan(T::zero())
1308    }
1309
1310    #[inline]
1311    fn is_zero(&self) -> bool {
1312        self.0.is_zero()
1313    }
1314}
1315
1316impl<T: Float> One for NotNan<T> {
1317    #[inline]
1318    fn one() -> Self {
1319        NotNan(T::one())
1320    }
1321}
1322
1323impl<T: Float> Bounded for NotNan<T> {
1324    #[inline]
1325    fn min_value() -> Self {
1326        NotNan(T::min_value())
1327    }
1328
1329    #[inline]
1330    fn max_value() -> Self {
1331        NotNan(T::max_value())
1332    }
1333}
1334
1335impl<T: Float + FromStr> FromStr for NotNan<T> {
1336    type Err = ParseNotNanError<T::Err>;
1337
1338    /// Convert a &str to `NotNan`. Returns an error if the string fails to parse,
1339    /// or if the resulting value is NaN
1340    ///
1341    /// ```
1342    /// use ordered_float::NotNan;
1343    ///
1344    /// assert!("-10".parse::<NotNan<f32>>().is_ok());
1345    /// assert!("abc".parse::<NotNan<f32>>().is_err());
1346    /// assert!("NaN".parse::<NotNan<f32>>().is_err());
1347    /// ```
1348    fn from_str(src: &str) -> Result<Self, Self::Err> {
1349        src.parse()
1350            .map_err(ParseNotNanError::ParseFloatError)
1351            .and_then(|f| NotNan::new(f).map_err(|_| ParseNotNanError::IsNaN))
1352    }
1353}
1354
1355impl<T: Float + FromPrimitive> FromPrimitive for NotNan<T> {
1356    fn from_i64(n: i64) -> Option<Self> {
1357        T::from_i64(n).and_then(|n| NotNan::new(n).ok())
1358    }
1359    fn from_u64(n: u64) -> Option<Self> {
1360        T::from_u64(n).and_then(|n| NotNan::new(n).ok())
1361    }
1362
1363    fn from_isize(n: isize) -> Option<Self> {
1364        T::from_isize(n).and_then(|n| NotNan::new(n).ok())
1365    }
1366    fn from_i8(n: i8) -> Option<Self> {
1367        T::from_i8(n).and_then(|n| NotNan::new(n).ok())
1368    }
1369    fn from_i16(n: i16) -> Option<Self> {
1370        T::from_i16(n).and_then(|n| NotNan::new(n).ok())
1371    }
1372    fn from_i32(n: i32) -> Option<Self> {
1373        T::from_i32(n).and_then(|n| NotNan::new(n).ok())
1374    }
1375    fn from_usize(n: usize) -> Option<Self> {
1376        T::from_usize(n).and_then(|n| NotNan::new(n).ok())
1377    }
1378    fn from_u8(n: u8) -> Option<Self> {
1379        T::from_u8(n).and_then(|n| NotNan::new(n).ok())
1380    }
1381    fn from_u16(n: u16) -> Option<Self> {
1382        T::from_u16(n).and_then(|n| NotNan::new(n).ok())
1383    }
1384    fn from_u32(n: u32) -> Option<Self> {
1385        T::from_u32(n).and_then(|n| NotNan::new(n).ok())
1386    }
1387    fn from_f32(n: f32) -> Option<Self> {
1388        T::from_f32(n).and_then(|n| NotNan::new(n).ok())
1389    }
1390    fn from_f64(n: f64) -> Option<Self> {
1391        T::from_f64(n).and_then(|n| NotNan::new(n).ok())
1392    }
1393}
1394
1395impl<T: Float> ToPrimitive for NotNan<T> {
1396    fn to_i64(&self) -> Option<i64> {
1397        self.0.to_i64()
1398    }
1399    fn to_u64(&self) -> Option<u64> {
1400        self.0.to_u64()
1401    }
1402
1403    fn to_isize(&self) -> Option<isize> {
1404        self.0.to_isize()
1405    }
1406    fn to_i8(&self) -> Option<i8> {
1407        self.0.to_i8()
1408    }
1409    fn to_i16(&self) -> Option<i16> {
1410        self.0.to_i16()
1411    }
1412    fn to_i32(&self) -> Option<i32> {
1413        self.0.to_i32()
1414    }
1415    fn to_usize(&self) -> Option<usize> {
1416        self.0.to_usize()
1417    }
1418    fn to_u8(&self) -> Option<u8> {
1419        self.0.to_u8()
1420    }
1421    fn to_u16(&self) -> Option<u16> {
1422        self.0.to_u16()
1423    }
1424    fn to_u32(&self) -> Option<u32> {
1425        self.0.to_u32()
1426    }
1427    fn to_f32(&self) -> Option<f32> {
1428        self.0.to_f32()
1429    }
1430    fn to_f64(&self) -> Option<f64> {
1431        self.0.to_f64()
1432    }
1433}
1434
1435/// An error indicating a parse error from a string for `NotNan`.
1436#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1437pub enum ParseNotNanError<E> {
1438    /// A plain parse error from the underlying float type.
1439    ParseFloatError(E),
1440    /// The parsed float value resulted in a NaN.
1441    IsNaN,
1442}
1443
1444#[cfg(feature = "std")]
1445impl<E: fmt::Debug + Error + 'static> Error for ParseNotNanError<E> {
1446    fn description(&self) -> &str {
1447        "Error parsing a not-NaN floating point value"
1448    }
1449
1450    fn source(&self) -> Option<&(dyn Error + 'static)> {
1451        match self {
1452            ParseNotNanError::ParseFloatError(e) => Some(e),
1453            ParseNotNanError::IsNaN => None,
1454        }
1455    }
1456}
1457
1458impl<E: fmt::Display> fmt::Display for ParseNotNanError<E> {
1459    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1460        match self {
1461            ParseNotNanError::ParseFloatError(e) => write!(f, "Parse error: {}", e),
1462            ParseNotNanError::IsNaN => write!(f, "NotNan parser encounter a NaN"),
1463        }
1464    }
1465}
1466
1467impl<T: Float> Num for NotNan<T> {
1468    type FromStrRadixErr = ParseNotNanError<T::FromStrRadixErr>;
1469
1470    fn from_str_radix(src: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
1471        T::from_str_radix(src, radix)
1472            .map_err(ParseNotNanError::ParseFloatError)
1473            .and_then(|n| NotNan::new(n).map_err(|_| ParseNotNanError::IsNaN))
1474    }
1475}
1476
1477impl<T: Float + Signed> Signed for NotNan<T> {
1478    #[inline]
1479    fn abs(&self) -> Self {
1480        NotNan(self.0.abs())
1481    }
1482
1483    fn abs_sub(&self, other: &Self) -> Self {
1484        NotNan::new(Signed::abs_sub(&self.0, &other.0)).expect("Subtraction resulted in NaN")
1485    }
1486
1487    #[inline]
1488    fn signum(&self) -> Self {
1489        NotNan(self.0.signum())
1490    }
1491    #[inline]
1492    fn is_positive(&self) -> bool {
1493        self.0.is_positive()
1494    }
1495    #[inline]
1496    fn is_negative(&self) -> bool {
1497        self.0.is_negative()
1498    }
1499}
1500
1501impl<T: Float> NumCast for NotNan<T> {
1502    fn from<F: ToPrimitive>(n: F) -> Option<Self> {
1503        T::from(n).and_then(|n| NotNan::new(n).ok())
1504    }
1505}
1506
1507#[cfg(feature = "serde")]
1508mod impl_serde {
1509    extern crate serde;
1510    use self::serde::de::{Error, Unexpected};
1511    use self::serde::{Deserialize, Deserializer, Serialize, Serializer};
1512    use super::{NotNan, OrderedFloat};
1513    use core::f64;
1514    #[cfg(not(feature = "std"))]
1515    use num_traits::float::FloatCore as Float;
1516    #[cfg(feature = "std")]
1517    use num_traits::Float;
1518
1519    #[cfg(test)]
1520    extern crate serde_test;
1521    #[cfg(test)]
1522    use self::serde_test::{assert_de_tokens_error, assert_tokens, Token};
1523
1524    impl<T: Float + Serialize> Serialize for OrderedFloat<T> {
1525        #[inline]
1526        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1527            self.0.serialize(s)
1528        }
1529    }
1530
1531    impl<'de, T: Float + Deserialize<'de>> Deserialize<'de> for OrderedFloat<T> {
1532        #[inline]
1533        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1534            T::deserialize(d).map(OrderedFloat)
1535        }
1536    }
1537
1538    impl<T: Float + Serialize> Serialize for NotNan<T> {
1539        #[inline]
1540        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1541            self.0.serialize(s)
1542        }
1543    }
1544
1545    impl<'de, T: Float + Deserialize<'de>> Deserialize<'de> for NotNan<T> {
1546        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1547            let float = T::deserialize(d)?;
1548            NotNan::new(float).map_err(|_| {
1549                Error::invalid_value(Unexpected::Float(f64::NAN), &"float (but not NaN)")
1550            })
1551        }
1552    }
1553
1554    #[test]
1555    fn test_ordered_float() {
1556        let float = OrderedFloat(1.0f64);
1557        assert_tokens(&float, &[Token::F64(1.0)]);
1558    }
1559
1560    #[test]
1561    fn test_not_nan() {
1562        let float = NotNan(1.0f64);
1563        assert_tokens(&float, &[Token::F64(1.0)]);
1564    }
1565
1566    #[test]
1567    fn test_fail_on_nan() {
1568        assert_de_tokens_error::<NotNan<f64>>(
1569            &[Token::F64(f64::NAN)],
1570            "invalid value: floating point `NaN`, expected float (but not NaN)",
1571        );
1572    }
1573}
1574
1575#[cfg(feature = "rkyv")]
1576mod impl_rkyv {
1577    use super::{NotNan, OrderedFloat};
1578    #[cfg(not(feature = "std"))]
1579    use num_traits::float::FloatCore as Float;
1580    #[cfg(feature = "std")]
1581    use num_traits::Float;
1582    #[cfg(test)]
1583    use rkyv::{archived_root, ser::Serializer};
1584    use rkyv::{from_archived, Archive, Deserialize, Fallible, Serialize};
1585
1586    #[cfg(test)]
1587    type DefaultSerializer = rkyv::ser::serializers::CoreSerializer<16, 16>;
1588    #[cfg(test)]
1589    type DefaultDeserializer = rkyv::Infallible;
1590
1591    impl<T: Float + Archive> Archive for OrderedFloat<T> {
1592        type Archived = OrderedFloat<T>;
1593
1594        type Resolver = ();
1595
1596        unsafe fn resolve(&self, _: usize, _: Self::Resolver, out: *mut Self::Archived) {
1597            out.write(*self);
1598        }
1599    }
1600
1601    impl<T: Float + Serialize<S>, S: Fallible + ?Sized> Serialize<S> for OrderedFloat<T> {
1602        fn serialize(&self, _: &mut S) -> Result<Self::Resolver, S::Error> {
1603            Ok(())
1604        }
1605    }
1606
1607    impl<T: Float + Deserialize<T, D>, D: Fallible + ?Sized> Deserialize<OrderedFloat<T>, D>
1608        for OrderedFloat<T>
1609    {
1610        fn deserialize(&self, _: &mut D) -> Result<OrderedFloat<T>, D::Error> {
1611            Ok(from_archived!(*self))
1612        }
1613    }
1614
1615    impl<T: Float + Archive> Archive for NotNan<T> {
1616        type Archived = NotNan<T>;
1617
1618        type Resolver = ();
1619
1620        unsafe fn resolve(&self, _: usize, _: Self::Resolver, out: *mut Self::Archived) {
1621            out.write(*self);
1622        }
1623    }
1624
1625    impl<T: Float + Serialize<S>, S: Fallible + ?Sized> Serialize<S> for NotNan<T> {
1626        fn serialize(&self, _: &mut S) -> Result<Self::Resolver, S::Error> {
1627            Ok(())
1628        }
1629    }
1630
1631    impl<T: Float + Deserialize<T, D>, D: Fallible + ?Sized> Deserialize<NotNan<T>, D> for NotNan<T> {
1632        fn deserialize(&self, _: &mut D) -> Result<NotNan<T>, D::Error> {
1633            Ok(from_archived!(*self))
1634        }
1635    }
1636
1637    #[test]
1638    fn test_ordered_float() {
1639        let float = OrderedFloat(1.0f64);
1640        let mut serializer = DefaultSerializer::default();
1641        serializer
1642            .serialize_value(&float)
1643            .expect("failed to archive value");
1644        let len = serializer.pos();
1645        let buffer = serializer.into_serializer().into_inner();
1646
1647        let archived_value = unsafe { archived_root::<OrderedFloat<f64>>(&buffer[0..len]) };
1648        assert_eq!(archived_value, &float);
1649        let mut deserializer = DefaultDeserializer::default();
1650        let deser_float: OrderedFloat<f64> = archived_value.deserialize(&mut deserializer).unwrap();
1651        assert_eq!(deser_float, float);
1652    }
1653
1654    #[test]
1655    fn test_not_nan() {
1656        let float = NotNan(1.0f64);
1657        let mut serializer = DefaultSerializer::default();
1658        serializer
1659            .serialize_value(&float)
1660            .expect("failed to archive value");
1661        let len = serializer.pos();
1662        let buffer = serializer.into_serializer().into_inner();
1663
1664        let archived_value = unsafe { archived_root::<NotNan<f64>>(&buffer[0..len]) };
1665        assert_eq!(archived_value, &float);
1666        let mut deserializer = DefaultDeserializer::default();
1667        let deser_float: NotNan<f64> = archived_value.deserialize(&mut deserializer).unwrap();
1668        assert_eq!(deser_float, float);
1669    }
1670}
1671
1672#[cfg(all(feature = "std", feature = "schemars"))]
1673mod impl_schemars {
1674    extern crate schemars;
1675    use self::schemars::gen::SchemaGenerator;
1676    use self::schemars::schema::{InstanceType, Schema, SchemaObject};
1677    use super::{NotNan, OrderedFloat};
1678
1679    macro_rules! primitive_float_impl {
1680        ($type:ty, $schema_name:literal) => {
1681            impl schemars::JsonSchema for $type {
1682                fn is_referenceable() -> bool {
1683                    false
1684                }
1685
1686                fn schema_name() -> std::string::String {
1687                    std::string::String::from($schema_name)
1688                }
1689
1690                fn json_schema(_: &mut SchemaGenerator) -> Schema {
1691                    SchemaObject {
1692                        instance_type: Some(InstanceType::Number.into()),
1693                        format: Some(std::string::String::from($schema_name)),
1694                        ..Default::default()
1695                    }
1696                    .into()
1697                }
1698            }
1699        };
1700    }
1701
1702    primitive_float_impl!(OrderedFloat<f32>, "float");
1703    primitive_float_impl!(OrderedFloat<f64>, "double");
1704    primitive_float_impl!(NotNan<f32>, "float");
1705    primitive_float_impl!(NotNan<f64>, "double");
1706
1707    #[test]
1708    fn schema_generation_does_not_panic_for_common_floats() {
1709        {
1710            let schema = schemars::gen::SchemaGenerator::default()
1711                .into_root_schema_for::<OrderedFloat<f32>>();
1712            assert_eq!(
1713                schema.schema.instance_type,
1714                Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new(
1715                    schemars::schema::InstanceType::Number
1716                )))
1717            );
1718            assert_eq!(
1719                schema.schema.metadata.unwrap().title.unwrap(),
1720                std::string::String::from("float")
1721            );
1722        }
1723        {
1724            let schema = schemars::gen::SchemaGenerator::default()
1725                .into_root_schema_for::<OrderedFloat<f64>>();
1726            assert_eq!(
1727                schema.schema.instance_type,
1728                Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new(
1729                    schemars::schema::InstanceType::Number
1730                )))
1731            );
1732            assert_eq!(
1733                schema.schema.metadata.unwrap().title.unwrap(),
1734                std::string::String::from("double")
1735            );
1736        }
1737        {
1738            let schema =
1739                schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f32>>();
1740            assert_eq!(
1741                schema.schema.instance_type,
1742                Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new(
1743                    schemars::schema::InstanceType::Number
1744                )))
1745            );
1746            assert_eq!(
1747                schema.schema.metadata.unwrap().title.unwrap(),
1748                std::string::String::from("float")
1749            );
1750        }
1751        {
1752            let schema =
1753                schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f64>>();
1754            assert_eq!(
1755                schema.schema.instance_type,
1756                Some(schemars::schema::SingleOrVec::Single(std::boxed::Box::new(
1757                    schemars::schema::InstanceType::Number
1758                )))
1759            );
1760            assert_eq!(
1761                schema.schema.metadata.unwrap().title.unwrap(),
1762                std::string::String::from("double")
1763            );
1764        }
1765    }
1766    #[test]
1767    fn ordered_float_schema_match_primitive_schema() {
1768        {
1769            let of_schema = schemars::gen::SchemaGenerator::default()
1770                .into_root_schema_for::<OrderedFloat<f32>>();
1771            let prim_schema =
1772                schemars::gen::SchemaGenerator::default().into_root_schema_for::<f32>();
1773            assert_eq!(of_schema, prim_schema);
1774        }
1775        {
1776            let of_schema = schemars::gen::SchemaGenerator::default()
1777                .into_root_schema_for::<OrderedFloat<f64>>();
1778            let prim_schema =
1779                schemars::gen::SchemaGenerator::default().into_root_schema_for::<f64>();
1780            assert_eq!(of_schema, prim_schema);
1781        }
1782        {
1783            let of_schema =
1784                schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f32>>();
1785            let prim_schema =
1786                schemars::gen::SchemaGenerator::default().into_root_schema_for::<f32>();
1787            assert_eq!(of_schema, prim_schema);
1788        }
1789        {
1790            let of_schema =
1791                schemars::gen::SchemaGenerator::default().into_root_schema_for::<NotNan<f64>>();
1792            let prim_schema =
1793                schemars::gen::SchemaGenerator::default().into_root_schema_for::<f64>();
1794            assert_eq!(of_schema, prim_schema);
1795        }
1796    }
1797}
1798
1799#[cfg(feature = "rand")]
1800mod impl_rand {
1801    use super::{NotNan, OrderedFloat};
1802    use rand::distributions::uniform::*;
1803    use rand::distributions::{Distribution, Open01, OpenClosed01, Standard};
1804    use rand::Rng;
1805
1806    macro_rules! impl_distribution {
1807        ($dist:ident, $($f:ty),+) => {
1808            $(
1809            impl Distribution<NotNan<$f>> for $dist {
1810                fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> NotNan<$f> {
1811                    // 'rand' never generates NaN values in the Standard, Open01, or
1812                    // OpenClosed01 distributions. Using 'new_unchecked' is therefore
1813                    // safe.
1814                    unsafe { NotNan::new_unchecked(self.sample(rng)) }
1815                }
1816            }
1817
1818            impl Distribution<OrderedFloat<$f>> for $dist {
1819                fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> OrderedFloat<$f> {
1820                    OrderedFloat(self.sample(rng))
1821                }
1822            }
1823            )*
1824        }
1825    }
1826
1827    impl_distribution! { Standard, f32, f64 }
1828    impl_distribution! { Open01, f32, f64 }
1829    impl_distribution! { OpenClosed01, f32, f64 }
1830
1831    pub struct UniformNotNan<T>(UniformFloat<T>);
1832    impl SampleUniform for NotNan<f32> {
1833        type Sampler = UniformNotNan<f32>;
1834    }
1835    impl SampleUniform for NotNan<f64> {
1836        type Sampler = UniformNotNan<f64>;
1837    }
1838
1839    pub struct UniformOrdered<T>(UniformFloat<T>);
1840    impl SampleUniform for OrderedFloat<f32> {
1841        type Sampler = UniformOrdered<f32>;
1842    }
1843    impl SampleUniform for OrderedFloat<f64> {
1844        type Sampler = UniformOrdered<f64>;
1845    }
1846
1847    macro_rules! impl_uniform_sampler {
1848        ($f:ty) => {
1849            impl UniformSampler for UniformNotNan<$f> {
1850                type X = NotNan<$f>;
1851                fn new<B1, B2>(low: B1, high: B2) -> Self
1852                where
1853                    B1: SampleBorrow<Self::X> + Sized,
1854                    B2: SampleBorrow<Self::X> + Sized,
1855                {
1856                    UniformNotNan(UniformFloat::<$f>::new(low.borrow().0, high.borrow().0))
1857                }
1858                fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
1859                where
1860                    B1: SampleBorrow<Self::X> + Sized,
1861                    B2: SampleBorrow<Self::X> + Sized,
1862                {
1863                    UniformSampler::new(low, high)
1864                }
1865                fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
1866                    // UniformFloat.sample() will never return NaN.
1867                    unsafe { NotNan::new_unchecked(self.0.sample(rng)) }
1868                }
1869            }
1870
1871            impl UniformSampler for UniformOrdered<$f> {
1872                type X = OrderedFloat<$f>;
1873                fn new<B1, B2>(low: B1, high: B2) -> Self
1874                where
1875                    B1: SampleBorrow<Self::X> + Sized,
1876                    B2: SampleBorrow<Self::X> + Sized,
1877                {
1878                    UniformOrdered(UniformFloat::<$f>::new(low.borrow().0, high.borrow().0))
1879                }
1880                fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
1881                where
1882                    B1: SampleBorrow<Self::X> + Sized,
1883                    B2: SampleBorrow<Self::X> + Sized,
1884                {
1885                    UniformSampler::new(low, high)
1886                }
1887                fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
1888                    OrderedFloat(self.0.sample(rng))
1889                }
1890            }
1891        };
1892    }
1893
1894    impl_uniform_sampler! { f32 }
1895    impl_uniform_sampler! { f64 }
1896
1897    #[cfg(all(test, feature = "randtest"))]
1898    mod tests {
1899        use super::*;
1900
1901        fn sample_fuzz<T>()
1902        where
1903            Standard: Distribution<NotNan<T>>,
1904            Open01: Distribution<NotNan<T>>,
1905            OpenClosed01: Distribution<NotNan<T>>,
1906            Standard: Distribution<OrderedFloat<T>>,
1907            Open01: Distribution<OrderedFloat<T>>,
1908            OpenClosed01: Distribution<OrderedFloat<T>>,
1909            T: crate::Float,
1910        {
1911            let mut rng = rand::thread_rng();
1912            let f1: NotNan<T> = rng.sample(Standard);
1913            let f2: NotNan<T> = rng.sample(Open01);
1914            let f3: NotNan<T> = rng.sample(OpenClosed01);
1915            let _: OrderedFloat<T> = rng.sample(Standard);
1916            let _: OrderedFloat<T> = rng.sample(Open01);
1917            let _: OrderedFloat<T> = rng.sample(OpenClosed01);
1918            assert!(!f1.into_inner().is_nan());
1919            assert!(!f2.into_inner().is_nan());
1920            assert!(!f3.into_inner().is_nan());
1921        }
1922
1923        #[test]
1924        fn sampling_f32_does_not_panic() {
1925            sample_fuzz::<f32>();
1926        }
1927
1928        #[test]
1929        fn sampling_f64_does_not_panic() {
1930            sample_fuzz::<f64>();
1931        }
1932
1933        #[test]
1934        #[should_panic]
1935        fn uniform_sampling_panic_on_infinity_notnan() {
1936            let (low, high) = (
1937                NotNan::new(0f64).unwrap(),
1938                NotNan::new(core::f64::INFINITY).unwrap(),
1939            );
1940            let uniform = Uniform::new(low, high);
1941            let _ = uniform.sample(&mut rand::thread_rng());
1942        }
1943
1944        #[test]
1945        #[should_panic]
1946        fn uniform_sampling_panic_on_infinity_ordered() {
1947            let (low, high) = (OrderedFloat(0f64), OrderedFloat(core::f64::INFINITY));
1948            let uniform = Uniform::new(low, high);
1949            let _ = uniform.sample(&mut rand::thread_rng());
1950        }
1951
1952        #[test]
1953        #[should_panic]
1954        fn uniform_sampling_panic_on_nan_ordered() {
1955            let (low, high) = (OrderedFloat(0f64), OrderedFloat(core::f64::NAN));
1956            let uniform = Uniform::new(low, high);
1957            let _ = uniform.sample(&mut rand::thread_rng());
1958        }
1959    }
1960}
1961
1962#[cfg(feature = "proptest")]
1963mod impl_proptest {
1964    use super::{NotNan, OrderedFloat};
1965    use proptest::arbitrary::{Arbitrary, StrategyFor};
1966    use proptest::num::{f32, f64};
1967    use proptest::strategy::{FilterMap, Map, Strategy};
1968    use std::convert::TryFrom;
1969
1970    macro_rules! impl_arbitrary {
1971        ($($f:ident),+) => {
1972            $(
1973                impl Arbitrary for NotNan<$f> {
1974                    type Strategy = FilterMap<StrategyFor<$f>, fn(_: $f) -> Option<NotNan<$f>>>;
1975                    type Parameters = <$f as Arbitrary>::Parameters;
1976                    fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
1977                        <$f>::arbitrary_with(params)
1978                            .prop_filter_map("filter nan values", |f| NotNan::try_from(f).ok())
1979                    }
1980                }
1981
1982                impl Arbitrary for OrderedFloat<$f> {
1983                    type Strategy = Map<StrategyFor<$f>, fn(_: $f) -> OrderedFloat<$f>>;
1984                    type Parameters = <$f as Arbitrary>::Parameters;
1985                    fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
1986                        <$f>::arbitrary_with(params).prop_map(|f| OrderedFloat::from(f))
1987                    }
1988                }
1989            )*
1990        }
1991    }
1992    impl_arbitrary! { f32, f64 }
1993}
1994
1995#[cfg(feature = "arbitrary")]
1996mod impl_arbitrary {
1997    use super::{FloatIsNan, NotNan, OrderedFloat};
1998    use arbitrary::{Arbitrary, Unstructured};
1999    use num_traits::FromPrimitive;
2000
2001    macro_rules! impl_arbitrary {
2002        ($($f:ident),+) => {
2003            $(
2004                impl<'a> Arbitrary<'a> for NotNan<$f> {
2005                    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
2006                        let float: $f = u.arbitrary()?;
2007                        match NotNan::new(float) {
2008                            Ok(notnan_value) => Ok(notnan_value),
2009                            Err(FloatIsNan) => {
2010                                // If our arbitrary float input was a NaN (encoded by exponent = max
2011                                // value), then replace it with a finite float, reusing the mantissa
2012                                // bits.
2013                                //
2014                                // This means the output is not uniformly distributed among all
2015                                // possible float values, but Arbitrary makes no promise that that
2016                                // is true.
2017                                //
2018                                // An alternative implementation would be to return an
2019                                // `arbitrary::Error`, but that is not as useful since it forces the
2020                                // caller to retry with new random/fuzzed data; and the precendent of
2021                                // `arbitrary`'s built-in implementations is to prefer the approach of
2022                                // mangling the input bits to fit.
2023
2024                                let (mantissa, _exponent, sign) =
2025                                    num_traits::Float::integer_decode(float);
2026                                let revised_float = <$f>::from_i64(
2027                                    i64::from(sign) * mantissa as i64
2028                                ).unwrap();
2029
2030                                // If this unwrap() fails, then there is a bug in the above code.
2031                                Ok(NotNan::new(revised_float).unwrap())
2032                            }
2033                        }
2034                    }
2035
2036                    fn size_hint(depth: usize) -> (usize, Option<usize>) {
2037                        <$f as Arbitrary>::size_hint(depth)
2038                    }
2039                }
2040
2041                impl<'a> Arbitrary<'a> for OrderedFloat<$f> {
2042                    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
2043                        let float: $f = u.arbitrary()?;
2044                        Ok(OrderedFloat::from(float))
2045                    }
2046
2047                    fn size_hint(depth: usize) -> (usize, Option<usize>) {
2048                        <$f as Arbitrary>::size_hint(depth)
2049                    }
2050                }
2051            )*
2052        }
2053    }
2054    impl_arbitrary! { f32, f64 }
2055}