1#![no_std]
2#![cfg_attr(test, deny(warnings))]
3#![deny(missing_docs)]
4
5extern crate num_traits;
8#[cfg(feature = "std")] extern crate std;
9
10use core::cmp::Ordering;
11use core::ops::{Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Rem,
12 RemAssign, Sub, SubAssign};
13use core::hash::{Hash, Hasher};
14use core::fmt;
15use core::mem;
16use core::hint::unreachable_unchecked;
17use core::iter::{Sum, Product};
18use core::str::FromStr;
19
20use num_traits::{Bounded, FromPrimitive, Num, NumCast, One, Signed, ToPrimitive, Zero};
21#[cfg(feature = "std")]
22use num_traits::Float;
23#[cfg(not(feature = "std"))]
24use num_traits::float::FloatCore as Float;
25
26#[deprecated(since = "0.6.0", note = "renamed to `NotNan`")]
30pub type NotNaN<T> = NotNan<T>;
31
32#[deprecated(since = "0.6.0", note = "renamed to `FloatIsNan`")]
34pub type FloatIsNaN = FloatIsNan;
35
36const SIGN_MASK: u64 = 0x8000000000000000u64;
38const EXP_MASK: u64 = 0x7ff0000000000000u64;
39const MAN_MASK: u64 = 0x000fffffffffffffu64;
40
41const CANONICAL_NAN_BITS: u64 = 0x7ff8000000000000u64;
43const CANONICAL_ZERO_BITS: u64 = 0x0u64;
44
45#[derive(Debug, Default, Clone, Copy)]
50#[repr(transparent)]
51pub struct OrderedFloat<T: Float>(pub T);
52
53impl<T: Float> OrderedFloat<T> {
54 pub fn into_inner(self) -> T {
56 let OrderedFloat(val) = self;
57 val
58 }
59}
60
61impl<T: Float> AsRef<T> for OrderedFloat<T> {
62 fn as_ref(&self) -> &T {
63 let OrderedFloat(ref val) = *self;
64 val
65 }
66}
67
68impl<T: Float> AsMut<T> for OrderedFloat<T> {
69 fn as_mut(&mut self) -> &mut T {
70 let OrderedFloat(ref mut val) = *self;
71 val
72 }
73}
74
75impl<T: Float> PartialOrd for OrderedFloat<T> {
76 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
77 Some(self.cmp(other))
78 }
79}
80
81impl<T: Float> Ord for OrderedFloat<T> {
82 fn cmp(&self, other: &Self) -> Ordering {
83 let lhs = self.as_ref();
84 let rhs = other.as_ref();
85 match lhs.partial_cmp(&rhs) {
86 Some(ordering) => ordering,
87 None => {
88 if lhs.is_nan() {
89 if rhs.is_nan() {
90 Ordering::Equal
91 } else {
92 Ordering::Greater
93 }
94 } else {
95 Ordering::Less
96 }
97 }
98 }
99 }
100}
101
102impl<T: Float> PartialEq for OrderedFloat<T> {
103 fn eq(&self, other: &OrderedFloat<T>) -> bool {
104 if self.as_ref().is_nan() {
105 other.as_ref().is_nan()
106 } else {
107 self.as_ref() == other.as_ref()
108 }
109 }
110}
111
112impl<T: Float> Hash for OrderedFloat<T> {
113 fn hash<H: Hasher>(&self, state: &mut H) {
114 if self.is_nan() {
115 hash_float(&T::nan(), state)
117 } else {
118 hash_float(self.as_ref(), state)
119 }
120 }
121}
122
123impl<T: Float + fmt::Display> fmt::Display for OrderedFloat<T> {
124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125 self.as_ref().fmt(f)
126 }
127}
128
129impl Into<f32> for OrderedFloat<f32> {
130 fn into(self) -> f32 {
131 self.into_inner()
132 }
133}
134
135impl Into<f64> for OrderedFloat<f64> {
136 fn into(self) -> f64 {
137 self.into_inner()
138 }
139}
140
141impl<T: Float> From<T> for OrderedFloat<T> {
142 fn from(val: T) -> Self {
143 OrderedFloat(val)
144 }
145}
146
147impl<T: Float> Deref for OrderedFloat<T> {
148 type Target = T;
149
150 fn deref(&self) -> &Self::Target {
151 self.as_ref()
152 }
153}
154
155impl<T: Float> DerefMut for OrderedFloat<T> {
156 fn deref_mut(&mut self) -> &mut Self::Target {
157 self.as_mut()
158 }
159}
160
161impl<T: Float> Eq for OrderedFloat<T> {}
162
163impl<T: Float> Add for OrderedFloat<T> {
164 type Output = Self;
165
166 fn add(self, other: Self) -> Self {
167 OrderedFloat(self.0 + other.0)
168 }
169}
170
171impl<T: Float> Sub for OrderedFloat<T> {
172 type Output = Self;
173
174 fn sub(self, other: Self) -> Self {
175 OrderedFloat(self.0 - other.0)
176 }
177}
178
179impl<T: Float> Mul for OrderedFloat<T> {
180 type Output = Self;
181
182 fn mul(self, other: Self) -> Self {
183 OrderedFloat(self.0 * other.0)
184 }
185}
186
187impl<T: Float> Div for OrderedFloat<T> {
188 type Output = Self;
189
190 fn div(self, other: Self) -> Self {
191 OrderedFloat(self.0 / other.0)
192 }
193}
194
195impl<T: Float> Bounded for OrderedFloat<T> {
196 fn min_value() -> Self {
197 OrderedFloat(T::min_value())
198 }
199
200 fn max_value() -> Self {
201 OrderedFloat(T::max_value())
202 }
203}
204
205impl<T: Float + FromStr> FromStr for OrderedFloat<T> {
206 type Err = T::Err;
207
208 fn from_str(s: &str) -> Result<Self, Self::Err> {
218 T::from_str(s).map(OrderedFloat)
219 }
220}
221
222impl<T: Float> Neg for OrderedFloat<T> {
223 type Output = Self;
224
225 fn neg(self) -> Self {
226 OrderedFloat(-self.0)
227 }
228}
229
230impl<T: Float> Zero for OrderedFloat<T> {
231 fn zero() -> Self { OrderedFloat(T::zero()) }
232
233 fn is_zero(&self) -> bool { self.0.is_zero() }
234}
235
236#[derive(PartialOrd, PartialEq, Debug, Default, Clone, Copy)]
240#[repr(transparent)]
241pub struct NotNan<T: Float>(T);
242
243impl<T: Float> NotNan<T> {
244 pub fn new(val: T) -> Result<Self, FloatIsNan> {
248 match val {
249 ref val if val.is_nan() => Err(FloatIsNan),
250 val => Ok(NotNan(val)),
251 }
252 }
253
254 pub unsafe fn unchecked_new(val: T) -> Self {
258 debug_assert!(!val.is_nan());
259 NotNan(val)
260 }
261
262 pub fn into_inner(self) -> T {
264 self.0
265 }
266}
267
268impl<T: Float> AsRef<T> for NotNan<T> {
269 fn as_ref(&self) -> &T {
270 &self.0
271 }
272}
273
274impl<T: Float> Ord for NotNan<T> {
275 fn cmp(&self, other: &NotNan<T>) -> Ordering {
276 match self.partial_cmp(&other) {
277 Some(ord) => ord,
278 None => unsafe { unreachable_unchecked() },
279 }
280 }
281}
282
283impl<T: Float> Hash for NotNan<T> {
284 fn hash<H: Hasher>(&self, state: &mut H) {
285 hash_float(self.as_ref(), state)
286 }
287}
288
289impl<T: Float + fmt::Display> fmt::Display for NotNan<T> {
290 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
291 self.as_ref().fmt(f)
292 }
293}
294
295impl From<NotNan<f32>> for f32 {
296 fn from(value: NotNan<f32>) -> Self {
297 value.into_inner()
298 }
299}
300
301impl From<NotNan<f64>> for f64 {
302 fn from(value: NotNan<f64>) -> Self {
303 value.into_inner()
304 }
305}
306
307impl<T: Float> From<T> for NotNan<T> {
311 fn from(v: T) -> Self {
312 NotNan::new(v).expect("Tried to create a NotNan from a NaN")
313 }
314}
315
316impl<T: Float> Deref for NotNan<T> {
317 type Target = T;
318
319 fn deref(&self) -> &Self::Target {
320 self.as_ref()
321 }
322}
323
324impl<T: Float + PartialEq> Eq for NotNan<T> {}
325
326impl<T: Float> Add for NotNan<T> {
330 type Output = Self;
331
332 fn add(self, other: Self) -> Self {
333 self + other.0
334 }
335}
336
337impl<T: Float> Add<T> for NotNan<T> {
341 type Output = Self;
342
343 fn add(self, other: T) -> Self {
344 NotNan::new(self.0 + other).expect("Addition resulted in NaN")
345 }
346}
347
348impl<T: Float + AddAssign> AddAssign for NotNan<T> {
349 fn add_assign(&mut self, other: Self) {
350 *self += other.0;
351 }
352}
353
354impl<T: Float + AddAssign> AddAssign<T> for NotNan<T> {
358 fn add_assign(&mut self, other: T) {
359 *self = *self + other;
360 }
361}
362
363
364impl<T: Float + Sum> Sum for NotNan<T> {
365 fn sum<I: Iterator<Item = NotNan<T>>>(iter: I) -> Self {
366 NotNan::new(iter.map(|v| v.0).sum()).expect("Sum resulted in NaN")
367 }
368}
369
370impl<'a, T: Float + Sum> Sum<&'a NotNan<T>> for NotNan<T> {
371 fn sum<I: Iterator<Item = &'a NotNan<T>>>(iter: I) -> Self {
372 iter.map(|v| *v).sum()
373 }
374}
375
376impl<T: Float> Sub for NotNan<T> {
377 type Output = Self;
378
379 fn sub(self, other: Self) -> Self {
380 self - other.0
381 }
382}
383
384impl<T: Float> Sub<T> for NotNan<T> {
388 type Output = Self;
389
390 fn sub(self, other: T) -> Self {
391 NotNan::new(self.0 - other).expect("Subtraction resulted in NaN")
392 }
393}
394
395impl<T: Float + SubAssign> SubAssign for NotNan<T> {
396 fn sub_assign(&mut self, other: Self) {
397 *self -= other.0
398 }
399}
400
401impl<T: Float + SubAssign> SubAssign<T> for NotNan<T> {
405 fn sub_assign(&mut self, other: T) {
406 *self = *self - other;
407 }
408}
409
410impl<T: Float> Mul for NotNan<T> {
411 type Output = Self;
412
413 fn mul(self, other: Self) -> Self {
414 self * other.0
415 }
416}
417
418impl<T: Float> Mul<T> for NotNan<T> {
422 type Output = Self;
423
424 fn mul(self, other: T) -> Self {
425 NotNan::new(self.0 * other).expect("Multiplication resulted in NaN")
426 }
427}
428
429impl<T: Float + MulAssign> MulAssign for NotNan<T> {
430 fn mul_assign(&mut self, other: Self) {
431 *self *= other.0
432 }
433}
434
435impl<T: Float + MulAssign> MulAssign<T> for NotNan<T> {
439 fn mul_assign(&mut self, other: T) {
440 *self = *self * other;
441 }
442}
443
444impl<T: Float + Product> Product for NotNan<T> {
445 fn product<I: Iterator<Item = NotNan<T>>>(iter: I) -> Self {
446 NotNan::new(iter.map(|v| v.0).product()).expect("Product resulted in NaN")
447 }
448}
449
450impl<'a, T: Float + Product> Product<&'a NotNan<T>> for NotNan<T> {
451 fn product<I: Iterator<Item = &'a NotNan<T>>>(iter: I) -> Self {
452 iter.map(|v| *v).product()
453 }
454}
455
456impl<T: Float> Div for NotNan<T> {
457 type Output = Self;
458
459 fn div(self, other: Self) -> Self {
460 self / other.0
461 }
462}
463
464impl<T: Float> Div<T> for NotNan<T> {
468 type Output = Self;
469
470 fn div(self, other: T) -> Self {
471 NotNan::new(self.0 / other).expect("Division resulted in NaN")
472 }
473}
474
475impl<T: Float + DivAssign> DivAssign for NotNan<T> {
476 fn div_assign(&mut self, other: Self) {
477 *self /= other.0;
478 }
479}
480
481impl<T: Float + DivAssign> DivAssign<T> for NotNan<T> {
485 fn div_assign(&mut self, other: T) {
486 *self = *self / other;
487 }
488}
489
490impl<T: Float> Rem for NotNan<T> {
491 type Output = Self;
492
493 fn rem(self, other: Self) -> Self {
494 self % other.0
495 }
496}
497
498impl<T: Float> Rem<T> for NotNan<T> {
502 type Output = Self;
503
504 fn rem(self, other: T) -> Self {
505 NotNan::new(self.0 % other).expect("Rem resulted in NaN")
506 }
507}
508
509impl<T: Float + RemAssign> RemAssign for NotNan<T> {
510 fn rem_assign(&mut self, other: Self) {
511 *self %= other.0
512 }
513}
514
515impl<T: Float + RemAssign> RemAssign<T> for NotNan<T> {
519 fn rem_assign(&mut self, other: T) {
520 *self = *self % other;
521 }
522}
523
524impl<T: Float> Neg for NotNan<T> {
525 type Output = Self;
526
527 fn neg(self) -> Self {
528 NotNan(-self.0)
529 }
530}
531
532#[derive(Copy, Clone, PartialEq, Eq, Debug)]
534pub struct FloatIsNan;
535
536#[cfg(feature = "std")]
537impl std::error::Error for FloatIsNan {
538 fn description(&self) -> &str {
539 "NotNan constructed with NaN"
540 }
541}
542
543impl fmt::Display for FloatIsNan {
544 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
545 write!(f, "NotNan constructed with NaN")
546 }
547}
548
549#[cfg(feature = "std")]
550impl Into<std::io::Error> for FloatIsNan {
551 fn into(self) -> std::io::Error {
552 std::io::Error::new(std::io::ErrorKind::InvalidInput, self)
553 }
554}
555
556#[inline]
557fn hash_float<F: Float, H: Hasher>(f: &F, state: &mut H) {
558 raw_double_bits(f).hash(state);
559}
560
561#[inline]
562fn raw_double_bits<F: Float>(f: &F) -> u64 {
563 if f.is_nan() {
564 return CANONICAL_NAN_BITS;
565 }
566
567 let (man, exp, sign) = f.integer_decode();
568 if man == 0 {
569 return CANONICAL_ZERO_BITS;
570 }
571
572 let exp_u64 = unsafe { mem::transmute::<i16, u16>(exp) } as u64;
573 let sign_u64 = if sign > 0 { 1u64 } else { 0u64 };
574 (man & MAN_MASK) | ((exp_u64 << 52) & EXP_MASK) | ((sign_u64 << 63) & SIGN_MASK)
575}
576
577impl<T: Float> Zero for NotNan<T> {
578 fn zero() -> Self { NotNan(T::zero()) }
579
580 fn is_zero(&self) -> bool { self.0.is_zero() }
581}
582
583impl<T: Float> One for NotNan<T> {
584 fn one() -> Self { NotNan(T::one()) }
585}
586
587impl<T: Float> Bounded for NotNan<T> {
588 fn min_value() -> Self {
589 NotNan(T::min_value())
590 }
591
592 fn max_value() -> Self {
593 NotNan(T::max_value())
594 }
595}
596
597impl<T: Float + FromStr> FromStr for NotNan<T> {
598 type Err = ParseNotNanError<T::Err>;
599
600 fn from_str(src: &str) -> Result<Self, Self::Err> {
611 src.parse()
612 .map_err(ParseNotNanError::ParseFloatError)
613 .and_then(|f| NotNan::new(f).map_err(|_| ParseNotNanError::IsNaN))
614 }
615}
616
617impl<T: Float + FromPrimitive> FromPrimitive for NotNan<T> {
618 fn from_i64(n: i64) -> Option<Self> { T::from_i64(n).and_then(|n| NotNan::new(n).ok()) }
619 fn from_u64(n: u64) -> Option<Self> { T::from_u64(n).and_then(|n| NotNan::new(n).ok()) }
620
621 fn from_isize(n: isize) -> Option<Self> { T::from_isize(n).and_then(|n| NotNan::new(n).ok()) }
622 fn from_i8(n: i8) -> Option<Self> { T::from_i8(n).and_then(|n| NotNan::new(n).ok()) }
623 fn from_i16(n: i16) -> Option<Self> { T::from_i16(n).and_then(|n| NotNan::new(n).ok()) }
624 fn from_i32(n: i32) -> Option<Self> { T::from_i32(n).and_then(|n| NotNan::new(n).ok()) }
625 fn from_usize(n: usize) -> Option<Self> { T::from_usize(n).and_then(|n| NotNan::new(n).ok()) }
626 fn from_u8(n: u8) -> Option<Self> { T::from_u8(n).and_then(|n| NotNan::new(n).ok()) }
627 fn from_u16(n: u16) -> Option<Self> { T::from_u16(n).and_then(|n| NotNan::new(n).ok()) }
628 fn from_u32(n: u32) -> Option<Self> { T::from_u32(n).and_then(|n| NotNan::new(n).ok()) }
629 fn from_f32(n: f32) -> Option<Self> { T::from_f32(n).and_then(|n| NotNan::new(n).ok()) }
630 fn from_f64(n: f64) -> Option<Self> { T::from_f64(n).and_then(|n| NotNan::new(n).ok()) }
631}
632
633impl<T: Float> ToPrimitive for NotNan<T> {
634 fn to_i64(&self) -> Option<i64> { self.0.to_i64() }
635 fn to_u64(&self) -> Option<u64> { self.0.to_u64() }
636
637 fn to_isize(&self) -> Option<isize> { self.0.to_isize() }
638 fn to_i8(&self) -> Option<i8> { self.0.to_i8() }
639 fn to_i16(&self) -> Option<i16> { self.0.to_i16() }
640 fn to_i32(&self) -> Option<i32> { self.0.to_i32() }
641 fn to_usize(&self) -> Option<usize> { self.0.to_usize() }
642 fn to_u8(&self) -> Option<u8> { self.0.to_u8() }
643 fn to_u16(&self) -> Option<u16> { self.0.to_u16() }
644 fn to_u32(&self) -> Option<u32> { self.0.to_u32() }
645 fn to_f32(&self) -> Option<f32> { self.0.to_f32() }
646 fn to_f64(&self) -> Option<f64> { self.0.to_f64() }
647}
648
649#[derive(Copy, Clone, PartialEq, Eq, Debug)]
651pub enum ParseNotNanError<E> {
652 ParseFloatError(E),
654 IsNaN,
656}
657
658#[cfg(feature = "std")]
659impl<E: fmt::Debug> std::error::Error for ParseNotNanError<E> {
660 fn description(&self) -> &str {
661 return "Error parsing a not-NaN floating point value";
662 }
663
664 }
666
667impl<E: fmt::Debug> fmt::Display for ParseNotNanError<E> {
668 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
669 <Self as fmt::Debug>::fmt(self, f)
671 }
672}
673
674impl<T: Float> Num for NotNan<T> {
675 type FromStrRadixErr = ParseNotNanError<T::FromStrRadixErr>;
676
677 fn from_str_radix(src: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
678 T::from_str_radix(src, radix)
679 .map_err(|err| ParseNotNanError::ParseFloatError(err))
680 .and_then(|n| NotNan::new(n).map_err(|_| ParseNotNanError::IsNaN))
681 }
682}
683
684impl<T: Float + Signed> Signed for NotNan<T> {
685 fn abs(&self) -> Self { NotNan(self.0.abs()) }
686
687 fn abs_sub(&self, other: &Self) -> Self {
688 NotNan::new(Signed::abs_sub(&self.0, &other.0)).expect("Subtraction resulted in NaN")
689 }
690
691 fn signum(&self) -> Self { NotNan(self.0.signum()) }
692 fn is_positive(&self) -> bool { self.0.is_positive() }
693 fn is_negative(&self) -> bool { self.0.is_negative() }
694}
695
696impl<T: Float> NumCast for NotNan<T> {
697 fn from<F: ToPrimitive>(n: F) -> Option<Self> {
698 T::from(n).and_then(|n| NotNan::new(n).ok())
699 }
700}
701
702#[cfg(feature = "serde")]
703mod impl_serde {
704 extern crate serde;
705 use self::serde::{Serialize, Serializer, Deserialize, Deserializer};
706 use self::serde::de::{Error, Unexpected};
707 use super::{OrderedFloat, NotNan};
708 #[cfg(feature = "std")]
709 use num_traits::Float;
710 #[cfg(not(feature = "std"))]
711 use num_traits::float::FloatCore as Float;
712 use core::f64;
713
714 #[cfg(test)]
715 extern crate serde_test;
716 #[cfg(test)]
717 use self::serde_test::{Token, assert_tokens, assert_de_tokens_error};
718
719 impl<T: Float + Serialize> Serialize for OrderedFloat<T> {
720 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
721 self.0.serialize(s)
722 }
723 }
724
725 impl<'de, T: Float + Deserialize<'de>> Deserialize<'de> for OrderedFloat<T> {
726 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
727 T::deserialize(d).map(OrderedFloat)
728 }
729 }
730
731 impl<T: Float + Serialize> Serialize for NotNan<T> {
732 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
733 self.0.serialize(s)
734 }
735 }
736
737 impl<'de, T: Float + Deserialize<'de>> Deserialize<'de> for NotNan<T> {
738 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
739 let float = T::deserialize(d)?;
740 NotNan::new(float).map_err(|_| {
741 Error::invalid_value(Unexpected::Float(f64::NAN), &"float (but not NaN)")
742 })
743 }
744 }
745
746 #[test]
747 fn test_ordered_float() {
748 let float = OrderedFloat(1.0f64);
749 assert_tokens(&float, &[Token::F64(1.0)]);
750 }
751
752 #[test]
753 fn test_not_nan() {
754 let float = NotNan(1.0f64);
755 assert_tokens(&float, &[Token::F64(1.0)]);
756 }
757
758 #[test]
759 fn test_fail_on_nan() {
760 assert_de_tokens_error::<NotNan<f64>>(
761 &[Token::F64(f64::NAN)],
762 "invalid value: floating point `NaN`, expected float (but not NaN)");
763 }
764}