use std::borrow::Cow;
use std::sync::LazyLock;
use unicode_security::confusable_detection::skeleton as confusable;
use super::is_ignorable;
use crate::scrub::classes::{class_ranges, range_of};
static MARKS: LazyLock<Vec<(u32, u32)>> = LazyLock::new(|| class_ranges(r"\p{M}"));
pub(in crate::scrub) fn is_mark(c: char) -> bool {
!c.is_ascii() && range_of(&MARKS, c).is_some()
}
const fn narrow(c: char) -> Option<char> {
match c {
'\u{ff01}'..='\u{ff5e}' => char::from_u32(c as u32 - 0xfee0),
_ => None,
}
}
fn code_unit(rest: &str) -> Option<u16> {
let hex = rest.strip_prefix("\\u")?.get(..4)?;
hex.bytes()
.all(|b| b.is_ascii_hexdigit())
.then(|| u16::from_str_radix(hex, 16).ok())
.flatten()
}
pub(super) fn escape_before(text: &str) -> usize {
let at = text.len().saturating_sub(6);
usize::from(text.is_char_boundary(at) && code_unit(&text[at..]).is_some()) * 6
}
const fn is_sgr_param(b: u8) -> bool {
b.is_ascii_digit() || b == b';'
}
pub(super) fn sgr_len(text: &str) -> usize {
let bytes = text.as_bytes();
if !bytes.starts_with(b"\x1b[") {
return 0;
}
let params = bytes[2..].iter().take_while(|&&b| is_sgr_param(b)).count();
if bytes.get(2 + params) == Some(&b'm') {
3 + params
} else {
0
}
}
pub(super) fn sgr_before(text: &str) -> usize {
let bytes = text.as_bytes();
let Some((&b'm', head)) = bytes.split_last() else {
return 0;
};
let params = head.iter().rev().take_while(|&&b| is_sgr_param(b)).count();
let open = head.len() - params;
if head[..open].ends_with(b"\x1b[") {
params + 3
} else {
0
}
}
pub(super) fn may_escape(text: &str) -> bool {
let bytes = text.as_bytes();
let mut at = 0;
while let Some(found) = memchr::memchr2(b'\\', 0x1b, &bytes[at..]) {
let i = at + found;
if bytes[i] == 0x1b || bytes.get(i + 1) == Some(&b'u') {
return true;
}
at = i + 1;
}
false
}
fn unescape(name: &str) -> Cow<'_, str> {
if !may_escape(name) {
return Cow::Borrowed(name);
}
let mut out = String::with_capacity(name.len());
let mut rest = name;
while let Some(c) = rest.chars().next() {
let sgr = sgr_len(rest);
if sgr > 0 {
rest = &rest[sgr..];
continue;
}
let Some(unit) = code_unit(rest) else {
out.push(c);
rest = &rest[c.len_utf8()..];
continue;
};
rest = &rest[6..];
let low = code_unit(rest).filter(|l| (0xdc00..0xe000).contains(l));
match (unit, low) {
(0xd800..0xdc00, Some(low)) => {
rest = &rest[6..];
let pair = [unit, low];
out.extend(char::decode_utf16(pair).map(|c| c.unwrap_or('\u{fffd}')));
}
_ => out.push(char::from_u32(u32::from(unit)).unwrap_or('\u{fffd}')),
}
}
Cow::Owned(out)
}
pub(in crate::scrub) fn skeleton(name: &str) -> Cow<'_, str> {
let name = unescape(name);
if name.is_ascii() {
return name;
}
let name = name.as_ref();
let mut out = String::with_capacity(name.len());
let mut utf8 = [0; 4];
for c in name.chars() {
if c.is_ascii() {
out.push(c);
} else if is_ignorable(c) || is_mark(c) {
} else if let Some(ascii) = narrow(c) {
out.push(ascii);
} else if c.is_uppercase() {
for lower in c.to_lowercase() {
let mapped = confusable(lower.encode_utf8(&mut utf8));
out.extend(mapped.filter(|&m| !is_mark(m)).flat_map(char::to_uppercase));
}
} else {
out.extend(confusable(c.encode_utf8(&mut utf8)).filter(|&m| !is_mark(m)));
}
}
Cow::Owned(out)
}