44 lines
1.3 KiB
Rust
44 lines
1.3 KiB
Rust
|
|
//! Strip terminal/UI-injection characters from untrusted peer text.
|
|||
|
|
//!
|
|||
|
|
//! Chat is not required to be valid UTF-8 (invalid bytes become U+FFFD).
|
|||
|
|
//! After lossy decode, these code points are removed:
|
|||
|
|
//! - C0 0x00–0x1F except `\t` and `\n`, plus DEL (0x7F)
|
|||
|
|
//! - C1 U+0080–U+009F
|
|||
|
|
//! - bidi/format: U+202A–U+202E, U+2066–U+2069, U+200E, U+200F
|
|||
|
|
//! - zero-width: U+200B (ZWSP), U+200C (ZWNJ)
|
|||
|
|
//!
|
|||
|
|
//! U+200D (ZWJ) is kept so emoji ZWJ sequences stay intact.
|
|||
|
|
|
|||
|
|
use std::borrow::Cow;
|
|||
|
|
|
|||
|
|
pub fn display_text(bytes: &[u8]) -> Cow<'_, str> {
|
|||
|
|
match std::str::from_utf8(bytes) {
|
|||
|
|
Ok(s) if !s.chars().any(is_stripped) => Cow::Borrowed(s),
|
|||
|
|
Ok(s) => Cow::Owned(filter_stripped(s)),
|
|||
|
|
Err(_) => Cow::Owned(filter_stripped(&String::from_utf8_lossy(bytes))),
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// True for C0/C1 controls and bidi/format marks (including `\t`/`\n`).
|
|||
|
|
pub fn is_control_or_bidi(c: char) -> bool {
|
|||
|
|
matches!(
|
|||
|
|
c,
|
|||
|
|
'\0'..='\u{1f}'
|
|||
|
|
| '\u{7f}'
|
|||
|
|
| '\u{80}'..='\u{9f}'
|
|||
|
|
| '\u{202a}'..='\u{202e}'
|
|||
|
|
| '\u{2066}'..='\u{2069}'
|
|||
|
|
| '\u{200e}'
|
|||
|
|
| '\u{200f}'
|
|||
|
|
| '\u{200b}'
|
|||
|
|
| '\u{200c}'
|
|||
|
|
)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
fn is_stripped(c: char) -> bool {
|
|||
|
|
c != '\t' && c != '\n' && is_control_or_bidi(c)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
fn filter_stripped(s: &str) -> String {
|
|||
|
|
s.chars().filter(|c| !is_stripped(*c)).collect()
|
|||
|
|
}
|