quickjs-compile 0.17.38

Bytecode compiler for the pure-Rust QuickJS port
Documentation
//! `Number::toString`, the one spelling of a number that both halves of the engine need.
//!
//! It lives here rather than in `quickjs-pure` because the **compiler** needs it too: a
//! numeric property key is turned into an atom at compile time (`get 0.0000001() {}` binds
//! the key `"1e-7"`), and that has to be the same string the runtime would produce. Two
//! copies of the spec's algorithm would be two things to keep in step, and the exponent
//! thresholds are exactly the part that is easy to get subtly wrong.
//!
//! `quickjs-pure` depends on this crate, so it re-exports [`number_to_string`] from here
//! instead of owning it — see `quickjs_pure::value`.

/// `ToString` applied to a number.
///
/// The thresholds are the ones the spec's `Number::toString` uses: exponential form below
/// `1e-6` and from `1e21` up, decimal form in between. Within the decimal range Rust's
/// shortest-round-trip formatter already agrees with JavaScript digit for digit — including
/// the notorious `0.30000000000000004` — so only the exponent spelling has to be
/// normalised.
pub fn number_to_string(value: f64) -> String {
    if value.is_nan() {
        return "NaN".to_string();
    }
    if value.is_infinite() {
        return if value > 0.0 {
            "Infinity".to_string()
        } else {
            "-Infinity".to_string()
        };
    }
    if value == 0.0 {
        // `ToString(-0)` is `"0"`; `print(-0)` is a different question, which is why
        // `quickjs-pure` keeps its own `number_to_string_for_print`.
        return "0".to_string();
    }
    let magnitude = value.abs();
    if magnitude >= 1e21 || magnitude < 1e-6 {
        return normalise_exponent(format!("{value:e}"));
    }
    format!("{value}")
}

/// Turn Rust's `1e-7` / `1e21` into JavaScript's `1e-7` / `1e+21`.
///
/// A negative exponent already has its sign; a positive one needs the `+` the spec
/// requires, and Rust leaves it out.
fn normalise_exponent(text: String) -> String {
    let Some((mantissa, exponent)) = text.split_once('e') else {
        return text;
    };
    if exponent.starts_with('-') {
        text
    } else {
        let digits = exponent.strip_prefix('+').unwrap_or(exponent);
        format!("{mantissa}e+{digits}")
    }
}

#[cfg(test)]
mod tests {
    use super::number_to_string;

    /// The thresholds themselves, and one value either side of each. These are the cases a
    /// hand-written formatter gets wrong, so they are the ones pinned down.
    #[test]
    fn the_exponent_thresholds_match_the_spec() {
        assert_eq!(number_to_string(0.000001), "0.000001");
        assert_eq!(number_to_string(0.0000001), "1e-7");
        assert_eq!(number_to_string(1e21), "1e+21");
        assert_eq!(number_to_string(1e20), "100000000000000000000");
    }

    #[test]
    fn negative_zero_stringifies_to_plain_zero() {
        assert_eq!(number_to_string(-0.0), "0");
        assert_eq!(number_to_string(0.0), "0");
    }

    #[test]
    fn the_awkward_decimal_keeps_every_digit() {
        assert_eq!(number_to_string(0.1 + 0.2), "0.30000000000000004");
    }

    #[test]
    fn the_non_finite_three_are_spelled_out() {
        assert_eq!(number_to_string(f64::NAN), "NaN");
        assert_eq!(number_to_string(f64::INFINITY), "Infinity");
        assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
    }
}