1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum TargetEncoding {
36 Utf8,
38 Utf8Bom,
40 Gb18030,
42 Utf16Le,
44 Utf16Be,
46}
47
48impl TargetEncoding {
49 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum TranscodeOutcome {
95 Unchanged,
98 Changed(Vec<u8>),
100}
101
102pub 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 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
169fn 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
196pub 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 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
253pub fn transcode(bytes: &[u8], target: TargetEncoding) -> Result<TranscodeOutcome, ForgeError> {
256 transcode_detected(bytes, detect(bytes), target)
257}
258
259pub 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 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 assert_eq!(
348 transcode(&out, TargetEncoding::Utf8).unwrap(),
349 TranscodeOutcome::Unchanged
350 );
351 }
352
353 #[test]
354 fn byte_identical_output_skips_write() {
355 assert_eq!(
357 transcode(b"plain ascii", TargetEncoding::Gb18030).unwrap(),
358 TranscodeOutcome::Unchanged
359 );
360 }
361}