Skip to main content

zero_client/json/
number.rs

1//! JS number semantics the client has to reproduce exactly:
2//! `Number.prototype.toString` (also what `JSON.stringify` writes) and
3//! `Number(string)`.
4
5/// `String(n)` in JS, i.e. ECMAScript `Number::toString(n, 10)`.
6///
7/// Uses the shortest round-tripping digits (which Rust's `{:e}` also
8/// produces) laid out with the JS rules: plain notation for decimal
9/// exponents in `-6..21`, exponential otherwise.
10pub fn format(value: f64) -> String {
11    if value.is_nan() {
12        return "NaN".into();
13    }
14    if value == 0.0 {
15        return "0".into();
16    }
17    if value.is_infinite() {
18        return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
19    }
20    if value < 0.0 {
21        return format!("-{}", format(-value));
22    }
23    // Integers below 2^53 print exactly; skip the digit extraction.
24    if value < 9_007_199_254_740_992.0 && value == value.trunc() {
25        return (value as i64).to_string();
26    }
27    let (digits, n) = shortest_digits(value);
28    let k = digits.len() as i32;
29    if k <= n && n <= 21 {
30        return digits + &"0".repeat((n - k) as usize);
31    }
32    if 0 < n && n <= 21 {
33        let (int, frac) = digits.split_at(n as usize);
34        return format!("{int}.{frac}");
35    }
36    if -6 < n && n <= 0 {
37        return format!("0.{}{digits}", "0".repeat(-n as usize));
38    }
39    let e = n - 1;
40    let sign = if e >= 0 { '+' } else { '-' };
41    if k == 1 {
42        format!("{digits}e{sign}{}", e.abs())
43    } else {
44        format!("{}.{}e{sign}{}", &digits[..1], &digits[1..], e.abs())
45    }
46}
47
48/// The shortest digit string `s` and exponent `n` with
49/// `value == 0.s × 10^n`, for a positive finite `value`.
50fn shortest_digits(value: f64) -> (String, i32) {
51    let text = format!("{value:e}"); // e.g. "1.2345e20", "1e-7"
52    let (mantissa, exponent) = text.split_once('e').expect("exponent");
53    let exponent: i32 = exponent.parse().expect("exponent");
54    let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
55    let digits = digits.trim_end_matches('0');
56    let digits = if digits.is_empty() { "0" } else { digits };
57    (digits.to_owned(), exponent + 1)
58}
59
60/// `Number(string)` in JS (ECMAScript `StringToNumber`): trims JS
61/// whitespace, maps the empty string to 0, and accepts decimal, `Infinity`,
62/// and `0x`/`0o`/`0b` literals. Anything else is `NaN`.
63pub fn parse(string: &str) -> f64 {
64    let s = string.trim_matches(is_js_whitespace);
65    if s.is_empty() {
66        return 0.0;
67    }
68    match s {
69        "Infinity" | "+Infinity" => return f64::INFINITY,
70        "-Infinity" => return f64::NEG_INFINITY,
71        _ => {}
72    }
73    let prefix = s.get(..2).map(str::to_ascii_lowercase);
74    let radix = match prefix.as_deref() {
75        Some("0x") => 16,
76        Some("0o") => 8,
77        Some("0b") => 2,
78        _ => 0,
79    };
80    if radix != 0 {
81        let body = &s[2..];
82        if body.is_empty() {
83            return f64::NAN;
84        }
85        let mut result = 0.0;
86        for c in body.chars() {
87            match c.to_digit(radix) {
88                Some(d) => result = result * f64::from(radix) + f64::from(d),
89                None => return f64::NAN,
90            }
91        }
92        return result;
93    }
94    if !is_decimal_literal(s) {
95        return f64::NAN;
96    }
97    s.parse().unwrap_or(f64::NAN)
98}
99
100fn is_decimal_literal(s: &str) -> bool {
101    let mut b = s.as_bytes();
102    let digits = |b: &mut &[u8]| {
103        let n = b.iter().take_while(|c| c.is_ascii_digit()).count();
104        *b = &b[n..];
105        n
106    };
107    if let [b'+' | b'-', rest @ ..] = b {
108        b = rest;
109    }
110    let int = digits(&mut b);
111    let mut frac = 0;
112    if let [b'.', rest @ ..] = b {
113        b = rest;
114        frac = digits(&mut b);
115    }
116    if int == 0 && frac == 0 {
117        return false;
118    }
119    if let [b'e' | b'E', rest @ ..] = b {
120        b = rest;
121        if let [b'+' | b'-', rest @ ..] = b {
122            b = rest;
123        }
124        if digits(&mut b) == 0 {
125            return false;
126        }
127    }
128    b.is_empty()
129}
130
131/// ECMAScript `WhiteSpace` plus `LineTerminator`.
132pub fn is_js_whitespace(c: char) -> bool {
133    matches!(
134        c,
135        '\u{9}'..='\u{d}'
136            | ' '
137            | '\u{a0}'
138            | '\u{1680}'
139            | '\u{2000}'..='\u{200a}'
140            | '\u{2028}'
141            | '\u{2029}'
142            | '\u{202f}'
143            | '\u{205f}'
144            | '\u{3000}'
145            | '\u{feff}'
146    )
147}
148
149/// `(n | 0) === n` in JS: whether `n` is exactly an int32. `-0` counts,
150/// because `-0 === 0`.
151pub fn is_int32(n: f64) -> bool {
152    (-2_147_483_648.0..=2_147_483_647.0).contains(&n) && n == n.trunc()
153}
154
155/// `Number.isSafeInteger(n)` in JS.
156pub fn is_safe_integer(n: f64) -> bool {
157    n.abs() <= 9_007_199_254_740_991.0 && n == n.trunc()
158}
159
160#[cfg(test)]
161mod tests {
162    #[test]
163    fn formats_like_js() {
164        for (n, s) in [
165            (1e21, "1e+21"),
166            (1e20, "100000000000000000000"),
167            (0.000001, "0.000001"),
168            (1e-7, "1e-7"),
169            (1.5e-7, "1.5e-7"),
170            (123.456, "123.456"),
171            (-0.0, "0"),
172            (2f64.powi(53), "9007199254740992"),
173        ] {
174            assert_eq!(super::format(n), s);
175        }
176    }
177}