Skip to main content

jubarte_dom/util/
mod.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2// SPDX-FileCopyrightText: Microsoft Corporation
3// SPDX-FileCopyrightText: 2025-2026 John Scrudato IV
4//
5// SPDX-License-Identifier: Apache-2.0 AND LicenseRef-Docxodus-MIT
6
7//! Small shared utilities, ported from `PtUtil.ts` (M1.6).
8//!
9//! Three submodules plus re-exports at this path:
10//!
11//! - [`sha1`]: SHA-1 hex helpers, FNV-1a 64 / 128 fingerprints, and
12//!   hex encoding helpers used by the LCS and atom-hash stream.
13//! - `group_adjacent`: the LINQ `GroupAdjacent` port — runs of items
14//!   sharing a key.
15//! - `words`: a word tokenizer that understands combining marks,
16//!   zero-width joiners, and skin-tone modifiers (so a decomposed
17//!   `cafe\u{301}` is one word like its composed form, and emoji
18//!   sequences stay together).
19//!
20//! The functions here back the comparer's LCS hot path and the
21//! Markdown projection. Nothing in this module is CLI-specific, but the
22//! `jubarte` CLI calls into `sha1_hex` (block hash) and
23//! `word_tokens` (diff mark rendering).
24
25#[doc(hidden)]
26pub mod datetime;
27pub mod group_adjacent;
28pub mod sha1;
29pub mod words;
30
31pub use group_adjacent::group_adjacent;
32pub use sha1::{fnv1a_64, fnv1a_128, sha1_hex, sha1_hex_bytes, sha1_hex_parts};
33pub use words::word_tokens;
34
35/// `arg` as a POSIX shell reads it back: bare when it holds only safe
36/// characters, else single-quoted. Library code (validate's next steps)
37/// and the CLI both word commands with it, so it lives outside `cli`.
38pub fn shell_word(arg: &str) -> String {
39    let safe = |c: char| c.is_ascii_alphanumeric() || "-_./:=@%+,".contains(c);
40    if !arg.is_empty() && arg.chars().all(safe) {
41        return arg.to_string();
42    }
43    format!("'{}'", arg.replace('\'', r"'\''"))
44}
45
46/// `text` with each run of whitespace (`char::is_whitespace`) written as
47/// one space and none at either end, built in one pass without collecting
48/// the words first.
49#[doc(hidden)]
50pub fn collapse_whitespace(text: &str) -> String {
51    let mut out = String::with_capacity(text.len());
52    for word in text.split_whitespace() {
53        if !out.is_empty() {
54            out.push(' ');
55        }
56        out.push_str(word);
57    }
58    out
59}
60
61/// A universal measure (`"612pt"`, `"1in"`, `"2.54cm"`, `"1mm"`, `"6pc"`) as
62/// twips, `None` for a plain number or an unknown unit. Strict packages write
63/// these on attributes whose Transitional form is integer twips
64/// (`ST_UniversalMeasure`/`ST_TwipsMeasure`).
65#[doc(hidden)]
66pub fn universal_measure_twips(value: &str) -> Option<f64> {
67    universal_measure(value, 20.0)
68}
69
70/// The same measure as half-points (`ST_HpsMeasure`, `w:sz`): points × 2.
71#[doc(hidden)]
72pub fn universal_measure_half_points(value: &str) -> Option<f64> {
73    universal_measure(value, 2.0)
74}
75
76fn universal_measure(value: &str, per_point: f64) -> Option<f64> {
77    let t = value.trim();
78    for (suffix, points) in [
79        ("pt", 1.0),
80        ("in", 72.0),
81        ("cm", 72.0 / 2.54),
82        ("mm", 72.0 / 25.4),
83        ("pc", 12.0),
84        ("pi", 12.0),
85    ] {
86        if let Some(n) = t.strip_suffix(suffix) {
87            // The schema's spelling and magnitude only: Rust's f64 grammar
88            // is wider (exponents, `nan`, `inf`, `5.`, `+5`), and a value
89            // past the twips domain's i64 saturates when callers cast.
90            return schema_number(n.trim()).and_then(|f| {
91                let v = f * points * per_point;
92                (v.is_finite() && v.abs() <= i64::MAX as f64).then_some(v)
93            });
94        }
95    }
96    None
97}
98
99/// `ST_UniversalMeasure`'s numeric part, `-?[0-9]+(\.[0-9]+)?`: digits on
100/// both sides of the point, a leading `-` as the only sign, no exponent.
101fn schema_number(s: &str) -> Option<f64> {
102    let unsigned = s.strip_prefix('-').unwrap_or(s);
103    let (int_part, frac_part) = match unsigned.split_once('.') {
104        Some((i, f)) => (i, Some(f)),
105        None => (unsigned, None),
106    };
107    if int_part.is_empty() || !int_part.bytes().all(|b| b.is_ascii_digit()) {
108        return None;
109    }
110    if frac_part.is_some_and(|f| f.is_empty() || !f.bytes().all(|b| b.is_ascii_digit())) {
111        return None;
112    }
113    s.parse::<f64>().ok()
114}
115
116/// A document number. `NaN`, an infinity and a value that overflows the
117/// float (`1e40` as `f32`) read as absent, the same as a token that does
118/// not parse. Finite values, including negatives and a finite exponent
119/// (`1e2`), are unchanged.
120#[doc(hidden)]
121pub fn parse_finite_f32(s: &str) -> Option<f32> {
122    let v: f32 = s.parse().ok()?;
123    v.is_finite().then_some(v)
124}
125
126/// [`parse_finite_f32`] for an `f64` attribute. `1e40` is finite here;
127/// a later narrowing to `f32` has to check again.
128#[doc(hidden)]
129pub fn parse_finite_f64(s: &str) -> Option<f64> {
130    let v: f64 = s.parse().ok()?;
131    v.is_finite().then_some(v)
132}
133
134/// `v` as `f32` when that value is finite. A finite `f64` past the `f32`
135/// range (`1e40`) is absent, the same as an infinity.
136#[doc(hidden)]
137pub fn narrow_finite_f32(v: f64) -> Option<f32> {
138    let n = v as f32;
139    n.is_finite().then_some(n)
140}
141
142/// SHA-256 of the exact input bytes, lowercase hex: the snapshot guard shared
143/// by inspection, comparer media reconciliation and edit plans.
144pub fn source_sha256(bytes: &[u8]) -> String {
145    use sha2::{Digest, Sha256};
146    let digest = Sha256::digest(bytes);
147    digest.iter().map(|b| format!("{b:02x}")).collect()
148}
149
150/// Decode the five predefined XML entities, `&nbsp;`, and numeric character
151/// references; unknown or invalid references remain literal.
152#[doc(hidden)]
153pub fn decode_entities(s: &str) -> String {
154    if !s.contains('&') {
155        return s.to_string();
156    }
157    let mut out = String::with_capacity(s.len());
158    let mut rest = s;
159    while let Some(a) = rest.find('&') {
160        out.push_str(&rest[..a]);
161        let tail = &rest[a..];
162        // A reference cannot span the next `&`: bound the `;` search to
163        // this candidate's own text so a later `&…;` stays available.
164        let body = &tail[1..];
165        let limit = body.find('&').unwrap_or(body.len());
166        let semi = body[..limit].find(';').map(|e| e + 1);
167        let decoded = semi.and_then(|e| {
168            let ent = &tail[1..e];
169            let ch = match ent {
170                "amp" => Some('&'),
171                "lt" => Some('<'),
172                "gt" => Some('>'),
173                "quot" => Some('"'),
174                "apos" => Some('\''),
175                "nbsp" => Some('\u{a0}'),
176                _ => decode_numeric_reference(ent),
177            };
178            ch.map(|c| (c, e))
179        });
180        if let Some((c, e)) = decoded {
181            out.push(c);
182            rest = &tail[e + 1..];
183        } else {
184            out.push('&');
185            rest = &tail[1..];
186        }
187    }
188    out.push_str(rest);
189    out
190}
191
192/// The character a numeric character reference names, when its digits are
193/// non-empty ASCII for the radix and the code point is XML 1.0 `Char`.
194fn decode_numeric_reference(ent: &str) -> Option<char> {
195    let (digits, radix) =
196        if let Some(digits) = ent.strip_prefix("#x").or_else(|| ent.strip_prefix("#X")) {
197            (digits, 16)
198        } else {
199            (ent.strip_prefix('#')?, 10)
200        };
201    let digits_valid = if radix == 16 {
202        digits.bytes().all(|b| b.is_ascii_hexdigit())
203    } else {
204        digits.bytes().all(|b| b.is_ascii_digit())
205    };
206    if digits.is_empty() || !digits_valid {
207        return None;
208    }
209    let value = u32::from_str_radix(digits, radix).ok()?;
210    let c = char::from_u32(value)?;
211    is_xml_char(c).then_some(c)
212}
213
214/// XML 1.0 `Char`: tab, LF, CR, then the planes' allowed ranges.
215fn is_xml_char(c: char) -> bool {
216    matches!(
217        c,
218        '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}'
219            | '\u{10000}'..='\u{10ffff}'
220    )
221}
222
223#[cfg(test)]
224mod tests {
225    use super::{
226        collapse_whitespace, decode_entities, narrow_finite_f32, parse_finite_f32,
227        parse_finite_f64, source_sha256, universal_measure_half_points, universal_measure_twips,
228    };
229
230    #[test]
231    fn finite_float_parses_reject_non_finite_tokens() {
232        for bad in [
233            "NaN",
234            "nan",
235            "inf",
236            "+inf",
237            "-inf",
238            "infinity",
239            "-infinity",
240            "1e40",
241            "  ",
242        ] {
243            assert_eq!(parse_finite_f32(bad), None, "{bad}");
244        }
245        assert_eq!(parse_finite_f32("1e2"), Some(100.0));
246        assert_eq!(parse_finite_f32("-1.5"), Some(-1.5));
247        // Rust's float grammar does not trim. Callers that used to trim still trim.
248        assert_eq!(parse_finite_f32(" -1.5 "), None);
249        assert_eq!(parse_finite_f64("1e40"), Some(1e40));
250        assert_eq!(parse_finite_f64("NaN"), None);
251        assert_eq!(parse_finite_f64("inf"), None);
252        assert_eq!(narrow_finite_f32(1e40), None);
253        assert_eq!(narrow_finite_f32(f64::INFINITY), None);
254        assert!(narrow_finite_f32(f64::NAN).is_none());
255        assert_eq!(narrow_finite_f32(12.5), Some(12.5));
256    }
257
258    #[test]
259    fn collapse_whitespace_writes_one_space_between_words() {
260        assert_eq!(collapse_whitespace(""), "");
261        assert_eq!(collapse_whitespace(" \t\n "), "");
262        assert_eq!(collapse_whitespace("  a \t b\n\nc  "), "a b c");
263        assert_eq!(collapse_whitespace("one"), "one");
264        assert_eq!(collapse_whitespace("a\u{A0}b"), "a b");
265    }
266
267    /// Every suffix, signed, with the rounding the callers do: `12.95pt`
268    /// is 259 twips once rounded.
269    #[test]
270    fn decodes_every_suffix_as_twips() {
271        for (value, twips) in [
272            ("0pt", 0.0),
273            ("12pt", 240.0),
274            ("12.95pt", 259.0),
275            ("612pt", 12240.0),
276            ("-36pt", -720.0),
277            ("1in", 1440.0),
278            ("2.54cm", 2.54 * (72.0 / 2.54) * 20.0),
279            ("10mm", 10.0 * (72.0 / 25.4) * 20.0),
280            ("1pc", 240.0),
281            ("1pi", 240.0),
282            (" 72pt ", 1440.0),
283        ] {
284            assert_eq!(universal_measure_twips(value), Some(twips), "{value}");
285        }
286        assert_eq!(
287            universal_measure_twips("12.95pt").map(f64::round),
288            Some(259.0)
289        );
290    }
291
292    /// A plain number is not a universal measure, and neither is anything
293    /// the schema does not spell: callers keep their own integer path.
294    #[test]
295    fn a_plain_number_or_garbage_is_not_a_universal_measure() {
296        for value in ["1440", "12.95", "12PT", "1ptx", "pt", ""] {
297            assert_eq!(universal_measure_twips(value), None, "{value}");
298        }
299    }
300
301    /// The schema's numeric part is `-?digits(.digits)?`: no exponent, no
302    /// `nan`/`inf`, no `+`, no bare or dangling point — Rust's f64 grammar
303    /// is wider, and a magnitude past the twips domain's i64 saturates
304    /// when the callers cast. None of them is a measure (#531).
305    #[test]
306    fn an_absurd_or_out_of_range_measure_is_not_a_measure() {
307        for value in [
308            "nanpt",
309            "infpt",
310            "-infpt",
311            "NaNpt",
312            "1e300pt",
313            "1E2pt",
314            "1.5e2pt",
315            "5.pt",
316            ".5pt",
317            "+5pt",
318            "1pt.",
319            "999999999999999999999999999pt",
320        ] {
321            assert_eq!(universal_measure_twips(value), None, "{value}");
322            assert_eq!(universal_measure_half_points(value), None, "{value}");
323        }
324    }
325
326    /// The half-point domain `w:sz` reads: `11pt` is 22 half-points, not
327    /// the twips the layout attributes carry.
328    #[test]
329    fn half_points_are_points_times_two() {
330        assert_eq!(universal_measure_half_points("11pt"), Some(22.0));
331        assert_eq!(universal_measure_half_points("8pt"), Some(16.0));
332        assert_eq!(universal_measure_half_points("1440"), None);
333    }
334
335    #[test]
336    fn source_sha256_and_entity_decoder_work() {
337        assert_eq!(
338            source_sha256(b"abc"),
339            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
340        );
341        assert_eq!(
342            decode_entities("&amp;&lt;&gt;&quot;&apos;&nbsp;&#65;&#x41;"),
343            "&<>\"'\u{a0}AA"
344        );
345    }
346
347    #[test]
348    fn numeric_references_decode_only_xml_chars() {
349        for (reference, expected) in [
350            ("&#65;", "A"),
351            ("&#x41;", "A"),
352            ("&#X41;", "A"),
353            ("&#x9;", "\t"),
354            ("&#xA;", "\n"),
355            ("&#xD;", "\r"),
356            ("&#x20;", " "),
357            ("&#xD7FF;", "\u{d7ff}"),
358            ("&#xE000;", "\u{e000}"),
359            ("&#xFFFD;", "\u{fffd}"),
360            ("&#x10000;", "\u{10000}"),
361            ("&#x10FFFF;", "\u{10ffff}"),
362            ("&#1114111;", "\u{10ffff}"),
363            ("&#000000000000000000065;", "A"),
364            ("&#x0000000000000041;", "A"),
365        ] {
366            assert_eq!(decode_entities(reference), expected, "{reference}");
367        }
368        for reference in [
369            "&#+65;",
370            "&#x+41;",
371            "&#x-41;",
372            "&#;",
373            "&#x;",
374            "&#xG;",
375            "&#12a;",
376            "&#0;",
377            "&#x0;",
378            "&#x1;",
379            "&#x8;",
380            "&#xB;",
381            "&#xC;",
382            "&#xE;",
383            "&#x1F;",
384            "&#xD800;",
385            "&#xDFFF;",
386            "&#xFFFE;",
387            "&#xFFFF;",
388            "&#x110000;",
389            "&#1114112;",
390        ] {
391            assert_eq!(decode_entities(reference), reference, "{reference}");
392        }
393    }
394}