forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

text.rs52 lines, 1.9 KiBHistoryRawDownload
1//! Cleaning of the text people type: titles, names and comments. Control characters are dropped, so a NUL
2//! or a CR/LF never reaches a page, a mail subject or a header. Bidi controls and invisible formatting
3//! characters are dropped too, because they change how text is shown: U+202E makes `invoice\u{202E}fdp.exe`
4//! read as `invoice exe.pdf`.
5
6/// Whether `c` is an invisible formatting character or a bidi control. The set is the one of `in`'s
7/// display-name rules (`in-core` `names.rs`); copied, not shared. U+200D stays: emoji sequences need it,
8/// and it cannot reorder text.
9pub fn is_invisible_or_bidi(c: char) -> bool {
10 matches!(
11 c,
12 '\u{200B}'..='\u{200C}'
13 | '\u{200E}'..='\u{200F}'
14 | '\u{202A}'..='\u{202E}'
15 | '\u{2060}'..='\u{2064}'
16 | '\u{2066}'..='\u{2069}'
17 | '\u{FEFF}'
18 | '\u{2028}'
19 | '\u{2029}'
20 )
21}
22
23/// One line of text: every control character, bidi control and invisible formatting character removed,
24/// then trimmed.
25pub fn single_line(raw: &str) -> String {
26 raw.chars()
27 .filter(|&c| !c.is_control() && !is_invisible_or_bidi(c))
28 .collect::<String>()
29 .trim()
30 .to_owned()
31}
32
33/// Several lines of text: like [`single_line`], but line feeds and tabs stay. A CR is dropped, so CRLF
34/// line ends become LF.
35pub fn multi_line(raw: &str) -> String {
36 raw.chars()
37 .filter(|&c| (c == '\n' || c == '\t' || !c.is_control()) && !is_invisible_or_bidi(c))
38 .collect::<String>()
39 .trim()
40 .to_owned()
41}
42
43#[cfg(test)]
44mod tests {
45 use super::{multi_line, single_line};
46
47 #[test]
48 fn controls_and_bidi_are_dropped_and_lines_kept_only_where_asked() {
49 assert_eq!(single_line(" a\u{0}b\r\nBcc: x\u{202E} "), "abBcc: x");
50 assert_eq!(multi_line("one\r\ntwo\t\u{0}\u{202E}"), "one\ntwo");
51 }
52}