Skip to main content

rust_css_parser/utils/
number.rs

1//! javascript number formatting (`Number.prototype.toString()`), used wherever the typescript code converts a number
2//! to a string (`"" + n`, template literals).
3
4/// `String(n)`: shortest round-trip representation, javascript exponent rules
5pub fn js_number_to_string(n: f64) -> String {
6    if n.is_nan() {
7        return "NaN".into();
8    }
9    if n.is_infinite() {
10        return if n > 0.0 { "Infinity".into() } else { "-Infinity".into() };
11    }
12    if n == 0.0 {
13        return "0".into();
14    }
15    // shortest round trip digits and exponent from rust's `{:e}` formatting
16    let formatted = format!("{:e}", n);
17    let (mantissa, exponent) = formatted.split_once('e').unwrap();
18    let exponent: i32 = exponent.parse().unwrap();
19    let negative = mantissa.starts_with('-');
20    let digits: String = mantissa.chars().filter(|c| c.is_ascii_digit()).collect();
21    let k = digits.len() as i32;
22    // decimal point position: n = 0.digits * 10^(exponent + 1)
23    let point = exponent + 1;
24    let mut result = String::new();
25    if negative {
26        result.push('-');
27    }
28    if k <= point && point <= 21 {
29        result.push_str(&digits);
30        for _ in 0..(point - k) {
31            result.push('0');
32        }
33    } else if 0 < point && point <= 21 {
34        result.push_str(&digits[..point as usize]);
35        result.push('.');
36        result.push_str(&digits[point as usize..]);
37    } else if -6 < point && point <= 0 {
38        result.push_str("0.");
39        for _ in 0..(-point) {
40            result.push('0');
41        }
42        result.push_str(&digits);
43    } else {
44        let e = point - 1;
45        result.push_str(&digits[..1]);
46        if k > 1 {
47            result.push('.');
48            result.push_str(&digits[1..]);
49        }
50        result.push('e');
51        result.push(if e >= 0 { '+' } else { '-' });
52        result.push_str(&e.abs().to_string());
53    }
54    result
55}
56
57/// `Number(str)` / unary `+str` for css numeric strings
58pub fn js_parse_number(s: &str) -> f64 {
59    let t = s.trim();
60    if t.is_empty() {
61        return 0.0;
62    }
63    match t {
64        "Infinity" | "+Infinity" => return f64::INFINITY,
65        "-Infinity" => return f64::NEG_INFINITY,
66        _ => {}
67    }
68    if t.len() > 2 && (t.starts_with("0x") || t.starts_with("0X")) {
69        return i64::from_str_radix(&t[2..], 16).map_or(f64::NAN, |v| v as f64);
70    }
71    if t.chars().all(|c| c.is_ascii_digit() || matches!(c, '+' | '-' | '.' | 'e' | 'E')) {
72        // rust rejects "1." and ".5"? it accepts both; it rejects "+.5"? accepted as well
73        t.parse::<f64>().unwrap_or(f64::NAN)
74    } else {
75        f64::NAN
76    }
77}
78
79/// `n.toFixed(digits)`
80pub fn to_fixed(n: f64, digits: usize) -> String {
81    if !n.is_finite() {
82        return js_number_to_string(n);
83    }
84    // javascript picks the larger n on exact ties (half away from zero for the magnitude), rust rounds half to even
85    let wide = format!("{:.*}", digits + 30, n.abs());
86    let cut = wide.len() - 30;
87    let tail = &wide[cut..];
88    let magnitude = if tail.starts_with('5') && tail[1..].bytes().all(|b| b == b'0') {
89        let bumped = n.abs() + 0.5 * 10f64.powi(-(digits as i32));
90        let s = format!("{:.*}", digits + 30, bumped);
91        s[..s.len() - 30].trim_end_matches('.').to_string()
92    } else {
93        format!("{:.*}", digits, n.abs())
94    };
95    // `(-0.0001).toFixed(2)` is "-0.00" in javascript
96    if n < 0.0 {
97        format!("-{}", magnitude)
98    } else {
99        magnitude
100    }
101}
102
103/// `Math.round()`: half up (towards +inf), `-0` for the values in [-0.5, 0)
104pub fn js_round(n: f64) -> f64 {
105    if !n.is_finite() {
106        return n;
107    }
108    let floor = n.floor();
109    let r = if n - floor >= 0.5 { floor + 1.0 } else { floor };
110    if r == 0.0 && n < 0.0 {
111        -0.0
112    } else {
113        r
114    }
115}
116
117/// `String(n)` for an integer or a float
118pub fn num_to_str(n: f64) -> String {
119    js_number_to_string(n)
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn number_to_string() {
128        for (n, s) in [(1.0, "1"), (0.1, "0.1"), (1e21, "1e+21"), (1e-7, "1e-7"), (123.456, "123.456"), (-0.5, "-0.5"), (1e20, "100000000000000000000"), (0.000001, "0.000001")] {
129            assert_eq!(js_number_to_string(n), s);
130        }
131    }
132
133    #[test]
134    fn fixed() {
135        assert_eq!(to_fixed(2.5, 0), "3");
136        assert_eq!(to_fixed(1.005, 2), "1.00");
137        assert_eq!(to_fixed(0.125, 2), "0.13");
138        assert_eq!(to_fixed(-1.5, 0), "-2");
139        assert_eq!(to_fixed(1.23456, 3), "1.235");
140    }
141}
142
143/// `+value.toPrecision(precision)`: the exact decimal value rounded half up to `precision` significant digits, parsed
144pub fn js_to_precision(value: f64, precision: usize) -> f64 {
145    if !value.is_finite() || value == 0.0 {
146        return value;
147    }
148    // exact decimal digits: the digit after the last kept digit decides (half up on the exact value)
149    let s = format!("{:.*e}", precision + 40, value.abs());
150    let (mantissa, exponent) = s.split_once('e').unwrap();
151    let mut exponent: i32 = exponent.parse().unwrap();
152    let digits: Vec<u8> = mantissa.bytes().filter(|b| b.is_ascii_digit()).map(|b| b - b'0').collect();
153    let mut kept: Vec<u8> = digits[..precision].to_vec();
154    if digits[precision] >= 5 {
155        let mut i = precision;
156        loop {
157            if i == 0 {
158                kept.insert(0, 1);
159                kept.pop();
160                exponent += 1;
161                break;
162            }
163            i -= 1;
164            if kept[i] == 9 {
165                kept[i] = 0;
166            } else {
167                kept[i] += 1;
168                break;
169            }
170        }
171    }
172    let text: String = kept.iter().map(|d| (b'0' + d) as char).collect();
173    let parsed: f64 = format!("{}.{}e{}", &text[..1], &text[1..], exponent).parse().unwrap();
174    if value < 0.0 {
175        -parsed
176    } else {
177        parsed
178    }
179}