use encoding_rs::GB18030;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DetectedEncoding {
Utf8,
Utf8Bom,
Utf16Le,
Utf16Be,
Utf32Le,
Utf32Be,
Gb18030,
Unknown,
}
impl DetectedEncoding {
pub fn tag(self) -> &'static str {
match self {
DetectedEncoding::Utf8 => "utf-8",
DetectedEncoding::Utf8Bom => "utf-8-bom",
DetectedEncoding::Utf16Le => "utf-16le",
DetectedEncoding::Utf16Be => "utf-16be",
DetectedEncoding::Utf32Le => "utf-32le",
DetectedEncoding::Utf32Be => "utf-32be",
DetectedEncoding::Gb18030 => "gb18030",
DetectedEncoding::Unknown => "unknown",
}
}
pub fn has_bom(self) -> bool {
matches!(
self,
DetectedEncoding::Utf8Bom
| DetectedEncoding::Utf16Le
| DetectedEncoding::Utf16Be
| DetectedEncoding::Utf32Le
| DetectedEncoding::Utf32Be
)
}
}
pub fn detect(bytes: &[u8]) -> DetectedEncoding {
if bytes.is_empty() {
return DetectedEncoding::Utf8;
}
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
return DetectedEncoding::Utf8Bom;
}
if bytes.starts_with(&[0x00, 0x00, 0xFE, 0xFF]) {
return DetectedEncoding::Utf32Be;
}
if bytes.starts_with(&[0xFF, 0xFE]) {
if bytes.starts_with(&[0xFF, 0xFE, 0x00, 0x00]) {
return DetectedEncoding::Utf32Le;
}
return DetectedEncoding::Utf16Le;
}
if bytes.starts_with(&[0xFE, 0xFF]) {
return DetectedEncoding::Utf16Be;
}
if std::str::from_utf8(bytes).is_ok() {
return DetectedEncoding::Utf8;
}
let (_, _, had_errors) = GB18030.decode(bytes);
if !had_errors {
return DetectedEncoding::Gb18030;
}
DetectedEncoding::Unknown
}