use std::borrow::Cow;
use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE};
pub fn fallback_encoding(
css: &[u8],
protocol: Option<&str>,
environment: Option<&'static Encoding>,
) -> &'static Encoding {
if let Some(e) = protocol.and_then(|label| Encoding::for_label(label.as_bytes())) {
return e;
}
let head = &css[..css.len().min(1024)];
if let Some(rest) = head.strip_prefix(b"@charset \"") {
let len = rest
.iter()
.take_while(|&&b| matches!(b, 0x00..=0x21 | 0x23..=0x7f))
.count();
if rest[len..].starts_with(b"\";") {
match Encoding::for_label(&rest[..len]) {
Some(e) if e == UTF_16BE || e == UTF_16LE => return UTF_8,
Some(e) => return e,
None => {}
}
}
}
environment.unwrap_or(UTF_8)
}
pub fn decode_stylesheet<'b>(
css: &'b [u8],
protocol: Option<&str>,
environment: Option<&'static Encoding>,
) -> (Cow<'b, str>, &'static Encoding) {
let (text, encoding, _) = fallback_encoding(css, protocol, environment).decode(css);
(text, encoding)
}