const TAB: usize = 4;
pub fn sanitize(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut col = 0;
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\n' => {
out.push('\n');
col = 0;
}
'\r' => {
if chars.peek() == Some(&'\n') {
chars.next();
}
out.push('\n');
col = 0;
}
'\t' => {
let n = TAB - col % TAB;
out.extend(std::iter::repeat_n(' ', n));
col += n;
}
c if c.is_control() || is_bidi_control(c) => {}
c => {
out.push(c);
col += 1;
}
}
}
out
}
fn is_bidi_control(c: char) -> bool {
matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_escape_sequences_to_their_printable_rest() {
assert_eq!(sanitize("a\x1b[31mred\x1b[0m"), "a[31mred[0m");
assert_eq!(sanitize("\x1b]0;title\x07x"), "]0;titlex");
assert_eq!(sanitize("\u{9b}31mx"), "31mx", "C1 CSI");
assert_eq!(sanitize("a\u{85}b\x7fc\x00d"), "abcd", "C1 NEL, DEL, NUL");
}
#[test]
fn keeps_newlines_and_unicode() {
assert_eq!(sanitize("one\ntwo\n"), "one\ntwo\n");
assert_eq!(sanitize("crlf\r\nline\rcr"), "crlf\nline\ncr");
assert_eq!(sanitize("世界 ✓ ünï"), "世界 ✓ ünï");
}
#[test]
fn expands_tabs_to_the_next_stop() {
assert_eq!(sanitize("\tx"), " x");
assert_eq!(sanitize("ab\tx"), "ab x");
assert_eq!(sanitize("abcd\tx"), "abcd x");
assert_eq!(sanitize("ab\n\tx"), "ab\n x", "columns restart per line");
}
#[test]
fn drops_bidi_overrides() {
assert_eq!(sanitize("a\u{202E}cba\u{202C}d"), "acbad");
assert_eq!(sanitize("\u{2066}x\u{2069}"), "x");
assert_eq!(sanitize("שלום"), "שלום");
}
}