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    to_fixed_short(n, digits).unwrap_or_else(|| to_fixed_exact(n, digits))
82}
83
84/// powers of ten represented exactly by a f64
85const POWERS_OF_TEN: [f64; 16] = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15];
86
87/// `n.toFixed(digits)` without the exact decimal expansion of `n`: `|n| * 10^digits` is rounded to the nearest integer
88/// when it is far enough from a tie for the error of the multiplication not to change the rounding. `None` for the
89/// other numbers: large numbers, many digits, ties
90fn to_fixed_short(n: f64, digits: usize) -> Option<String> {
91    if !n.is_finite() || digits >= POWERS_OF_TEN.len() {
92        return None;
93    }
94    let scaled = n.abs() * POWERS_OF_TEN[digits];
95    // the integers are exact below 2^53. the error of the multiplication is less than 2^-52 of the result
96    if scaled >= 4_503_599_627_370_496.0 {
97        return None;
98    }
99    let floor = scaled.floor();
100    let fraction = scaled - floor;
101    if (fraction - 0.5).abs() <= scaled * 1e-15 + 1e-15 {
102        return None;
103    }
104    let integer = if fraction > 0.5 { floor as u64 + 1 } else { floor as u64 };
105    let mut text = integer.to_string();
106    if digits > 0 {
107        if text.len() <= digits {
108            text.insert_str(0, &"0".repeat(digits + 1 - text.len()));
109        }
110        text.insert(text.len() - digits, '.');
111    }
112    // `(-0.0001).toFixed(2)` is "-0.00" in javascript
113    if n < 0.0 {
114        text.insert(0, '-');
115    }
116    Some(text)
117}
118
119/// see [`to_fixed`]: the exact decimal expansion of the number is rounded
120fn to_fixed_exact(n: f64, digits: usize) -> String {
121    if !n.is_finite() {
122        return js_number_to_string(n);
123    }
124    // javascript picks the larger n on exact ties (half away from zero for the magnitude), rust rounds half to even
125    let wide = format!("{:.*}", digits + 30, n.abs());
126    let cut = wide.len() - 30;
127    let tail = &wide[cut..];
128    let magnitude = if tail.starts_with('5') && tail[1..].bytes().all(|b| b == b'0') {
129        let bumped = n.abs() + 0.5 * 10f64.powi(-(digits as i32));
130        let s = format!("{:.*}", digits + 30, bumped);
131        s[..s.len() - 30].trim_end_matches('.').to_string()
132    } else {
133        format!("{:.*}", digits, n.abs())
134    };
135    // `(-0.0001).toFixed(2)` is "-0.00" in javascript
136    if n < 0.0 {
137        format!("-{}", magnitude)
138    } else {
139        magnitude
140    }
141}
142
143/// `Math.round()`: half up (towards +inf), `-0` for the values in [-0.5, 0)
144pub fn js_round(n: f64) -> f64 {
145    if !n.is_finite() {
146        return n;
147    }
148    let floor = n.floor();
149    let r = if n - floor >= 0.5 { floor + 1.0 } else { floor };
150    if r == 0.0 && n < 0.0 {
151        -0.0
152    } else {
153        r
154    }
155}
156
157/// `String(n)` for an integer or a float
158pub fn num_to_str(n: f64) -> String {
159    js_number_to_string(n)
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    /// the numbers formatted by `to_fixed_short` have the text of `to_fixed_exact`
167    #[test]
168    fn short_to_fixed() {
169        let mut values: Vec<f64> = vec![0.0, -0.0, 0.5, 1.5, 2.5, -2.5, 0.125, 1.005, 1.045, -0.0001, 123.456, 1e10, 359.99999, 0.1 + 0.2];
170        let mut seed: u64 = 0x9e3779b97f4a7c15;
171        for _ in 0..50000 {
172            seed ^= seed << 13;
173            seed ^= seed >> 7;
174            seed ^= seed << 17;
175            let magnitude = 10f64.powi((seed % 12) as i32 - 5);
176            let value = ((seed >> 12) as f64 / (1u64 << 52) as f64 - 0.5) * magnitude;
177            values.push(value);
178            // decimal values: ties and near ties
179            values.push(((seed >> 20) % 100000) as f64 / 1000.0);
180        }
181        for value in values {
182            for digits in 0..8 {
183                if let Some(short) = to_fixed_short(value, digits) {
184                    assert_eq!(short, to_fixed_exact(value, digits), "{}.toFixed({})", value, digits);
185                }
186            }
187        }
188    }
189
190    #[test]
191    fn number_to_string() {
192        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")] {
193            assert_eq!(js_number_to_string(n), s);
194        }
195    }
196
197    #[test]
198    fn fixed() {
199        assert_eq!(to_fixed(2.5, 0), "3");
200        assert_eq!(to_fixed(1.005, 2), "1.00");
201        assert_eq!(to_fixed(0.125, 2), "0.13");
202        assert_eq!(to_fixed(-1.5, 0), "-2");
203        assert_eq!(to_fixed(1.23456, 3), "1.235");
204    }
205}
206
207/// `+value.toPrecision(precision)`: the exact decimal value rounded half up to `precision` significant digits, parsed
208pub fn js_to_precision(value: f64, precision: usize) -> f64 {
209    if !value.is_finite() || value == 0.0 {
210        return value;
211    }
212    // exact decimal digits: the digit after the last kept digit decides (half up on the exact value)
213    let s = format!("{:.*e}", precision + 40, value.abs());
214    let (mantissa, exponent) = s.split_once('e').unwrap();
215    let mut exponent: i32 = exponent.parse().unwrap();
216    let digits: Vec<u8> = mantissa.bytes().filter(|b| b.is_ascii_digit()).map(|b| b - b'0').collect();
217    let mut kept: Vec<u8> = digits[..precision].to_vec();
218    if digits[precision] >= 5 {
219        let mut i = precision;
220        loop {
221            if i == 0 {
222                kept.insert(0, 1);
223                kept.pop();
224                exponent += 1;
225                break;
226            }
227            i -= 1;
228            if kept[i] == 9 {
229                kept[i] = 0;
230            } else {
231                kept[i] += 1;
232                break;
233            }
234        }
235    }
236    let text: String = kept.iter().map(|d| (b'0' + d) as char).collect();
237    let parsed: f64 = format!("{}.{}e{}", &text[..1], &text[1..], exponent).parse().unwrap();
238    if value < 0.0 {
239        -parsed
240    } else {
241        parsed
242    }
243}