Skip to content

Truly independent web browser

LibJS: Compute modulo of safe integers without fmod()

Andreas Klingfdb12db920bd
diff --git a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
index 7f6b651e5c6..cb1597fd17a 100644
--- a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
+++ b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
@@ -2878,6 +2878,17 @@ pub fn big_floor(numerator: &SignedBigInteger, denominator: &SignedBigInteger) -
/// that abs(k) < abs(y) and x - k = q × y for some integer q.
pub fn modulo(x: f64, y: f64) -> f64 {
assert!(y != 0.0 && y.is_finite());
+
+ // OPTIMIZATION: The operands are usually integers that an i64 holds exactly, and their integer remainder is far
+ // cheaper than the fmod() call that the remainder of doubles compiles to.
+ const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
+ let is_safe_integer = |value: f64| value.abs() <= MAX_SAFE_INTEGER && (value as i64) as f64 == value;
+ if is_safe_integer(x) && is_safe_integer(y) {
+ let y = y as i64;
+ let r = (x as i64) % y;
+ return (if r < 0 { r + y } else { r }) as f64;
+ }
+
let r = x % y;
if r < 0.0 { r + y } else { r }
}
diff --git a/Libraries/LibJS/Rust/src/runtime/date.rs b/Libraries/LibJS/Rust/src/runtime/date.rs
index e5f33125949..1f534c590fd 100644
--- a/Libraries/LibJS/Rust/src/runtime/date.rs
+++ b/Libraries/LibJS/Rust/src/runtime/date.rs
@@ -19,6 +19,7 @@ use crate::gc::class::{GcCell, define_cell};
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
use crate::layout::object::Object;
+use crate::runtime::abstract_operations::modulo;
use crate::runtime::big_int::SignedBigInteger;
use crate::runtime::completion::ThrowCompletionOr;
use crate::runtime::error::ErrorKind;
@@ -127,13 +128,6 @@ pub const NS_PER_DAY: f64 = 86_400_000_000_000.0;
// A time value supports a [...] range of -8,640,000,000,000,000 to 8,640,000,000,000,000 milliseconds
pub const MAX_TIME_VALUE: f64 = 8.64E15;
-/// The notation “x modulo y” of the spec for doubles, computed with fmod.
-fn modulo(x: f64, y: f64) -> f64 {
- assert!(y != 0.0 && y.is_finite());
- let remainder = x % y;
- if remainder < 0.0 { remainder + y } else { remainder }
-}
-
// 21.4.1.3 Day ( t ), https://tc39.es/ecma262/#sec-day
pub fn day(time_value: f64) -> f64 {
// 1. Return 𝔽(floor(ℝ(t / msPerDay))).