Skip to content

Commit

Permalink
Merge pull request #1827 from CosmWasm/use-const-ten
Browse files Browse the repository at this point in the history
Use const ten
  • Loading branch information
webmaster128 authored Aug 22, 2023
2 parents 4923079 + 928f70b commit ebb3785
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
2 changes: 1 addition & 1 deletion packages/std/src/math/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ impl Decimal {
) -> Result<Self, DecimalRangeExceeded> {
let atomics = atomics.into();
const TEN: Uint128 = Uint128::new(10);
Ok(match decimal_places.cmp(&(Self::DECIMAL_PLACES)) {
Ok(match decimal_places.cmp(&Self::DECIMAL_PLACES) {
Ordering::Less => {
let digits = (Self::DECIMAL_PLACES) - decimal_places; // No overflow because decimal_places < DECIMAL_PLACES
let factor = TEN.checked_pow(digits).unwrap(); // Safe because digits <= 17
Expand Down
11 changes: 7 additions & 4 deletions packages/std/src/math/decimal256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,14 @@ impl Decimal256 {
decimal_places: u32,
) -> Result<Self, Decimal256RangeExceeded> {
let atomics = atomics.into();
let ten = Uint256::from(10u64); // TODO: make const
Ok(match decimal_places.cmp(&(Self::DECIMAL_PLACES)) {
const TEN: Uint256 = Uint256::from_be_bytes([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 10,
]);
Ok(match decimal_places.cmp(&Self::DECIMAL_PLACES) {
Ordering::Less => {
let digits = (Self::DECIMAL_PLACES) - decimal_places; // No overflow because decimal_places < DECIMAL_PLACES
let factor = ten.checked_pow(digits).unwrap(); // Safe because digits <= 17
let factor = TEN.checked_pow(digits).unwrap(); // Safe because digits <= 17
Self(
atomics
.checked_mul(factor)
Expand All @@ -171,7 +174,7 @@ impl Decimal256 {
Ordering::Equal => Self(atomics),
Ordering::Greater => {
let digits = decimal_places - (Self::DECIMAL_PLACES); // No overflow because decimal_places > DECIMAL_PLACES
if let Ok(factor) = ten.checked_pow(digits) {
if let Ok(factor) = TEN.checked_pow(digits) {
Self(atomics.checked_div(factor).unwrap()) // Safe because factor cannot be zero
} else {
// In this case `factor` exceeds the Uint256 range.
Expand Down

0 comments on commit ebb3785

Please sign in to comment.