diff --git a/src/lib.rs b/src/lib.rs index 601a66d..babac0b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -40,10 +40,8 @@ impl Display for TryNewError { } #[cfg_attr(feature = "const_convert_and_const_trait_impl", const_trait)] -pub trait Number: Sized { - type UnderlyingType: Copy - + Clone - + Number +pub trait Number: Sized + Copy + Clone { + type UnderlyingType: Number + Debug + From + TryFrom @@ -68,8 +66,12 @@ pub trait Number: Sized { fn value(self) -> Self::UnderlyingType; + #[cfg(not(feature = "const_convert_and_const_trait_impl"))] fn new_(value: T) -> Self; + /// Creates an instance from the given `value`. Unlike the various `new...` functions, this + /// will never fail as the value is masked to the result size. + #[cfg(not(feature = "const_convert_and_const_trait_impl"))] fn masked_new(value: T) -> Self; fn as_u8(&self) -> u8; @@ -82,6 +84,7 @@ pub trait Number: Sized { fn as_u128(&self) -> u128; + #[cfg(not(feature = "const_convert_and_const_trait_impl"))] #[inline] fn as_(self) -> T { T::masked_new(self) @@ -107,24 +110,6 @@ macro_rules! impl_number_native { #[inline] fn value(self) -> Self::UnderlyingType { self } - #[inline] - fn new_(value: T) -> Self { - match Self::BITS { - 8 => value.as_u8() as Self, - 16 => value.as_u16() as Self, - 32 => value.as_u32() as Self, - 64 => value.as_u64() as Self, - 128 => value.as_u128() as Self, - _ => panic!("Unhandled Number type") - } - } - - #[inline] - fn masked_new(value: T) -> Self { - // Primitive types don't need masking - Self::new_(value) - } - #[inline] fn as_u8(&self) -> u8 { *self as u8 } diff --git a/tests/tests.rs b/tests/tests.rs index bc201dd..bb9ad09 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -2069,6 +2069,7 @@ fn new_and_as_specific_types() { assert_eq!(f.as_u128(), 42); } +#[cfg(not(feature = "const_convert_and_const_trait_impl"))] #[test] fn new_flexible() { let a = u10::new(1000); @@ -2078,6 +2079,7 @@ fn new_flexible() { assert_eq!(b.as_u32(), 1000); } +#[cfg(not(feature = "const_convert_and_const_trait_impl"))] #[test] #[should_panic] fn new_flexible_catches_out_of_bounds() { @@ -2085,6 +2087,7 @@ fn new_flexible_catches_out_of_bounds() { let _b = u9::new_(a); } +#[cfg(not(feature = "const_convert_and_const_trait_impl"))] #[test] fn new_masked() { let a = u16::new(1000); @@ -2092,6 +2095,7 @@ fn new_masked() { assert_eq!(b.as_u32(), 488); } +#[cfg(not(feature = "const_convert_and_const_trait_impl"))] #[test] fn as_flexible() { let a: u32 = u14::new(123).as_();