Skip to content

Commit 1fb4393

Browse files
f-frmbrubeck
authored andcommitted
Implement NumCast for NotNaN
1 parent 6939372 commit 1fb4393

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/lib.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ use std::fmt;
1515
use std::io;
1616
use std::mem;
1717
use unreachable::unreachable;
18-
use num_traits::{Bounded, Float, FromPrimitive, Num, One, Signed, ToPrimitive, Zero};
18+
use num_traits::{Bounded, Float, FromPrimitive, Num, NumCast, One, Signed, ToPrimitive,
19+
Zero};
1920

2021
/// A wrapper around Floats providing an implementation of Ord and Hash.
2122
///
@@ -664,6 +665,12 @@ impl<T: Float + Signed> Signed for NotNaN<T> {
664665
fn is_negative(&self) -> bool { self.0.is_negative() }
665666
}
666667

668+
impl<T: Float + NumCast> NumCast for NotNaN<T> {
669+
fn from<F: ToPrimitive>(n: F) -> Option<Self> {
670+
T::from(n).and_then(|n| NotNaN::new(n).ok())
671+
}
672+
}
673+
667674
#[cfg(feature = "serde")]
668675
mod impl_serde {
669676
extern crate serde;

tests/test.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ describe! not_nan32 {
168168
assert_eq!(NotNaN::from(50f32).abs_sub(&NotNaN::from(8f32)), NotNaN::from(42f32));
169169
assert_eq!(NotNaN::from(8f32).abs_sub(&NotNaN::from(50f32)), NotNaN::from(0f32));
170170
}
171+
172+
it "should implement NumCast" {
173+
assert_eq!(<NotNaN<f32> as num_traits::NumCast>::from(42), Some(NotNaN::from(42f32)));
174+
assert_eq!(<NotNaN<f32> as num_traits::NumCast>::from(f32::nan()), None);
175+
}
171176
}
172177

173178
describe! not_nan64 {
@@ -295,6 +300,11 @@ describe! not_nan64 {
295300
assert_eq!(NotNaN::from(50f64).abs_sub(&NotNaN::from(8f64)), NotNaN::from(42f64));
296301
assert_eq!(NotNaN::from(8f64).abs_sub(&NotNaN::from(50f64)), NotNaN::from(0f64));
297302
}
303+
304+
it "should implement NumCast" {
305+
assert_eq!(<NotNaN<f64> as num_traits::NumCast>::from(42), Some(NotNaN::from(42f64)));
306+
assert_eq!(<NotNaN<f64> as num_traits::NumCast>::from(f64::nan()), None);
307+
}
298308
}
299309

300310
describe! hashing {

0 commit comments

Comments
 (0)