Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TryFrom<Decimal256> impl for Decimal #1832

Merged
merged 1 commit into from
Aug 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading