textprep 0.1.5

Text preprocessing primitives: normalization, tokenization, and fast keyword matching.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Unicode normalization utilities.

use unicode_normalization::UnicodeNormalization;

/// Return the NFC (Canonical Decomposition, followed by Canonical Composition) form of the text.
pub fn nfc(text: &str) -> String {
    text.nfc().collect()
}

/// Return the NFD (Canonical Decomposition) form of the text.
pub fn nfd(text: &str) -> String {
    text.nfd().collect()
}

/// Return the NFKC (Compatibility Decomposition, followed by Canonical Composition) form of the text.
pub fn nfkc(text: &str) -> String {
    text.nfkc().collect()
}

/// Return the NFKD (Compatibility Decomposition) form of the text.
pub fn nfkd(text: &str) -> String {
    text.nfkd().collect()
}

/// Normalize newlines to LF (`\n`).
///
/// Converts:
/// - Windows CRLF (`\r\n`) → `\n`
/// - Old Mac CR (`\r`) → `\n`
pub fn normalize_newlines(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\r' {
            if chars.peek() == Some(&'\n') {
                let _ = chars.next();
            }
            out.push('\n');
        } else {
            out.push(c);
        }
    }
    out
}

/// Like [`normalize_newlines`], but writes into an existing `String`.
pub fn normalize_newlines_into(text: &str, out: &mut String) {
    out.clear();
    out.reserve(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\r' {
            if chars.peek() == Some(&'\n') {
                let _ = chars.next();
            }
            out.push('\n');
        } else {
            out.push(c);
        }
    }
}

