Skip to main content

bilingua_model/
enc.rs

1//! Reading and writing text files in the encoding they came in (Localization OS `read_text_upload`, decisions 22
2//! and B-bytes).
3//!
4//! **Reading** ([`decode_text`]): UTF-8 first (a UTF-8 BOM is kept); then a UTF-16 BOM; then, for formats that
5//! declare their charset (HTML, XML, PO: [`DecodeOptions::declared`]), the declared legacy charset; then a
6//! binary-file check; then the Windows code page of the project's source language (Greek read as Windows-1253,
7//! Japanese as Shift_JIS, ...) with Windows-1252 as the default. When the letters of a legacy decode look wrong
8//! ([`crate::garble`]) the result carries a [`Warning`], never an error. A file no encoding can read is refused
9//! with [`Error::Encoding`] and a "re-save as UTF-8" message.
10//!
11//! **Writing** ([`encode_text`]): the merged text goes back out in the original's envelope: its byte-order mark, its
12//! line endings (when it used one style throughout) and its encoding when every character fits; a translation
13//! that does not fit a legacy code page is written as UTF-8 instead (the declaration, if any, then says so).
14//!
15//! The envelope travels in the skeleton's `encoding` string, which stays `"utf-8"` / `"utf-8-bom"` for the common
16//! files. Grammar: `base[;nl=crlf|cr][;feff=<n>][;label=<declared charset>]`, with `base` one of `utf-8`,
17//! `utf-8-bom`, `utf-16le`, `utf-16be` (both with a BOM) or an `encoding_rs` name such as `windows-1253` or
18//! `shift_jis`. `feff=n` says the decoded text starts with n U+FEFF characters that are content (a file with two
19//! byte order marks): the writer then keeps them ([`strip_own_mark`]).
20
21use crate::codepage::{label as cp_label, source_encoding};
22use crate::garble::text_looks_garbled;
23use crate::guard::{check_lines, Limits};
24use crate::{Error, ExtractOptions, MergeOptions, OutputEncoding, Warning};
25use encoding_rs::{DecoderResult, Encoding};
26use regex::Regex;
27use std::sync::OnceLock;
28
29const BOM8: &[u8] = &[0xEF, 0xBB, 0xBF];
30const RESAVE: &str = "Check the source text; if it is garbled, re-save the file as UTF-8 and upload it again.";
31
32/// How one text file is read. Build it with [`DecodeOptions::new`] (from the extraction options) or
33/// [`DecodeOptions::with_limits`], then [`DecodeOptions::declared`] for a format that declares its charset.
34#[derive(Debug, Clone, Copy)]
35#[non_exhaustive]
36pub struct DecodeOptions<'a> {
37    /// The format declares its charset in the file (HTML `meta`, XML declaration, PO `Content-Type`): honour a
38    /// declared legacy charset, and write the declaration back when the file is merged.
39    pub declared: bool,
40    /// The project's source language, which picks the legacy code page of an undeclared non-UTF-8 file.
41    pub source_lang: Option<&'a str>,
42    /// The limits the decoded text is checked against.
43    pub limits: Limits,
44    /// A UTF-8 byte order mark followed by bytes that are not UTF-8 is read as UTF-8 with replacement characters
45    /// (U+FFFD), as Localization OS does for plain text and subtitles. Off: such a file is refused.
46    pub lossy_after_utf8_bom: bool,
47    /// A UTF-8 byte order mark followed by bytes that are not UTF-8 is read as a mark, and the bytes after it as an
48    /// undeclared legacy file (Localization OS BOM read version 2, #799.4 / #800.4: its subtitle readers). The
49    /// envelope tag records the mark (`;bom8`), so a merge writes it back: before the code page's bytes, or before
50    /// UTF-8 when the text is written as UTF-8. Off: the mark's three bytes are read as code-page text.
51    pub mark_before_legacy: bool,
52}
53
54impl<'a> DecodeOptions<'a> {
55    /// The options of one extraction: its source language and its limits.
56    pub fn new(opts: &'a ExtractOptions) -> DecodeOptions<'a> {
57        DecodeOptions { declared: false, source_lang: opts.source_lang.as_deref(), limits: opts.limits(), lossy_after_utf8_bom: false, mark_before_legacy: false }
58    }
59    /// No source language, not declared, these limits.
60    pub fn with_limits(limits: Limits) -> DecodeOptions<'static> {
61        DecodeOptions { declared: false, source_lang: None, limits, lossy_after_utf8_bom: false, mark_before_legacy: false }
62    }
63    /// The source language that picks the code page of an undeclared legacy file.
64    pub fn with_source_lang(mut self, lang: Option<&'a str>) -> Self {
65        self.source_lang = lang;
66        self
67    }
68    /// See [`DecodeOptions::lossy_after_utf8_bom`].
69    pub fn lossy_after_utf8_bom(mut self) -> Self {
70        self.lossy_after_utf8_bom = true;
71        self
72    }
73    /// See [`DecodeOptions::mark_before_legacy`].
74    pub fn mark_before_legacy(mut self) -> Self {
75        self.mark_before_legacy = true;
76        self
77    }
78    /// The same, for a format that declares its charset in the file.
79    pub fn declared(mut self) -> Self {
80        self.declared = true;
81        self
82    }
83}
84
85/// A decoded text file: the text (without BOM), the envelope tag for the skeleton and any warnings.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct Decoded {
88    /// The decoded text.
89    pub text: String,
90    /// Goes into `Skeleton::Text::encoding`; hand it back to [`encode_text`] on merge.
91    pub encoding: String,
92    /// What the decoder noticed (text that looks garbled in the code page it was read with).
93    pub warnings: Vec<Warning>,
94}
95
96fn enc_err(msg: impl Into<String>) -> Error {
97    Error::Encoding(msg.into())
98}
99
100fn decl_re() -> &'static Regex {
101    static R: OnceLock<Regex> = OnceLock::new();
102    R.get_or_init(|| {
103        Regex::new(
104            r#"(?i)(<\?xml[^>]{0,200}?\bencoding\s*=\s*["']\s*|<meta\b[^>]{0,400}?\bcharset\s*=\s*["']?\s*|Content-Type:[^"\n]{0,100}?\bcharset\s*=\s*)([A-Za-z0-9_.:-]{1,40})"#,
105        )
106        .expect("charset declaration pattern")
107    })
108}
109
110/// Charsets a file may declare and be read as: the common legacy text encodings (not UTF-8, UTF-16 or the
111/// Windows-1252 family, which the default path reads).
112fn declared_ok(e: &'static Encoding) -> bool {
113    use encoding_rs::*;
114    [
115        WINDOWS_1250, WINDOWS_1251, WINDOWS_1253, WINDOWS_1254, WINDOWS_1255, WINDOWS_1256, WINDOWS_1257, WINDOWS_1258, ISO_8859_2,
116        ISO_8859_5, ISO_8859_7, ISO_8859_15, KOI8_R, KOI8_U, SHIFT_JIS, EUC_JP, GBK, GB18030, BIG5, EUC_KR,
117    ]
118    .contains(&e)
119        || declared_if_strict(e)
120}
121
122/// The rarer charsets added on 11-07 (LocOS issue 810.3). A file that declares one is read in it when every byte
123/// decodes; one that does not (often a page labelled ISO-8859-8 that holds Windows-1255 vowel points) is read the
124/// way it was before, by the default path, not refused. ISO-8859-8 visual and -8-I logical decode to the same
125/// characters in the order of the bytes: nothing is reordered.
126fn declared_if_strict(e: &'static Encoding) -> bool {
127    use encoding_rs::*;
128    [
129        ISO_8859_3, ISO_8859_4, ISO_8859_6, ISO_8859_8, ISO_8859_8_I, ISO_8859_10, ISO_8859_13, ISO_8859_14, ISO_8859_16, WINDOWS_874,
130        IBM866, MACINTOSH, X_MAC_CYRILLIC,
131    ]
132    .contains(&e)
133}
134
135fn ascii_head(data: &[u8], n: usize) -> String {
136    data.iter().take(n).map(|b| if b.is_ascii() { *b as char } else { '?' }).collect()
137}
138
139/// True for the legacy charsets a file may declare and be read as (see [`decode_text`]).
140pub fn is_declared_legacy(e: &'static Encoding) -> bool {
141    declared_ok(e)
142}
143
144/// Decodes all of `data` as `enc`, or says where the first undecodable byte is.
145pub fn decode_strict(enc: &'static Encoding, data: &[u8]) -> Result<String, usize> {
146    strict(enc, data)
147}
148
149/// The encoding of a skeleton tag without its newline and label parts ("windows-1253;nl=crlf" is "windows-1253").
150pub fn base(tag: &str) -> &str {
151    tag.split(';').next().unwrap_or(tag)
152}
153
154/// Every charset declaration in `text` rewritten to say UTF-8, as LocOS's `read_text_upload(declared=True)` does
155/// to a file it converted.
156#[doc(hidden)]
157pub fn rewrite_declarations(text: &str) -> String {
158    rewrite_declared(text)
159}
160
161/// The skeleton tag without its newline part, so a merge leaves the line breaks of the text as they are (the LocOS
162/// profile's XML resource writers: LocOS does not normalise the breaks a translation brings in).
163#[doc(hidden)]
164pub fn keep_newlines(tag: &str) -> String {
165    tag.split(';').filter(|p| !p.starts_with("nl=")).collect::<Vec<_>>().join(";")
166}
167
168/// The skeleton of a LocOS-profile document whose writer works on the decoded file (po, srt and vtt): the file's
169/// skeleton tag, a line break, then the decoded text without its BOM. Read it back with [`locos_skeleton_parts`].
170#[doc(hidden)]
171pub fn locos_skeleton(tag: &str, text: &str) -> Vec<u8> {
172    let text = strip_own_mark(text, tag);
173    let mut v = Vec::with_capacity(tag.len() + 1 + text.len());
174    v.extend_from_slice(tag.as_bytes());
175    v.push(b'\n');
176    v.extend_from_slice(text.as_bytes());
177    v
178}
179
180/// (skeleton tag, decoded text) of a [`locos_skeleton`]; `None` when `data` is not one.
181#[doc(hidden)]
182pub fn locos_skeleton_parts(data: &[u8]) -> Option<(&str, &str)> {
183    let s = std::str::from_utf8(data).ok()?;
184    let (tag, text) = s.split_once('\n')?;
185    // a tag is a charset name with `;nl=` / `;label=` (markdown: `;fm=`) parts: nothing a declaration could carry
186    // as markup
187    let ok = !tag.is_empty() && tag.len() <= 4096 && tag.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.:;=-".contains(&b));
188    ok.then_some((tag, text))
189}
190
191/// The tag LocOS's UTF-8 export writes a file under: UTF-8, its UTF-8 BOM and its line breaks kept (a UTF-16 BOM,
192/// a code page and its label are not).
193#[doc(hidden)]
194pub fn locos_utf8_tag(tag: &str) -> String {
195    let mut t = String::from(if base(tag) == "utf-8-bom" { "utf-8-bom" } else { "utf-8" });
196    for p in tag.split(';').skip(1).filter(|p| p.starts_with("nl=") || p.starts_with("feff=")) {
197        t.push(';');
198        t.push_str(p);
199    }
200    t
201}
202
203/// The charset a file declares in its first 4 KB, as a decoder.
204pub fn declared_encoding(data: &[u8]) -> Option<&'static Encoding> {
205    let head = ascii_head(data, 4096);
206    let m = decl_re().captures(&head)?;
207    label_encoding(m.get(2)?.as_str())
208}
209
210/// The encoding a charset label names, as Localization OS reads a declaration (`codecs.lookup`, then its
211/// `_LABEL_ALIASES`): the WHATWG label first (what `encoding_rs` knows), then Python's codec names and aliases of
212/// the legacy charsets a file may declare (`CP932`, `cp936`, `sjis`, `ujis`, `uhc`, `ms949`, `iso8859_2` ...),
213/// normalised the way Python does (case, and runs of punctuation as one `_`). Python's ISO-8859-1, Windows-1252
214/// and UTF-16 aliases are not in the table: LocOS reads those by its default path, not as a declaration.
215pub fn label_encoding(label: &str) -> Option<&'static Encoding> {
216    if let Some(e) = Encoding::for_label(label.trim().as_bytes()) {
217        return Some(e);
218    }
219    let norm = python_normalize(&label.to_ascii_lowercase());
220    let find = |k: &str| PY_ALIASES.binary_search_by(|(a, _)| (*a).cmp(k)).ok().map(|i| PY_ALIASES[i].1);
221    let whatwg = find(&norm).or_else(|| find(&norm.replace('.', "_")))?;
222    Encoding::for_label(whatwg.as_bytes())
223}
224
225/// Python's `encodings.normalize_encoding`: letters, digits and dots kept, every other run of characters one `_`
226/// (none at the ends).
227fn python_normalize(s: &str) -> String {
228    let mut out = String::with_capacity(s.len());
229    let mut punct = false;
230    for c in s.chars() {
231        if c.is_alphanumeric() || c == '.' {
232            if punct && !out.is_empty() {
233                out.push('_');
234            }
235            if c.is_ascii() {
236                out.push(c);
237            }
238            punct = false;
239        } else {
240            punct = true;
241        }
242    }
243    out
244}
245
246/// Python 3 codec aliases (normalised) of the charsets LocOS reads from a declaration, to the WHATWG label of the
247/// same encoding. Sorted (binary search). Generated from `encodings.aliases` and the codec module names.
248const PY_ALIASES: &[(&str, &str)] = &[
249    ("1250", "windows-1250"),
250    ("1251", "windows-1251"),
251    ("1253", "windows-1253"),
252    ("1254", "windows-1254"),
253    ("1255", "windows-1255"),
254    ("1256", "windows-1256"),
255    ("1257", "windows-1257"),
256    ("1258", "windows-1258"),
257    ("866", "ibm866"),
258    ("932", "shift_jis"),
259    ("936", "gbk"),
260    ("949", "euc-kr"),
261    ("arabic", "iso-8859-6"),
262    ("asmo_708", "iso-8859-6"),
263    ("big5", "big5"),
264    ("big5_tw", "big5"),
265    ("chinese", "gbk"),
266    ("cp1250", "windows-1250"),
267    ("cp1251", "windows-1251"),
268    ("cp1253", "windows-1253"),
269    ("cp1254", "windows-1254"),
270    ("cp1255", "windows-1255"),
271    ("cp1256", "windows-1256"),
272    ("cp1257", "windows-1257"),
273    ("cp1258", "windows-1258"),
274    ("cp866", "ibm866"),
275    ("cp874", "windows-874"),
276    ("cp932", "shift_jis"),
277    ("cp936", "gbk"),
278    ("cp949", "euc-kr"),
279    ("csbig5", "big5"),
280    ("csibm866", "ibm866"),
281    ("csiso58gb231280", "gbk"),
282    ("csisolatin2", "iso-8859-2"),
283    ("csisolatin3", "iso-8859-3"),
284    ("csisolatin4", "iso-8859-4"),
285    ("csisolatin5", "iso-8859-9"),
286    ("csisolatin6", "iso-8859-10"),
287    ("csisolatinarabic", "iso-8859-6"),
288    ("csisolatincyrillic", "iso-8859-5"),
289    ("csisolatingreek", "iso-8859-7"),
290    ("csisolatinhebrew", "iso-8859-8"),
291    ("cskoi8r", "koi8-r"),
292    ("csshiftjis", "shift_jis"),
293    ("cyrillic", "iso-8859-5"),
294    ("ecma_114", "iso-8859-6"),
295    ("ecma_118", "iso-8859-7"),
296    ("elot_928", "iso-8859-7"),
297    ("euc_cn", "gbk"),
298    ("euc_jp", "euc-jp"),
299    ("euc_kr", "euc-kr"),
300    ("euccn", "gbk"),
301    ("eucgb2312_cn", "gbk"),
302    ("eucjp", "euc-jp"),
303    ("euckr", "euc-kr"),
304    ("gb18030", "gb18030"),
305    ("gb18030_2000", "gb18030"),
306    ("gb2312", "gbk"),
307    ("gb2312_1980", "gbk"),
308    ("gb2312_80", "gbk"),
309    ("gbk", "gbk"),
310    ("greek", "iso-8859-7"),
311    ("greek8", "iso-8859-7"),
312    ("hebrew", "iso-8859-8"),
313    ("ibm866", "ibm866"),
314    ("iso8859_10", "iso-8859-10"),
315    ("iso8859_13", "iso-8859-13"),
316    ("iso8859_14", "iso-8859-14"),
317    ("iso8859_15", "iso-8859-15"),
318    ("iso8859_16", "iso-8859-16"),
319    ("iso8859_2", "iso-8859-2"),
320    ("iso8859_3", "iso-8859-3"),
321    ("iso8859_4", "iso-8859-4"),
322    ("iso8859_5", "iso-8859-5"),
323    ("iso8859_6", "iso-8859-6"),
324    ("iso8859_7", "iso-8859-7"),
325    ("iso8859_8", "iso-8859-8"),
326    ("iso8859_9", "iso-8859-9"),
327    ("iso_8859_10", "iso-8859-10"),
328    ("iso_8859_10_1992", "iso-8859-10"),
329    ("iso_8859_13", "iso-8859-13"),
330    ("iso_8859_14", "iso-8859-14"),
331    ("iso_8859_14_1998", "iso-8859-14"),
332    ("iso_8859_15", "iso-8859-15"),
333    ("iso_8859_16", "iso-8859-16"),
334    ("iso_8859_16_2001", "iso-8859-16"),
335    ("iso_8859_2", "iso-8859-2"),
336    ("iso_8859_2_1987", "iso-8859-2"),
337    ("iso_8859_3", "iso-8859-3"),
338    ("iso_8859_3_1988", "iso-8859-3"),
339    ("iso_8859_4", "iso-8859-4"),
340    ("iso_8859_4_1988", "iso-8859-4"),
341    ("iso_8859_5", "iso-8859-5"),
342    ("iso_8859_5_1988", "iso-8859-5"),
343    ("iso_8859_6", "iso-8859-6"),
344    ("iso_8859_6_1987", "iso-8859-6"),
345    ("iso_8859_7", "iso-8859-7"),
346    ("iso_8859_7_1987", "iso-8859-7"),
347    ("iso_8859_8", "iso-8859-8"),
348    ("iso_8859_8_1988", "iso-8859-8"),
349    ("iso_8859_9", "iso-8859-9"),
350    ("iso_8859_9_1989", "iso-8859-9"),
351    ("iso_celtic", "iso-8859-14"),
352    ("iso_ir_101", "iso-8859-2"),
353    ("iso_ir_109", "iso-8859-3"),
354    ("iso_ir_110", "iso-8859-4"),
355    ("iso_ir_126", "iso-8859-7"),
356    ("iso_ir_127", "iso-8859-6"),
357    ("iso_ir_138", "iso-8859-8"),
358    ("iso_ir_144", "iso-8859-5"),
359    ("iso_ir_148", "iso-8859-9"),
360    ("iso_ir_157", "iso-8859-10"),
361    ("iso_ir_199", "iso-8859-14"),
362    ("iso_ir_226", "iso-8859-16"),
363    ("iso_ir_58", "gbk"),
364    ("koi8_r", "koi8-r"),
365    ("koi8_u", "koi8-u"),
366    ("korean", "euc-kr"),
367    ("ks_c_5601", "euc-kr"),
368    ("ks_c_5601_1987", "euc-kr"),
369    ("ks_x_1001", "euc-kr"),
370    ("ksc5601", "euc-kr"),
371    ("ksx1001", "euc-kr"),
372    ("l10", "iso-8859-16"),
373    ("l2", "iso-8859-2"),
374    ("l3", "iso-8859-3"),
375    ("l4", "iso-8859-4"),
376    ("l5", "iso-8859-9"),
377    ("l6", "iso-8859-10"),
378    ("l7", "iso-8859-13"),
379    ("l8", "iso-8859-14"),
380    ("l9", "iso-8859-15"),
381    ("latin10", "iso-8859-16"),
382    ("latin2", "iso-8859-2"),
383    ("latin3", "iso-8859-3"),
384    ("latin4", "iso-8859-4"),
385    ("latin5", "iso-8859-9"),
386    ("latin6", "iso-8859-10"),
387    ("latin7", "iso-8859-13"),
388    ("latin8", "iso-8859-14"),
389    ("latin9", "iso-8859-15"),
390    ("mac_cyrillic", "x-mac-cyrillic"),
391    ("mac_roman", "macintosh"),
392    ("maccyrillic", "x-mac-cyrillic"),
393    ("macintosh", "macintosh"),
394    ("macroman", "macintosh"),
395    ("ms932", "shift_jis"),
396    ("ms936", "gbk"),
397    ("ms949", "euc-kr"),
398    ("ms_kanji", "shift_jis"),
399    ("mskanji", "shift_jis"),
400    ("s_jis", "shift_jis"),
401    ("shift_jis", "shift_jis"),
402    ("shiftjis", "shift_jis"),
403    ("sjis", "shift_jis"),
404    ("u_jis", "euc-jp"),
405    ("uhc", "euc-kr"),
406    ("ujis", "euc-jp"),
407    ("windows_1250", "windows-1250"),
408    ("windows_1251", "windows-1251"),
409    ("windows_1253", "windows-1253"),
410    ("windows_1254", "windows-1254"),
411    ("windows_1255", "windows-1255"),
412    ("windows_1256", "windows-1256"),
413    ("windows_1257", "windows-1257"),
414    ("windows_1258", "windows-1258"),
415    ("windows_31j", "shift_jis"),
416    ("x_mac_japanese", "shift_jis"),
417    ("x_mac_korean", "euc-kr"),
418    ("x_mac_simp_chinese", "gbk"),
419    ("x_mac_trad_chinese", "big5"),
420];
421
422/// The charset name a file declares in its first 4 KB, as written.
423#[doc(hidden)]
424pub fn declared_label(data: &[u8]) -> Option<String> {
425    let head = ascii_head(data, 4096);
426    Some(decl_re().captures(&head)?.get(2)?.as_str().to_string())
427}
428
429/// Whether bytes that are not UTF-8 would be refused as binary by [`decode_text`]: a NUL, or more C0 controls than a
430/// text file carries. A writer that puts text back in a legacy code page checks its output with this, so a merge
431/// never writes a file that the same extract refuses.
432pub fn looks_binary(data: &[u8]) -> bool {
433    if data.contains(&0) {
434        return true;
435    }
436    // C0 controls a text file never carries (TAB, LF, VT, FF, CR, SUB and ESC are allowed).
437    let bad = data.iter().filter(|b| **b < 0x20 && !matches!(**b, 0x09 | 0x0A | 0x0B | 0x0C | 0x0D | 0x1A | 0x1B)).count();
438    bad > 2 + data.len() / 100
439}
440
441/// Decodes all of `data` as `enc` or says where the first undecodable byte is. Windows-1252 is strict like
442/// Python's `cp1252`: its five undefined bytes are errors, not C1 controls.
443fn strict(enc: &'static Encoding, data: &[u8]) -> Result<String, usize> {
444    if enc == encoding_rs::WINDOWS_1252 {
445        if let Some(p) = data.iter().position(|b| matches!(b, 0x81 | 0x8D | 0x8F | 0x90 | 0x9D)) {
446            return Err(p);
447        }
448    }
449    let mut dec = enc.new_decoder_without_bom_handling();
450    let mut out = String::with_capacity(dec.max_utf8_buffer_length_without_replacement(data.len()).unwrap_or(data.len() * 4));
451    let (res, read) = dec.decode_to_string_without_replacement(data, &mut out, true);
452    match res {
453        DecoderResult::InputEmpty => Ok(out),
454        DecoderResult::Malformed(bad, after) => Err(read.saturating_sub(bad as usize + after as usize)),
455        DecoderResult::OutputFull => Err(read),
456    }
457}
458
459/// The line-ending style of a text when it uses one throughout: `"\r\n"` (every `\n` follows `\r` and every `\r`
460/// precedes `\n`), `"\r"` (no `\n` at all), else `""`.
461pub fn newline_style(text: &str) -> &'static str {
462    let b = text.as_bytes();
463    let (mut crlf, mut lf, mut cr) = (0usize, 0usize, 0usize);
464    for (i, c) in b.iter().enumerate() {
465        match c {
466            b'\n' => {
467                lf += 1;
468                if i > 0 && b[i - 1] == b'\r' {
469                    crlf += 1;
470                }
471            }
472            b'\r' => cr += 1,
473            _ => {}
474        }
475    }
476    if crlf > 0 && crlf == lf && lf == cr {
477        "\r\n"
478    } else if cr > 0 && lf == 0 {
479        "\r"
480    } else {
481        ""
482    }
483}
484
485fn tag(base: &str, text: &str, label: Option<&str>) -> String {
486    let mut t = base.to_string();
487    match newline_style(text) {
488        "\r\n" => t.push_str(";nl=crlf"),
489        "\r" => t.push_str(";nl=cr"),
490        _ => {}
491    }
492    let marks = leading_marks(text);
493    if marks > 0 {
494        t.push_str(&format!(";feff={marks}"));
495    }
496    if let Some(l) = label {
497        t.push_str(";label=");
498        t.push_str(l);
499    }
500    t
501}
502
503/// The skeleton base for a file read as `enc` under a declared `label`. WHATWG (and so `encoding_rs`) reads
504/// ISO-8859-1 as Windows-1252; a file that declares ISO-8859-1 and has none of the bytes 0x80..0x9F (where the two
505/// differ) is tagged `iso-8859-1`, so a merge writes true ISO-8859-1 and a translation with a character outside it
506/// (French oe, the euro sign) becomes UTF-8, never Windows-1252 bytes under an ISO-8859-1 label (LocOS
507/// `text_envelope`, B-bytes gate). A file that does carry those bytes keeps the Windows-1252 tag, so an untouched
508/// merge stays byte-identical.
509fn declared_base(enc: &'static Encoding, label: Option<&str>, data: &[u8]) -> String {
510    if enc == encoding_rs::WINDOWS_1252 && label.is_some_and(is_latin1_label) && !data.iter().any(|b| (0x80..=0x9F).contains(b)) {
511        return LATIN1.to_string();
512    }
513    enc.name().to_ascii_lowercase()
514}
515
516const LATIN1: &str = "iso-8859-1";
517
518fn is_latin1_label(l: &str) -> bool {
519    matches!(
520        l.to_ascii_lowercase().as_str(),
521        "iso-8859-1" | "iso8859-1" | "iso88591" | "iso_8859-1" | "iso_8859-1:1987" | "latin1" | "l1" | "cp819" | "ibm819" | "csisolatin1" | "iso-ir-100"
522    )
523}
524
525/// Declarations live at the top of a file: only those in the first 4096 characters are the file's own. A page that
526/// embeds another page (a forum export with a second `<meta charset>` deep in its body) has text there that looks
527/// like a declaration but is content, and must come back as it was.
528fn split_head(text: &str) -> (&str, &str) {
529    let cut = text.char_indices().nth(4096).map_or(text.len(), |(i, _)| i);
530    text.split_at(cut)
531}
532
533fn rewrite_declared(text: &str) -> String {
534    let (head, tail) = split_head(text);
535    let mut out = decl_re().replace_all(head, |c: &regex::Captures| format!("{}UTF-8", &c[1])).into_owned();
536    out.push_str(tail);
537    out
538}
539
540/// `text` with every charset declaration that names a charset other than UTF-8 (`<?xml encoding>`, `<meta
541/// charset>`, a PO `Content-Type`) rewritten to say UTF-8. For a writer that produces UTF-8 itself.
542pub fn declare_utf8(text: &str) -> String {
543    // declarations live at the top of a file; text further down that looks like one is content
544    let mut cut = text.len().min(4096);
545    while !text.is_char_boundary(cut) {
546        cut -= 1;
547    }
548    let (head, tail) = text.split_at(cut);
549    let mut out = decl_re()
550        .replace_all(head, |c: &regex::Captures| {
551            if c[2].eq_ignore_ascii_case("UTF-8") || c[2].eq_ignore_ascii_case("UTF8") {
552                c[0].to_string()
553            } else {
554                format!("{}UTF-8", &c[1])
555            }
556        })
557        .into_owned();
558    out.push_str(tail);
559    out
560}
561
562fn done(text: String, base: &str, label: Option<&str>, warnings: Vec<Warning>, l: &Limits) -> Result<Decoded, Error> {
563    check_lines(&text, l)?;
564    let encoding = tag(base, &text, label);
565    Ok(Decoded { text, encoding, warnings })
566}
567
568/// Reads a text file (see the module docs for the order of attempts).
569pub fn decode_text(data: &[u8], o: &DecodeOptions) -> Result<Decoded, Error> {
570    let mut d = decode_text_inner(data, o)?;
571    // GBK files from Windows write the euro sign as the single byte 0x80; the GB18030 spelling is A2 E3. A file
572    // that uses A2 E3 keeps it on merge (an untouched merge is byte-identical); the tag says so.
573    if base(&d.encoding) == "gbk" && d.text.contains('\u{20AC}') && gbk_has_a2e3(data) {
574        d.encoding.push_str(";euro=a2e3");
575    }
576    Ok(d)
577}
578
579/// True when the GBK / GB18030 bytes hold the character A2 E3 (not the two bytes straddling two characters, such as
580/// a trail byte A2 followed by a lead byte E3).
581fn gbk_has_a2e3(data: &[u8]) -> bool {
582    let mut i = 0;
583    while i < data.len() {
584        let b = data[i];
585        if !(0x81..=0xFE).contains(&b) || i + 1 >= data.len() {
586            i += 1;
587        } else if (0x30..=0x39).contains(&data[i + 1]) {
588            i += 4; // a GB18030 four-byte form
589        } else {
590            if b == 0xA2 && data[i + 1] == 0xE3 {
591                return true;
592            }
593            i += 2;
594        }
595    }
596    false
597}
598
599fn decode_text_inner(data: &[u8], o: &DecodeOptions) -> Result<Decoded, Error> {
600    crate::guard::check_input(data, &o.limits)?;
601    let locale = o.source_lang.unwrap_or("");
602    let hint = source_encoding(locale);
603    let (body, bom) = match data.strip_prefix(BOM8) {
604        Some(r) => (r, true),
605        None => (data, false),
606    };
607    if let Ok(s) = std::str::from_utf8(body) {
608        let mut w = Vec::new();
609        if let Some(h) = hint {
610            if let Some(m) = legacy_as_utf8(body, s, h, locale) {
611                w.push(m);
612            }
613        }
614        if o.declared && !bom && s.is_ascii() {
615            // a pure-ASCII file that declares another charset (an ISO-8859-2 PO file without accents yet): read
616            // it as that charset, so text added to it later is written in it, not as UTF-8 under its declaration
617            let named = declared_label(body).map(|l| l.to_ascii_lowercase());
618            let skip = matches!(named.as_deref(), None | Some("utf-8" | "utf8" | "us-ascii" | "ascii" | "charset"));
619            if let (false, Some(e)) = (skip, declared_encoding(body)) {
620                if e != encoding_rs::UTF_8 && e != encoding_rs::UTF_16LE && e != encoding_rs::UTF_16BE {
621                    let label = declared_label(body);
622                    return done(rewrite_declared(s), &declared_base(e, label.as_deref(), body), label.as_deref(), w, &o.limits);
623                }
624            }
625        }
626        // a UTF-8 file that declares another charset keeps the label in its tag, so a merge asked for UTF-8
627        // ([`MergeOptions`]) can rewrite the false declaration; the bytes of an untouched merge do not change
628        let label = if o.declared && !s.is_ascii() {
629            declared_label(body).filter(|l| !matches!(l.to_ascii_lowercase().as_str(), "utf-8" | "utf8" | "us-ascii" | "ascii" | "charset"))
630        } else {
631            None
632        };
633        return done(s.to_string(), if bom { "utf-8-bom" } else { "utf-8" }, label.as_deref(), w, &o.limits);
634    }
635    // In a format that declares its charset (XML, HTML, PO, ...) a byte order mark is a declaration too: bytes
636    // that are not valid in it are refused, never read with a fallback code page (lxml in LocOS refuses them). An
637    // undeclared format falls back to a code page, as LocOS's `read_text_upload` does; LocOS's plain text and
638    // subtitle readers instead read UTF-8 with replacement characters (`lossy_after_utf8_bom`).
639    if bom {
640        let bad = std::str::from_utf8(body).err().map_or(0, |e| e.valid_up_to());
641        if o.lossy_after_utf8_bom {
642            return done(String::from_utf8_lossy(body).into_owned(), "utf-8-bom", None, Vec::new(), &o.limits);
643        }
644        if o.declared {
645            return Err(enc_err(format!(
646            "This file starts with a UTF-8 byte order mark but is not valid UTF-8 (byte 0x{:02x} at position {}). Re-save the file as UTF-8.",
647            body.get(bad).copied().unwrap_or(0),
648            bad + 3
649            )));
650        }
651        // BOM read version 2 (LocOS subtitle readers): the mark is a mark, the rest an undeclared legacy file
652        if o.mark_before_legacy && !o.declared {
653            let mut d = decode_text_inner(body, &DecodeOptions { mark_before_legacy: false, ..*o })?;
654            if !matches!(base(&d.encoding), "utf-8" | "utf-8-bom" | "utf-16le" | "utf-16be") {
655                d.encoding.push_str(";bom8");
656                return Ok(d);
657            }
658        }
659        // an undeclared format reads it as LocOS's `read_text_upload` does: the code page fallback below
660    }
661    if data.starts_with(&[0xFF, 0xFE]) || data.starts_with(&[0xFE, 0xFF]) {
662        let (e, name) = if data[0] == 0xFF { (encoding_rs::UTF_16LE, "utf-16le") } else { (encoding_rs::UTF_16BE, "utf-16be") };
663        let decoded = e.decode_without_bom_handling_and_without_replacement(&data[2..]);
664        if decoded.is_none() && o.declared {
665            return Err(enc_err(format!("This file starts with a {} byte order mark but is not valid {}. Re-save the file as UTF-8.", name.to_ascii_uppercase(), name.to_ascii_uppercase())));
666        }
667        if let Some(s) = decoded {
668            let (text, label) = if o.declared {
669                let head = e.decode_without_bom_handling(&data[2..data.len().min(8194)]).0.into_owned();
670                let l = decl_re().captures(&head).and_then(|c| c.get(2)).map(|m| m.as_str().to_string());
671                (rewrite_declared(&s), l)
672            } else {
673                (s.into_owned(), None)
674            };
675            return done(text, name, label.as_deref(), Vec::new(), &o.limits);
676        }
677    }
678    if o.declared {
679        if let Some(e) = declared_encoding(data) {
680            let label = declared_label(data);
681            let name = label.clone().unwrap_or_else(|| e.name().to_string());
682            // the file says UTF-8 (or a code page it does not fit): refused, as an XML parser and LocOS do
683            if e == encoding_rs::UTF_8 {
684                let bad = std::str::from_utf8(data).err().map_or(0, |e| e.valid_up_to());
685                return Err(bad_declared(&name, data, bad));
686            }
687            // a declared Windows-1252 / ISO-8859-1 file is read in it whatever the source language (B-SIDE W6 ts-1:
688            // a Japanese project read it as Shift_JIS); bytes it cannot read fall through to the default path
689            let latin = e == encoding_rs::WINDOWS_1252;
690            if declared_ok(e) || latin {
691                match strict(e, data) {
692                    Ok(s) => {
693                        // the same tag the default path gives a Latin-1 file (`iso-8859-1` when no C1 byte is used)
694                        let b = if latin { declared_base(e, label.as_deref(), data) } else { e.name().to_ascii_lowercase() };
695                        return done(rewrite_declared(&s), &b, label.as_deref(), Vec::new(), &o.limits);
696                    }
697                    Err(pos) => {
698                        // Windows-1255 holds all of ISO-8859-8 at the same bytes, plus the vowel points pages use;
699                        // the declared label stays, so a merge writes the same bytes back
700                        let hebrew = e == encoding_rs::ISO_8859_8 || e == encoding_rs::ISO_8859_8_I;
701                        if let Some(s) = hebrew.then(|| strict(encoding_rs::WINDOWS_1255, data).ok()).flatten() {
702                            return done(rewrite_declared(&s), "windows-1255", label.as_deref(), Vec::new(), &o.limits);
703                        }
704                        if !declared_if_strict(e) && !latin {
705                            return Err(bad_declared(&name, data, pos));
706                        }
707                    }
708                }
709            }
710        }
711    }
712    if looks_binary(data) {
713        return Err(enc_err("This file is not valid UTF-8 and looks like a binary file, not text. Re-save the file as UTF-8."));
714    }
715    let mut warnings = Vec::new();
716    let (text, enc) = decode_legacy(data, hint, locale, &mut warnings)?;
717    if o.declared {
718        // the label the file carries stays with it, so an untouched merge writes it back
719        let label = declared_label(data);
720        if label.is_none() {
721            if let Some(m) = late_declaration(&text, enc) {
722                add(&mut warnings, m);
723            }
724        }
725        return done(rewrite_declared(&text), &declared_base(enc, label.as_deref(), data), label.as_deref(), warnings, &o.limits);
726    }
727    done(text, &enc.name().to_ascii_lowercase(), None, warnings, &o.limits)
728}
729
730/// What [`decode_source_legacy`] returns: the text, the code page it was read in and the warnings.
731pub type SourceLegacy = Result<(String, &'static Encoding, Vec<Warning>), Error>;
732
733/// For a reader with its own BOM and UTF-8 handling (ini, yaml, js modules): the last step of [`decode_text`] for
734/// bytes that are not UTF-8 and carry no byte order mark. Returns `None` when `source_lang` has no code page of its
735/// own (the caller keeps its Windows-1252 path); else the text, the code page it was read in and the warnings
736/// (the letters look wrong in it, or it did not read and Windows-1252 was used). The caller has already refused
737/// binary files.
738pub fn decode_source_legacy(data: &[u8], source_lang: Option<&str>) -> Option<SourceLegacy> {
739    let locale = source_lang.unwrap_or("");
740    let hint = source_encoding(locale)?;
741    let mut warnings = Vec::new();
742    Some(decode_legacy(data, Some(hint), locale, &mut warnings).map(|(t, e)| (t, e, warnings)))
743}
744
745fn where_(hint: Option<&'static Encoding>, locale: &str) -> String {
746    if hint.is_some() && !locale.is_empty() {
747        format!(", the code page of the project's source language {locale},")
748    } else {
749        String::new()
750    }
751}
752
753fn bad_declared(name: &str, data: &[u8], pos: usize) -> Error {
754    enc_err(format!(
755        "This file declares the encoding {name} but its bytes are not valid in it (byte 0x{:02x} at position {pos}). Re-save the file as UTF-8.",
756        data.get(pos).copied().unwrap_or(0)
757    ))
758}
759
760fn bad_byte(label: &str, data: &[u8], pos: usize, also: &str) -> Error {
761    enc_err(format!(
762        "This file is not valid UTF-8 and could not be read as {label}{also} (byte 0x{:02x} at position {pos}). Re-save the file as UTF-8.",
763        data.get(pos).copied().unwrap_or(0)
764    ))
765}
766
767/// The last step: no UTF-8, no BOM, no usable declaration. The source language's code page, or Windows-1252.
768fn decode_legacy(
769    data: &[u8],
770    hint: Option<&'static Encoding>,
771    locale: &str,
772    warnings: &mut Vec<Warning>,
773) -> Result<(String, &'static Encoding), Error> {
774    let primary = hint.unwrap_or(encoding_rs::WINDOWS_1252);
775    let where_s = where_(hint, locale);
776    let comma = if where_s.is_empty() { "," } else { where_s.as_str() };
777    let (text, primary) = match strict(primary, data) {
778        Ok(t) => (t, primary),
779        Err(pos) => {
780            let wider = (primary == encoding_rs::GBK).then_some(encoding_rs::GB18030);
781            match wider.and_then(|w| strict(w, data).ok().map(|t| (t, w))) {
782                Some(x) => x,
783                None if primary == encoding_rs::WINDOWS_1252 => return Err(bad_byte(&cp_label(primary), data, pos, "")),
784                None => {
785                    // the source code page cannot read it: Windows-1252 with a warning, or refuse
786                    let alt = strict(encoding_rs::WINDOWS_1252, data)
787                        .map_err(|_| bad_byte(&cp_label(primary), data, pos, &format!("{where_s} or Windows-1252 either")))?;
788                    add(
789                        warnings,
790                        format!(
791                            "This file is not UTF-8 and declares no encoding. It could not be read as {}{where_s} so it was read as Western European (Windows-1252) instead. {RESAVE}",
792                            cp_label(primary)
793                        ),
794                    );
795                    return Ok((alt, encoding_rs::WINDOWS_1252));
796                }
797            }
798        }
799    };
800    if let Some(reason) = text_looks_garbled(&text, primary, locale, data) {
801        if primary != encoding_rs::WINDOWS_1252 {
802            if let Ok(alt) = strict(encoding_rs::WINDOWS_1252, data) {
803                if text_looks_garbled(&alt, encoding_rs::WINDOWS_1252, "", data).is_none() {
804                    add(
805                        warnings,
806                        format!(
807                            "This file is not UTF-8 and declares no encoding. Read as {}{comma} its letters looked wrong ({reason}), so it was read as Western European (Windows-1252) instead. {RESAVE}",
808                            cp_label(primary)
809                        ),
810                    );
811                    return Ok((alt, encoding_rs::WINDOWS_1252));
812                }
813            }
814        }
815        add(
816            warnings,
817            format!(
818                "This file is not UTF-8 and declares no encoding, so it was read as {}{comma} but its letters look wrong ({reason}). {RESAVE}",
819                cp_label(primary)
820            ),
821        );
822    }
823    Ok((text, primary))
824}
825
826/// A file with no declaration in its first 4 KB that names another legacy charset further down (a page whose
827/// `<meta charset>` comes after a long script): that later one is not the file's declaration (it may be content),
828/// so the file was read in `enc`; the warning says so, so a page that really is in the later charset is not
829/// silently read as the wrong one.
830fn late_declaration(text: &str, enc: &'static Encoding) -> Option<String> {
831    decl_re().captures_iter(text).find_map(|c| {
832        let name = c.get(2)?.as_str();
833        let e = label_encoding(name)?;
834        (e != enc && e != encoding_rs::UTF_8 && e != encoding_rs::UTF_16LE && e != encoding_rs::UTF_16BE).then(|| {
835            format!(
836                "This file is not UTF-8 and declares no encoding in its first 4096 characters, so it was read as {}. A declaration of {name} further down was not used. {RESAVE}",
837                cp_label(enc)
838            )
839        })
840    })
841}
842
843fn add(w: &mut Vec<Warning>, message: String) {
844    let x = Warning::new("text_encoding", "text encoding", message);
845    if !w.contains(&x) {
846        w.push(x);
847    }
848}
849
850/// A few Chinese, Japanese or Korean characters are valid UTF-8 by accident surprisingly often. The file stays
851/// UTF-8 (UTF-8 comes first), but in a project whose source language is CJK it warns when all of these hold: at
852/// most 16 non-ASCII characters, every one in U+0080..U+07FF, at least one past Latin Extended-A, no CJK at all,
853/// and the source code page reads the same bytes cleanly as CJK text.
854fn legacy_as_utf8(data: &[u8], text: &str, hint: &'static Encoding, locale: &str) -> Option<Warning> {
855    if !crate::garble::is_cjk_code_page(hint) {
856        return None;
857    }
858    let mut odd = false;
859    for (n, c) in text.chars().filter(|c| !c.is_ascii()).enumerate() {
860        if n + 1 > 16 || (c as u32) > 0x7FF {
861            return None;
862        }
863        odd = odd || (c as u32) >= 0x180;
864    }
865    if !odd {
866        return None;
867    }
868    let alt = strict(hint, data).ok()?;
869    if !alt.chars().any(crate::garble::is_cjk_char) || text_looks_garbled(&alt, hint, locale, &[]).is_some() {
870        return None;
871    }
872    Some(Warning::new(
873        "text_encoding",
874        "text encoding",
875        format!(
876            "This file is valid UTF-8, so it was read as UTF-8, but its few non-English letters look wrong for the project's source language {locale} (read as {} the same bytes give Chinese, Japanese or Korean text). {RESAVE}",
877            cp_label(hint)
878        ),
879    ))
880}
881
882/// For a reader with its own legacy decode (Java `.properties` are ISO-8859-1 by specification): the warning
883/// to attach when `text`, read as `enc`, looks wrong for the project's source language `locale`.
884pub fn warn_if_garbled(text: &str, enc: &'static Encoding, locale: &str, label: Option<&str>) -> Option<Warning> {
885    if locale.is_empty() {
886        return None;
887    }
888    let reason = text_looks_garbled(text, enc, locale, &[])?;
889    Some(Warning::new(
890        "text_encoding",
891        "text encoding",
892        format!(
893            "This file is not UTF-8, so it was read as {}, but its letters look wrong ({reason}). {RESAVE}",
894            label.map(str::to_string).unwrap_or_else(|| cp_label(enc))
895        ),
896    ))
897}
898
899struct Envelope<'a> {
900    base: &'a str,
901    nl: &'static str,
902    label: Option<&'a str>,
903    /// GBK file whose euro sign was the two bytes A2 E3 (GB18030's spelling)
904    euro_a2e3: bool,
905    /// leading U+FEFF characters of the decoded text that are content (`feff=n`)
906    feff: usize,
907    /// a UTF-8 byte order mark stood before the legacy bytes (`bom8`, [`DecodeOptions::mark_before_legacy`])
908    bom8: bool,
909}
910
911fn leading_marks(text: &str) -> usize {
912    text.chars().take_while(|c| *c == '\u{FEFF}').count()
913}
914
915/// `text` without the one leading U+FEFF a writer may have put in front as its byte order mark, which the encoder
916/// writes itself. The decoder records how many leading U+FEFF of the file's text are content (`feff=n` in the
917/// skeleton tag, a file that starts with two marks); only a U+FEFF beyond those is taken off, so an untouched merge
918/// of such a file is exact, and a writer that adds one more U+FEFF in front (php, subtext, csv) still gets one.
919pub fn strip_own_mark<'t>(text: &'t str, encoding: &str) -> &'t str {
920    if leading_marks(text) > parse_tag(encoding).feff {
921        &text['\u{FEFF}'.len_utf8()..]
922    } else {
923        text
924    }
925}
926
927/// Marks a skeleton encoding tag with the file's own bytes, for a reader of a legacy code page (Shift_JIS, Big5 ...)
928/// whose bytes do not come back the same from the decoded text: the code page maps two byte sequences to one
929/// character (NEC row 13, IBM extensions) and writes only one of them. `written_back` is what the reader's writer
930/// gives for the decoded text; when it is not `bytes`, the original bytes ride along in the tag (`;orig=<base64>`) so
931/// [`original_if_same`] can give an untouched file back exactly. The tag is otherwise unchanged.
932pub fn keep_original(name: &str, bytes: &[u8], written_back: Option<&[u8]>) -> String {
933    if written_back == Some(bytes) {
934        name.to_string()
935    } else {
936        format!("{name};orig={}", crate::b64::encode(bytes))
937    }
938}
939
940/// A tag made by [`keep_original`]: the encoding name without the marker, and the original bytes when it had one.
941pub fn split_original(tag: &str) -> (&str, Option<Vec<u8>>) {
942    match tag.split_once(";orig=") {
943        Some((name, rest)) => {
944            let b64 = rest.split(';').next().unwrap_or("");
945            (name, crate::b64::decode(b64).ok())
946        }
947        None => (tag, None),
948    }
949}
950
951/// The original bytes of a file read with [`keep_original`] when `text` is exactly the text those bytes decode to
952/// (nothing changed), else `None`.
953pub fn original_if_same(tag: &str, text: &str) -> Option<Vec<u8>> {
954    let (name, orig) = split_original(tag);
955    let orig = orig?;
956    let enc = Encoding::for_label(name.as_bytes())?;
957    (enc.decode_without_bom_handling(&orig).0 == text).then_some(orig)
958}
959
960fn parse_tag(t: &str) -> Envelope<'_> {
961    let mut parts = t.split(';');
962    let base = parts.next().unwrap_or("utf-8");
963    let (mut nl, mut label, mut euro_a2e3, mut feff, mut bom8) = ("", None, false, 0, false);
964    for p in parts {
965        match p {
966            "euro=a2e3" => euro_a2e3 = true,
967            "bom8" => bom8 = true,
968            "nl=crlf" => nl = "\r\n",
969            "nl=cr" => nl = "\r",
970            _ => {
971                if let Some(l) = p.strip_prefix("label=") {
972                    label = Some(l);
973                } else if let Some(n) = p.strip_prefix("feff=") {
974                    feff = n.parse().unwrap_or(0);
975                }
976            }
977        }
978    }
979    Envelope { base, nl, label, euro_a2e3, feff, bom8 }
980}
981
982fn with_newlines(text: &str, nl: &str) -> String {
983    let mut out = String::with_capacity(text.len() + text.len() / 16);
984    let mut it = text.chars().peekable();
985    while let Some(c) = it.next() {
986        match c {
987            '\r' => {
988                if it.peek() == Some(&'\n') {
989                    it.next();
990                }
991                out.push_str(nl);
992            }
993            '\n' => out.push_str(nl),
994            c => out.push(c),
995        }
996    }
997    out
998}
999
1000/// [`encode_text`] with [`MergeOptions`]: with `output_encoding` UTF-8 the text is written as UTF-8 whatever the
1001/// original encoding was (a UTF-8 BOM is kept; a UTF-16 BOM or a legacy code page is not), the newline style of the
1002/// original is kept, and an XML, HTML or PO charset declaration that still names another charset is rewritten to
1003/// UTF-8, so the file says what it is.
1004pub fn encode_text_with(text: &str, encoding: &str, opts: &MergeOptions) -> Result<Vec<u8>, Error> {
1005    // LocOS rewrites every declaration of a converted file to UTF-8 when it reads it (not only those near the top)
1006    // and gives each the file's own label back when it writes it. Under the LocOS profile a file that carries a
1007    // label does the same: a declaration further down becomes the file's label (or UTF-8, when the file is written
1008    // as UTF-8). Without the profile it is content and comes back as it was.
1009    let every;
1010    let text = if opts.is_profile(crate::profile::LOCOS) && parse_tag(encoding).label.is_some() {
1011        every = decl_re().replace_all(text, |c: &regex::Captures| format!("{}UTF-8", &c[1])).into_owned();
1012        every.as_str()
1013    } else {
1014        text
1015    };
1016    if opts.output_encoding != OutputEncoding::Utf8 {
1017        return encode_text(text, encoding);
1018    }
1019    Ok(utf8_text(text, encoding, false))
1020}
1021
1022/// [`encode_text_with`] for an HTML page (a format whose LocOS filter reads with `declared=True`). LocOS rewrites
1023/// every charset declaration of a converted page to UTF-8 when it reads it and, when the page has no label of its own
1024/// to give back (its only declaration sits past the first 4096 characters, so it never named the page's charset),
1025/// writes the page as UTF-8: the gate in `encode_like` finds a declaration that does not name the code page. Under the
1026/// LocOS profile a legacy page with no label and such a late declaration does the same. Native mode keeps the
1027/// declaration as content and the code page, as before.
1028pub fn encode_declared_with(text: &str, encoding: &str, opts: &MergeOptions) -> Result<Vec<u8>, Error> {
1029    if opts.is_profile(crate::profile::LOCOS) {
1030        let env = parse_tag(encoding);
1031        let legacy = !(env.base.starts_with("utf-8") || env.base.starts_with("utf-16"));
1032        if legacy && env.label.is_none() && decl_re().is_match(text) {
1033            let every = decl_re().replace_all(text, |c: &regex::Captures| format!("{}UTF-8", &c[1])).into_owned();
1034            return Ok(utf8_text(&every, encoding, false));
1035        }
1036    }
1037    encode_text_with(text, encoding, opts)
1038}
1039
1040/// For a format crate with its own codec and its own encoding names: the bytes to write when `opts` asks for UTF-8
1041/// out ([`OutputEncoding::Utf8`]), or `None` when the crate writes its own encoding (`Keep`). The text is written as
1042/// UTF-8 (a UTF-8 BOM is kept when `encoding` is `utf-8-bom`; a UTF-16 BOM is not), and an XML, HTML or PO charset
1043/// declaration that names `encoding` (or UTF-16, for a UTF-16 file) is rewritten to say UTF-8. Newlines stay as
1044/// they are in `text`, except that a model envelope's `nl=` is honoured.
1045pub fn utf8_output(text: &str, encoding: &str, opts: &MergeOptions) -> Option<Vec<u8>> {
1046    (opts.output_encoding == OutputEncoding::Utf8).then(|| utf8_text(text, encoding, true))
1047}
1048
1049fn utf8_text(text: &str, encoding: &str, base_is_label: bool) -> Vec<u8> {
1050    let env = parse_tag(encoding);
1051    let text = strip_own_mark(text, encoding);
1052    let mut out = if env.nl.is_empty() { text.to_string() } else { with_newlines(text, env.nl) };
1053    let is_utf8 = |l: &str| l.eq_ignore_ascii_case("utf-8") || l.eq_ignore_ascii_case("utf8") || l.eq_ignore_ascii_case("utf-8-bom");
1054    let mut labels: Vec<&str> = env.label.into_iter().collect();
1055    if base_is_label {
1056        labels.push(env.base);
1057        if env.base.to_ascii_lowercase().starts_with("utf-16") {
1058            labels.push("utf-16");
1059        }
1060    }
1061    labels.retain(|l| !is_utf8(l));
1062    if !labels.is_empty() {
1063        out = decl_re()
1064            .replace_all(&out, |c: &regex::Captures| {
1065                if labels.iter().any(|l| c[2].eq_ignore_ascii_case(l)) {
1066                    format!("{}UTF-8", &c[1])
1067                } else {
1068                    c[0].to_string()
1069                }
1070            })
1071            .into_owned();
1072    }
1073    let mut v = Vec::with_capacity(out.len() + 3);
1074    if env.base == "utf-8-bom" || env.bom8 {
1075        v.extend_from_slice(BOM8);
1076    }
1077    v.extend_from_slice(out.as_bytes());
1078    v
1079}
1080
1081/// Writes the merged `text` in the envelope `encoding` (a skeleton tag from [`decode_text`], or plain `"utf-8"` /
1082/// `"utf-8-bom"`). Text that does not fit the original legacy encoding is written as UTF-8.
1083///
1084/// A legacy code page result that the same extract would refuse as binary ([`looks_binary`]: a merge that shortened
1085/// a file below its control-byte allowance) is written as UTF-8 instead, which LocOS also writes and which always
1086/// reads back ([`legacy_output_or_utf8`]).
1087pub fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, Error> {
1088    let out = encode_text_as_is(text, encoding, true)?;
1089    legacy_output_or_utf8(out, text, encoding)
1090}
1091
1092/// [`encode_text`] for a file nothing was changed in: the bytes it was read from. The one difference: a page
1093/// labelled ISO-8859-8 that was read as Windows-1255 keeps its own bytes even when it holds a sign that
1094/// [`encode_text`] would switch to UTF-8 for (LocOS gives such a page back as it was when nothing in it changed,
1095/// and writes UTF-8 only for a changed page). A reader that refuses a file which does not write back unchanged
1096/// checks with this function.
1097pub fn encode_text_unchanged(text: &str, encoding: &str) -> Result<Vec<u8>, Error> {
1098    let out = encode_text_as_is(text, encoding, false)?;
1099    legacy_output_or_utf8(out, text, encoding)
1100}
1101
1102/// For a writer with its own legacy codec: `out` (the bytes it wrote for `text` under the skeleton tag `encoding`)
1103/// unless they are a legacy code page that [`decode_text`] would refuse as binary; then `text` written as UTF-8
1104/// (newline style kept). Every filter that writes a legacy code page goes through this, so a merge never writes a
1105/// file its own extract refuses.
1106pub fn legacy_output_or_utf8(out: Vec<u8>, text: &str, encoding: &str) -> Result<Vec<u8>, Error> {
1107    let b = base(encoding);
1108    let legacy = !matches!(b, "utf-8" | "utf-8-bom" | "utf-16le" | "utf-16be");
1109    if legacy && std::str::from_utf8(&out).is_err() && looks_binary(&out) {
1110        return encode_text_as_is(text, &format!("utf-8{}", &encoding[b.len()..]), true);
1111    }
1112    Ok(out)
1113}
1114
1115fn encode_text_as_is(text: &str, encoding: &str, changed: bool) -> Result<Vec<u8>, Error> {
1116    let mut out = encode_text_unmarked(text, encoding, changed)?;
1117    // a mark read before the legacy bytes goes back in front of whatever was written (UTF-8 or the code page)
1118    if parse_tag(encoding).bom8 {
1119        out.splice(0..0, BOM8.iter().copied());
1120    }
1121    Ok(out)
1122}
1123
1124/// `changed`: false for a file nothing was changed in (see [`encode_text_unchanged`]).
1125fn encode_text_unmarked(text: &str, encoding: &str, changed: bool) -> Result<Vec<u8>, Error> {
1126    let env = parse_tag(encoding);
1127    let text = strip_own_mark(text, encoding);
1128    let normalized;
1129    let text = if env.nl.is_empty() {
1130        text
1131    } else {
1132        normalized = with_newlines(text, env.nl);
1133        &normalized
1134    };
1135    let utf8 = |bom: bool| {
1136        let mut v = Vec::with_capacity(text.len() + 3);
1137        if bom {
1138            v.extend_from_slice(BOM8);
1139        }
1140        v.extend_from_slice(text.as_bytes());
1141        v
1142    };
1143    match env.base {
1144        "utf-8" => return Ok(utf8(false)),
1145        "utf-8-bom" => return Ok(utf8(true)),
1146        _ => {}
1147    }
1148    // a declared charset: each declaration parse rewrote to UTF-8 gets its own label back. The whole text is
1149    // looked at, not only its head: a longer translation before a declaration near the 4096th character moves it
1150    // out of the head, and it must still say the charset the bytes are written in
1151    let restored = match env.label {
1152        Some(l) => decl_re()
1153            .replace_all(text, |c: &regex::Captures| {
1154                if c[2].eq_ignore_ascii_case("UTF-8") {
1155                    format!("{}{l}", &c[1])
1156                } else {
1157                    c[0].to_string()
1158                }
1159            })
1160            .into_owned(),
1161        None => text.to_string(),
1162    };
1163    let utf16 = match env.base {
1164        "utf-16le" => Some(false),
1165        "utf-16be" => Some(true),
1166        _ => None,
1167    };
1168    if let Some(be) = utf16 {
1169        let mut v: Vec<u8> = if be { vec![0xFE, 0xFF] } else { vec![0xFF, 0xFE] };
1170        for u in restored.encode_utf16() {
1171            v.extend_from_slice(&if be { u.to_be_bytes() } else { u.to_le_bytes() });
1172        }
1173        return Ok(v);
1174    }
1175    if env.base == LATIN1 {
1176        // true ISO-8859-1: every character must be U+0000..U+00FF, else UTF-8 under the UTF-8 labels
1177        let agree = decl_re().captures_iter(split_head(&restored).0).all(|c| {
1178            let name = c.get(2).map_or("", |m| m.as_str());
1179            is_latin1_label(name) || name.eq_ignore_ascii_case("us-ascii")
1180        });
1181        if !agree || restored.chars().any(|c| (c as u32) > 0xFF) {
1182            return Ok(utf8(false));
1183        }
1184        return Ok(restored.chars().map(|c| c as u32 as u8).collect());
1185    }
1186    let Some(enc) = Encoding::for_label(env.base.as_bytes()) else {
1187        return Err(Error::Write(format!("unknown encoding {}", env.base)));
1188    };
1189    // the bytes and every declaration in the file must agree; if one does not, write UTF-8 under the UTF-8 labels
1190    let agree = decl_re().captures_iter(split_head(&restored).0).all(|c| {
1191        let name = c.get(2).map_or("", |m| m.as_str());
1192        label_encoding(name) == Some(enc)
1193            || env.label.is_some_and(|l| l.eq_ignore_ascii_case(name))
1194            || name.eq_ignore_ascii_case("us-ascii")
1195    });
1196    if !agree {
1197        return Ok(utf8(false));
1198    }
1199    // A page labelled ISO-8859-8 that was read as Windows-1255 (it holds vowel points) keeps its label only while
1200    // no character is one that Windows-1255 writes at a byte meaning another sign under that label (curly quotes,
1201    // dashes, the ellipsis, the euro and shekel signs): a browser would show a C1 control or the currency sign.
1202    // Such a page is written as UTF-8 (LocOS #810 gate, G7).
1203    if changed && enc == encoding_rs::WINDOWS_1255 {
1204        let says_8859_8 = decl_re().captures_iter(split_head(&restored).0).any(|c| {
1205            let name = c.get(2).map_or("", |m| m.as_str());
1206            matches!(label_encoding(name), Some(e) if e == encoding_rs::ISO_8859_8 || e == encoding_rs::ISO_8859_8_I)
1207        });
1208        if says_8859_8 && restored.chars().any(|c| cp1255_only_signs().contains(&c)) {
1209            return Ok(utf8(false));
1210        }
1211    }
1212    // GB18030 writes everything GBK does, with the same bytes, and the four-byte forms GBK's encoder lacks
1213    // (B6); only the euro sign differs: GBK and Windows code page 936 readers expect the single byte 0x80
1214    if enc == encoding_rs::GBK && !env.euro_a2e3 {
1215        return Ok(encode_gbk(&restored).0);
1216    }
1217    let writer = if enc == encoding_rs::GBK { encoding_rs::GB18030 } else { enc };
1218    let (bytes, _, unmappable) = writer.encode(&restored);
1219    if unmappable {
1220        return Ok(utf8(false));
1221    }
1222    Ok(bytes.into_owned())
1223}
1224
1225/// The characters Windows-1255 writes at a byte that ISO-8859-8 reads as another character (both define the byte):
1226/// the C1 range signs Windows-1255 uses for curly quotes, dashes, the ellipsis, the euro and the new shekel sign.
1227fn cp1255_only_signs() -> &'static [char] {
1228    static S: OnceLock<Vec<char>> = OnceLock::new();
1229    S.get_or_init(|| {
1230        (0x80u8..=0xFF)
1231            .filter_map(|b| {
1232                let one = [b];
1233                let a = encoding_rs::WINDOWS_1255.decode_without_bom_handling_and_without_replacement(&one)?;
1234                let c = encoding_rs::ISO_8859_8.decode_without_bom_handling_and_without_replacement(&one)?;
1235                (a != c).then(|| a.chars().next()).flatten()
1236            })
1237            .collect()
1238    })
1239}
1240
1241/// Encodes `text` for a GBK / GB2312 / code page 936 file: GB18030's bytes (it holds everything GBK does, plus
1242/// four-byte forms for the rest), except that the euro sign U+20AC is the single byte 0x80, which is what GBK and
1243/// Windows readers expect (GB18030's A2 E3 is read as a different character by some of them). The flag is true
1244/// when a character has no mapping at all (never for GB18030; kept for the caller's fallback logic).
1245pub fn encode_gbk(text: &str) -> (Vec<u8>, bool) {
1246    let mut out = Vec::with_capacity(text.len() + text.len() / 2);
1247    let mut bad = false;
1248    for (i, piece) in text.split('\u{20AC}').enumerate() {
1249        if i > 0 {
1250            out.push(0x80);
1251        }
1252        let (b, _, unmappable) = encoding_rs::GB18030.encode(piece);
1253        bad |= unmappable;
1254        out.extend_from_slice(&b);
1255    }
1256    (out, bad)
1257}
1258
1259/// True when `tag` names a legacy (neither UTF-8 nor UTF-16) encoding.
1260pub fn is_legacy(tag: &str) -> bool {
1261    !matches!(parse_tag(tag).base, "utf-8" | "utf-8-bom" | "utf-16le" | "utf-16be")
1262}
1263
1264/// A plain name for the encoding of a tag, for messages ("Greek (Windows-1253)").
1265pub fn describe(tag: &str) -> String {
1266    let b = parse_tag(tag).base;
1267    match Encoding::for_label(b.as_bytes()) {
1268        Some(e) if is_legacy(tag) => cp_label(e),
1269        _ => b.to_string(),
1270    }
1271}
1272
1273#[cfg(test)]
1274mod tests {
1275    use super::*;
1276
1277    fn dec(bytes: &[u8], lang: Option<&str>, declared: bool) -> Result<Decoded, Error> {
1278        let o = DecodeOptions { declared, source_lang: lang, limits: Limits::default(), lossy_after_utf8_bom: false, mark_before_legacy: false };
1279        decode_text(bytes, &o)
1280    }
1281
1282    fn legacy(enc: &'static Encoding, s: &str) -> Vec<u8> {
1283        let (b, _, bad) = enc.encode(s);
1284        assert!(!bad);
1285        b.into_owned()
1286    }
1287
1288    /// LocOS BOM read version 2 (#799.4, #800.4; B-SIDE W6 st-1, ass-1): with `mark_before_legacy` a UTF-8 BOM
1289    /// before Windows-1252 bytes is a mark, the rest is read in the code page; the mark comes back on merge.
1290    #[test]
1291    fn mark_before_legacy_bytes() {
1292        let data = b"\xef\xbb\xbfCaf\xe9\nSecond\n";
1293        let o = DecodeOptions::with_limits(Limits::default()).mark_before_legacy();
1294        let d = decode_text(data, &o).unwrap();
1295        assert_eq!(d.text, "Caf\u{e9}\nSecond\n");
1296        assert_eq!(d.encoding, "windows-1252;bom8");
1297        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), data.to_vec());
1298        // UTF-8 out (the LocOS profile): the mark, then UTF-8
1299        let opts = MergeOptions::new().with_output_encoding(OutputEncoding::Utf8);
1300        assert_eq!(encode_text_with(&d.text, &d.encoding, &opts).unwrap(), "\u{feff}Caf\u{e9}\nSecond\n".as_bytes());
1301        assert_eq!(utf8_output(&d.text, &d.encoding, &opts).unwrap(), "\u{feff}Caf\u{e9}\nSecond\n".as_bytes());
1302        // without the option the mark's bytes are code-page text, as before
1303        let d = decode_text(data, &DecodeOptions::with_limits(Limits::default())).unwrap();
1304        assert!(d.text.starts_with("\u{ef}\u{bb}\u{bf}Caf"), "{:?}", d.text);
1305        // a valid UTF-8 file after the mark is unchanged
1306        let d = decode_text("\u{feff}Caf\u{e9}".as_bytes(), &o).unwrap();
1307        assert_eq!((d.text.as_str(), d.encoding.as_str()), ("Caf\u{e9}", "utf-8-bom"));
1308    }
1309
1310    #[test]
1311    fn utf8_and_bom_are_kept_and_written_back() {
1312        let d = dec("h\u{e9}llo\r\nw\u{f6}rld\r\n".as_bytes(), None, false).unwrap();
1313        assert_eq!(d.encoding, "utf-8;nl=crlf");
1314        assert!(d.warnings.is_empty());
1315        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), "h\u{e9}llo\r\nw\u{f6}rld\r\n".as_bytes());
1316        let mut b = BOM8.to_vec();
1317        b.extend_from_slice("x\n".as_bytes());
1318        let d = dec(&b, None, false).unwrap();
1319        assert_eq!(d.encoding, "utf-8-bom");
1320        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1321    }
1322
1323    /// A file with two (or three) byte order marks: the marks after the first are text, and every envelope writes
1324    /// them back; a writer that puts one more U+FEFF in front (its own mark) still gets exactly one taken off.
1325    #[test]
1326    fn a_second_byte_order_mark_is_content_and_kept() {
1327        let utf16 = |be: bool, s: &str| {
1328            let mut v = if be { vec![0xFE, 0xFF] } else { vec![0xFF, 0xFE] };
1329            for u in s.encode_utf16() {
1330                v.extend_from_slice(&if be { u.to_be_bytes() } else { u.to_le_bytes() });
1331            }
1332            v
1333        };
1334        for marks in 1..=2 {
1335            let text = format!("{}a\r\nb\r\n", "\u{FEFF}".repeat(marks));
1336            for b in [[BOM8, text.as_bytes()].concat(), utf16(false, &text), utf16(true, &text)] {
1337                let d = dec(&b, None, false).unwrap();
1338                assert_eq!(d.text, text);
1339                assert!(d.encoding.contains(&format!(";feff={marks}")), "{}", d.encoding);
1340                assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1341                assert_eq!(encode_text(&format!("\u{FEFF}{}", d.text), &d.encoding).unwrap(), b, "own mark taken off");
1342                assert_eq!(locos_skeleton_parts(&locos_skeleton(&d.encoding, &d.text)).unwrap().1, text);
1343                let utf8 = encode_text_with(&d.text, &d.encoding, &MergeOptions { output_encoding: OutputEncoding::Utf8, ..Default::default() }).unwrap();
1344                assert!(utf8.ends_with(text.as_bytes()), "UTF-8 output keeps the content marks");
1345            }
1346        }
1347        // one mark only: the tag and the writer are as before
1348        let d = dec(b"\xEF\xBB\xBFa", None, false).unwrap();
1349        assert_eq!(d.encoding, "utf-8-bom");
1350        assert_eq!(encode_text("\u{FEFF}a", &d.encoding).unwrap(), b"\xEF\xBB\xBFa");
1351        assert_eq!(strip_own_mark("\u{FEFF}a", "utf-8-bom"), "a");
1352        assert_eq!(strip_own_mark("\u{FEFF}a", "utf-8-bom;feff=1"), "\u{FEFF}a");
1353        assert_eq!(strip_own_mark("\u{FEFF}\u{FEFF}a", "utf-16le;nl=crlf;feff=1;label=utf-16"), "\u{FEFF}a");
1354    }
1355
1356    #[test]
1357    fn newline_style_is_restored_for_new_text() {
1358        let d = dec(b"a\r\nb\r\n", None, false).unwrap();
1359        assert_eq!(encode_text("x\ny\r\nz\rw", &d.encoding).unwrap(), b"x\r\ny\r\nz\r\nw");
1360        let d = dec(b"a\rb\r", None, false).unwrap();
1361        assert_eq!(encode_text("x\ny", &d.encoding).unwrap(), b"x\ry");
1362        // mixed endings are left alone
1363        let d = dec(b"a\r\nb\nc", None, false).unwrap();
1364        assert_eq!(d.encoding, "utf-8");
1365        assert_eq!(encode_text("x\ny\r\n", &d.encoding).unwrap(), b"x\ny\r\n");
1366    }
1367
1368    #[test]
1369    fn utf16_with_bom_round_trips() {
1370        let mut b = vec![0xFF, 0xFE];
1371        for u in "Caf\u{e9} \u{4e2d}\r\nok\r\n".encode_utf16() {
1372            b.extend_from_slice(&u.to_le_bytes());
1373        }
1374        let d = dec(&b, None, false).unwrap();
1375        assert_eq!(d.encoding, "utf-16le;nl=crlf");
1376        assert_eq!(d.text, "Caf\u{e9} \u{4e2d}\r\nok\r\n");
1377        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1378        let mut be = vec![0xFE, 0xFF];
1379        for u in "ab".encode_utf16() {
1380            be.extend_from_slice(&u.to_be_bytes());
1381        }
1382        let d = dec(&be, None, false).unwrap();
1383        assert_eq!((d.text.as_str(), d.encoding.as_str()), ("ab", "utf-16be"));
1384        assert_eq!(encode_text("ab", "utf-16be").unwrap(), be);
1385    }
1386
1387    #[test]
1388    fn western_default_is_windows_1252() {
1389        let b = legacy(encoding_rs::WINDOWS_1252, "Caf\u{e9} \u{201c}ok\u{201d}");
1390        let d = dec(&b, None, false).unwrap();
1391        assert_eq!(d.text, "Caf\u{e9} \u{201c}ok\u{201d}");
1392        assert_eq!(d.encoding, "windows-1252");
1393        assert!(d.warnings.is_empty());
1394        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1395        // a translation that does not fit is written as UTF-8
1396        assert_eq!(encode_text("\u{4e2d}", &d.encoding).unwrap(), "\u{4e2d}".as_bytes());
1397        // an undefined Windows-1252 byte is refused, with its position
1398        let e = dec(&[b'a', 0x81, b'b'], None, false).unwrap_err();
1399        assert!(matches!(&e, Error::Encoding(m) if m.contains("0x81") && m.contains("position 1")), "{e}");
1400    }
1401
1402    #[test]
1403    fn source_language_picks_the_code_page() {
1404        let cases: [(&str, &'static Encoding, &str, &str); 7] = [
1405            ("el", encoding_rs::WINDOWS_1253, "\u{39a}\u{3b1}\u{3bb}\u{3b7}\u{3bc}\u{3ad}\u{3c1}\u{3b1} \u{3ba}\u{3cc}\u{3c3}\u{3bc}\u{3b5}", "windows-1253"),
1406            ("ru", encoding_rs::WINDOWS_1251, "\u{41f}\u{440}\u{438}\u{432}\u{435}\u{442}, \u{43c}\u{438}\u{440}. \u{41a}\u{430}\u{43a} \u{434}\u{435}\u{43b}\u{430}?", "windows-1251"),
1407            ("ar", encoding_rs::WINDOWS_1256, "\u{645}\u{631}\u{62d}\u{628}\u{627} \u{628}\u{627}\u{644}\u{639}\u{627}\u{644}\u{645} \u{643}\u{64a}\u{641} \u{62d}\u{627}\u{644}\u{643}", "windows-1256"),
1408            ("ja", encoding_rs::SHIFT_JIS, "\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}\u{3001}\u{4e16}\u{754c}\u{3002}\u{30c6}\u{30b9}\u{30c8}\u{3067}\u{3059}\u{3002}", "shift_jis"),
1409            ("zh-CN", encoding_rs::GBK, "\u{4f60}\u{597d}\u{ff0c}\u{4e16}\u{754c}\u{3002}\u{8fd9}\u{662f}\u{4e00}\u{4e2a}\u{6d4b}\u{8bd5}\u{3002}", "gbk"),
1410            ("zh-TW", encoding_rs::BIG5, "\u{4f60}\u{597d}\u{ff0c}\u{4e16}\u{754c}\u{3002}\u{9019}\u{662f}\u{4e00}\u{500b}\u{6e2c}\u{8a66}\u{3002}", "big5"),
1411            ("ko", encoding_rs::EUC_KR, "\u{c548}\u{b155}\u{d558}\u{c138}\u{c694}, \u{c138}\u{acc4}. \u{d14c}\u{c2a4}\u{d2b8}\u{c785}\u{b2c8}\u{b2e4}.", "euc-kr"),
1412        ];
1413        for (lang, enc, text, name) in cases {
1414            let b = legacy(enc, text);
1415            let d = dec(&b, Some(lang), false).unwrap();
1416            assert_eq!((d.text.as_str(), d.encoding.as_str()), (text, name), "{lang}");
1417            assert!(d.warnings.is_empty(), "{lang}: {:?}", d.warnings);
1418            assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b, "{lang} round trip");
1419        }
1420    }
1421
1422    #[test]
1423    fn four_byte_gb18030_is_read_in_a_chinese_project() {
1424        // a four-byte GB18030 sequence (U+20000): the GBK decoder of encoding_rs is the GB18030 one
1425        let b = legacy(encoding_rs::GB18030, "\u{4f60}\u{597d}\u{20000}\u{4e16}\u{754c}");
1426        let d = dec(&b, Some("zh-CN"), false).unwrap();
1427        assert_eq!(d.text, "\u{4f60}\u{597d}\u{20000}\u{4e16}\u{754c}");
1428        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1429    }
1430
1431    #[test]
1432    fn declared_charset_is_read_rewritten_and_restored() {
1433        let src = "<html><head><meta charset=\"windows-1253\"></head><body>\u{39a}\u{3b1}\u{3bb}\u{3b7}\u{3bc}\u{3ad}\u{3c1}\u{3b1}</body></html>";
1434        let b = legacy(encoding_rs::WINDOWS_1253, src);
1435        let d = dec(&b, Some("en"), true).unwrap();
1436        assert!(d.text.contains("charset=\"UTF-8\"") && d.text.contains("\u{39a}\u{3b1}"));
1437        assert_eq!(d.encoding, "windows-1253;label=windows-1253");
1438        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1439        // text that does not fit is UTF-8 under the UTF-8 label
1440        let out = encode_text(&d.text.replace('\u{3b1}', "\u{4e2d}"), &d.encoding).unwrap();
1441        assert!(String::from_utf8(out).unwrap().contains("charset=\"UTF-8\""));
1442    }
1443
1444    #[test]
1445    fn a_declaration_deep_in_the_body_is_content_and_comes_back_as_written() {
1446        // a page that embeds another page: the second charset name is text, not the file's declaration
1447        let pad = "<p>x</p>".repeat(700);
1448        let src = format!(
1449            "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1251\"></head><body>{pad}<p>\u{41f}\u{440}\u{438}</p><!-- <meta charset=windows-1252> --></body></html>"
1450        );
1451        let b = legacy(encoding_rs::WINDOWS_1251, &src);
1452        let d = dec(&b, Some("en"), true).unwrap();
1453        assert_eq!(d.encoding, "windows-1251;label=windows-1251");
1454        assert!(d.text.contains("charset=UTF-8\"") && d.text.contains("<meta charset=windows-1252>"));
1455        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1456    }
1457
1458    #[test]
1459    fn a_declaration_moved_past_the_head_by_a_longer_translation_still_gets_its_label_back() {
1460        // the page's own declaration sits just inside the first 4096 characters, after a title
1461        let pad = "x".repeat(3900);
1462        let src = format!("<html><head><title>Hi</title><style>{pad}</style><meta charset=\"windows-1251\"></head><body>\u{41f}</body></html>");
1463        let b = legacy(encoding_rs::WINDOWS_1251, &src);
1464        let d = dec(&b, Some("en"), true).unwrap();
1465        assert!(d.text.contains("charset=\"UTF-8\""));
1466        let longer = d.text.replace("<title>Hi</title>", &format!("<title>{}</title>", "\u{41f}".repeat(400)));
1467        let out = encode_text(&longer, &d.encoding).unwrap();
1468        let back = encoding_rs::WINDOWS_1251.decode(&out).0.into_owned();
1469        assert!(back.contains("charset=\"windows-1251\"") && !back.contains("UTF-8"), "the bytes are Windows-1251 and must say so");
1470    }
1471
1472    #[test]
1473    fn a_file_whose_only_declaration_is_past_the_head_is_read_with_a_warning() {
1474        let pad = "<p>x</p>".repeat(600);
1475        let src = format!("<html><head><script>{pad}</script><meta charset=\"windows-1251\"></head><body>\u{41f}\u{440}\u{438}</body></html>");
1476        let b = legacy(encoding_rs::WINDOWS_1251, &src);
1477        let d = dec(&b, Some("en"), true).unwrap();
1478        // not the file's declaration (it may be content): read by the default path, never rewritten, and said so
1479        assert!(d.text.contains("charset=\"windows-1251\""));
1480        assert!(d.warnings.iter().any(|w| w.message.contains("windows-1251 further down")), "{:?}", d.warnings);
1481        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1482        // the same page in the code page it is read in: no warning
1483        let d = dec(&b, Some("ru"), true).unwrap();
1484        assert!(d.text.contains("\u{41f}\u{440}\u{438}") && d.warnings.is_empty(), "{:?}", d.warnings);
1485    }
1486
1487    #[test]
1488    fn declared_hebrew_and_other_rare_charsets_are_read_not_mojibake() {
1489        // ISO-8859-8 was read as Windows-1252 soup before
1490        let src = "<html><head><meta charset=\"iso-8859-8\"></head><body>\u{5e9}\u{5dc}\u{5d5}\u{5dd}</body></html>";
1491        let b = legacy(encoding_rs::ISO_8859_8, src);
1492        let d = dec(&b, None, true).unwrap();
1493        assert!(d.text.contains("\u{5e9}\u{5dc}\u{5d5}\u{5dd}"), "{}", d.text);
1494        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1495        let src = "<meta charset=\"windows-874\"><p>\u{e2a}\u{e27}\u{e31}\u{e2a}\u{e14}\u{e35}</p>";
1496        let b = legacy(encoding_rs::WINDOWS_874, src);
1497        let d = dec(&b, None, true).unwrap();
1498        assert!(d.text.contains("\u{e2a}\u{e27}"), "{}", d.text);
1499        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1500    }
1501
1502    #[test]
1503    fn rare_declared_charsets_never_refuse_a_file_they_used_to_open_and_never_lose_a_character() {
1504        // a page labelled ISO-8859-8 with a Windows-1255 vowel point (qamats, byte 0xC8, undefined in ISO-8859-8)
1505        let mut b = b"<meta charset=\"iso-8859-8\"><p>".to_vec();
1506        b.extend_from_slice(&[0xF9, 0xC8, 0xEC, 0xE5, 0xED]);
1507        b.extend_from_slice(b"</p>");
1508        let d = dec(&b, None, true).unwrap();
1509        assert!(d.text.contains("\u{5e9}\u{5b8}\u{5dc}\u{5d5}\u{5dd}"), "{}", d.text);
1510        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1511        // ISO-8859-6 with a byte it leaves undefined (0xA1): read by the default path as before, not refused
1512        let b = b"<meta charset=\"iso-8859-6\"><p>a\xA1b</p>".to_vec();
1513        let d = dec(&b, None, true).unwrap();
1514        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1515        // Mac Roman and Mac Cyrillic: the unchanged text comes back byte for byte
1516        for (e, s) in [(encoding_rs::MACINTOSH, "<meta charset=\"macintosh\"><p>caf\u{e9} \u{2022}</p>"), (encoding_rs::X_MAC_CYRILLIC, "<meta charset=\"x-mac-cyrillic\"><p>\u{43f}\u{440}\u{438}\u{432}\u{435}\u{442}</p>")] {
1517            let b = legacy(e, s);
1518            let d = dec(&b, None, true).unwrap();
1519            assert!(d.text.contains(&s[s.find("<p>").unwrap()..]), "{}", d.text);
1520            assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1521        }
1522        // a translation the code page cannot hold: the whole file is written as UTF-8 and says so, nothing is replaced
1523        let b = legacy(encoding_rs::ISO_8859_8, "<meta charset=\"iso-8859-8\"><p>\u{5e9}\u{5dc}\u{5d5}\u{5dd}</p>");
1524        let d = dec(&b, None, true).unwrap();
1525        let out = encode_text(&d.text.replace("\u{5e9}\u{5dc}\u{5d5}\u{5dd}", "\u{65e5}\u{672c}"), &d.encoding).unwrap();
1526        let out = String::from_utf8(out).unwrap();
1527        assert!(out.contains("charset=\"UTF-8\"") && out.contains("\u{65e5}\u{672c}"), "{out}");
1528    }
1529
1530    #[test]
1531    fn iso_8859_8_label_over_windows_1255_bytes_becomes_utf8_for_signs_it_lacks() {
1532        let mut b = b"<meta charset=\"iso-8859-8\"><p>".to_vec();
1533        b.extend_from_slice(&[0xF9, 0xC8, 0xEC, 0xE5, 0xED]);
1534        b.extend_from_slice(b"</p>");
1535        let d = dec(&b, None, true).unwrap();
1536        assert!(d.encoding.starts_with("windows-1255"), "{}", d.encoding);
1537        // a curly quote, a dash, an ellipsis, the euro sign, the new shekel sign: not in ISO-8859-8
1538        for sign in ["\u{201c}", "\u{2013}", "\u{2026}", "\u{20ac}", "\u{20aa}"] {
1539            let out = encode_text(&format!("{}{sign}", d.text), &d.encoding).unwrap();
1540            let out = String::from_utf8(out).unwrap_or_else(|_| panic!("{sign:?} was written as code page bytes"));
1541            assert!(out.contains("charset=\"UTF-8\"") && out.contains(sign), "{out}");
1542        }
1543        // a letter and a vowel point both exist in the page's code page: the label stays
1544        let out = encode_text(&format!("{}\u{5d0}\u{5b0}", d.text), &d.encoding).unwrap();
1545        assert!(std::str::from_utf8(&out).is_err() && out.starts_with(b"<meta charset=\"iso-8859-8\">"));
1546        // a page that already holds such a sign: encode_text switches it, an unchanged page gets its own bytes back
1547        let mut b = b"<meta charset=\"iso-8859-8\"><p>".to_vec();
1548        b.extend_from_slice(&[0xF9, 0xC8, 0xEC, 0xE5, 0xED, b' ', 0x93, 0xE0, 0x94]);
1549        let d = dec(&b, None, true).unwrap();
1550        assert!(d.encoding.starts_with("windows-1255"), "{}", d.encoding);
1551        assert!(String::from_utf8(encode_text(&d.text, &d.encoding).unwrap()).unwrap().contains("\u{201c}"));
1552        assert_eq!(encode_text_unchanged(&d.text, &d.encoding).unwrap(), b);
1553    }
1554
1555    #[test]
1556    fn locos_profile_gives_every_declaration_the_files_label_or_utf8() {
1557        // a Windows-1256 page whose first declaration says so and whose second one (past the head) says 1252
1558        let page = format!("<meta charset=\"windows-1256\"><p>{}</p><meta charset=\"windows-1252\">", "x".repeat(5000));
1559        let b = legacy(encoding_rs::WINDOWS_1256, &page);
1560        let d = dec(&b, None, true).unwrap();
1561        assert_eq!(d.encoding, "windows-1256;label=windows-1256");
1562        let locos = MergeOptions::new().with_profile(crate::profile::LOCOS);
1563        // native: the late declaration is content and stays; LocOS: it takes the file's label
1564        assert_eq!(encode_text_with(&d.text, &d.encoding, &MergeOptions::new()).unwrap(), b);
1565        let out = String::from_utf8(encode_text_with(&d.text, &d.encoding, &locos).unwrap()).unwrap();
1566        assert!(out.ends_with("<meta charset=\"windows-1256\">") && !out.contains("1252"), "{}", &out[out.len() - 60..]);
1567        // a translation the code page cannot hold: UTF-8, and no declaration keeps the old label (LocOS)
1568        let text = d.text.replacen("xx", "\u{65e5}\u{672c}", 1);
1569        let out = String::from_utf8(encode_text_with(&text, &d.encoding, &locos).unwrap()).unwrap();
1570        assert!(!out.contains("1256") && !out.contains("1252") && out.matches("charset=\"UTF-8\"").count() == 2, "{}", &out[out.len() - 60..]);
1571    }
1572
1573    #[test]
1574    fn locos_profile_writes_a_legacy_page_with_only_a_late_declaration_as_utf8() {
1575        // the only declaration is past the first 4096 characters: the page is read as Windows-1252 with no label
1576        let page = format!("<html><head><script>/*{}*/</script><meta charset=\"windows-1252\"></head><body><p>Caf\u{e9}</p></body></html>", "x".repeat(5000));
1577        let b = legacy(encoding_rs::WINDOWS_1252, &page);
1578        let d = dec(&b, None, true).unwrap();
1579        assert_eq!(d.encoding, "windows-1252");
1580        let locos = MergeOptions::new().with_profile(crate::profile::LOCOS);
1581        // native: the code page and the declaration as they were
1582        assert_eq!(encode_declared_with(&d.text, &d.encoding, &MergeOptions::new()).unwrap(), b);
1583        // LocOS: UTF-8 under a UTF-8 label, whether the text fits the code page or not
1584        for text in [d.text.clone(), d.text.replace("Caf\u{e9}", "\u{436}")] {
1585            let out = String::from_utf8(encode_declared_with(&text, &d.encoding, &locos).unwrap()).unwrap();
1586            assert!(out.contains("<meta charset=\"UTF-8\">") && !out.contains("1252"), "{}", &out[out.len() - 80..]);
1587        }
1588        // a page with no declaration at all keeps its code page
1589        let plain = legacy(encoding_rs::WINDOWS_1252, "<p>Caf\u{e9}</p>");
1590        let d = dec(&plain, None, true).unwrap();
1591        assert_eq!(encode_declared_with(&d.text, &d.encoding, &locos).unwrap(), plain);
1592    }
1593
1594    #[test]
1595    fn declared_iso_8859_1_is_written_as_iso_8859_1_or_utf8() {
1596        let po = b"msgid \"\"\nmsgstr \"\"\n\"Content-Type: text/plain; charset=ISO-8859-1\\n\"\n\nmsgid \"a\"\nmsgstr \"caf\xe9\"\n".to_vec();
1597        let d = dec(&po, Some("en"), true).unwrap();
1598        assert_eq!(d.encoding, "iso-8859-1;label=ISO-8859-1");
1599        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), po);
1600        // French oe and the euro sign are not ISO-8859-1: UTF-8 under the UTF-8 label, never Windows-1252 bytes
1601        let out = encode_text(&d.text.replace("caf\u{e9}", "c\u{153}ur \u{20ac}"), &d.encoding).unwrap();
1602        let s = String::from_utf8(out).unwrap();
1603        assert!(s.contains("charset=UTF-8") && s.contains("c\u{153}ur \u{20ac}"));
1604        // a pure-ASCII file under the same label
1605        let ascii = b"msgid \"\"\nmsgstr \"\"\n\"Content-Type: text/plain; charset=ISO-8859-1\\n\"\n".to_vec();
1606        let d = dec(&ascii, Some("en"), true).unwrap();
1607        assert!(d.encoding.starts_with("iso-8859-1"), "{}", d.encoding);
1608        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), ascii);
1609        // a mislabelled file with Windows-1252 bytes keeps its bytes on an untouched merge
1610        let mut bad = po.clone();
1611        bad.extend_from_slice(b"msgid \"b\"\nmsgstr \"\x80\"\n");
1612        let d = dec(&bad, Some("en"), true).unwrap();
1613        assert!(d.encoding.starts_with("windows-1252"), "{}", d.encoding);
1614        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), bad);
1615    }
1616
1617    #[test]
1618    fn declared_unknown_label_comes_back_untouched() {
1619        let b = b"<?xml version=\"1.0\" encoding=\"x-nonsense\"?><a>caf\xe9</a>".to_vec();
1620        let d = dec(&b, None, true).unwrap();
1621        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1622    }
1623
1624    #[test]
1625    fn wrong_code_page_gives_a_warning_not_an_error() {
1626        // Greek saved as Windows-1253 in a project with no source language: read as Windows-1252 it is accented
1627        // Latin soup, so the upload warns and never fails
1628        let b = legacy(encoding_rs::WINDOWS_1253, "\u{39a}\u{3b1}\u{3bb}\u{3b7}\u{3bc}\u{3ad}\u{3c1}\u{3b1} \u{3ba}\u{3cc}\u{3c3}\u{3bc}\u{3b5}, \u{3ba}\u{3b1}\u{3bb}\u{3b7}\u{3c3}\u{3c0}\u{3ad}\u{3c1}\u{3b1} \u{3c3}\u{3b1}\u{3c2}");
1629        let d = dec(&b, Some("en"), false).unwrap();
1630        assert_eq!(d.warnings.len(), 1);
1631        assert_eq!(d.warnings[0].kind, "text_encoding");
1632        assert!(d.warnings[0].message.contains("re-save the file as UTF-8"));
1633        // the same bytes in a Greek project are read correctly, without a warning
1634        assert!(dec(&b, Some("el"), false).unwrap().warnings.is_empty());
1635    }
1636
1637    #[test]
1638    fn western_text_is_not_flagged_in_a_cjk_project() {
1639        assert!(dec("caf\u{e9}".as_bytes(), Some("ja"), false).unwrap().warnings.is_empty());
1640    }
1641
1642    #[test]
1643    fn binary_and_unreadable_files_are_refused() {
1644        let e = dec(&[0x89, b'P', b'N', b'G', 0, 0, 0, 1], None, false).unwrap_err();
1645        assert!(matches!(&e, Error::Encoding(m) if m.contains("binary")), "{e}");
1646        let e = dec(&[b'a', 0x90, b'b'], Some("en"), false).unwrap_err();
1647        assert!(matches!(e, Error::Encoding(_)));
1648    }
1649
1650    #[test]
1651    fn python_charset_names_are_read_and_written_back() {
1652        use encoding_rs::*;
1653        // LocOS reads a declared charset with Python's codec lookup: CP932, cp936, sjis, uhc are not WHATWG labels
1654        for (l, e) in [
1655            ("CP932", SHIFT_JIS),
1656            ("ms_kanji", SHIFT_JIS),
1657            ("x.mac.japanese", SHIFT_JIS),
1658            ("cp936", GBK),
1659            ("UHC", EUC_KR),
1660            ("cp949", EUC_KR),
1661            ("ujis", EUC_JP),
1662            ("iso8859_2", ISO_8859_2),
1663            ("KOI8_R", KOI8_R),
1664        ] {
1665            assert_eq!(label_encoding(l), Some(e), "{l}");
1666        }
1667        // WHATWG first: its meaning wins where both know a label; unknown names stay unknown
1668        assert_eq!(label_encoding("latin1"), Some(WINDOWS_1252));
1669        assert_eq!(label_encoding("x-made-up"), None);
1670        assert_eq!(label_encoding("cp437"), None);
1671        assert_eq!(label_encoding("MS-932"), None); // Python does not know it either
1672        assert!(PY_ALIASES.windows(2).all(|w| w[0].0 < w[1].0), "PY_ALIASES must stay sorted");
1673        // a PO header declaring CP932: read as Shift_JIS, written back in it under its own label
1674        let mut b = b"msgid \"\"\nmsgstr \"Content-Type: text/plain; charset=CP932\\n\"\n\nmsgid \"a\"\nmsgstr \"".to_vec();
1675        b.extend_from_slice(&[0x93, 0xfa, 0x96, 0x7b]);
1676        b.extend_from_slice(b"\"\n");
1677        let d = dec(&b, Some("en"), true).unwrap();
1678        assert!(d.text.contains("\u{65e5}\u{672c}") && d.text.contains("charset=UTF-8"), "{}", d.text);
1679        assert!(d.encoding.starts_with("shift_jis") && d.encoding.contains("label=CP932"), "{}", d.encoding);
1680        assert_eq!(encode_text(&d.text, &d.encoding).unwrap(), b);
1681    }
1682
1683    #[test]
1684    fn line_budget_applies_to_decoded_text() {
1685        let mut o = DecodeOptions { declared: false, source_lang: None, limits: Limits::default(), lossy_after_utf8_bom: false, mark_before_legacy: false };
1686        o.limits.max_lines = 3;
1687        assert!(decode_text(b"a\nb\n", &o).is_ok());
1688        let e = decode_text(b"\n\n\n\n\n", &o).unwrap_err();
1689        assert!(matches!(e, Error::Limit(l) if l.kind == crate::LimitKind::Lines));
1690    }
1691}