1use encoding_rs::GB18030;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum DetectedEncoding {
11 Utf8,
13 Utf8Bom,
15 Utf16Le,
17 Utf16Be,
19 Gb18030,
22 Unknown,
24}
25
26impl DetectedEncoding {
27 pub fn tag(self) -> &'static str {
29 match self {
30 DetectedEncoding::Utf8 => "utf-8",
31 DetectedEncoding::Utf8Bom => "utf-8-bom",
32 DetectedEncoding::Utf16Le => "utf-16le",
33 DetectedEncoding::Utf16Be => "utf-16be",
34 DetectedEncoding::Gb18030 => "gb18030",
35 DetectedEncoding::Unknown => "unknown",
36 }
37 }
38
39 pub fn has_bom(self) -> bool {
41 matches!(
42 self,
43 DetectedEncoding::Utf8Bom | DetectedEncoding::Utf16Le | DetectedEncoding::Utf16Be
44 )
45 }
46}
47
48pub fn detect(bytes: &[u8]) -> DetectedEncoding {
50 if bytes.is_empty() {
51 return DetectedEncoding::Utf8;
52 }
53 if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
54 return DetectedEncoding::Utf8Bom;
55 }
56 if bytes.starts_with(&[0xFF, 0xFE]) {
57 return DetectedEncoding::Utf16Le;
58 }
59 if bytes.starts_with(&[0xFE, 0xFF]) {
60 return DetectedEncoding::Utf16Be;
61 }
62 if std::str::from_utf8(bytes).is_ok() {
63 return DetectedEncoding::Utf8;
64 }
65 let (_, _, had_errors) = GB18030.decode(bytes);
66 if !had_errors {
67 return DetectedEncoding::Gb18030;
68 }
69 DetectedEncoding::Unknown
70}