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). Consequence of that precedence: a file starting `FF FE 00 00`
80/// is always read as UTF-32LE, even when the bytes would also decode as
81/// UTF-16LE whose first character is U+0000 — the two encodings are
82/// indistinguishable there. To keep such files from ever being created, the
83/// UTF-16LE encoder refuses content that begins with U+0000 (the transcoder
84/// reports `encode_error`), and malformed UTF-32 payloads still fail the
85/// strict decode loudly (`decode_error`) instead of being transcoded.
86pub fn detect(bytes: &[u8]) -> DetectedEncoding {
87 if bytes.is_empty() {
88 return DetectedEncoding::Utf8;
89 }
90 if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
91 return DetectedEncoding::Utf8Bom;
92 }
93 // WHATWG BOM sniffing: the 4-byte UTF-32 patterns are checked before the
94 // 2-byte UTF-16 patterns. The UTF-32BE BOM is `00 00 FE FF`; a payload
95 // starting `FE FF 00 00` is a UTF-16BE file whose first character is
96 // U+0000 — UTF-16BE, not UTF-32BE.
97 if bytes.starts_with(&[0x00, 0x00, 0xFE, 0xFF]) {
98 return DetectedEncoding::Utf32Be;
99 }
100 if bytes.starts_with(&[0xFF, 0xFE]) {
101 if bytes.starts_with(&[0xFF, 0xFE, 0x00, 0x00]) {
102 return DetectedEncoding::Utf32Le;
103 }
104 return DetectedEncoding::Utf16Le;
105 }
106 if bytes.starts_with(&[0xFE, 0xFF]) {
107 return DetectedEncoding::Utf16Be;
108 }
109 if std::str::from_utf8(bytes).is_ok() {
110 return DetectedEncoding::Utf8;
111 }
112 let (_, _, had_errors) = GB18030.decode(bytes);
113 if !had_errors {
114 return DetectedEncoding::Gb18030;
115 }
116 DetectedEncoding::Unknown
117}