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 (default; Playbook Strategy A).
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 Default for TargetEncoding {
80    /// `utf-8` — required by `#[derive(Default)]` on the CLI arg structs.
81    fn default() -> Self {
82        TargetEncoding::Utf8
83    }
84}
85
86impl FromStr for TargetEncoding {
87    type Err = String;
88
89    /// Enables clap `value_parser` semantics; parse failure → exit code 2.
90    fn from_str(s: &str) -> Result<Self, Self::Err> {
91        TargetEncoding::parse(s).ok_or_else(|| {
92            format!(
93                "invalid target encoding `{s}` (expected utf-8 | utf-8-bom | gb18030 | utf-16le | utf-16be)"
94            )
95        })
96    }
97}
98
99/// Result of transcoding a byte stream.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub enum TranscodeOutcome {
102    /// Encoded output is byte-identical to the input (or the fast path hit) —
103    /// the caller must skip the write to avoid needless mtime churn.
104    Unchanged,
105    /// New bytes to persist.
106    Changed(Vec<u8>),
107}
108
109/// Strictly decode `bytes` according to a prior [`detect`] verdict.
110///
111/// Only the real leading BOM is stripped (via `decode_without_bom_handling` for
112/// UTF-16 — `Encoding::decode` would BOM-sniff again and silently eat a
113/// content U+FEFF in double-BOM files). Any `had_errors` from `encoding_rs`
114/// aborts with [`ForgeError::DecodeError`] — mojibake is never written.
115/// Truncated BOM payloads are a hard error, never a panic, so the pub API is
116/// safe even when callers pass a verdict that does not match `bytes`.
117pub fn decode_strict(bytes: &[u8], enc: DetectedEncoding) -> Result<Cow<'_, str>, ForgeError> {
118    match enc {
119        DetectedEncoding::Utf8 => std::str::from_utf8(bytes)
120            .map(Cow::Borrowed)
121            .map_err(|e| ForgeError::DecodeError(format!("invalid utf-8: {e}"))),
122        DetectedEncoding::Utf8Bom => {
123            let rest = bytes
124                .get(3..)
125                .ok_or_else(|| ForgeError::DecodeError("truncated utf-8 bom".into()))?;
126            std::str::from_utf8(rest)
127                .map(Cow::Borrowed)
128                .map_err(|e| ForgeError::DecodeError(format!("invalid utf-8 after BOM: {e}")))
129        }
130        DetectedEncoding::Utf16Le => {
131            let rest = bytes
132                .get(2..)
133                .ok_or_else(|| ForgeError::DecodeError("truncated utf-16le bom".into()))?;
134            let (cow, had_errors) = UTF_16LE.decode_without_bom_handling(rest);
135            if had_errors {
136                return Err(ForgeError::DecodeError("invalid utf-16le sequence".into()));
137            }
138            Ok(cow)
139        }
140        DetectedEncoding::Utf16Be => {
141            let rest = bytes
142                .get(2..)
143                .ok_or_else(|| ForgeError::DecodeError("truncated utf-16be bom".into()))?;
144            let (cow, had_errors) = UTF_16BE.decode_without_bom_handling(rest);
145            if had_errors {
146                return Err(ForgeError::DecodeError("invalid utf-16be sequence".into()));
147            }
148            Ok(cow)
149        }
150        DetectedEncoding::Utf32Le => decode_utf32(
151            bytes
152                .get(4..)
153                .ok_or_else(|| ForgeError::DecodeError("truncated utf-32le bom".into()))?,
154            true,
155        ),
156        DetectedEncoding::Utf32Be => decode_utf32(
157            bytes
158                .get(4..)
159                .ok_or_else(|| ForgeError::DecodeError("truncated utf-32be bom".into()))?,
160            false,
161        ),
162        DetectedEncoding::Gb18030 => {
163            let (cow, _, had_errors) = GB18030.decode(bytes);
164            if had_errors {
165                return Err(ForgeError::DecodeError("invalid gb18030 sequence".into()));
166            }
167            Ok(cow)
168        }
169        DetectedEncoding::Unknown => Err(ForgeError::UnknownEncoding),
170    }
171}
172
173/// Decode UTF-32 units (after the BOM). A misaligned tail, a surrogate
174/// (`0xD800..=0xDFFF`) or a value above `0x10FFFF` is a hard decode error —
175/// `char::from_u32` rejects surrogates and out-of-range values in one check.
176fn decode_utf32(rest: &[u8], little_endian: bool) -> Result<Cow<'_, str>, ForgeError> {
177    if !rest.len().is_multiple_of(4) {
178        let enc = if little_endian {
179            "utf-32le"
180        } else {
181            "utf-32be"
182        };
183        return Err(ForgeError::DecodeError(format!("misaligned {enc} payload")));
184    }
185    let mut out = String::with_capacity(rest.len() / 4);
186    for unit in rest.as_chunks::<4>().0 {
187        let v = if little_endian {
188            u32::from_le_bytes(*unit)
189        } else {
190            u32::from_be_bytes(*unit)
191        };
192        let c = char::from_u32(v).ok_or_else(|| {
193            ForgeError::DecodeError(format!("invalid utf-32 code point U+{v:04X}"))
194        })?;
195        out.push(c);
196    }
197    Ok(Cow::Owned(out))
198}
199
200/// Encode `text` into `target`. BOMs for `utf-8-bom` / `utf-16le` /
201/// `utf-16be` are prepended manually — `encoding_rs` never emits them.
202pub fn encode(text: &str, target: TargetEncoding) -> Vec<u8> {
203    match target {
204        TargetEncoding::Utf8 => text.as_bytes().to_vec(),
205        TargetEncoding::Utf8Bom => {
206            let mut v = Vec::with_capacity(3 + text.len());
207            v.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
208            v.extend_from_slice(text.as_bytes());
209            v
210        }
211        TargetEncoding::Gb18030 => {
212            let (cow, _, _) = GB18030.encode(text);
213            cow.into_owned()
214        }
215        TargetEncoding::Utf16Le => {
216            // encoding_rs' generic `encode()` would silently emit UTF-8 here
217            // (its `output_encoding()` maps UTF-16 targets back to UTF-8), so
218            // UTF-16 bytes are produced directly from std's `encode_utf16()`,
219            // which cannot yield lone surrogates for a valid `&str`.
220            let mut v = Vec::with_capacity(2 + text.len() * 2);
221            v.extend_from_slice(&[0xFF, 0xFE]);
222            for unit in text.encode_utf16() {
223                v.extend_from_slice(&unit.to_le_bytes());
224            }
225            v
226        }
227        TargetEncoding::Utf16Be => {
228            let mut v = Vec::with_capacity(2 + text.len() * 2);
229            v.extend_from_slice(&[0xFE, 0xFF]);
230            for unit in text.encode_utf16() {
231                v.extend_from_slice(&unit.to_be_bytes());
232            }
233            v
234        }
235    }
236}
237
238/// Detect + transcode in one call. Prefer [`transcode_detected`] when the
239/// detection verdict is already known (avoids a second sniff).
240pub fn transcode(bytes: &[u8], target: TargetEncoding) -> Result<TranscodeOutcome, ForgeError> {
241    transcode_detected(bytes, detect(bytes), target)
242}
243
244/// Transcode with a pre-computed detection verdict.
245///
246/// Fast path: `Utf8` → `utf-8` returns [`TranscodeOutcome::Unchanged`] with
247/// zero allocation. Otherwise strict-decode, encode, and compare: a
248/// byte-identical result is reported as `Unchanged` so callers skip the write
249/// (invariants #5 and #10).
250pub fn transcode_detected(
251    bytes: &[u8],
252    detected: DetectedEncoding,
253    target: TargetEncoding,
254) -> Result<TranscodeOutcome, ForgeError> {
255    if detected == DetectedEncoding::Utf8 && target == TargetEncoding::Utf8 {
256        return Ok(TranscodeOutcome::Unchanged);
257    }
258    let text = decode_strict(bytes, detected)?;
259    let encoded = encode(&text, target);
260    if encoded == bytes {
261        Ok(TranscodeOutcome::Unchanged)
262    } else {
263        Ok(TranscodeOutcome::Changed(encoded))
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn parse_accepts_canonical_tags_case_insensitive() {
273        assert_eq!(TargetEncoding::parse("utf-8"), Some(TargetEncoding::Utf8));
274        assert_eq!(
275            TargetEncoding::parse("UTF-16LE"),
276            Some(TargetEncoding::Utf16Le)
277        );
278        assert_eq!(
279            TargetEncoding::parse("gb18030"),
280            Some(TargetEncoding::Gb18030)
281        );
282        assert_eq!(
283            TargetEncoding::parse("utf-8-bom"),
284            Some(TargetEncoding::Utf8Bom)
285        );
286        assert_eq!(
287            TargetEncoding::parse("utf-16be"),
288            Some(TargetEncoding::Utf16Be)
289        );
290        assert_eq!(TargetEncoding::parse("gbk"), None);
291        assert_eq!(TargetEncoding::parse(""), None);
292    }
293
294    #[test]
295    fn utf16_targets_manually_prepend_bom() {
296        // "hi" encoded to UTF-16LE must start with FF FE — encoding_rs alone
297        // would not emit it.
298        assert_eq!(
299            encode("hi", TargetEncoding::Utf16Le),
300            vec![0xFF, 0xFE, b'h', 0, b'i', 0]
301        );
302        assert_eq!(
303            encode("hi", TargetEncoding::Utf16Be),
304            vec![0xFE, 0xFF, 0, b'h', 0, b'i']
305        );
306        assert_eq!(encode("hi", TargetEncoding::Utf8Bom), {
307            let mut v = vec![0xEF, 0xBB, 0xBF];
308            v.extend_from_slice(b"hi");
309            v
310        });
311    }
312
313    #[test]
314    fn fast_path_utf8_to_utf8_is_unchanged() {
315        assert_eq!(
316            transcode(b"hello", TargetEncoding::Utf8).unwrap(),
317            TranscodeOutcome::Unchanged
318        );
319    }
320
321    #[test]
322    fn empty_bom_only_file_converges_idempotently() {
323        let bom = [0xEF, 0xBB, 0xBF];
324        let out = match transcode(&bom, TargetEncoding::Utf8).unwrap() {
325            TranscodeOutcome::Changed(v) => v,
326            TranscodeOutcome::Unchanged => panic!("BOM-only file must change"),
327        };
328        assert!(out.is_empty());
329        // Second pass: empty file detects as Utf8 → fast path.
330        assert_eq!(
331            transcode(&out, TargetEncoding::Utf8).unwrap(),
332            TranscodeOutcome::Unchanged
333        );
334    }
335
336    #[test]
337    fn byte_identical_output_skips_write() {
338        // ASCII is identical in GB18030 — must not be reported as Changed.
339        assert_eq!(
340            transcode(b"plain ascii", TargetEncoding::Gb18030).unwrap(),
341            TranscodeOutcome::Unchanged
342        );
343    }
344}