1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum TargetEncoding {
44 Utf8,
46 Utf8Bom,
48 Gb18030,
50 Utf16Le,
52 Utf16Be,
54}
55
56impl TargetEncoding {
57 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
102pub enum TranscodeOutcome {
103 Unchanged,
106 Changed(Vec<u8>),
108}
109
110pub 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 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
177fn 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
204pub 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 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
261pub fn transcode(bytes: &[u8], target: TargetEncoding) -> Result<TranscodeOutcome, ForgeError> {
264 transcode_detected(bytes, detect(bytes), target)
265}
266
267pub 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 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 assert_eq!(
356 transcode(&out, TargetEncoding::Utf8).unwrap(),
357 TranscodeOutcome::Unchanged
358 );
359 }
360
361 #[test]
362 fn byte_identical_output_skips_write() {
363 assert_eq!(
365 transcode(b"plain ascii", TargetEncoding::Gb18030).unwrap(),
366 TranscodeOutcome::Unchanged
367 );
368 }
369}