Skip to content

Commit

Permalink
Add TryFrom<Decimal256> impl for Decimal
Browse files Browse the repository at this point in the history
  • Loading branch information
chipshort committed Aug 23, 2023
1 parent 2543067 commit 03e3d46
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ and this project adheres to
- cosmwasm-std: Add iterators for `Coins` ([#1806]).
- cosmwasm-std: Make `abs_diff` const for `Uint{256,512}` and
`Int{64,128,256,512}`. It is now const for all integer types.
- cosmwasm-std: Implement `TryFrom<Decimal256>` for `Decimal` ([#1832])

[#1799]: https://github.com/CosmWasm/cosmwasm/pull/1799
[#1806]: https://github.com/CosmWasm/cosmwasm/pull/1806
[#1832]: https://github.com/CosmWasm/cosmwasm/pull/1832

### Changed

Expand Down
30 changes: 29 additions & 1 deletion packages/std/src/math/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::errors::{
CheckedFromRatioError, CheckedMultiplyRatioError, DivideByZeroError, OverflowError,
OverflowOperation, RoundUpOverflowError, StdError,
};
use crate::forward_ref_partial_eq;
use crate::{forward_ref_partial_eq, Decimal256};

use super::Fraction;
use super::Isqrt;
Expand Down Expand Up @@ -498,6 +498,18 @@ impl Fraction<Uint128> for Decimal {
}
}

impl TryFrom<Decimal256> for Decimal {
type Error = DecimalRangeExceeded;

fn try_from(value: Decimal256) -> Result<Self, Self::Error> {
value
.atomics()
.try_into()
.map(Decimal)
.map_err(|_| DecimalRangeExceeded)
}
}

impl FromStr for Decimal {
type Err = StdError;

Expand Down Expand Up @@ -817,6 +829,22 @@ mod tests {
assert_eq!(value.0, Decimal::DECIMAL_FRACTIONAL / Uint128::from(80u8));
}

#[test]
fn decimal_from_decimal256_works() {
let too_big = Decimal256::new(Uint256::from(Uint128::MAX) + Uint256::one());
assert_eq!(Decimal::try_from(too_big), Err(DecimalRangeExceeded));

let just_right = Decimal256::new(Uint256::from(Uint128::MAX));
assert_eq!(Decimal::try_from(just_right), Ok(Decimal::MAX));

assert_eq!(Decimal::try_from(Decimal256::zero()), Ok(Decimal::zero()));
assert_eq!(Decimal::try_from(Decimal256::one()), Ok(Decimal::one()));
assert_eq!(
Decimal::try_from(Decimal256::percent(50)),
Ok(Decimal::percent(50))
);
}

#[test]
fn decimal_from_atomics_works() {
let one = Decimal::one();
Expand Down

0 comments on commit 03e3d46

Please sign in to comment.