Skip to main content

bilingua_model/
codepage.rs

1//! Windows code pages per language: which legacy encoding an undeclared, non-UTF-8 text file most likely uses
2//! when its project's source language is known (Localization OS decision 22, `code_pages.py`).
3
4use encoding_rs::Encoding;
5
6/// Splits a BCP 47 or POSIX tag into (language, script, region): lower, title and upper case.
7pub fn split_locale(tag: &str) -> (String, String, String) {
8    let mut it = tag.trim().split(['-', '_']);
9    let lang = it.next().unwrap_or("").to_ascii_lowercase();
10    let (mut script, mut region) = (String::new(), String::new());
11    for p in it {
12        if p.len() == 4 && p.chars().all(|c| c.is_ascii_alphabetic()) {
13            let mut cs = p.chars();
14            script = cs.next().map(|c| c.to_ascii_uppercase().to_string()).unwrap_or_default() + &cs.as_str().to_ascii_lowercase();
15        } else if (p.len() == 2 && p.chars().all(|c| c.is_ascii_alphabetic())) || (p.len() == 3 && p.chars().all(|c| c.is_ascii_digit())) {
16            region = p.to_ascii_uppercase();
17        }
18    }
19    (lang, script, region)
20}
21
22fn lang_cp(lang: &str) -> Option<u16> {
23    const TABLE: &[(u16, &str)] = &[
24        (1250, "cs pl hu hr sk sl ro sq bs hsb dsb"),
25        (1251, "ru uk bg be mk sr kk ky tt mn ba sah tg"),
26        (
27            1252,
28            "en fr de es it pt nl da sv nb nn no fi is ca eu gl ga id ms sw af fo fy lb rm oc br co gd cy tl fil zu xh tn st nso rw quz",
29        ),
30        (1253, "el"),
31        (1254, "tr az uz"),
32        (1255, "he yi"),
33        (1256, "ar fa ur ps ug sd"),
34        (1257, "et lv lt"),
35        (1258, "vi"),
36        (874, "th"),
37        (932, "ja"),
38        (936, "zh"),
39        (949, "ko"),
40    ];
41    TABLE.iter().find(|(_, langs)| langs.split(' ').any(|l| l == lang)).map(|(cp, _)| *cp)
42}
43
44/// The Windows ANSI code page of a language tag, or `None` when it has none we know.
45pub fn target_code_page(locale: &str) -> Option<u16> {
46    let (lang, script, region) = split_locale(locale);
47    if lang.is_empty() {
48        return None;
49    }
50    if lang == "zh" {
51        return Some(if script == "Hant" || matches!(region.as_str(), "TW" | "HK" | "MO") { 950 } else { 936 });
52    }
53    if script == "Cyrl" && matches!(lang.as_str(), "sr" | "bs" | "az" | "uz" | "mn" | "tg") {
54        return Some(1251);
55    }
56    if script == "Latn" && lang == "sr" {
57        return Some(1250);
58    }
59    lang_cp(&lang)
60}
61
62/// The decoder for a code page number.
63pub fn encoding_for_code_page(cp: u16) -> Option<&'static Encoding> {
64    Some(match cp {
65        874 => encoding_rs::WINDOWS_874,
66        932 => encoding_rs::SHIFT_JIS,
67        936 => encoding_rs::GBK,
68        949 => encoding_rs::EUC_KR,
69        950 => encoding_rs::BIG5,
70        1250 => encoding_rs::WINDOWS_1250,
71        1251 => encoding_rs::WINDOWS_1251,
72        1252 => encoding_rs::WINDOWS_1252,
73        1253 => encoding_rs::WINDOWS_1253,
74        1254 => encoding_rs::WINDOWS_1254,
75        1255 => encoding_rs::WINDOWS_1255,
76        1256 => encoding_rs::WINDOWS_1256,
77        1257 => encoding_rs::WINDOWS_1257,
78        1258 => encoding_rs::WINDOWS_1258,
79        _ => return None,
80    })
81}
82
83/// The code page number of a decoder (GBK is 936; GB18030 has none).
84pub fn code_page_for_encoding(e: &'static Encoding) -> Option<u16> {
85    [874u16, 932, 936, 949, 950, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258]
86        .into_iter()
87        .find(|cp| encoding_for_code_page(*cp) == Some(e))
88}
89
90/// The legacy decoder for a source language, `None` for Western ones (Windows-1252 is the default anyway).
91pub fn source_encoding(locale: &str) -> Option<&'static Encoding> {
92    let e = encoding_for_code_page(target_code_page(locale)?)?;
93    (e != encoding_rs::WINDOWS_1252).then_some(e)
94}
95
96/// A plain name for messages: "Greek (Windows-1253)".
97pub fn label(e: &'static Encoding) -> String {
98    match code_page_for_encoding(e) {
99        Some(874) => "Thai (Windows-874)".into(),
100        Some(932) => "Japanese (Shift_JIS)".into(),
101        Some(936) => "Chinese Simplified (GBK)".into(),
102        Some(949) => "Korean (Windows-949)".into(),
103        Some(950) => "Chinese Traditional (Big5)".into(),
104        Some(1250) => "Central European (Windows-1250)".into(),
105        Some(1251) => "Cyrillic (Windows-1251)".into(),
106        Some(1252) => "Western European (Windows-1252)".into(),
107        Some(1253) => "Greek (Windows-1253)".into(),
108        Some(1254) => "Turkish (Windows-1254)".into(),
109        Some(1255) => "Hebrew (Windows-1255)".into(),
110        Some(1256) => "Arabic (Windows-1256)".into(),
111        Some(1257) => "Baltic (Windows-1257)".into(),
112        Some(1258) => "Vietnamese (Windows-1258)".into(),
113        _ => e.name().to_string(),
114    }
115}
116
117/// The accented letters of a Latin-script language's own alphabet (lower and upper case), used so that ordinary
118/// Polish or Czech text read with its own code page is not called garbled.
119fn native_letters_of(lang: &str) -> &'static str {
120    match lang {
121        "pl" => "ąćęłńóśźż",
122        "cs" => "áčďéěíňóřšťúůýž",
123        "sk" => "áäčďéíĺľňóôŕšťúýž",
124        "hu" => "áéíóöőúüű",
125        "sl" | "hr" | "bs" | "sr" => "čšžćđ",
126        "ro" => "ăâîșțşţ",
127        "tr" => "çğıöşüâîûİ",
128        "lt" => "ąčęėįšųūž",
129        "lv" => "āčēģīķļņšūž",
130        "et" => "äöõüšž",
131        "vi" => "àáâãèéêìíòóôõùúýăđĩũơưạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ\u{300}\u{301}\u{303}\u{309}\u{323}",
132        "de" => "äöüß",
133        "fr" => "àâæçéèêëîïôœùûüÿ",
134        "es" => "áéíñóúü",
135        "pt" => "áâãàçéêíóôõú",
136        "it" => "àèéìíîòóù",
137        "nl" => "áéëïóöüè",
138        "sv" => "åäöé",
139        "da" | "no" | "nb" | "nn" => "æøåé",
140        "fi" => "äöåšž",
141        "is" => "áðéíóúýþæö",
142        "ca" => "àçéèíïòóúü·",
143        _ => "",
144    }
145}
146
147/// The native accented letters when `enc` is the locale's own Windows code page, else an empty list.
148pub fn native_letters(locale: &str, enc: &'static Encoding) -> Vec<char> {
149    let (lang, _, _) = split_locale(locale);
150    let letters = native_letters_of(&lang);
151    if letters.is_empty() || code_page_for_encoding(enc) != target_code_page(locale) {
152        return Vec::new();
153    }
154    let mut v: Vec<char> = letters.chars().collect();
155    let upper: Vec<char> = letters
156        .chars()
157        .filter_map(|c| {
158            let mut u = c.to_uppercase();
159            let first = u.next()?;
160            u.next().is_none().then_some(first)
161        })
162        .collect();
163    v.extend(upper);
164    v
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn languages_map_to_their_code_pages() {
173        assert_eq!(target_code_page("ja-JP"), Some(932));
174        assert_eq!(target_code_page("ko"), Some(949));
175        assert_eq!(target_code_page("zh-CN"), Some(936));
176        assert_eq!(target_code_page("zh-Hant"), Some(950));
177        assert_eq!(target_code_page("zh_TW"), Some(950));
178        assert_eq!(target_code_page("ar-SA"), Some(1256));
179        assert_eq!(target_code_page("sr-Latn"), Some(1250));
180        assert_eq!(target_code_page("sr-Cyrl"), Some(1251));
181        assert_eq!(target_code_page("hi"), None);
182        assert!(source_encoding("en").is_none());
183        assert_eq!(source_encoding("el").unwrap().name(), "windows-1253");
184    }
185}