Skip to content

Commit

Permalink
fix(stdlib): Optimize number modulo (#2144)
Browse files Browse the repository at this point in the history
  • Loading branch information
spotandjake authored Aug 16, 2024
1 parent c8624c3 commit 960fadd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
2 changes: 1 addition & 1 deletion compiler/test/runtime/numbers.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ assert isNaN(NaN % Infinity)
assert isNaN(NaN % -Infinity)
assert -17 % 4 == 3
assert -17 % -4 == -1
assert 17 % -4 == 5
assert 17 % -4 == -3
assert -17 % 17 == 0
assert 17 % -17 == 0
assert 17 % 17 == 0
18 changes: 9 additions & 9 deletions stdlib/runtime/numbers.gr
Original file line number Diff line number Diff line change
Expand Up @@ -1613,7 +1613,7 @@ let i64abs = x => {

@unsafe
let numberMod = (x, y) => {
use WasmI64.{ (!=), (-), (*), (<), (>) }
use WasmI64.{ (!=), (-), (*), (<), (>), (^) }
// incRef x and y to reuse them via WasmI32.toGrain
Memory.incRef(x)
Memory.incRef(y)
Expand All @@ -1636,14 +1636,14 @@ let numberMod = (x, y) => {
throw Exception.ModuloByZero
}
// We implement true modulo
if (xval < 0N && yval > 0N || xval > 0N && yval < 0N) {
let modval = WasmI64.remS(i64abs(xval), i64abs(yval))
let result = if (modval != 0N) {
i64abs(yval) - modval * (if (yval < 0N) -1N else 1N)
} else {
modval
}
reducedInteger(result)
if ((xval ^ yval) < 0N) {
let xabs = i64abs(xval)
let yabs = i64abs(yval)
let mval = WasmI64.remS(xabs, yabs)
let mres = yabs - mval
reducedInteger(
if (mval != 0N) (if (yval < 0N) 0N - mres else mres) else 0N
)
} else {
reducedInteger(WasmI64.remS(xval, yval))
}
Expand Down

0 comments on commit 960fadd

Please sign in to comment.