ifc_lite_diff/
utf16.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! UTF-16 code-unit ordering and the 64-bit FNV-1a content hash.
6//!
7//! Both exist because the TypeScript engine this crate ports
8//! (`packages/diff/src/fingerprint.ts`) is specified in terms of JavaScript
9//! strings, which are sequences of UTF-16 code units. Rust strings are UTF-8,
10//! and the two disagree in ways that move a hash:
11//!
12//! - **Ordering.** `str`'s `Ord` compares UTF-8 bytes, which agrees with
13//!   codepoint order. UTF-16 code-unit order does not, above the BMP: a
14//!   surrogate pair's units (`D800 DC00`) sort below `E000`, while its
15//!   codepoint (`U+10000`) sorts above it. Measured against V8:
16//!   `"" < "\u{10000}"` is `false` in JavaScript and `true` in Rust.
17//!   Every sort in the fingerprint module feeds a `JSON.stringify` that is
18//!   then hashed, so using Rust's natural order silently reorders any
19//!   collection holding an astral character and the fingerprint moves.
20//! - **Hashing.** The digest consumes one 16-bit code unit per step, not one
21//!   UTF-8 byte. `ifc_lite_core`'s FNV-1a twin hashes bytes; the two agree on
22//!   constants and mixing but not on output for a given string, so this is a
23//!   deliberate second implementation rather than a reuse. The comment in
24//!   `fingerprint.ts` says the same thing from the other side.
25
26use std::cmp::Ordering;
27
28/// FNV-1a 64-bit offset basis.
29const FNV_OFFSET_BASIS_64: u64 = 0xcbf2_9ce4_8422_2325;
30/// FNV-1a 64-bit prime.
31const FNV_PRIME_64: u64 = 0x0000_0100_0000_01b3;
32
33/// Compare two strings by UTF-16 code unit, the ordering JavaScript's `<` and
34/// `Array.prototype.sort` use.
35///
36/// Never `localeCompare`, and never Rust's `Ord`: see the module docs. A
37/// locale-sensitive comparison would make the fingerprint depend on the
38/// machine that computed it, in a hash whose whole purpose is cross-machine
39/// identity; Rust's `Ord` would differ above the BMP.
40pub(crate) trait CodeUnits { fn code_units(&self) -> std::borrow::Cow<'_, [u16]>; }
41impl CodeUnits for str {
42    fn code_units(&self) -> std::borrow::Cow<'_, [u16]> { self.encode_utf16().collect::<Vec<_>>().into() }
43}
44impl CodeUnits for String {
45    fn code_units(&self) -> std::borrow::Cow<'_, [u16]> { self.as_str().code_units() }
46}
47impl CodeUnits for crate::JsString {
48    fn code_units(&self) -> std::borrow::Cow<'_, [u16]> { self.units().into() }
49}
50impl<T: CodeUnits + ?Sized> CodeUnits for &T {
51    fn code_units(&self) -> std::borrow::Cow<'_, [u16]> { (*self).code_units() }
52}
53pub(crate) fn cmp_code_units<A: CodeUnits + ?Sized, B: CodeUnits + ?Sized>(a: &A, b: &B) -> Ordering {
54    a.code_units().cmp(&b.code_units())
55}
56
57/// 64-bit FNV-1a over the string's UTF-16 code units, rendered as 16 lowercase
58/// hex digits, zero-padded.
59///
60/// Byte-exact with `stableHash` in `packages/diff/src/fingerprint.ts`. Not a
61/// cryptographic hash: it is chosen for non-adversarial drift catching and
62/// content matching, and the callers in the diff pass guard a residual
63/// collision by bucketing on `ifcType` and requiring component agreement.
64/// The 64-bit width replaced a 32-bit one that was demonstrably too narrow
65/// (upstream issue #1962).
66pub fn stable_hash(value: &str) -> String {
67    stable_hash_units(value.encode_utf16())
68}
69
70/// Hash raw JS code units, including unpaired surrogates without lossy UTF-8 conversion.
71pub fn stable_hash_units(units: impl IntoIterator<Item = u16>) -> String {
72    let mut hash = StableHasher::default();
73    hash.write(units);
74    hash.finish()
75}
76
77/// Incremental [`stable_hash_units`]: feeding a string in chunks gives the same
78/// digest, so a serializer can hash without materializing its output (#8114).
79pub(crate) struct StableHasher(u64);
80impl Default for StableHasher {
81    fn default() -> Self { Self(FNV_OFFSET_BASIS_64) }
82}
83impl StableHasher {
84    pub(crate) fn write(&mut self, units: impl IntoIterator<Item = u16>) {
85        for unit in units {
86            self.0 = (self.0 ^ u64::from(unit)).wrapping_mul(FNV_PRIME_64);
87        }
88    }
89    pub(crate) fn finish(&self) -> String { format!("{:016x}", self.0) }
90}
91
92#[cfg(test)]
93#[path = "utf16_tests.rs"]
94mod tests;