Skip to content

Commit

Permalink
Implement TryFrom<&str> for Decimal (#560)
Browse files Browse the repository at this point in the history
  • Loading branch information
c410-f3r committed Dec 8, 2022
1 parent 7911979 commit 69c1e7f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1770,7 +1770,7 @@ impl_try_from_decimal!(u128, Decimal::to_u128, integer_docs!(true));
// See https://github.com/rust-lang/rustfmt/issues/5062 for more information.
#[rustfmt::skip]
macro_rules! impl_try_from_primitive {
($TFrom:ty, $conversion_fn:path) => {
($TFrom:ty, $conversion_fn:path $(, $err:expr)?) => {
#[doc = concat!(
"Try to convert a `",
stringify!($TFrom),
Expand All @@ -1781,14 +1781,15 @@ macro_rules! impl_try_from_primitive {

#[inline]
fn try_from(t: $TFrom) -> Result<Self, Error> {
$conversion_fn(t).ok_or_else(|| Error::ConversionTo("Decimal".into()))
$conversion_fn(t) $( .ok_or_else(|| $err) )?
}
}
};
}

impl_try_from_primitive!(f32, Self::from_f32);
impl_try_from_primitive!(f64, Self::from_f64);
impl_try_from_primitive!(f32, Self::from_f32, Error::ConversionTo("Decimal".into()));
impl_try_from_primitive!(f64, Self::from_f64, Error::ConversionTo("Decimal".into()));
impl_try_from_primitive!(&str, core::str::FromStr::from_str);

macro_rules! impl_from {
($T:ty, $from_ty:path) => {
Expand Down
6 changes: 6 additions & 0 deletions tests/decimal_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2859,6 +2859,12 @@ fn it_converts_from_u128() {
}
}

#[test]
fn it_converts_from_str() {
assert_eq!(Decimal::try_from("1").unwrap(), Decimal::ONE);
assert_eq!(Decimal::try_from("10").unwrap(), Decimal::TEN);
}

#[test]
fn it_converts_from_f32() {
use num_traits::FromPrimitive;
Expand Down

0 comments on commit 69c1e7f

Please sign in to comment.