//! Cleaning of the text people type: titles, names and comments. Control characters are dropped, so a NUL //! or a CR/LF never reaches a page, a mail subject or a header. Bidi controls and invisible formatting //! characters are dropped too, because they change how text is shown: U+202E makes `invoice\u{202E}fdp.exe` //! read as `invoice exe.pdf`. /// Whether `c` is an invisible formatting character or a bidi control. The set is the one of `in`'s /// display-name rules (`in-core` `names.rs`); copied, not shared. U+200D stays: emoji sequences need it, /// and it cannot reorder text. pub fn is_invisible_or_bidi(c: char) -> bool { matches!( c, '\u{200B}'..='\u{200C}' | '\u{200E}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{2064}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}' | '\u{2028}' | '\u{2029}' ) } /// One line of text: every control character, bidi control and invisible formatting character removed, /// then trimmed. pub fn single_line(raw: &str) -> String { raw.chars() .filter(|&c| !c.is_control() && !is_invisible_or_bidi(c)) .collect::() .trim() .to_owned() } /// Several lines of text: like [`single_line`], but line feeds and tabs stay. A CR is dropped, so CRLF /// line ends become LF. pub fn multi_line(raw: &str) -> String { raw.chars() .filter(|&c| (c == '\n' || c == '\t' || !c.is_control()) && !is_invisible_or_bidi(c)) .collect::() .trim() .to_owned() } #[cfg(test)] mod tests { use super::{multi_line, single_line}; #[test] fn controls_and_bidi_are_dropped_and_lines_kept_only_where_asked() { assert_eq!(single_line(" a\u{0}b\r\nBcc: x\u{202E} "), "abBcc: x"); assert_eq!(multi_line("one\r\ntwo\t\u{0}\u{202E}"), "one\ntwo"); } }