|
| 1 | +use crate::{approximate_float, approximate_float_unsigned, FromPrimitive, Ratio}; |
| 2 | +use std::convert::TryFrom; |
| 3 | + |
| 4 | +macro_rules! impl_try_from { |
| 5 | + ( $($name:ty),* => $into:ty ; $approx:ident) => { |
| 6 | + $( |
| 7 | + impl TryFrom<$name> for Ratio<$into> { |
| 8 | + type Error = (); |
| 9 | + paste::paste! { |
| 10 | + fn try_from(n: $name) -> Result<Self, ()> { |
| 11 | + <$into as FromPrimitive>::[< from_ $name>](n) |
| 12 | + .map(Ratio::from_integer) |
| 13 | + .ok_or(()) |
| 14 | + } |
| 15 | + } |
| 16 | + } |
| 17 | + )* |
| 18 | + |
| 19 | + impl TryFrom<f32> for Ratio<$into> { |
| 20 | + type Error = (); |
| 21 | + fn try_from(n: f32) -> Result<Self, ()> { |
| 22 | + $approx(n, 10e-20, 30).ok_or(()) |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + impl TryFrom<f64> for Ratio<$into> { |
| 27 | + type Error = (); |
| 28 | + fn try_from(n: f64) -> Result<Self, ()> { |
| 29 | + $approx(n, 10e-20, 30).ok_or(()) |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + }; |
| 34 | +} |
| 35 | + |
| 36 | +impl_try_from!(i8, u16, i16, u32, i32, u64, i64, u128, i128 => u8 ; approximate_float_unsigned); |
| 37 | +impl_try_from!(u8, u16, i16, u32, i32, u64, i64, u128, i128 => i8 ; approximate_float); |
| 38 | + |
| 39 | +impl_try_from!(i16, u32, i32, u64, i64, u128, i128 => u16 ; approximate_float_unsigned); |
| 40 | +impl_try_from!(u16, u32, i32, u64, i64, u128, i128 => i16 ; approximate_float); |
| 41 | + |
| 42 | +impl_try_from!(i32, u64, i64, u128, i128 => u32 ; approximate_float_unsigned); |
| 43 | +impl_try_from!(u32, u64, i64, u128, i128 => i32 ; approximate_float); |
| 44 | + |
| 45 | +impl_try_from!(i64, u128, i128 => u64 ; approximate_float_unsigned); |
| 46 | +impl_try_from!(u64, u128, i128 => i64 ; approximate_float); |
| 47 | + |
| 48 | +impl_try_from!(i128 => u128 ; approximate_float_unsigned); |
| 49 | +impl_try_from!(u128 => i128 ; approximate_float); |
| 50 | + |
| 51 | +macro_rules! impl_from { |
| 52 | + ( $($name:ty),* => $into:ty) => { |
| 53 | + $( |
| 54 | + impl From<$name> for Ratio<$into> { |
| 55 | + paste::paste! { |
| 56 | + fn from(n: $name) -> Self { |
| 57 | + <$into as FromPrimitive>::[< from_ $name>](n) |
| 58 | + .map(Ratio::from_integer) |
| 59 | + .unwrap() |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + )* |
| 64 | + }; |
| 65 | +} |
| 66 | + |
| 67 | +impl_from!(u8, u16, u32, u64 => u128); |
| 68 | +impl_from!(u8, i8, u16, i16, u32, i32, u64, i64 => i128); |
| 69 | + |
| 70 | +impl_from!(u8, u16, u32 => u64); |
| 71 | +impl_from!(u8, i8, u16, i16, u32, i32 => i64); |
| 72 | + |
| 73 | +impl_from!(u8, u16 => u32); |
| 74 | +impl_from!(u8, i8, u16, i16 => i32); |
| 75 | + |
| 76 | +impl_from!(u8 => u16); |
| 77 | +impl_from!(u8, i8 => i16); |
0 commit comments