perf: parse_js_number 去 lowercase 分配 + int32 位运算直取

This commit is contained in:
2026-08-13 14:48:19 +08:00
parent 033ef9abea
commit d2c21c3a4a
2 changed files with 17 additions and 10 deletions
+11 -10
View File
@@ -245,15 +245,16 @@ fn parse_js_number(s: &str) -> f64 {
if t.is_empty() { if t.is_empty() {
return 0.0; return 0.0;
} }
let lower = t.to_ascii_lowercase(); let b = t.as_bytes();
if let Some(digits) = lower.strip_prefix("0x") { // 前缀探测按字节直接比较(ASCII 大小写不敏感),避免每次转换分配 lowercase。
return parse_radix_int(digits, 16); if b.len() >= 2 && b[0] == b'0' && (b[1] == b'x' || b[1] == b'X') {
return parse_radix_int(&t[2..], 16);
} }
if let Some(digits) = lower.strip_prefix("0o") { if b.len() >= 2 && b[0] == b'0' && (b[1] == b'o' || b[1] == b'O') {
return parse_radix_int(digits, 8); return parse_radix_int(&t[2..], 8);
} }
if let Some(digits) = lower.strip_prefix("0b") { if b.len() >= 2 && b[0] == b'0' && (b[1] == b'b' || b[1] == b'B') {
return parse_radix_int(digits, 2); return parse_radix_int(&t[2..], 2);
} }
if t == "Infinity" || t == "+Infinity" { if t == "Infinity" || t == "+Infinity" {
return f64::INFINITY; return f64::INFINITY;
@@ -263,9 +264,9 @@ fn parse_js_number(s: &str) -> f64 {
} }
// 十进制语法仅允许数字、符号、小数点与指数 e;含其它字符的令牌(如 // 十进制语法仅允许数字、符号、小数点与指数 e;含其它字符的令牌(如
// inf/nan 变体)不是合法 StringNumericLiteral,一律 NaN。 // inf/nan 变体)不是合法 StringNumericLiteral,一律 NaN。
if !t if !b
.chars() .iter()
.all(|c| c.is_ascii_digit() || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E') .all(|&c| c.is_ascii_digit() || c == b'+' || c == b'-' || c == b'.' || c == b'e' || c == b'E')
{ {
return f64::NAN; return f64::NAN;
} }
+6
View File
@@ -505,6 +505,9 @@ impl Vm {
} }
pub(crate) fn coerce_int32_bounded(&mut self, value: JsValue) -> Result<i32, String> { pub(crate) fn coerce_int32_bounded(&mut self, value: JsValue) -> Result<i32, String> {
if value.is_int() {
return Ok(value.as_int());
}
let n = self.coerce_number_bounded(value)?; let n = self.coerce_number_bounded(value)?;
if n == 0.0 || !n.is_finite() { if n == 0.0 || !n.is_finite() {
return Ok(0); return Ok(0);
@@ -518,6 +521,9 @@ impl Vm {
} }
pub(crate) fn coerce_uint32_bounded(&mut self, value: JsValue) -> Result<u32, String> { pub(crate) fn coerce_uint32_bounded(&mut self, value: JsValue) -> Result<u32, String> {
if value.is_int() {
return Ok(value.as_int() as u32);
}
let n = self.coerce_number_bounded(value)?; let n = self.coerce_number_bounded(value)?;
if n == 0.0 || !n.is_finite() { if n == 0.0 || !n.is_finite() {
return Ok(0); return Ok(0);