Skip to content

Commit

Permalink
update reverts to depend on flags
Browse files Browse the repository at this point in the history
  • Loading branch information
SwayStar123 committed Oct 16, 2024
1 parent c366d21 commit c42c383
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions sway-lib-std/src/u128.sw
Original file line number Diff line number Diff line change
Expand Up @@ -556,8 +556,11 @@ impl core::ops::Add for U128 {
fn add(self, other: Self) -> Self {
let mut upper_128 = self.upper.overflowing_add(other.upper);

// If the upper overflows, then the number cannot fit in 128 bits, so panic.
assert(upper_128.upper == 0);
if panic_on_overflow_enabled() {
// If the upper overflows, then the number cannot fit in 128 bits, so panic.
assert(upper_128.upper == 0);
}

let lower_128 = self.lower.overflowing_add(other.lower);

// If overflow has occurred in the lower component addition, carry.
Expand All @@ -566,8 +569,10 @@ impl core::ops::Add for U128 {
upper_128 = upper_128.lower.overflowing_add(lower_128.upper);
}

// If overflow has occurred in the upper component addition, panic.
assert(upper_128.upper == 0);
if panic_on_overflow_enabled() {
// If overflow has occurred in the upper component addition, panic.
assert(upper_128.upper == 0);
}

Self {
upper: upper_128.lower,
Expand All @@ -577,10 +582,13 @@ impl core::ops::Add for U128 {
}

impl core::ops::Subtract for U128 {
/// Subtract a `U128` from a `U128`. Reverts of overflow.
/// Subtract a `U128` from a `U128`. Reverts on underflow.
fn subtract(self, other: Self) -> Self {
// If trying to subtract a larger number, panic.
assert(!(self < other));
// panic_on_overflow_enabled is also for underflow
if panic_on_overflow_enabled() {
// If trying to subtract a larger number, panic.
assert(!(self < other));
}

let mut upper = self.upper - other.upper;
let mut lower = 0;
Expand All @@ -602,7 +610,9 @@ impl core::ops::Multiply for U128 {
// in case both of the `U128` upper parts are bigger than zero,
// it automatically means overflow, as any `U128` value
// is upper part multiplied by 2 ^ 64 + lower part
assert(self.upper == 0 || other.upper == 0);
if panic_on_unsafe_math_enabled() {
assert(self.upper == 0 || other.upper == 0);
}

let mut result = self.lower.overflowing_mul(other.lower);
if self.upper == 0 {
Expand All @@ -622,7 +632,9 @@ impl core::ops::Divide for U128 {
fn divide(self, divisor: Self) -> Self {
let zero = Self::from((0, 0));

assert(divisor != zero);
if panic_on_unsafe_math_enabled() {
assert(divisor != zero);
}

if self.upper == 0 && divisor.upper == 0 {
return Self::from((0, self.lower / divisor.lower));
Expand Down

0 comments on commit c42c383

Please sign in to comment.