Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert when overflow using pow for u8, u16, u32 #6340

Merged
merged 17 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions sway-lib-std/src/math.sw
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
library;

use ::assert::*;
use ::flags::{disable_panic_on_overflow, F_UNSAFEMATH_DISABLE_MASK, set_flags};
use ::flags::{
disable_panic_on_overflow,
F_UNSAFEMATH_DISABLE_MASK,
F_WRAPPING_DISABLE_MASK,
set_flags,
SwayStar123 marked this conversation as resolved.
Show resolved Hide resolved
};
use ::registers::{flags, overflow};

/// Calculates the square root.
Expand Down Expand Up @@ -113,27 +118,48 @@ impl Power for u64 {

impl Power for u32 {
fn pow(self, exponent: u32) -> Self {
asm(r1: self, r2: exponent, r3) {
let res = asm(r1: self, r2: exponent, r3) {
exp r3 r1 r2;
r3: Self
r3: u64
};
// If panic on wrapping math is enabled, only then revert
if flags() & F_WRAPPING_DISABLE_MASK == 0 {
assert(res <= Self::max().as_u64());
}
asm(r1: res) {
r1: Self
}
}
}

impl Power for u16 {
fn pow(self, exponent: u32) -> Self {
asm(r1: self, r2: exponent, r3) {
let res = asm(r1: self, r2: exponent, r3) {
exp r3 r1 r2;
r3: Self
r3: u64
};
// If panic on wrapping math is enabled, only then revert
if flags() & F_WRAPPING_DISABLE_MASK == 0 {
assert(res <= Self::max().as_u64());
}
asm(r1: res) {
r1: Self
}
}
}

impl Power for u8 {
fn pow(self, exponent: u32) -> Self {
asm(r1: self, r2: exponent, r3) {
let res = asm(r1: self, r2: exponent, r3) {
exp r3 r1 r2;
r3: Self
r3: u64
};
// If panic on wrapping math is enabled, only then revert
if flags() & F_WRAPPING_DISABLE_MASK == 0 {
assert(res <= Self::max().as_u64());
}
asm(r1: res) {
r1: Self
}
}
}
Expand Down
Loading
Loading