Skip to content

Commit a7689fb

Browse files
author
Max Pollard
committed
fix(string): filter non-finite results after parsing instead of matching the sign
Keeps the overflow case: a decimal literal too large for f64 is a valid StringNumericLiteral whose value rounds to an infinity, so only an infinite result with no digits is rejected.
1 parent ac04a71 commit a7689fb

2 files changed

Lines changed: 14 additions & 10 deletions

File tree

‎core/string/src/str.rs‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -331,15 +331,6 @@ impl<'a> JsStr<'a> {
331331
(Some(b'0'), Some(b'b' | b'B')) => Some(2),
332332
(Some(b'0'), Some(b'o' | b'O')) => Some(8),
333333
(Some(b'0'), Some(b'x' | b'X')) => Some(16),
334-
// Make sure that no further variants of "infinity" are parsed.
335-
//
336-
// `Infinity`, `+Infinity` and `-Infinity` are the only spellings accepted by
337-
// `StrUnsignedDecimalLiteral`, and all three already returned above. Anything else
338-
// starting with `i` or `I`, with or without a sign, is not a `StringNumericLiteral`,
339-
// but `fast_float2` would still parse it as an infinity.
340-
(Some(b'i' | b'I'), _) | (Some(b'+' | b'-'), Some(b'i' | b'I')) => {
341-
return f64::NAN;
342-
}
343334
_ => None,
344335
};
345336

@@ -369,7 +360,14 @@ impl<'a> JsStr<'a> {
369360
return value;
370361
}
371362

372-
fast_float2::parse(string).unwrap_or(f64::NAN)
363+
match fast_float2::parse::<f64, &str>(string) {
364+
// `Infinity`, `+Infinity` and `-Infinity` already returned above, so any other
365+
// spelling `fast_float2` reads as infinite (`inf`, `+infinity`, ...) is not a
366+
// `StringNumericLiteral`. A decimal literal that overflows does have digits, and
367+
// its `StringNumericValue` is infinite, so it must be kept.
368+
Ok(f) if f.is_finite() || string.bytes().any(|b| b.is_ascii_digit()) => f,
369+
Ok(_) | Err(_) => f64::NAN,
370+
}
373371
}
374372

375373
/// Gets an iterator of all the Unicode codepoints of a [`JsStr`].

‎core/string/src/tests.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,4 +624,10 @@ fn to_number() {
624624
);
625625
assert!(JsString::from(" -inf ").to_number().is_nan());
626626
assert!(JsString::from(" 0x+1 ").to_number().is_nan());
627+
628+
// A decimal literal too large for `f64` is still a `StringNumericLiteral`; its
629+
// `StringNumericValue` rounds to an infinity and must not be rejected.
630+
assert_eq!(JsString::from("1e400").to_number(), f64::INFINITY);
631+
assert_eq!(JsString::from("-1e400").to_number(), f64::NEG_INFINITY);
632+
assert_eq!(JsString::from("1e999").to_number(), f64::INFINITY);
627633
}

0 commit comments

Comments
 (0)