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