Skip to content

Commit

Permalink
Manually clone self in subtract for U256 and pow for U128 (F…
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammadfawaz authored Mar 16, 2023
1 parent 2ffb034 commit 52ac42b
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
4 changes: 3 additions & 1 deletion sway-lib-std/src/u128.sw
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,9 @@ impl Power for U128 {
}

if exp == one {
return self;
// Manually clone `self`. Otherwise, we may have a `MemoryOverflow`
// issue with code that looks like: `x = x.pow(other)`
return U128::from((self.upper, self.lower));
}

while exp & one == zero {
Expand Down
4 changes: 3 additions & 1 deletion sway-lib-std/src/u256.sw
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,9 @@ impl core::ops::Subtract for U256 {
if self == other {
return Self::min();
} else if other == Self::min() {
return self;
// Manually clone `self`. Otherwise, we may have a `MemoryOverflow`
// issue with code that looks like: `x = x - other`
return U256::from((self.a, self.b, self.c, self.d));
}
// If trying to subtract a larger number, panic.
assert(self > other);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,10 @@ fn main() -> bool {
pow_of_u_128 = u_128.pow(U128::from((0, 3)));
assert(pow_of_u_128 == U128::from((0, 1728)));

// Test reassignment
u_128 = U128::from((0, 13));
u_128 = u_128.pow(U128::from((0, 1)));
assert(u_128 == U128::from((0, 13)));

true
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::u256::U256;

fn main() -> bool {
let first = U256::from((0, 0, 0, 0));
let second = U256::from((0, 0, 0, 1));
let mut second = U256::from((0, 0, 0, 1));
let max_u64 = U256::from((0, 0, 0, u64::max()));

let one = first + second;
Expand Down Expand Up @@ -40,6 +40,13 @@ fn main() -> bool {
assert(sub_max_again.c == 0);
assert(sub_max_again.d == u64::max());

// Test reassignment
second = second - U256::min();
assert(second.a == 0);
assert(second.b == 0);
assert(second.c == 0);
assert(second.d == 1);

let zero_in_between = U256::from((0, 1, 0, 10));
let d_nonzero = U256::from((0, 0, 0, 12));

Expand Down

0 comments on commit 52ac42b

Please sign in to comment.