Skip to main content

utf8_forge/
transcoder.rs

1//! Strict decode / encode / transcode (`DESIGN.md §4`).
2//!
3//! Invariants enforced here:
4//! - UTF-16 encoders never emit a BOM by themselves — the BOM is prepended
5//!   manually by [`encode`] (invariant #2).
6//! - Any decode that reports `had_errors` is a hard error, never a
7//!   replacement-char pass-through (invariant #7).
8//! - No newline normalization — `encoding_rs` preserves `\r\n` verbatim
9//!   (invariant #3).
10
11use std::borrow::Cow;
12use std::fmt;
13use std::str::FromStr;
14
15use encoding_rs::{GB18030, UTF_16BE, UTF_16LE};
16
17use crate::detector::{detect, DetectedEncoding};
18use crate::error::ForgeError;
19
20/// Encodings the tool can write.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum TargetEncoding {
23    /// UTF-8 without BOM (default; Playbook Strategy A).
24    Utf8,
25    /// UTF-8 with `EF BB BF` prepended.
26    Utf8Bom,
27    /// GB18030 (superset of GB2312 / GBK).
28    Gb18030,
29    /// UTF-16 little endian with `FF FE` prepended.
30    Utf16Le,
31    /// UTF-16 big endian with `FE FF` prepended.
32    Utf16Be,
33}
34
35impl TargetEncoding {
36    /// Default target: UTF-8 without BOM (invariant #1).
37    pub fn utf8_default() -> TargetEncoding {
38        TargetEncoding::Utf8
39    }
40
41    /// Parse a CLI value. Case-insensitive. Only canonical tags are accepted.
42    pub fn parse(s: &str) -> Option<TargetEncoding> {
43        match s.to_ascii_lowercase().as_str() {
44            "utf-8" => Some(TargetEncoding::Utf8),
45            "utf-8-bom" => Some(TargetEncoding::Utf8Bom),
46            "gb18030" => Some(TargetEncoding::Gb18030),
47            "utf-16le" => Some(TargetEncoding::Utf16Le),
48            "utf-16be" => Some(TargetEncoding::Utf16Be),
49            _ => None,
50        }
51    }
52
53    /// Stable snake-case tag used in reports and console output.
54    pub fn tag(self) -> &'static str {
55        match self {
56            TargetEncoding::Utf8 => "utf-8",
57            TargetEncoding::Utf8Bom => "utf-8-bom",
58            TargetEncoding::Gb18030 => "gb18030",
59            TargetEncoding::Utf16Le => "utf-16le",
60            TargetEncoding::Utf16Be => "utf-16be",
61        }
62    }
63}
64
65impl fmt::Display for TargetEncoding {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(self.tag())
68    }
69}
70
71impl Default for TargetEncoding {
72    /// `utf-8` — required by `#[derive(Default)]` on the CLI arg structs.
73    fn default() -> Self {
74        TargetEncoding::Utf8
75    }
76}
77
78impl FromStr for TargetEncoding {
79    type Err = String;
80
81    /// Enables clap `value_parser` semantics; parse failure → exit code 2.
82    fn from_str(s: &str) -> Result<Self, Self::Err> {
83        TargetEncoding::parse(s).ok_or_else(|| {
84            format!(
85                "invalid target encoding `{s}` (expected utf-8 | utf-8-bom | gb18030 | utf-16le | utf-16be)"
86            )
87        })
88    }
89}
90
91/// Result of transcoding a byte stream.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum TranscodeOutcome {
94    /// Encoded output is byte-identical to the input (or the fast path hit) —
95    /// caller must not write (invariant #5).
96    Unchanged,
97    /// New bytes to persist.
98    Changed(Vec<u8>),
99}
100
101/// Strictly decode `bytes` according to a prior [`detect`] verdict.
102///
103/// BOMs are stripped before decoding. Any `had_errors` from `encoding_rs`
104/// aborts with [`ForgeError::DecodeError`] — mojibake is never written.
105pub fn decode_strict(bytes: &[u8], enc: DetectedEncoding) -> Result<Cow<'_, str>, ForgeError> {
106    match enc {
107        DetectedEncoding::Utf8 => std::str::from_utf8(bytes)
108            .map(Cow::Borrowed)
109            .map_err(|e| ForgeError::DecodeError(format!("invalid utf-8: {e}"))),
110        DetectedEncoding::Utf8Bom => std::str::from_utf8(&bytes[3..])
111            .map(Cow::Borrowed)
112            .map_err(|e| ForgeError::DecodeError(format!("invalid utf-8 after BOM: {e}"))),
113        DetectedEncoding::Utf16Le => {
114            let (cow, _, had_errors) = UTF_16LE.decode(&bytes[2..]);
115            if had_errors {
116                return Err(ForgeError::DecodeError("invalid utf-16le sequence".into()));
117            }
118            Ok(cow)
119        }
120        DetectedEncoding::Utf16Be => {
121            let (cow, _, had_errors) = UTF_16BE.decode(&bytes[2..]);
122            if had_errors {
123                return Err(ForgeError::DecodeError("invalid utf-16be sequence".into()));
124            }
125            Ok(cow)
126        }
127        DetectedEncoding::Gb18030 => {
128            let (cow, _, had_errors) = GB18030.decode(bytes);
129            if had_errors {
130                return Err(ForgeError::DecodeError("invalid gb18030 sequence".into()));
131            }
132            Ok(cow)
133        }
134        DetectedEncoding::Unknown => Err(ForgeError::UnknownEncoding),
135    }
136}
137
138/// Encode `text` into `target`. BOMs for `utf-8-bom` / `utf-16le` /
139/// `utf-16be` are prepended manually — `encoding_rs` never emits them.
140pub fn encode(text: &str, target: TargetEncoding) -> Vec<u8> {
141    match target {
142        TargetEncoding::Utf8 => text.as_bytes().to_vec(),
143        TargetEncoding::Utf8Bom => {
144            let mut v = Vec::with_capacity(3 + text.len());
145            v.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
146            v.extend_from_slice(text.as_bytes());
147            v
148        }
149        TargetEncoding::Gb18030 => {
150            let (cow, _, _) = GB18030.encode(text);
151            cow.into_owned()
152        }
153        TargetEncoding::Utf16Le => {
154            let mut v = Vec::with_capacity(2 + text.len() * 2);
155            v.extend_from_slice(&[0xFF, 0xFE]);
156            let (cow, _, _) = UTF_16LE.encode(text);
157            v.extend_from_slice(&cow);
158            v
159        }
160        TargetEncoding::Utf16Be => {
161            let mut v = Vec::with_capacity(2 + text.len() * 2);
162            v.extend_from_slice(&[0xFE, 0xFF]);
163            let (cow, _, _) = UTF_16BE.encode(text);
164            v.extend_from_slice(&cow);
165            v
166        }
167    }
168}
169
170/// Detect + transcode in one call. Prefer [`transcode_detected`] when the
171/// detection verdict is already known (avoids a second sniff).
172pub fn transcode(bytes: &[u8], target: TargetEncoding) -> Result<TranscodeOutcome, ForgeError> {
173    transcode_detected(bytes, detect(bytes), target)
174}
175
176/// Transcode with a pre-computed detection verdict.
177///
178/// Fast path: `Utf8` → `utf-8` returns [`TranscodeOutcome::Unchanged`] with
179/// zero allocation. Otherwise strict-decode, encode, and compare: a
180/// byte-identical result is reported as `Unchanged` so callers skip the write
181/// (invariants #5 and #10).
182pub fn transcode_detected(
183    bytes: &[u8],
184    detected: DetectedEncoding,
185    target: TargetEncoding,
186) -> Result<TranscodeOutcome, ForgeError> {
187    if detected == DetectedEncoding::Utf8 && target == TargetEncoding::Utf8 {
188        return Ok(TranscodeOutcome::Unchanged);
189    }
190    let text = decode_strict(bytes, detected)?;
191    let encoded = encode(&text, target);
192    if encoded == bytes {
193        Ok(TranscodeOutcome::Unchanged)
194    } else {
195        Ok(TranscodeOutcome::Changed(encoded))
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use crate::detector::detect;
203
204    #[test]
205    fn parse_accepts_canonical_tags_case_insensitive() {
206        assert_eq!(TargetEncoding::parse("utf-8"), Some(TargetEncoding::Utf8));
207        assert_eq!(TargetEncoding::parse("UTF-16LE"), Some(TargetEncoding::Utf16Le));
208        assert_eq!(TargetEncoding::parse("gb18030"), Some(TargetEncoding::Gb18030));
209        assert_eq!(TargetEncoding::parse("utf-8-bom"), Some(TargetEncoding::Utf8Bom));
210        assert_eq!(TargetEncoding::parse("utf-16be"), Some(TargetEncoding::Utf16Be));
211        assert_eq!(TargetEncoding::parse("gbk"), None);
212        assert_eq!(TargetEncoding::parse(""), None);
213    }
214
215    #[test]
216    fn utf16_targets_manually_prepend_bom() {
217        // "hi" encoded to UTF-16LE must start with FF FE — encoding_rs alone
218        // would not emit it (invariant #2).
219        assert_eq!(
220            encode("hi", TargetEncoding::Utf16Le),
221            vec![0xFF, 0xFE, b'h', 0, b'i', 0]
222        );
223        assert_eq!(
224            encode("hi", TargetEncoding::Utf16Be),
225            vec![0xFE, 0xFF, 0, b'h', 0, b'i']
226        );
227        assert_eq!(encode("hi", TargetEncoding::Utf8Bom), {
228            let mut v = vec![0xEF, 0xBB, 0xBF];
229            v.extend_from_slice(b"hi");
230            v
231        });
232    }
233
234    #[test]
235    fn fast_path_utf8_to_utf8_is_unchanged() {
236        assert_eq!(
237            transcode(b"hello", TargetEncoding::Utf8).unwrap(),
238            TranscodeOutcome::Unchanged
239        );
240    }
241
242    #[test]
243    fn empty_bom_only_file_converges_idempotently() {
244        let bom = [0xEF, 0xBB, 0xBF];
245        let out = match transcode(&bom, TargetEncoding::Utf8).unwrap() {
246            TranscodeOutcome::Changed(v) => v,
247            TranscodeOutcome::Unchanged => panic!("BOM-only file must change"),
248        };
249        assert!(out.is_empty());
250        // Second pass: empty file detects as Utf8 → fast path.
251        assert_eq!(
252            transcode(&out, TargetEncoding::Utf8).unwrap(),
253            TranscodeOutcome::Unchanged
254        );
255    }
256
257    #[test]
258    fn byte_identical_output_skips_write() {
259        // ASCII is identical in GB18030 — must not be reported as Changed.
260        assert_eq!(
261            transcode(b"plain ascii", TargetEncoding::Gb18030).unwrap(),
262            TranscodeOutcome::Unchanged
263        );
264    }
265}