Skip to main content

utf8_forge/
transcoder.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//! Strict decode / encode / transcode.
16//!
17//! Rules enforced here:
18//! - UTF-16 encoders never emit a BOM by themselves — [`encode`] prepends it
19//!   manually.
20//! - Any decode that reports `had_errors` is a hard error, never a
21//!   replacement-char pass-through, so mojibake is never written.
22//! - No newline normalization — `encoding_rs` preserves `\r\n` verbatim.
23
24use std::borrow::Cow;
25use std::fmt;
26use std::str::FromStr;
27
28use encoding_rs::{GB18030, UTF_16BE, UTF_16LE};
29
30use crate::detector::{DetectedEncoding, detect};
31use crate::error::ForgeError;
32
33/// Encodings the tool can write.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum TargetEncoding {
36    /// UTF-8 without BOM (the default target).
37    Utf8,
38    /// UTF-8 with `EF BB BF` prepended.
39    Utf8Bom,
40    /// GB18030 (superset of GB2312 / GBK).
41    Gb18030,
42    /// UTF-16 little endian with `FF FE` prepended.
43    Utf16Le,
44    /// UTF-16 big endian with `FE FF` prepended.
45    Utf16Be,
46}
47
48impl TargetEncoding {
49    /// Parse a CLI value. Case-insensitive. Only canonical tags are accepted.
50    pub fn parse(s: &str) -> Option<TargetEncoding> {
51        match s.to_ascii_lowercase().as_str() {
52            "utf-8" => Some(TargetEncoding::Utf8),
53            "utf-8-bom" => Some(TargetEncoding::Utf8Bom),
54            "gb18030" => Some(TargetEncoding::Gb18030),
55            "utf-16le" => Some(TargetEncoding::Utf16Le),
56            "utf-16be" => Some(TargetEncoding::Utf16Be),
57            _ => None,
58        }
59    }
60
61    /// Stable snake-case tag used in reports and console output.
62    pub fn tag(self) -> &'static str {
63        match self {
64            TargetEncoding::Utf8 => "utf-8",
65            TargetEncoding::Utf8Bom => "utf-8-bom",
66            TargetEncoding::Gb18030 => "gb18030",
67            TargetEncoding::Utf16Le => "utf-16le",
68            TargetEncoding::Utf16Be => "utf-16be",
69        }
70    }
71}
72
73impl fmt::Display for TargetEncoding {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.write_str(self.tag())
76    }
77}
78
79impl FromStr for TargetEncoding {
80    type Err = String;
81
82    /// Enables clap `value_parser` semantics; parse failure → exit code 2.
83    fn from_str(s: &str) -> Result<Self, Self::Err> {
84        TargetEncoding::parse(s).ok_or_else(|| {
85            format!(
86                "invalid target encoding `{s}` (expected utf-8 | utf-8-bom | gb18030 | utf-16le | utf-16be)"
87            )
88        })
89    }
90}
91
92/// Result of transcoding a byte stream.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum TranscodeOutcome {
95    /// Encoded output is byte-identical to the input (or the fast path hit) —
96    /// the caller must skip the write to avoid needless mtime churn.
97    Unchanged,
98    /// New bytes to persist.
99    Changed(Vec<u8>),
100}
101
102/// Strictly decode `bytes` according to a prior [`detect`] verdict.
103///
104/// Only the real leading BOM is stripped (via `decode_without_bom_handling` for
105/// UTF-16 — `Encoding::decode` would BOM-sniff again and silently eat a
106/// content U+FEFF in double-BOM files). Any `had_errors` from `encoding_rs`
107/// aborts with [`ForgeError::DecodeError`] — mojibake is never written.
108/// Truncated BOM payloads are a hard error, never a panic, so the pub API is
109/// safe even when callers pass a verdict that does not match `bytes`.
110pub fn decode_strict(bytes: &[u8], enc: DetectedEncoding) -> Result<Cow<'_, str>, ForgeError> {
111    match enc {
112        DetectedEncoding::Utf8 => std::str::from_utf8(bytes)
113            .map(Cow::Borrowed)
114            .map_err(|e| ForgeError::DecodeError(format!("invalid utf-8: {e}"))),
115        DetectedEncoding::Utf8Bom => {
116            let rest = bytes
117                .get(3..)
118                .ok_or_else(|| ForgeError::DecodeError("truncated utf-8 bom".into()))?;
119            std::str::from_utf8(rest)
120                .map(Cow::Borrowed)
121                .map_err(|e| ForgeError::DecodeError(format!("invalid utf-8 after BOM: {e}")))
122        }
123        DetectedEncoding::Utf16Le => {
124            let rest = bytes
125                .get(2..)
126                .ok_or_else(|| ForgeError::DecodeError("truncated utf-16le bom".into()))?;
127            let (cow, had_errors) = UTF_16LE.decode_without_bom_handling(rest);
128            if had_errors {
129                return Err(ForgeError::DecodeError("invalid utf-16le sequence".into()));
130            }
131            Ok(cow)
132        }
133        DetectedEncoding::Utf16Be => {
134            let rest = bytes
135                .get(2..)
136                .ok_or_else(|| ForgeError::DecodeError("truncated utf-16be bom".into()))?;
137            let (cow, had_errors) = UTF_16BE.decode_without_bom_handling(rest);
138            if had_errors {
139                return Err(ForgeError::DecodeError("invalid utf-16be sequence".into()));
140            }
141            Ok(cow)
142        }
143        DetectedEncoding::Utf32Le => decode_utf32(
144            bytes
145                .get(4..)
146                .ok_or_else(|| ForgeError::DecodeError("truncated utf-32le bom".into()))?,
147            true,
148        ),
149        DetectedEncoding::Utf32Be => decode_utf32(
150            bytes
151                .get(4..)
152                .ok_or_else(|| ForgeError::DecodeError("truncated utf-32be bom".into()))?,
153            false,
154        ),
155        DetectedEncoding::Gb18030 => {
156            // Skip encoding_rs' BOM sniffing: the caller's verdict came from
157            // `detect`, which routes every BOM prefix to its own encoding, so
158            // a UTF-16 BOM here must be a decode error, not a re-routed read.
159            let (cow, had_errors) = GB18030.decode_without_bom_handling(bytes);
160            if had_errors {
161                return Err(ForgeError::DecodeError("invalid gb18030 sequence".into()));
162            }
163            Ok(cow)
164        }
165        DetectedEncoding::Unknown => Err(ForgeError::UnknownEncoding),
166    }
167}
168
169/// Decode UTF-32 units (after the BOM). A misaligned tail, a surrogate
170/// (`0xD800..=0xDFFF`) or a value above `0x10FFFF` is a hard decode error —
171/// `char::from_u32` rejects surrogates and out-of-range values in one check.
172fn decode_utf32(rest: &[u8], little_endian: bool) -> Result<Cow<'_, str>, ForgeError> {
173    if !rest.len().is_multiple_of(4) {
174        let enc = if little_endian {
175            "utf-32le"
176        } else {
177            "utf-32be"
178        };
179        return Err(ForgeError::DecodeError(format!("misaligned {enc} payload")));
180    }
181    let mut out = String::with_capacity(rest.len() / 4);
182    for unit in rest.as_chunks::<4>().0 {
183        let v = if little_endian {
184            u32::from_le_bytes(*unit)
185        } else {
186            u32::from_be_bytes(*unit)
187        };
188        let c = char::from_u32(v).ok_or_else(|| {
189            ForgeError::DecodeError(format!("invalid utf-32 code point U+{v:04X}"))
190        })?;
191        out.push(c);
192    }
193    Ok(Cow::Owned(out))
194}
195
196/// Encode `text` into `target`. BOMs for `utf-8-bom` / `utf-16le` /
197/// `utf-16be` are prepended manually — `encoding_rs` never emits them.
198///
199/// Fails instead of writing mojibake: a UTF-16LE target whose content begins
200/// with U+0000 is refused (the output would begin `FF FE 00 00`, which the
201/// detector reads back as the UTF-32LE BOM), and GB18030 refuses content
202/// containing U+E5E5 — the single Unicode scalar the WHATWG gb18030 encoder
203/// cannot map (encoding_rs would silently write the literal text `&#58853;`).
204pub fn encode(text: &str, target: TargetEncoding) -> Result<Vec<u8>, ForgeError> {
205    match target {
206        TargetEncoding::Utf8 => Ok(text.as_bytes().to_vec()),
207        TargetEncoding::Utf8Bom => {
208            let mut v = Vec::with_capacity(3 + text.len());
209            v.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
210            v.extend_from_slice(text.as_bytes());
211            Ok(v)
212        }
213        TargetEncoding::Gb18030 => {
214            let (cow, _, had_errors) = GB18030.encode(text);
215            if had_errors {
216                return Err(ForgeError::EncodeError(
217                    "content contains characters unmappable in gb18030 (U+E5E5)".into(),
218                ));
219            }
220            Ok(cow.into_owned())
221        }
222        TargetEncoding::Utf16Le => {
223            if text.starts_with('\u{0}') {
224                return Err(ForgeError::EncodeError(
225                    "utf-16le output would begin with `FF FE 00 00` (indistinguishable from the \
226                     utf-32le BOM) because the content begins with U+0000; the file could not be \
227                     re-read as UTF-16 on the next run"
228                        .into(),
229                ));
230            }
231            // encoding_rs' generic `encode()` would silently emit UTF-8 here
232            // (its `output_encoding()` maps UTF-16 targets back to UTF-8), so
233            // UTF-16 bytes are produced directly from std's `encode_utf16()`,
234            // which cannot yield lone surrogates for a valid `&str`.
235            let mut v = Vec::with_capacity(2 + text.len() * 2);
236            v.extend_from_slice(&[0xFF, 0xFE]);
237            for unit in text.encode_utf16() {
238                v.extend_from_slice(&unit.to_le_bytes());
239            }
240            Ok(v)
241        }
242        TargetEncoding::Utf16Be => {
243            let mut v = Vec::with_capacity(2 + text.len() * 2);
244            v.extend_from_slice(&[0xFE, 0xFF]);
245            for unit in text.encode_utf16() {
246                v.extend_from_slice(&unit.to_be_bytes());
247            }
248            Ok(v)
249        }
250    }
251}
252
253/// Detect + transcode in one call. Prefer [`transcode_detected`] when the
254/// detection verdict is already known (avoids a second sniff).
255pub fn transcode(bytes: &[u8], target: TargetEncoding) -> Result<TranscodeOutcome, ForgeError> {
256    transcode_detected(bytes, detect(bytes), target)
257}
258
259/// Transcode with a pre-computed detection verdict.
260///
261/// Fast path: `Utf8` → `utf-8` returns [`TranscodeOutcome::Unchanged`] with
262/// zero allocation. Otherwise strict-decode, encode, and compare: a
263/// byte-identical result is reported as `Unchanged` so callers skip the write
264/// and a second pass over the same tree touches no file. Encoding refusals
265/// ([`ForgeError::EncodeError`] — the UTF-16LE NUL guard and the GB18030
266/// unmappable scalar) come from [`encode`] and never write mojibake.
267pub fn transcode_detected(
268    bytes: &[u8],
269    detected: DetectedEncoding,
270    target: TargetEncoding,
271) -> Result<TranscodeOutcome, ForgeError> {
272    if detected == DetectedEncoding::Utf8 && target == TargetEncoding::Utf8 {
273        return Ok(TranscodeOutcome::Unchanged);
274    }
275    let text = decode_strict(bytes, detected)?;
276    let encoded = encode(&text, target)?;
277    if encoded == bytes {
278        Ok(TranscodeOutcome::Unchanged)
279    } else {
280        Ok(TranscodeOutcome::Changed(encoded))
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    #[test]
289    fn parse_accepts_canonical_tags_case_insensitive() {
290        assert_eq!(TargetEncoding::parse("utf-8"), Some(TargetEncoding::Utf8));
291        assert_eq!(
292            TargetEncoding::parse("UTF-16LE"),
293            Some(TargetEncoding::Utf16Le)
294        );
295        assert_eq!(
296            TargetEncoding::parse("gb18030"),
297            Some(TargetEncoding::Gb18030)
298        );
299        assert_eq!(
300            TargetEncoding::parse("utf-8-bom"),
301            Some(TargetEncoding::Utf8Bom)
302        );
303        assert_eq!(
304            TargetEncoding::parse("utf-16be"),
305            Some(TargetEncoding::Utf16Be)
306        );
307        assert_eq!(TargetEncoding::parse("gbk"), None);
308        assert_eq!(TargetEncoding::parse(""), None);
309    }
310
311    #[test]
312    fn utf16_targets_manually_prepend_bom() {
313        // "hi" encoded to UTF-16LE must start with FF FE — encoding_rs alone
314        // would not emit it.
315        assert_eq!(
316            encode("hi", TargetEncoding::Utf16Le).unwrap(),
317            vec![0xFF, 0xFE, b'h', 0, b'i', 0]
318        );
319        assert_eq!(
320            encode("hi", TargetEncoding::Utf16Be).unwrap(),
321            vec![0xFE, 0xFF, 0, b'h', 0, b'i']
322        );
323        assert_eq!(encode("hi", TargetEncoding::Utf8Bom).unwrap(), {
324            let mut v = vec![0xEF, 0xBB, 0xBF];
325            v.extend_from_slice(b"hi");
326            v
327        });
328    }
329
330    #[test]
331    fn fast_path_utf8_to_utf8_is_unchanged() {
332        assert_eq!(
333            transcode(b"hello", TargetEncoding::Utf8).unwrap(),
334            TranscodeOutcome::Unchanged
335        );
336    }
337
338    #[test]
339    fn empty_bom_only_file_converges_idempotently() {
340        let bom = [0xEF, 0xBB, 0xBF];
341        let out = match transcode(&bom, TargetEncoding::Utf8).unwrap() {
342            TranscodeOutcome::Changed(v) => v,
343            TranscodeOutcome::Unchanged => panic!("BOM-only file must change"),
344        };
345        assert!(out.is_empty());
346        // Second pass: empty file detects as Utf8 → fast path.
347        assert_eq!(
348            transcode(&out, TargetEncoding::Utf8).unwrap(),
349            TranscodeOutcome::Unchanged
350        );
351    }
352
353    #[test]
354    fn byte_identical_output_skips_write() {
355        // ASCII is identical in GB18030 — must not be reported as Changed.
356        assert_eq!(
357            transcode(b"plain ascii", TargetEncoding::Gb18030).unwrap(),
358            TranscodeOutcome::Unchanged
359        );
360    }
361}