Skip to main content

utf8_forge/
detector.rs

1//! Encoding detection (frozen rule-based algorithm, `DESIGN.md §3`).
2//!
3//! Detection order is frozen: BOM sniffing first, then strict UTF-8, then
4//! strict GB18030. Reordering breaks idempotence on ASCII-only files.
5
6use encoding_rs::GB18030;
7
8/// Encodings this tool can classify a byte stream as.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum DetectedEncoding {
11    /// No BOM + strict UTF-8 valid. Pure ASCII also lands here (fast path).
12    Utf8,
13    /// Starts with `EF BB BF`.
14    Utf8Bom,
15    /// Starts with `FF FE`.
16    Utf16Le,
17    /// Starts with `FE FF`.
18    Utf16Be,
19    /// UTF-8 strict decode failed, GB18030 strict decode succeeded.
20    /// Covers GB2312 / GBK / GB18030.
21    Gb18030,
22    /// All detectors failed. Reported & skipped — never guessed.
23    Unknown,
24}
25
26impl DetectedEncoding {
27    /// Stable snake-case tag used in JSON reports and console output.
28    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    /// True when the encoding was identified purely by a byte-order mark.
40    pub fn has_bom(self) -> bool {
41        matches!(
42            self,
43            DetectedEncoding::Utf8Bom | DetectedEncoding::Utf16Le | DetectedEncoding::Utf16Be
44        )
45    }
46}
47
48/// Classify raw bytes. Rule-based on purpose — no statistical guessing.
49pub 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}