Skip to content

Commit

Permalink
Use ryu-js crate for number formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Tropid committed Jun 21, 2020
1 parent 1ffeb5c commit 064c736
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 10 deletions.
6 changes: 6 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions boa/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ rustc-hash = "1.1.0"
num-bigint = { version = "0.3.0", features = ["serde"] }
num-integer = "0.1.43"
bitflags = "1.2.1"
ryu-js = { git = "https://github.com/Tropid/ryu-js" }

# Optional Dependencies
serde = { version = "1.0.111", features = ["derive"], optional = true }
Expand Down
16 changes: 6 additions & 10 deletions boa/src/builtins/value/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,19 +186,15 @@ impl Display for ValueData {
None => write!(f, "Symbol()"),
},
Self::String(ref v) => write!(f, "{}", v),
Self::Rational(v) => write!(
f,
"{}",
match v {
_ if v.is_nan() => "NaN".to_string(),
_ if v.is_infinite() && v.is_sign_negative() => "-Infinity".to_string(),
_ if v.is_infinite() => "Infinity".to_string(),
_ => v.to_string(),
}
),
Self::Rational(v) => format_rational(*v, f),
Self::Object(_) => write!(f, "{}", log_string_from(self, true)),
Self::Integer(v) => write!(f, "{}", v),
Self::BigInt(ref num) => write!(f, "{}n", num),
}
}
}

fn format_rational(v: f64, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut buffer = ryu_js::Buffer::new();
write!(f, "{}", buffer.format(v))
}
25 changes: 25 additions & 0 deletions boa/src/builtins/value/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,28 @@ fn get_types() {
Type::Symbol
);
}

#[test]
fn to_string() {
let f64_to_str = |f| { ValueData::Rational(f).to_string() };

assert_eq!(f64_to_str(f64::NAN), "NaN");
assert_eq!(f64_to_str(0.0), "0");
assert_eq!(f64_to_str(f64::INFINITY), "Infinity");
assert_eq!(f64_to_str(f64::NEG_INFINITY), "-Infinity");
assert_eq!(f64_to_str(90.12), "90.12");
assert_eq!(f64_to_str(111111111111111111111.0), "111111111111111110000");
assert_eq!(f64_to_str(1111111111111111111111.0), "1.1111111111111111e+21");

assert_eq!(f64_to_str(-90.12), "-90.12");

assert_eq!(f64_to_str(-111111111111111111111.0), "-111111111111111110000");
assert_eq!(f64_to_str(-1111111111111111111111.0), "-1.1111111111111111e+21");

assert_eq!(f64_to_str(0.0000001), "1e-7");
assert_eq!(f64_to_str(0.000001), "0.000001");
assert_eq!(f64_to_str(0.0000002), "2e-7");
assert_eq!(f64_to_str(-0.0000001), "-1e-7");

assert_eq!(f64_to_str(3e50), "3e+50");
}

0 comments on commit 064c736

Please sign in to comment.