Cotton code
448 lines · 17.0 KB · RustRaw
//! JavaScript's own semantics, where the store's material depends on them.//!//! Three of the ported units hash or store a string that TypeScript produced//! with a JS built-in — `JSON.stringify` for every fingerprint's material and//! the `json` codec, `String(number)` for `decimalText`, `new Date(...)` and//! `toISOString()` for `timestamp` and `minuteBucket`. Getting those *nearly*//! right is worse than not porting them: a fingerprint that differs in one//! digit duplicates a person's whole message history on the next import.//!//! So the rules are implemented here, once, from the ECMAScript spec, and//! pinned against vectors computed by running the TypeScript.//!//! Known, deliberate divergence — a date-time string carrying NO zone//! (`2026-08-23T14:30:00`) is read as UTC here, where ECMAScript reads it in//! the RUNTIME's local zone. This crate may not read the clock or the//! machine's zone (spec R1), the host runs `TZ=UTC`, and `toUtcInstant` is the//! only caller that can produce one — it appends a `Z` before parsing, so the//! zone-less path is unreachable from it.use serde_json::Value;// ─────────────────────────────────────────────────────────────────────────────// Number → string, the way `String(n)` and `JSON.stringify(n)` do it.// ─────────────────────────────────────────────────────────────────────────────/// ECMA-262 `Number::toString(x, 10)`.////// Rust's own `Display` agrees for most values but never uses exponent form,/// so `1e21` and `1e-7` — the two thresholds ECMAScript switches at — would/// come out as digit soup. The digits themselves come from Rust's shortest/// round-trip formatter, which is the same guarantee ECMAScript states.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" } else { "-Infinity" }.to_string();    }    if value == 0.0 {        // Both zeros print "0" — `String(-0)` is "0" in JS.        return "0".to_string();    }    if value < 0.0 {        return format!("-{}", number_to_string(-value));    }    // `{:e}` gives the shortest round-trip digits as `d[.ddd]e<exp>`, i.e.    // value = <digits> × 10^(exp - (k - 1)). ECMAScript states the same digits    // as `s × 10^(n - k)`, so n = exp + 1.    let exp_form = format!("{value:e}");    // `LowerExp` for a finite f64 always emits `<digits>[.<digits>]e<int>`, so    // neither of these can fail — but a fallback rather than an `expect` keeps    // the library free of a panic path, and Rust's plain `Display` is the    // honest answer if the formatter ever changed shape.    let Some((mantissa, exponent)) = exp_form.split_once('e') else {        return format!("{value}");    };    let Ok(exponent) = exponent.parse::<i32>() else {        return format!("{value}");    };    let digits: String = mantissa.chars().filter(|c| c.is_ascii_digit()).collect();    let digits = digits.trim_end_matches('0');    let digits = if digits.is_empty() { "0" } else { digits };    let k = digits.len() as i32;    let n = exponent + 1;    if k <= n && n <= 21 {        let mut out = String::from(digits);        out.push_str(&"0".repeat((n - k) as usize));        out    } else if 0 < n && n <= 21 {        format!("{}.{}", &digits[..n as usize], &digits[n as usize..])    } else if -6 < n && n <= 0 {        format!("0.{}{}", "0".repeat((-n) as usize), digits)    } else {        let e = n - 1;        let sign = if e >= 0 { "+" } else { "-" };        if k == 1 {            format!("{digits}e{sign}{}", e.abs())        } else {            format!("{}.{}e{sign}{}", &digits[..1], &digits[1..], e.abs())        }    }}// ─────────────────────────────────────────────────────────────────────────────// JSON.stringify// ─────────────────────────────────────────────────────────────────────────────/// `JSON.stringify(value)` — no replacer, no indent.////// serde_json's own `to_string` differs in exactly one place that matters/// here: it renders an integral f64 as `1.0` where JS renders `1`. Object key/// order is insertion order on both sides (the workspace turns on serde_json's/// `preserve_order`), and the escaping rules already agree.pub fn json_stringify(value: &Value) -> String {    let mut out = String::new();    write_json(value, &mut out);    out}fn write_json(value: &Value, out: &mut String) {    match value {        Value::Null => out.push_str("null"),        Value::Bool(true) => out.push_str("true"),        Value::Bool(false) => out.push_str("false"),        Value::Number(n) => {            if let Some(i) = n.as_i64() {                out.push_str(&i.to_string());            } else if let Some(u) = n.as_u64() {                out.push_str(&u.to_string());            } else if let Some(f) = n.as_f64() {                // A non-finite number serializes as `null` in JSON.stringify.                if f.is_finite() {                    out.push_str(&number_to_string(f));                } else {                    out.push_str("null");                }            } else {                out.push_str("null");            }        }        Value::String(s) => write_json_string(s, out),        Value::Array(items) => {            out.push('[');            for (i, item) in items.iter().enumerate() {                if i > 0 {                    out.push(',');                }                // `undefined` and functions become `null` inside an array; a                // serde Value can hold neither, so every item serializes.                write_json(item, out);            }            out.push(']');        }        Value::Object(fields) => {            out.push('{');            for (i, (key, val)) in fields.iter().enumerate() {                if i > 0 {                    out.push(',');                }                write_json_string(key, out);                out.push(':');                write_json(val, out);            }            out.push('}');        }    }}/// `QuoteJSONString` — the two structural characters, the five named control/// escapes, `\u00XX` for the rest of C0, and every other code point verbatim.fn write_json_string(s: &str, out: &mut String) {    out.push('"');    for ch in s.chars() {        match ch {            '"' => out.push_str("\\\""),            '\\' => out.push_str("\\\\"),            '\u{8}' => out.push_str("\\b"),            '\u{c}' => out.push_str("\\f"),            '\n' => out.push_str("\\n"),            '\r' => out.push_str("\\r"),            '\t' => out.push_str("\\t"),            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),            c => out.push(c),        }    }    out.push('"');}// ─────────────────────────────────────────────────────────────────────────────// Dates// ─────────────────────────────────────────────────────────────────────────────/// ECMAScript's outer limit: a Date beyond this is `Invalid Date`.const MAX_TIME_VALUE: i64 = 8_640_000_000_000_000;/// `new Date(s).getTime()`, for the Date Time String Format.////// `None` where JS would give `NaN` — the caller decides whether that is a/// throw (`toUtcInstant`, `minuteBucket`) or something quieter. Only the ISO/// grammar is accepted: ECMAScript leaves every other spelling/// implementation-defined, and nothing the store stores uses one.pub fn parse_date_ms(input: &str) -> Option<i64> {    let bytes = input.as_bytes();    let mut i: usize;    // Year: `YYYY`, or the expanded `±YYYYYY`.    let (year, negative_zero_year) = if bytes.first() == Some(&b'+') || bytes.first() == Some(&b'-')    {        let sign = if bytes[0] == b'-' { -1i64 } else { 1i64 };        let digits = read_digits(bytes, 1, 6)?;        i = 7;        let value = sign * digits as i64;        // `-000000` is explicitly not a valid year in the grammar.        (value, sign == -1 && digits == 0)    } else {        let digits = read_digits(bytes, 0, 4)?;        i = 4;        (digits as i64, false)    };    if negative_zero_year {        return None;    }    let mut month = 1u32;    let mut day = 1u32;    if bytes.get(i) == Some(&b'-') {        month = read_digits(bytes, i + 1, 2)?;        i += 3;        if bytes.get(i) == Some(&b'-') {            day = read_digits(bytes, i + 1, 2)?;            i += 3;        }    }    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {        return None;    }    let mut hour = 0u32;    let mut minute = 0u32;    let mut second = 0u32;    let mut milli = 0u32;    let mut had_time = false;    if bytes.get(i) == Some(&b'T') || bytes.get(i) == Some(&b't') {        had_time = true;        hour = read_digits(bytes, i + 1, 2)?;        if bytes.get(i + 3) != Some(&b':') {            return None;        }        minute = read_digits(bytes, i + 4, 2)?;        i += 6;        if bytes.get(i) == Some(&b':') {            second = read_digits(bytes, i + 1, 2)?;            i += 3;            if bytes.get(i) == Some(&b'.') {                // The grammar says exactly three digits; every engine accepts                // one or more and TRUNCATES the rest, which is what the                // codecs suite pins (`.123456Z` → `.123Z`).                let start = i + 1;                let mut end = start;                while end < bytes.len() && bytes[end].is_ascii_digit() {                    end += 1;                }                if end == start {                    return None;                }                let mut frac: String = input[start..end].chars().take(3).collect();                while frac.len() < 3 {                    frac.push('0');                }                milli = frac.parse().ok()?;                i = end;            }        }        if hour > 24 || minute > 59 || second > 59 {            return None;        }        if hour == 24 && (minute != 0 || second != 0 || milli != 0) {            return None;        }    }    // The offset. Absent on a DATE-ONLY form means UTC; absent on a date-TIME    // form means local, which this crate reads as UTC (see the module note).    let mut offset_minutes = 0i64;    if i < bytes.len() {        match bytes[i] {            b'Z' | b'z' => {                i += 1;            }            b'+' | b'-' => {                let sign = if bytes[i] == b'-' { -1i64 } else { 1i64 };                let oh = read_digits(bytes, i + 1, 2)?;                let om = if bytes.get(i + 3) == Some(&b':') {                    let m = read_digits(bytes, i + 4, 2)?;                    i += 6;                    m                } else {                    let m = read_digits(bytes, i + 3, 2)?;                    i += 5;                    m                };                if oh > 23 || om > 59 {                    return None;                }                offset_minutes = sign * (oh as i64 * 60 + om as i64);            }            _ => return None,        }    }    if i != bytes.len() {        return None;    }    // An offset with no time of day is not in the grammar.    if !had_time && offset_minutes != 0 {        return None;    }    // A day beyond the month's LENGTH rolls over, it is not rejected —    // `new Date("2026-02-30T00:00:00Z")` is 2026-03-02, not Invalid Date, and    // `minuteBucket("2026-02-29T12:00:00.000Z")` is 2026-03-01T12:00. Only the    // grammar's 01-31 range is checked (above); the arithmetic below does the    // rest, exactly as the engine's does.    let days = days_from_civil(year, month, day);    let ms = days        .checked_mul(86_400_000)?        .checked_add(hour as i64 * 3_600_000)?        .checked_add(minute as i64 * 60_000)?        .checked_add(second as i64 * 1_000)?        .checked_add(milli as i64)?        .checked_sub(offset_minutes.checked_mul(60_000)?)?;    if ms.abs() > MAX_TIME_VALUE {        return None;    }    Some(ms)}/// `new Date(ms).toISOString()` — always UTC, always millisecond precision.////// `None` where JS throws `RangeError` on an out-of-range time value.pub fn to_iso_string(ms: i64) -> Option<String> {    if ms.abs() > MAX_TIME_VALUE {        return None;    }    let days = ms.div_euclid(86_400_000);    let rest = ms.rem_euclid(86_400_000);    let (year, month, day) = civil_from_days(days);    let hour = rest / 3_600_000;    let minute = (rest / 60_000) % 60;    let second = (rest / 1_000) % 60;    let milli = rest % 1_000;    let year_text = if (0..=9999).contains(&year) {        format!("{year:04}")    } else if year > 9999 {        format!("+{year:06}")    } else {        format!("-{:06}", -year)    };    Some(format!(        "{year_text}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{milli:03}Z"    ))}fn read_digits(bytes: &[u8], from: usize, count: usize) -> Option<u32> {    let slice = bytes.get(from..from + count)?;    if !slice.iter().all(u8::is_ascii_digit) {        return None;    }    let mut value = 0u32;    for byte in slice {        value = value * 10 + u32::from(byte - b'0');    }    Some(value)}/// Days since 1970-01-01 (Howard Hinnant's `days_from_civil`).fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {    let y = if month <= 2 { year - 1 } else { year };    let era = if y >= 0 { y } else { y - 399 } / 400;    let yoe = y - era * 400;    let m = month as i64;    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i64 - 1;    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;    era * 146_097 + doe - 719_468}/// The inverse (`civil_from_days`).fn civil_from_days(days: i64) -> (i64, u32, u32) {    let z = days + 719_468;    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;    let doe = z - era * 146_097;    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;    let y = yoe + era * 400;    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);    let mp = (5 * doy + 2) / 153;    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;    (if m <= 2 { y + 1 } else { y }, m, d)}/// JS `String.prototype.replace(/\s+/g, " ")` then `.trim()`.////// The whitespace class is the ECMAScript one: `WhiteSpace` (the Unicode/// `Space_Separator` category plus tab, vertical tab, form feed, no-break/// space, BOM) and `LineTerminator` (LF, CR, LS, PS). Rust's own/// `char::is_whitespace` is the Unicode `White_Space` property, which differs/// in both directions — it excludes U+FEFF and includes U+0085 — and either/// difference would change a fingerprint.pub fn collapse_whitespace_and_trim(input: &str) -> String {    let mut out = String::with_capacity(input.len());    let mut pending_space = false;    let mut wrote_any = false;    for ch in input.chars() {        if is_js_whitespace(ch) {            pending_space = true;            continue;        }        if pending_space && wrote_any {            out.push(' ');        }        pending_space = false;        out.push(ch);        wrote_any = true;    }    out}/// ECMAScript `WhiteSpace ∪ LineTerminator` — the `\s` character class.pub fn is_js_whitespace(ch: char) -> bool {    matches!(        ch,        '\u{9}'      // TAB            | '\u{a}'    // LF   (LineTerminator)            | '\u{b}'    // VT            | '\u{c}'    // FF            | '\u{d}'    // CR   (LineTerminator)            | '\u{20}'   // SPACE            | '\u{a0}'   // NBSP            | '\u{1680}' // OGHAM SPACE MARK            | '\u{2000}'            ..='\u{200a}'            | '\u{2028}' // LS   (LineTerminator)            | '\u{2029}' // PS   (LineTerminator)            | '\u{202f}' // NARROW NBSP            | '\u{205f}' // MEDIUM MATHEMATICAL SPACE            | '\u{3000}' // IDEOGRAPHIC SPACE            | '\u{feff}' // ZWNBSP / BOM    )}#[cfg(test)]#[path = "js_tests.rs"]mod tests;/// `String.prototype.trim()` — the ECMAScript whitespace class, which trims/// U+FEFF and does NOT trim U+0085. Rust's `str::trim` is the other way round.pub fn js_trim(input: &str) -> &str {    input.trim_matches(is_js_whitespace)}/// A JavaScript-truthy string: present and not empty.pub fn truthy_str(value: Option<&str>) -> Option<&str> {    value.filter(|text| !text.is_empty())}