use std::borrow::Cow;
use crate::encode::OutputEncoder;
#[derive(Clone, Copy, Debug, Default)]
pub struct CssEncoder;
fn needs_css_encoding(c: char) -> bool {
!matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_')
}
impl OutputEncoder for CssEncoder {
fn encode<'a>(&self, input: &'a str) -> Cow<'a, str> {
if !input.chars().any(needs_css_encoding) {
return Cow::Borrowed(input);
}
let mut out = String::with_capacity(input.len() * 4);
for c in input.chars() {
if c == '\0' {
} else if needs_css_encoding(c) {
let code = c as u32;
out.push_str(&format!("\\{code:06x}"));
} else {
out.push(c);
}
}
Cow::Owned(out)
}
}
#[must_use]
pub fn encode(input: &str) -> Cow<'_, str> {
CssEncoder.encode(input)
}