Skip to content

Commit 3b7b3a4

Browse files
committed
Implement to_uint_ceil without modulo operation
1 parent 2bcc2d1 commit 3b7b3a4

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

packages/std/src/math/decimal.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -399,10 +399,14 @@ impl Decimal {
399399
/// assert_eq!(d.to_uint_ceil(), Uint128::new(75));
400400
/// ```
401401
pub fn to_uint_ceil(self) -> Uint128 {
402-
if (self.0 % Self::DECIMAL_FRACTIONAL).is_zero() {
403-
self.0 / Self::DECIMAL_FRACTIONAL
402+
// Using `q = 1 + ((x - 1) / y); // if x != 0` with unsigned integers x, y, q
403+
// from https://stackoverflow.com/a/2745086/2013738. We know `x + y` CAN overflow.
404+
let x = self.0;
405+
let y = Self::DECIMAL_FRACTIONAL;
406+
if x.is_zero() {
407+
Uint128::zero()
404408
} else {
405-
self.0 / Self::DECIMAL_FRACTIONAL + Uint128::one()
409+
Uint128::one() + ((x - Uint128::one()) / y)
406410
}
407411
}
408412
}

packages/std/src/math/decimal256.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -416,10 +416,14 @@ impl Decimal256 {
416416
/// assert_eq!(d.to_uint_ceil(), Uint256::from(75u64));
417417
/// ```
418418
pub fn to_uint_ceil(self) -> Uint256 {
419-
if (self.0 % Self::DECIMAL_FRACTIONAL).is_zero() {
420-
self.0 / Self::DECIMAL_FRACTIONAL
419+
// Using `q = 1 + ((x - 1) / y); // if x != 0` with unsigned integers x, y, q
420+
// from https://stackoverflow.com/a/2745086/2013738. We know `x + y` CAN overflow.
421+
let x = self.0;
422+
let y = Self::DECIMAL_FRACTIONAL;
423+
if x.is_zero() {
424+
Uint256::zero()
421425
} else {
422-
self.0 / Self::DECIMAL_FRACTIONAL + Uint256::one()
426+
Uint256::one() + ((x - Uint256::one()) / y)
423427
}
424428
}
425429
}

0 commit comments

Comments
 (0)