/// Trim each line (preserving internal spacing) and drop blank lines.
///
/// This is a “document cleaning” primitive:
/// - preserves case
/// - preserves internal whitespace runs (e.g. `"Hello   World"`)
/// - normalizes newlines to `\n`
/// - trims leading/trailing whitespace per line
/// - removes empty lines
///
/// If you want a *search key* (casefold + diacritics stripping + whitespace collapse),
/// use `crate::scrub_with` and an explicit `ScrubConfig`.
pub fn trim_lines_preserve_spaces(text: &str) -> String {
    let normalized = normalize_newlines(text);
    normalized
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

/// Remove common zero-width characters that often cause "ghost mismatches".
///
/// This is intentionally conservative and targets the usual culprits:
/// - U+200B ZERO WIDTH SPACE
/// - U+200C ZERO WIDTH NON-JOINER
/// - U+200D ZERO WIDTH JOINER
/// - U+2060 WORD JOINER
/// - U+FEFF ZERO WIDTH NO-BREAK SPACE (BOM)
///
/// Warning: some of these characters are semantically meaningful in certain scripts
/// (e.g. ZWNJ/ZWJ) or sequences (emoji ZWJ). Treat this as a normalization step for
/// matching/search, not as a general-purpose text rewriting.
pub fn remove_zero_width(text: &str) -> String {
    text.chars()
        .filter(|&c| {
            !matches!(
                c,
                '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}'
            )
        })
        .collect()
}

/// Like [`remove_zero_width`], but writes into an existing `String`.
pub fn remove_zero_width_into(text: &str, out: &mut String) {
    out.clear();
    out.reserve(text.len());
    out.extend(text.chars().filter(|&c| {
        !matches!(
            c,
            '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}'
        )
    }));
}

/// Check whether text contains any of the "common zero-width" characters targeted by
/// [`remove_zero_width`].
#[must_use]
pub fn contains_zero_width(text: &str) -> bool {
    text.chars().any(|c| {
        matches!(
            c,
            '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}'
        )
    })
}

/// Return all "common zero-width" characters found, with **character offsets**.
///
/// This is the detection/reporting counterpart to [`remove_zero_width`].
#[must_use]
pub fn zero_width_with_offsets(text: &str) -> Vec<(usize, char)> {
    text.chars()
        .enumerate()
        .filter_map(|(i, c)| {
            if matches!(
                c,
                '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{2060}' | '\u{FEFF}'
            ) {
                Some((i, c))
            } else {
                None
            }
        })
        .collect()
}

/// Remove Unicode bidirectional control characters.
///
/// This targets the classes of control characters used in "Trojan Source"-style
/// display obfuscation attacks (plus the common LRM/RLM marks):
/// - U+202A..U+202E (embeddings + overrides)
/// - U+2066..U+2069 (isolates)
/// - U+200E, U+200F (LRM/RLM)
/// - U+061C (ARABIC LETTER MARK, ALM)
///
/// This is a *policy* tool: for some natural-language text you may want to keep these.
pub fn remove_bidi_controls(text: &str) -> String {
    text.chars()
        .filter(|&c| {
            !matches!(
                c,
                '\u{202A}'
                    | '\u{202B}'
                    | '\u{202C}'
                    | '\u{202D}'
                    | '\u{202E}'
                    | '\u{2066}'
                    | '\u{2067}'
                    | '\u{2068}'
                    | '\u{2069}'
                    | '\u{200E}'
                    | '\u{200F}'
                    | '\u{061C}'
            )
        })
        .collect()
}

/// Like [`remove_bidi_controls`], but writes into an existing `String`.
pub fn remove_bidi_controls_into(text: &str, out: &mut String) {
    out.clear();
    out.reserve(text.len());
    out.extend(text.chars().filter(|&c| {
        !matches!(
            c,
            '\u{202A}'
                | '\u{202B}'
                | '\u{202C}'
                | '\u{202D}'
                | '\u{202E}'
                | '\u{2066}'
                | '\u{2067}'
                | '\u{2068}'
                | '\u{2069}'
                | '\u{200E}'
                | '\u{200F}'
                | '\u{061C}'
        )
    }));
}

/// Check whether text contains bidi control characters.
#[must_use]
pub fn contains_bidi_controls(text: &str) -> bool {
    text.chars().any(|c| {
        matches!(
            c,
            '\u{202A}'
                | '\u{202B}'
                | '\u{202C}'
                | '\u{202D}'
                | '\u{202E}'
                | '\u{2066}'
                | '\u{2067}'
                | '\u{2068}'
                | '\u{2069}'
                | '\u{200E}'
                | '\u{200F}'
                | '\u{061C}'
        )
    })
}

/// Return all bidi control characters found, with **character offsets**.
///
/// This is useful when you want to *detect and report* (like `rustc`'s
/// `text_direction_codepoint_in_comment` / `text_direction_codepoint_in_literal` lints)
/// instead of silently stripping.
///
/// Offsets are in **characters**, not bytes.
#[must_use]
pub fn bidi_controls_with_offsets(text: &str) -> Vec<(usize, char)> {
    text.chars()
        .enumerate()
        .filter_map(|(i, c)| {
            if matches!(
                c,
                '\u{202A}'
                    | '\u{202B}'
                    | '\u{202C}'
                    | '\u{202D}'
                    | '\u{202E}'
                    | '\u{2066}'
                    | '\u{2067}'
                    | '\u{2068}'
                    | '\u{2069}'
                    | '\u{200E}'
                    | '\u{200F}'
                    | '\u{061C}'
            ) {
                Some((i, c))
            } else {
                None
            }
        })
        .collect()
}

/// Collapse all Unicode whitespace into single ASCII spaces.
///
/// - Converts any `char::is_whitespace()` run into a single `' '`.
/// - Trims leading/trailing whitespace (by construction).
///
/// This intentionally loses newlines. If you want to preserve newlines,
/// normalize newlines first and apply a line-wise collapse yourself.
pub fn collapse_whitespace(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut in_ws = true; // treat start as whitespace to avoid leading space
    for c in text.chars() {
        if c.is_whitespace() {
            in_ws = true;
            continue;
        }
        if in_ws && !out.is_empty() {
            out.push(' ');
        }
        in_ws = false;
        out.push(c);
    }
    out
}

/// Like [`collapse_whitespace`], but writes into an existing `String`.
pub fn collapse_whitespace_into(text: &str, out: &mut String) {
    out.clear();
    out.reserve(text.len());

    let mut in_ws = true; // treat start as whitespace to avoid leading space
    for c in text.chars() {
        if c.is_whitespace() {
            in_ws = true;
            continue;
        }
        if in_ws && !out.is_empty() {
            out.push(' ');
        }
        in_ws = false;
        out.push(c);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    #[test]
    fn test_nfc() {
        let decomposed = "a\u{0308}";
        let normalized = nfc(decomposed);
        assert_eq!(normalized, "ä");
    }

    #[test]
    fn test_normalize_newlines() {
        let text = "Line 1\r\nLine 2\rLine 3\nLine 4";
        let normalized = normalize_newlines(text);
        assert!(!normalized.contains("\r\n"));
        assert!(!normalized.contains('\r'));
        assert!(normalized.contains('\n'));
    }

    #[test]
    fn test_normalize_newlines_into_matches() {
        let text = "Line 1\r\nLine 2\rLine 3\nLine 4";
        let expected = normalize_newlines(text);
        let mut out = String::new();
        normalize_newlines_into(text, &mut out);
        assert_eq!(out, expected);
    }

    #[test]
    fn test_trim_lines_preserve_spaces() {
        // Mixed scripts + diacritics + extra whitespace.
        let text = "  Hello   World  \r\n\r\n  東京  \n\n  Müller  ";
        let out = trim_lines_preserve_spaces(text);
        assert_eq!(out, "Hello   World\n東京\nMüller");
    }

    #[test]
    fn test_remove_zero_width() {
        let text = "a\u{200b}b\u{200c}c\u{200d}d\u{2060}e\u{feff}f";
        assert!(contains_zero_width(text));
        assert_eq!(
            zero_width_with_offsets(text),
            vec![
                (1, '\u{200B}'),
                (3, '\u{200C}'),
                (5, '\u{200D}'),
                (7, '\u{2060}'),
                (9, '\u{FEFF}')
            ]
        );
        assert_eq!(remove_zero_width(text), "abcdef");
        assert!(!contains_zero_width(&remove_zero_width(text)));

        let mut out = String::new();
        remove_zero_width_into(text, &mut out);
        assert_eq!(out, "abcdef");
    }

    #[test]
    fn test_remove_bidi_controls() {
        // Mix embeddings/overrides + isolates + marks.
        let text = "a\u{202e}\u{2066}b\u{2069}\u{202c}\u{200f}c";
        assert!(contains_bidi_controls(text));
        assert_eq!(
            bidi_controls_with_offsets(text),
            vec![
                (1, '\u{202E}'),
                (2, '\u{2066}'),
                (4, '\u{2069}'),
                (5, '\u{202C}'),
                (6, '\u{200F}')
            ]
        );
        assert_eq!(remove_bidi_controls(text), "abc");
        assert!(!contains_bidi_controls(&remove_bidi_controls(text)));

        let mut out = String::new();
        remove_bidi_controls_into(text, &mut out);
        assert_eq!(out, "abc");
    }

    #[test]
    fn test_remove_bidi_controls_includes_alm() {
        let text = "a\u{061c}b";
        assert!(contains_bidi_controls(text));
        assert_eq!(bidi_controls_with_offsets(text), vec![(1, '\u{061C}')]);
        assert_eq!(remove_bidi_controls(text), "ab");
    }

    #[test]
    fn test_collapse_whitespace() {
        let text = "  hello\tworld \n  東京  \r\n  Müller  ";
        let collapsed = collapse_whitespace(text);
        assert_eq!(collapsed, "hello world 東京 Müller");
    }

    #[test]
    fn test_collapse_whitespace_into_matches() {
        let text = "  hello\tworld \n  東京  \r\n  Müller  ";
        let expected = collapse_whitespace(text);
        let mut out = String::new();
        collapse_whitespace_into(text, &mut out);
        assert_eq!(out, expected);
    }

    proptest! {
        #[test]
        fn prop_remove_zero_width_removes_all_targets(s in ".*") {
            let out = remove_zero_width(&s);
            // Provide explicit messages: proptest's default message uses `stringify!(...)`
            // which includes `\u{...}` and can be interpreted as formatting braces.
            prop_assert!(!out.contains('\u{200B}'), "ZWSP (U+200B) not removed");
            prop_assert!(!out.contains('\u{200C}'), "ZWNJ (U+200C) not removed");
            prop_assert!(!out.contains('\u{200D}'), "ZWJ (U+200D) not removed");
            prop_assert!(!out.contains('\u{2060}'), "WORD JOINER (U+2060) not removed");
            prop_assert!(!out.contains('\u{FEFF}'), "BOM (U+FEFF) not removed");
        }

        #[test]
        fn prop_collapse_whitespace_has_no_runs(s in ".*") {
            let out = collapse_whitespace(&s);
            // By construction, output has no leading/trailing whitespace and no internal whitespace runs.
            prop_assert!(!out.starts_with(char::is_whitespace), "leading whitespace present");
            prop_assert!(!out.ends_with(char::is_whitespace), "trailing whitespace present");
            prop_assert!(!out.contains("  "), "double-space present");
            prop_assert!(!out.contains('\n'), "newline present");
            prop_assert!(!out.contains('\t'), "tab present");
            prop_assert!(!out.contains('\r'), "CR present");
        }

        #[test]
        fn prop_normalize_newlines_into_equivalent(s in ".*") {
            let expected = normalize_newlines(&s);
            let mut out = String::new();
            normalize_newlines_into(&s, &mut out);
            prop_assert_eq!(out, expected);
        }

        #[test]
        fn prop_collapse_whitespace_into_equivalent(s in ".*") {
            let expected = collapse_whitespace(&s);
            let mut out = String::new();
            collapse_whitespace_into(&s, &mut out);
            prop_assert_eq!(out, expected);
        }
    }
}