Skip to content

Commit

Permalink
Merge 4c61ba8 into 6e3f93e
Browse files Browse the repository at this point in the history
  • Loading branch information
HalidOdat authored Mar 1, 2022
2 parents 6e3f93e + 4c61ba8 commit fafa942
Showing 1 changed file with 46 additions and 17 deletions.
63 changes: 46 additions & 17 deletions boa_engine/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,26 +472,55 @@ impl JsString {
pub(crate) fn string_to_number(&self) -> f64 {
let string = self.trim_matches(is_trimmable_whitespace);

// TODO: write our own lexer to match syntax StrDecimalLiteral
match string {
"" => 0.0,
"Infinity" | "+Infinity" => f64::INFINITY,
"-Infinity" => f64::NEG_INFINITY,
_ if matches!(
string
.chars()
.take(4)
.collect::<String>()
.to_ascii_lowercase()
.as_str(),
"inf" | "+inf" | "-inf" | "nan" | "+nan" | "-nan"
) =>
{
// Prevent fast_float from parsing "inf", "+inf" as Infinity and "-inf" as -Infinity
f64::NAN
"" => return 0.0,
"inf" | "+inf" | "-inf" | "nan" | "+nan" | "-nan" => return f64::NAN,
"Infinity" | "+Infinity" => return f64::INFINITY,
"-Infinity" => return f64::NEG_INFINITY,
_ => {}
}

let mut s = string.bytes().peekable();

let sign = match s.peek() {
Some(b'+') => Some(1.0),
Some(b'-') => Some(-1.0),
Some(_) => None,
None => return f64::NAN,
};

// If it has a sign (+ or -) then it must be a float.
if sign.is_some() {
return fast_float::parse(string).unwrap_or(f64::NAN);
}

let base = match (s.next(), s.next().as_ref().map(u8::to_ascii_lowercase)) {
(Some(b'0'), Some(b'b')) => Some(2),
(Some(b'0'), Some(b'o')) => Some(8),
(Some(b'0'), Some(b'x')) => Some(16),
_ => None,
};

// Parse number that begin with `0b`, `0o` and `0x`.
if let Some(base) = base {
// Fast path
if let Ok(value) = u32::from_str_radix(&string[2..], base) {
return f64::from(value);
}
_ => fast_float::parse(string).unwrap_or(f64::NAN),

// Slow path
let mut value = 0.0;
for c in s {
if let Some(digit) = char::from(c).to_digit(base) {
value = value * f64::from(base) + f64::from(digit);
} else {
return f64::NAN;
}
}
return value;
}

fast_float::parse(string).unwrap_or(f64::NAN)
}
}

Expand Down

0 comments on commit fafa942

Please sign in to comment.