Skip to content

Commit

Permalink
Implement to_uint_ceil without modulo operation
Browse files Browse the repository at this point in the history
  • Loading branch information
webmaster128 committed Jan 30, 2023
1 parent 2bcc2d1 commit 3b7b3a4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
10 changes: 7 additions & 3 deletions packages/std/src/math/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,10 +399,14 @@ impl Decimal {
/// assert_eq!(d.to_uint_ceil(), Uint128::new(75));
/// ```
pub fn to_uint_ceil(self) -> Uint128 {
if (self.0 % Self::DECIMAL_FRACTIONAL).is_zero() {
self.0 / Self::DECIMAL_FRACTIONAL
// Using `q = 1 + ((x - 1) / y); // if x != 0` with unsigned integers x, y, q
// from https://stackoverflow.com/a/2745086/2013738. We know `x + y` CAN overflow.
let x = self.0;
let y = Self::DECIMAL_FRACTIONAL;
if x.is_zero() {
Uint128::zero()
} else {
self.0 / Self::DECIMAL_FRACTIONAL + Uint128::one()
Uint128::one() + ((x - Uint128::one()) / y)
}
}
}
Expand Down
10 changes: 7 additions & 3 deletions packages/std/src/math/decimal256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,10 +416,14 @@ impl Decimal256 {
/// assert_eq!(d.to_uint_ceil(), Uint256::from(75u64));
/// ```
pub fn to_uint_ceil(self) -> Uint256 {
if (self.0 % Self::DECIMAL_FRACTIONAL).is_zero() {
self.0 / Self::DECIMAL_FRACTIONAL
// Using `q = 1 + ((x - 1) / y); // if x != 0` with unsigned integers x, y, q
// from https://stackoverflow.com/a/2745086/2013738. We know `x + y` CAN overflow.
let x = self.0;
let y = Self::DECIMAL_FRACTIONAL;
if x.is_zero() {
Uint256::zero()
} else {
self.0 / Self::DECIMAL_FRACTIONAL + Uint256::one()
Uint256::one() + ((x - Uint256::one()) / y)
}
}
}
Expand Down

0 comments on commit 3b7b3a4

Please sign in to comment.