Skip to content

Commit

Permalink
Fix compile errors
Browse files Browse the repository at this point in the history
  • Loading branch information
danlehmann committed Aug 25, 2024
1 parent 35b1079 commit 5c1aaa2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 22 deletions.
29 changes: 7 additions & 22 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>
+ TryFrom<u16>
Expand All @@ -68,8 +66,12 @@ pub trait Number: Sized {

fn value(self) -> Self::UnderlyingType;

#[cfg(not(feature = "const_convert_and_const_trait_impl"))]
fn new_<T: Number>(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<T: Number>(value: T) -> Self;

fn as_u8(&self) -> u8;
Expand All @@ -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_<T: Number>(self) -> T {
T::masked_new(self)
Expand All @@ -107,24 +110,6 @@ macro_rules! impl_number_native {
#[inline]
fn value(self) -> Self::UnderlyingType { self }

#[inline]
fn new_<T: Number>(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<T: Number>(value: T) -> Self {
// Primitive types don't need masking
Self::new_(value)
}

#[inline]
fn as_u8(&self) -> u8 { *self as u8 }

Expand Down
4 changes: 4 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -2078,20 +2079,23 @@ 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() {
let a = u10::new(1000);
let _b = u9::new_(a);
}

#[cfg(not(feature = "const_convert_and_const_trait_impl"))]
#[test]
fn new_masked() {
let a = u16::new(1000);
let b = u9::masked_new(a);
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_();
Expand Down

0 comments on commit 5c1aaa2

Please sign in to comment.