Skip to content

Commit

Permalink
Change unchecked_new to use const fn
Browse files Browse the repository at this point in the history
  • Loading branch information
notgull authored and mbrubeck committed Jul 10, 2020
1 parent 4c884c8 commit e2a0efe
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,16 @@ impl<T: Float> Zero for OrderedFloat<T> {
/// A NaN value cannot be stored in this type.
#[derive(PartialOrd, PartialEq, Debug, Default, Clone, Copy)]
#[repr(transparent)]
pub struct NotNan<T: Float>(T);
pub struct NotNan<T>(T);

impl<T> NotNan<T> {
/// Create a NotNan value from a value that is guaranteed to not be NaN
///
/// Behaviour is undefined if `val` is NaN
pub const unsafe fn unchecked_new(val: T) -> Self {
NotNan(val)
}
}

impl<T: Float> NotNan<T> {
/// Create a NotNan value.
Expand All @@ -248,14 +257,6 @@ impl<T: Float> NotNan<T> {
}
}

/// Create a NotNan value from a value that is guaranteed to not be NaN
///
/// Behaviour is undefined if `val` is NaN
pub unsafe fn unchecked_new(val: T) -> Self {
debug_assert!(!val.is_nan());
NotNan(val)
}

/// Get the value out.
pub fn into_inner(self) -> T {
self.0
Expand Down
7 changes: 7 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,3 +584,10 @@ fn not_nan64_sum_product() {
assert_eq!([a,b,c].iter().product::<NotNan<_>>(), a * b * c);

}

#[test]
fn not_nan_usage_in_const_context() {
const A: NotNan<f32> = unsafe { NotNan::unchecked_new(111f32) };

assert_eq!(A, NotNan::new(111f32).unwrap());
}

0 comments on commit e2a0efe

Please sign in to comment.