Skip to content

Commit

Permalink
add Math.clz32 method (boa-dev#524)
Browse files Browse the repository at this point in the history
  • Loading branch information
mr-rodgers committed Jun 24, 2020
1 parent 3fe8942 commit 4bc31ef
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
21 changes: 21 additions & 0 deletions boa/src/builtins/math/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::{
exec::Interpreter,
BoaProfiler,
};
use num_traits::cast::ToPrimitive;
use std::f64;

#[cfg(test)]
Expand Down Expand Up @@ -165,6 +166,25 @@ impl Math {
Ok(args.get(0).map_or(f64::NAN, |x| f64::from(x).ceil()).into())
}

/// Get the number of leading zeros in the 32 bit representation of a number
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-math.exp
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp
pub(crate) fn clz32(_: &Value, args: &[Value], _: &mut Interpreter) -> ResultValue {
Ok(args
.get(0)
.and_then(|x| f64::from(x).to_u32())
.map_or(32usize, |u| {
let s = format!("{:032b}", u);
s.chars().take_while(|x| *x == '0').count()
})
.into())
}

/// Get the cosine of a number.
///
/// More information:
Expand Down Expand Up @@ -485,6 +505,7 @@ impl Math {
make_builtin_fn(Self::atan2, "atan2", &math, 2);
make_builtin_fn(Self::cbrt, "cbrt", &math, 1);
make_builtin_fn(Self::ceil, "ceil", &math, 1);
make_builtin_fn(Self::clz32, "clz32", &math, 1);
make_builtin_fn(Self::cos, "cos", &math, 1);
make_builtin_fn(Self::cosh, "cosh", &math, 1);
make_builtin_fn(Self::exp, "exp", &math, 1);
Expand Down
30 changes: 30 additions & 0 deletions boa/src/builtins/math/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,36 @@ fn ceil() {
assert_eq!(c.to_number(), -7_f64);
}

#[test]
fn clz32() {
let realm = Realm::create();
let mut engine = Interpreter::new(realm);
let init = r#"
var a = Math.clz32();
var b = Math.clz32({});
var c = Math.clz32(1);
var d = Math.clz32("1");
var e = Math.clz32(4);
var f = Math.clz32(Infinity);
"#;

eprintln!("{}", forward(&mut engine, init));

let a = forward_val(&mut engine, "a").unwrap();
let b = forward_val(&mut engine, "b").unwrap();
let c = forward_val(&mut engine, "c").unwrap();
let d = forward_val(&mut engine, "d").unwrap();
let e = forward_val(&mut engine, "e").unwrap();
let f = forward_val(&mut engine, "f").unwrap();

assert_eq!(a.to_number(), 32_f64);
assert_eq!(b.to_number(), 32_f64);
assert_eq!(c.to_number(), 31_f64);
assert_eq!(d.to_number(), 31_f64);
assert_eq!(e.to_number(), 29_f64);
assert_eq!(f.to_number(), 32_f64);
}

#[test]
fn cos() {
let realm = Realm::create();
Expand Down

0 comments on commit 4bc31ef

Please sign in to comment.