use crate::osc::{TERMINATOR_BEL, TERMINATOR_C1_ST};
#[must_use]
pub fn sanitize_label(label: &str) -> &str {
let trimmed = label.trim();
if is_clean(trimmed) {
return trimmed;
}
for (i, ch) in trimmed.char_indices() {
let start = i;
let end = start + ch.len_utf8();
for &b in &trimmed.as_bytes()[start..end] {
if is_dangerous_byte(b) {
return trimmed[..i].trim_end();
}
}
}
trimmed
}
#[inline]
#[must_use]
pub fn is_clean(label: &str) -> bool {
!label.bytes().any(is_dangerous_byte)
}
fn is_dangerous_byte(b: u8) -> bool {
match b {
0x1b => true,
b if b == TERMINATOR_BEL[0] => true,
b if b == TERMINATOR_C1_ST[0] => true,
b']' => true,
0x00..=0x08 | 0x0e..=0x1a | 0x1c..=0x1f | 0x7f => true,
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clean_label_unchanged() {
assert_eq!(sanitize_label("Building project"), "Building project");
}
#[test]
fn trims_whitespace() {
assert_eq!(sanitize_label(" hello "), "hello");
}
#[test]
fn strips_from_escape() {
assert_eq!(sanitize_label("good\x1bbad"), "good");
}
#[test]
fn strips_from_bel() {
assert_eq!(sanitize_label("good\x07bad"), "good");
}
#[test]
fn strips_from_bracket() {
assert_eq!(sanitize_label("good]bad"), "good");
}
#[test]
fn strips_from_c1_st() {
assert_eq!(sanitize_label("good\u{009c}bad"), "good");
}
#[test]
fn empty_label() {
assert_eq!(sanitize_label(""), "");
}
#[test]
fn all_dangerous() {
assert_eq!(sanitize_label("\x1b\x07\u{009c}"), "");
}
#[test]
fn is_clean_true() {
assert!(is_clean("Hello World 123"));
assert!(is_clean("path/to/file.rs"));
}
#[test]
fn is_clean_false() {
assert!(!is_clean("has\x1bescape"));
assert!(!is_clean("has\x07bell"));
}
}