Skip to main content

utf8_forge/
detector.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Encoding detection: a frozen rule-based algorithm, deliberately without
16//! statistical guessing so results are auditable and reproducible.
17//!
18//! Detection order is fixed: BOM sniffing first, then strict UTF-8, then
19//! strict GB18030. Reordering the UTF-8/GB18030 checks would reclassify
20//! ASCII-only files and break idempotence.
21
22use encoding_rs::GB18030;
23
24/// Encodings this tool can classify a byte stream as.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum DetectedEncoding {
27    /// No BOM + strict UTF-8 valid. Pure ASCII also lands here (fast path).
28    Utf8,
29    /// Starts with `EF BB BF`.
30    Utf8Bom,
31    /// Starts with `FF FE`.
32    Utf16Le,
33    /// Starts with `FE FF`.
34    Utf16Be,
35    /// Starts with `FF FE 00 00` (UTF-32LE BOM; the 4-byte prefix wins over
36    /// the 2-byte UTF-16LE check — WHATWG-style longest-BOM precedence).
37    Utf32Le,
38    /// Starts with `00 00 FE FF` (UTF-32BE BOM).
39    Utf32Be,
40    /// UTF-8 strict decode failed, GB18030 strict decode succeeded.
41    /// Covers GB2312 / GBK / GB18030.
42    Gb18030,
43    /// All detectors failed. Reported & skipped — never guessed.
44    Unknown,
45}
46
47impl DetectedEncoding {
48    /// Stable snake-case tag used in JSON reports and console output.
49    pub fn tag(self) -> &'static str {
50        match self {
51            DetectedEncoding::Utf8 => "utf-8",
52            DetectedEncoding::Utf8Bom => "utf-8-bom",
53            DetectedEncoding::Utf16Le => "utf-16le",
54            DetectedEncoding::Utf16Be => "utf-16be",
55            DetectedEncoding::Utf32Le => "utf-32le",
56            DetectedEncoding::Utf32Be => "utf-32be",
57            DetectedEncoding::Gb18030 => "gb18030",
58            DetectedEncoding::Unknown => "unknown",
59        }
60    }
61
62    /// True when the encoding was identified purely by a byte-order mark.
63    pub fn has_bom(self) -> bool {
64        matches!(
65            self,
66            DetectedEncoding::Utf8Bom
67                | DetectedEncoding::Utf16Le
68                | DetectedEncoding::Utf16Be
69                | DetectedEncoding::Utf32Le
70                | DetectedEncoding::Utf32Be
71        )
72    }
73}
74
75/// Classify raw bytes. Rule-based on purpose — no statistical guessing.
76///
77/// The UTF-32 BOMs (`FF FE 00 00` LE / `00 00 FE FF` BE) are checked before
78/// the 2-byte UTF-16 BOMs (longest-prefix precedence, as in WHATWG BOM
79/// sniffing). Documented consequence: a UTF-16LE file whose first character
80/// is U+0000 shares its leading bytes with the UTF-32LE BOM; such a payload
81/// fails the strict UTF-32 decode loudly (`decode_error`) instead of being
82/// silently transcoded, so a detection ambiguity never produces mojibake.
83pub fn detect(bytes: &[u8]) -> DetectedEncoding {
84    if bytes.is_empty() {
85        return DetectedEncoding::Utf8;
86    }
87    if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
88        return DetectedEncoding::Utf8Bom;
89    }
90    // WHATWG BOM sniffing: the 4-byte UTF-32 patterns are checked before the
91    // 2-byte UTF-16 patterns. The UTF-32BE BOM is `00 00 FE FF`; a payload
92    // starting `FE FF 00 00` is a UTF-16BE file whose first character is
93    // U+0000 — UTF-16BE, not UTF-32BE.
94    if bytes.starts_with(&[0x00, 0x00, 0xFE, 0xFF]) {
95        return DetectedEncoding::Utf32Be;
96    }
97    if bytes.starts_with(&[0xFF, 0xFE]) {
98        if bytes.starts_with(&[0xFF, 0xFE, 0x00, 0x00]) {
99            return DetectedEncoding::Utf32Le;
100        }
101        return DetectedEncoding::Utf16Le;
102    }
103    if bytes.starts_with(&[0xFE, 0xFF]) {
104        return DetectedEncoding::Utf16Be;
105    }
106    if std::str::from_utf8(bytes).is_ok() {
107        return DetectedEncoding::Utf8;
108    }
109    let (_, _, had_errors) = GB18030.decode(bytes);
110    if !had_errors {
111        return DetectedEncoding::Gb18030;
112    }
113    DetectedEncoding::Unknown
114}