Skip to main content

JS_RS

Constant JS_RS 

Source
pub const JS_RS: &str = "//! JS values that JSON cannot express, and the JSON transport of the bindings.\n\n#![forbid(unsafe_code)]\n\n/// Reads a structured argument sent by `index.cjs`.\npub fn from_json<T: serde::de::DeserializeOwned>(text: &str) -> Result<T, String> {\n    let mut de = serde_json::Deserializer::from_str(text);\n    de.disable_recursion_limit();\n    let value = <T as serde::Deserialize>::deserialize(&mut de).map_err(|e| format!(\"TypeError: {e}\"))?;\n    de.end().map_err(|e| format!(\"TypeError: {e}\"))?;\n    Ok(value)\n}\n\n/// Writes a structured result for `index.cjs`.\npub fn to_json<T: serde::Serialize>(value: &T) -> Result<String, String> {\n    serde_json::to_string(value).map_err(|e| e.to_string())\n}\n\n/// JS `undefined` inside a structured value: `{ a: undefined }` is not `{ a: null }`.\npub fn undefined() -> serde_json::Value {\n    serde_json::json!({ \"$undefined\": true })\n}\n\n/// Whether a structured value received from JS was `undefined`.\npub fn is_undefined(value: &serde_json::Value) -> bool {\n    value.as_object().is_some_and(|o| {\n        o.len() == 1 && o.get(\"$undefined\") == Some(&serde_json::Value::Bool(true))\n    })\n}\n\n/// A JS string from UTF-16 code units: a plain string when well-formed, else a marker that\n/// `index.cjs` turns into the exact JS string, lone surrogates included.\npub fn utf16_string(units: &[u16]) -> serde_json::Value {\n    match String::from_utf16(units) {\n        Ok(s) => serde_json::Value::String(s),\n        Err(_) => serde_json::json!({ \"$utf16\": units }),\n    }\n}\n\n/// The UTF-16 code units of a string received from JS, plain or marked.\npub fn string_units(value: &serde_json::Value) -> Option<Vec<u16>> {\n    match value {\n        serde_json::Value::String(s) => Some(s.encode_utf16().collect()),\n        serde_json::Value::Object(o) if o.len() == 1 => o\n            .get(\"$utf16\")?\n            .as_array()?\n            .iter()\n            .map(|u| u.as_u64().and_then(|u| u16::try_from(u).ok()))\n            .collect(),\n        _ => None,\n    }\n}\n\n/// A JS number inside a structured value. JSON has no NaN, Infinity or -0: those cross as\n/// `{\"$num\": \"NaN\"}` and friends, which `index.cjs` turns back into numbers.\npub fn number(n: f64) -> serde_json::Value {\n    if n.is_nan() {\n        serde_json::json!({ \"$num\": \"NaN\" })\n    } else if n.is_infinite() {\n        serde_json::json!({ \"$num\": if n > 0.0 { \"Infinity\" } else { \"-Infinity\" } })\n    } else if n == 0.0 && n.is_sign_negative() {\n        serde_json::json!({ \"$num\": \"-0\" })\n    } else if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 {\n        serde_json::Value::from(n as i64)\n    } else {\n        serde_json::Value::from(n)\n    }\n}\n\n/// JS `Array.prototype.sort(compare)`, as V8 runs it.\n///\n/// With a consistent comparator any stable sort agrees with JS. With one that returns NaN or\n/// contradicts itself, the order depends on the algorithm: under 64 elements this reproduces\n/// V8\'s TimSort exactly (one run, then binary insertion); longer arrays use Rust\'s stable sort.\npub fn sort<T>(items: &mut [T], mut compare: impl FnMut(&T, &T) -> f64) {\n    let n = items.len();\n    if n < 2 {\n        return;\n    }\n    if n >= 64 {\n        items.sort_by(|a, b| compare(a, b).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));\n        return;\n    }\n    // CountAndMakeRun: the leading ascending run, or strictly descending run (reversed).\n    let mut run = 2;\n    let descending = compare(&items[1], &items[0]) < 0.0;\n    while run < n {\n        let order = compare(&items[run], &items[run - 1]);\n        if (descending && order >= 0.0) || (!descending && order < 0.0) {\n            break;\n        }\n        run += 1;\n    }\n    if descending {\n        items[..run].reverse();\n    }\n    // BinaryInsertionSort of the rest.\n    for start in run..n {\n        let (mut left, mut right) = (0, start);\n        while left < right {\n            let mid = left + ((right - left) >> 1);\n            if compare(&items[start], &items[mid]) < 0.0 {\n                right = mid;\n            } else {\n                left = mid + 1;\n            }\n        }\n        items[left..=start].rotate_right(1);\n    }\n}\n\n/// A number received from JS inside a structured value, plain or marked.\npub fn as_number(value: &serde_json::Value) -> Option<f64> {\n    match value {\n        serde_json::Value::Number(n) => n.as_f64(),\n        serde_json::Value::Object(o) if o.len() == 1 => match o.get(\"$num\")?.as_str()? {\n            \"NaN\" => Some(f64::NAN),\n            \"Infinity\" => Some(f64::INFINITY),\n            \"-Infinity\" => Some(f64::NEG_INFINITY),\n            \"-0\" => Some(-0.0),\n            _ => None,\n        },\n        _ => None,\n    }\n}\n/// JS `Number.prototype.toString()` (what `${n}` and `String(n)` print): `1e+21`, `5e-324`,\n/// `0` for `-0`, `NaN`, `Infinity`, and the shortest digits that read back as the same number\n/// (the closest of them on a tie, as V8 picks). The digits come from serde_json\'s printer, several\n/// times faster than `format!`.\n#[allow(dead_code)]\npub fn number_to_string(x: f64) -> String {\n    if x.is_nan() {\n        return \"NaN\".into();\n    }\n    if x.is_infinite() {\n        return if x > 0.0 { \"Infinity\" } else { \"-Infinity\" }.into();\n    }\n    if x == 0.0 {\n        return \"0\".into();\n    }\n    if x.fract() == 0.0 && x.abs() < 9007199254740992.0 {\n        return (x as i64).to_string();\n    }\n    let json = serde_json::to_string(&x).unwrap_or_default();\n    let (sign, json) = match json.strip_prefix(\'-\') {\n        Some(rest) => (\"-\", rest),\n        None => (\"\", json.as_str()),\n    };\n    let (mantissa, exponent) = match json.find([\'e\', \'E\']) {\n        Some(i) => (&json[..i], json[i + 1..].parse::<i64>().unwrap_or(0)),\n        None => (json, 0),\n    };\n    let (int, frac) = mantissa.split_once(\'.\').unwrap_or((mantissa, \"\"));\n    let all = format!(\"{int}{frac}\");\n    let lead = all.len() - all.trim_start_matches(\'0\').len();\n    let digits = all[lead..].trim_end_matches(\'0\');\n    let k = digits.len() as i64;\n    let n = int.len() as i64 - lead as i64 + exponent;\n    let mut out = String::with_capacity(digits.len() + 8);\n    out.push_str(sign);\n    if k <= n && n <= 21 {\n        out.push_str(digits);\n        out.extend(std::iter::repeat_n(\'0\', (n - k) as usize));\n    } else if 0 < n && n <= 21 {\n        out.push_str(&digits[..n as usize]);\n        out.push(\'.\');\n        out.push_str(&digits[n as usize..]);\n    } else if -6 < n && n <= 0 {\n        out.push_str(\"0.\");\n        out.extend(std::iter::repeat_n(\'0\', (-n) as usize));\n        out.push_str(digits);\n    } else {\n        let e = n - 1;\n        out.push_str(&digits[..1]);\n        if k > 1 {\n            out.push(\'.\');\n            out.push_str(&digits[1..]);\n        }\n        out.push(\'e\');\n        out.push(if e < 0 { \'-\' } else { \'+\' });\n        out.push_str(&e.abs().to_string());\n    }\n    out\n}\n\n/// JS `Math.round`: the nearest integer, halves toward positive infinity (`-2.5` gives `-2`,\n/// where Rust\'s `round` gives `-3`), and `-0` for negatives that round to zero.\n#[allow(dead_code)]\npub fn math_round(x: f64) -> f64 {\n    if !x.is_finite() || x == x.trunc() {\n        return x;\n    }\n    let floor = x.floor();\n    let r = if x - floor >= 0.5 { floor + 1.0 } else { floor };\n    if r == 0.0 && x < 0.0 { -0.0 } else { r }\n}\n\n#[cfg(test)]\nmod js_number_tests {\n    use super::*;\n\n    #[test]\n    fn prints_numbers_as_js_does() {\n        for (x, js) in [\n            (0.0, \"0\"),\n            (-0.0, \"0\"),\n            (1.0, \"1\"),\n            (-7.5, \"-7.5\"),\n            (0.1, \"0.1\"),\n            (0.30000000000000004, \"0.30000000000000004\"),\n            (1e21, \"1e+21\"),\n            (123456789012345680000.0, \"123456789012345680000\"),\n            (1e-7, \"1e-7\"),\n            (0.000001, \"0.000001\"),\n            (5e-324, \"5e-324\"),\n            (1.7976931348623157e308, \"1.7976931348623157e+308\"),\n            (2.5e-7, \"2.5e-7\"),\n            (9007199254740993.0, \"9007199254740992\"),\n            (-123456789.0, \"-123456789\"),\n            (1e300, \"1e+300\"),\n            (153596401214599.62, \"153596401214599.62\"),\n            (-25.728225708007812, \"-25.728225708007812\"),\n            (f64::NAN, \"NaN\"),\n            (f64::NEG_INFINITY, \"-Infinity\"),\n        ] {\n            assert_eq!(number_to_string(x), js, \"{x:?}\");\n        }\n    }\n\n    #[test]\n    fn rounds_as_math_round() {\n        for (x, js) in [\n            (2.5, 3.0),\n            (-2.5, -2.0),\n            (-2.6, -3.0),\n            (0.49999999999999994, 0.0),\n            (1.5, 2.0),\n            (-0.4, -0.0),\n            (4503599627370495.5, 4503599627370496.0),\n            (-7.0, -7.0),\n        ] {\n            let r = math_round(x);\n            assert_eq!(r.to_bits(), f64::to_bits(js), \"{x}: {r}\");\n        }\n    }\n}\n";