Skip to main content

formats/
multibyte.rs

1// multibyte -- the multi-byte encodings of the WHATWG Encoding Standard for formats::encoding: Shift_JIS,
2// EUC-JP, ISO-2022-JP, GBK, gb18030, Big5 and EUC-KR.  The encoders here, the decoders in decode.rs, both as
3// the standard writes them step by step; the indexes are generated (cjk.rs, cjk.bin).
4//
5// A pointer is a character's place in an index (row × columns + column); the decoders compute it from the
6// bytes and look the code point up, the encoders search the pointers sorted by code point (*_ORDER) and
7// compute the bytes from it.
8use alloc::{string::String, vec::Vec};
9
10use crate::cjk::{self, Table};
11use crate::decode::Decoder;
12use crate::encoding::{Error, Label};
13
14/// A multi-byte encoding of the WHATWG Encoding Standard: the legacy encodings of Chinese, Japanese and
15/// Korean text that browsers, mail and old files still use.  Each is the standard's: the Windows variants
16/// where the web uses them (Shift_JIS is Windows' code page 932, EUC-KR its 949, GBK its 936).
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
18#[non_exhaustive]
19pub enum MultiByte {
20    /// Shift_JIS: Japanese as Windows writes it (code page 932, windows-31j: JIS X 0208 with the NEC and
21    /// IBM extensions, half-width katakana, the user-defined rows as the Private Use Area)
22    ShiftJis,
23    /// EUC-JP: Japanese on Unix (JIS X 0208, JIS X 0212 after 0x8F, half-width katakana after 0x8E)
24    EucJp,
25    /// ISO-2022-JP: Japanese in mail and news, 7 bits with escape sequences (ASCII, JIS X 0201 Roman and
26    /// katakana, JIS X 0208)
27    Iso2022Jp,
28    /// GBK: simplified Chinese (code page 936; also what the labels gb2312 and chinese name).  It reads
29    /// gb18030; it writes only its two-byte characters and the euro sign as 0x80.
30    Gbk,
31    /// gb18030: simplified Chinese with all of Unicode but U+E5E5, which it does not write (GB18030-2022;
32    /// code page 54936)
33    Gb18030,
34    /// Big5: traditional Chinese with the Hong Kong Supplementary Character Set (HKSCS-2008; code page 950)
35    Big5,
36    /// EUC-KR: Korean as Windows writes it (code page 949, the Unified Hangul Code: all 11 172 syllables)
37    EucKr,
38}
39
40impl MultiByte {
41    /// every multi-byte encoding, in declaration order
42    pub const ALL: &'static [MultiByte] =
43        &[MultiByte::ShiftJis, MultiByte::EucJp, MultiByte::Iso2022Jp, MultiByte::Gbk, MultiByte::Gb18030, MultiByte::Big5, MultiByte::EucKr];
44
45    /// its name in the WHATWG Encoding Standard ("Shift_JIS", "EUC-JP", "ISO-2022-JP", "GBK", "gb18030",
46    /// "Big5", "EUC-KR")
47    pub const fn name(self) -> &'static str {
48        match self {
49            MultiByte::ShiftJis => "Shift_JIS",
50            MultiByte::EucJp => "EUC-JP",
51            MultiByte::Iso2022Jp => "ISO-2022-JP",
52            MultiByte::Gbk => "GBK",
53            MultiByte::Gb18030 => "gb18030",
54            MultiByte::Big5 => "Big5",
55            MultiByte::EucKr => "EUC-KR",
56        }
57    }
58
59    /// its Windows code page number: 932, 20932, 50220, 936, 54936, 950, 949
60    pub const fn code_page(self) -> u16 {
61        match self {
62            MultiByte::ShiftJis => 932,
63            MultiByte::EucJp => 20932,
64            MultiByte::Iso2022Jp => 50220,
65            MultiByte::Gbk => 936,
66            MultiByte::Gb18030 => 54936,
67            MultiByte::Big5 => 950,
68            MultiByte::EucKr => 949,
69        }
70    }
71
72    /// the encoding of a Windows code page number: 932, 936, 949, 950, 20932 and 51932 (EUC-JP), 50220 and
73    /// 50221 (ISO-2022-JP), 51949 (EUC-KR), 54936.  None for the others: Johab (1361) is none of the standard's,
74    /// and 50222 writes half-width katakana between SO and SI, which the standard's ISO-2022-JP does not read.
75    pub const fn from_code_page(cp: u16) -> Option<MultiByte> {
76        Some(match cp {
77            932 => MultiByte::ShiftJis,
78            20932 | 51932 => MultiByte::EucJp,
79            50220 | 50221 => MultiByte::Iso2022Jp,
80            936 => MultiByte::Gbk,
81            54936 => MultiByte::Gb18030,
82            950 => MultiByte::Big5,
83            949 | 51949 => MultiByte::EucKr,
84            _ => return None,
85        })
86    }
87
88    /// the encoding a WHATWG label names ("shift_jis", "sjis", "windows-31j", "gb2312", "big5-hkscs",
89    /// "ks_c_5601-1987" ...; `encoding::label`), multi-byte encodings only
90    pub fn from_label(name: &str) -> Option<MultiByte> {
91        match crate::encoding::label(name)? {
92            Label::Multi(m) => Some(m),
93            _ => None,
94        }
95    }
96
97    /// The text of these bytes, as the standard decodes them: malformed or unassigned sequences become
98    /// U+FFFD, ASCII bytes after a broken lead byte are kept.  For input in pieces: `Decoder`.
99    pub fn decode(self, bytes: &[u8]) -> String {
100        let mut out = String::with_capacity(bytes.len() + bytes.len() / 2);
101        Decoder::new(Label::Multi(self)).decode(bytes, true, &mut out);
102        out
103    }
104
105    /// The bytes of a text; Unmappable: the first character this encoding does not have (ISO-2022-JP ends
106    /// in ASCII, with ESC ( B where needed).
107    pub fn encode(self, text: &str) -> Result<Vec<u8>, Error> {
108        self.encode_with(text, |c, _, _| Err(Error::Unmappable(c)))
109    }
110
111    /// The bytes of a text, a character this encoding does not have as a decimal character reference
112    /// ("&#128512;"), as browsers submit forms (the standard's "html" error mode).
113    pub fn encode_html(self, text: &str) -> Vec<u8> {
114        self.encode_with(text, |_, reported, out| {
115            out.extend_from_slice(b"&#");
116            let mut n = reported as u32;
117            let mut digits = [0u8; 7];
118            let mut k = 0;
119            loop {
120                digits[k] = b'0' + (n % 10) as u8;
121                k += 1;
122                n /= 10;
123                if n == 0 {
124                    break;
125                }
126            }
127            out.extend(digits[..k].iter().rev());
128            out.push(b';');
129            Ok(())
130        })
131        .unwrap_or_default()
132    }
133
134    // the encoder: each character through the standard's algorithm; `fallback` gets a character without bytes,
135    // the code point the standard reports for it (U+FFFD for ISO-2022-JP's SO, SI and ESC) and the output
136    fn encode_with(self, text: &str, mut fallback: impl FnMut(char, char, &mut Vec<u8>) -> Result<(), Error>) -> Result<Vec<u8>, Error> {
137        let mut out = Vec::with_capacity(text.len() + text.len() / 4);
138        let mut jis = Jis::Ascii;
139        for c in text.chars() {
140            if c.is_ascii() && (self != MultiByte::Iso2022Jp || jis == Jis::Ascii && !matches!(c, '\x0E' | '\x0F' | '\x1B')) {
141                out.push(c as u8);
142                continue;
143            }
144            let r = match self {
145                MultiByte::ShiftJis => shift_jis(c, &mut out),
146                MultiByte::EucJp => euc_jp(c, &mut out),
147                MultiByte::Iso2022Jp => iso2022jp(c, &mut jis, &mut out),
148                MultiByte::Gbk => gb18030(c, true, &mut out),
149                MultiByte::Gb18030 => gb18030(c, false, &mut out),
150                MultiByte::Big5 => big5(c, &mut out),
151                MultiByte::EucKr => euc_kr(c, &mut out),
152            };
153            if let Err(reported) = r {
154                fallback(c, reported, &mut out)?;
155            }
156        }
157        if jis != Jis::Ascii {
158            out.extend_from_slice(b"\x1B(B");
159        }
160        Ok(out)
161    }
162}
163
164// ---------------------------------------------------------------- the indexes
165
166/// the code point of a pointer in big5 (0: none)
167pub(crate) fn big5_code_point(p: usize) -> u32 {
168    let low = cjk::BIG5.get(p) as u32;
169    if low != 0 && cjk::BIG5_ASTRAL.get(p / 16) >> (p % 16) & 1 != 0 { low + 0x20000 } else { low }
170}
171
172/// index gb18030 ranges code point: the code point of a four-byte pointer (None: no character)
173pub(crate) fn gb18030_range_code_point(p: u32) -> Option<u32> {
174    if p > 39419 && p < 189000 || p > 1237575 {
175        return None;
176    }
177    if p == 7457 {
178        return Some(0xE7C7);
179    }
180    let r = cjk::GB18030_RANGES;
181    let i = r.partition_point(|e| e.0 <= p) - 1;
182    Some(r[i].1 + p - r[i].0)
183}
184
185// index gb18030 ranges pointer
186fn gb18030_range_pointer(c: u32) -> u32 {
187    if c == 0xE7C7 {
188        return 7457;
189    }
190    let r = cjk::GB18030_RANGES;
191    let i = r.partition_point(|e| e.1 <= c) - 1;
192    r[i].0 + c - r[i].1
193}
194
195// the pointers of a code point in an index, lowest first: the place of the first in `order`
196fn first_of(order: Table, value: impl Fn(usize) -> u32, c: u32) -> usize {
197    let (mut lo, mut hi) = (0, order.len);
198    while lo < hi {
199        let mid = (lo + hi) / 2;
200        if value(order.get(mid) as usize) < c {
201            lo = mid + 1;
202        } else {
203            hi = mid;
204        }
205    }
206    lo
207}
208
209// the first pointer of a code point that `keep` accepts
210fn pointer(order: Table, value: impl Fn(usize) -> u32, c: u32, keep: impl Fn(usize) -> bool) -> Option<usize> {
211    let mut i = first_of(order, &value, c);
212    while i < order.len {
213        let p = order.get(i) as usize;
214        if value(p) != c {
215            return None;
216        }
217        if keep(p) {
218            return Some(p);
219        }
220        i += 1;
221    }
222    None
223}
224
225fn put(out: &mut Vec<u8>, b: u8) -> Result<(), char> {
226    out.push(b);
227    Ok(())
228}
229
230fn jis0208(p: usize) -> u32 {
231    cjk::JIS0208.get(p) as u32
232}
233
234// ---------------------------------------------------------------- the encoders (Err: the code point reported)
235
236fn shift_jis(c: char, out: &mut Vec<u8>) -> Result<(), char> {
237    let mut u = c as u32;
238    match u {
239        0x80 => return put(out, 0x80),
240        0xA5 => return put(out, 0x5C),
241        0x203E => return put(out, 0x7E),
242        0xFF61..=0xFF9F => return put(out, (u - 0xFF61 + 0xA1) as u8),
243        0x2212 => u = 0xFF0D,
244        _ => {}
245    }
246    // index Shift_JIS pointer: not the NEC-selected IBM extensions (the IBM extensions have them again)
247    let p = pointer(cjk::JIS0208_ORDER, jis0208, u, |p| !(8272..=8835).contains(&p)).ok_or(c)?;
248    let (lead, trail) = (p / 188, p % 188);
249    out.push((lead + if lead < 0x1F { 0x81 } else { 0xC1 }) as u8);
250    out.push((trail + if trail < 0x3F { 0x40 } else { 0x41 }) as u8);
251    Ok(())
252}
253
254fn euc_jp(c: char, out: &mut Vec<u8>) -> Result<(), char> {
255    let mut u = c as u32;
256    match u {
257        0xA5 => return put(out, 0x5C),
258        0x203E => return put(out, 0x7E),
259        0xFF61..=0xFF9F => {
260            out.push(0x8E);
261            return put(out, (u - 0xFF61 + 0xA1) as u8);
262        }
263        0x2212 => u = 0xFF0D,
264        _ => {}
265    }
266    let p = pointer(cjk::JIS0208_ORDER, jis0208, u, |_| true).ok_or(c)?;
267    out.push((p / 94 + 0xA1) as u8);
268    out.push((p % 94 + 0xA1) as u8);
269    Ok(())
270}
271
272#[derive(Clone, Copy, PartialEq, Eq)]
273enum Jis {
274    Ascii,
275    Roman,
276    Jis0208,
277}
278
279fn iso2022jp(c: char, state: &mut Jis, out: &mut Vec<u8>) -> Result<(), char> {
280    let u = c as u32;
281    // each turn either writes the character or switches the state and tries again (the standard's "restore")
282    loop {
283        if *state != Jis::Jis0208 && matches!(u, 0x0E | 0x0F | 0x1B) {
284            return Err('\u{FFFD}');
285        }
286        if *state == Jis::Ascii && u < 0x80 {
287            return put(out, u as u8);
288        }
289        if *state == Jis::Roman && (u < 0x80 && u != 0x5C && u != 0x7E || u == 0xA5 || u == 0x203E) {
290            return put(out, match u {
291                0xA5 => 0x5C,
292                0x203E => 0x7E,
293                _ => u as u8,
294            });
295        }
296        if u < 0x80 {
297            out.extend_from_slice(b"\x1B(B");
298            *state = Jis::Ascii;
299            continue;
300        }
301        if (u == 0xA5 || u == 0x203E) && *state != Jis::Roman {
302            out.extend_from_slice(b"\x1B(J");
303            *state = Jis::Roman;
304            continue;
305        }
306        let v = match u {
307            0x2212 => 0xFF0D,
308            0xFF61..=0xFF9F => cjk::ISO2022JP_KATAKANA[(u - 0xFF61) as usize] as u32,
309            _ => u,
310        };
311        let Some(p) = pointer(cjk::JIS0208_ORDER, jis0208, v, |_| true) else {
312            if *state == Jis::Jis0208 {
313                out.extend_from_slice(b"\x1B(B");
314                *state = Jis::Ascii;
315                continue;
316            }
317            return Err(c);
318        };
319        if *state != Jis::Jis0208 {
320            out.extend_from_slice(b"\x1B$B");
321            *state = Jis::Jis0208;
322            continue;
323        }
324        out.push((p / 94 + 0x21) as u8);
325        out.push((p % 94 + 0x21) as u8);
326        return Ok(());
327    }
328}
329
330fn gb18030(c: char, gbk: bool, out: &mut Vec<u8>) -> Result<(), char> {
331    let u = c as u32;
332    if u == 0xE5E5 {
333        return Err(c);
334    }
335    if gbk && u == 0x20AC {
336        return put(out, 0x80);
337    }
338    let two = if let Ok(i) = cjk::GB18030_PUA.binary_search_by_key(&u, |e| e.0 as u32) {
339        Some(cjk::GB18030_PUA[i].1 as usize)
340    } else {
341        pointer(cjk::GB18030_ORDER, |p| cjk::GB18030.get(p) as u32, u, |_| true)
342    };
343    if let Some(p) = two {
344        let (lead, trail) = (p / 190, p % 190);
345        out.push((lead + 0x81) as u8);
346        out.push((trail + if trail < 0x3F { 0x40 } else { 0x41 }) as u8);
347        return Ok(());
348    }
349    if gbk {
350        return Err(c);
351    }
352    let p = gb18030_range_pointer(u);
353    out.extend_from_slice(&[(p / 12600 + 0x81) as u8, (p / 1260 % 10 + 0x30) as u8, (p / 10 % 126 + 0x81) as u8, (p % 10 + 0x30) as u8]);
354    Ok(())
355}
356
357fn big5(c: char, out: &mut Vec<u8>) -> Result<(), char> {
358    let u = c as u32;
359    // index Big5 pointer: from row 0xA1 on (HKSCS's rows decode, they are not written), the last of six
360    // characters that are there twice
361    let p = if matches!(u, 0x2550 | 0x255E | 0x2561 | 0x256A | 0x5341 | 0x5345) {
362        let mut i = first_of(cjk::BIG5_ORDER, big5_code_point, u);
363        let mut last = None;
364        while i < cjk::BIG5_ORDER.len && big5_code_point(cjk::BIG5_ORDER.get(i) as usize) == u {
365            last = Some(cjk::BIG5_ORDER.get(i) as usize);
366            i += 1;
367        }
368        last
369    } else {
370        pointer(cjk::BIG5_ORDER, big5_code_point, u, |_| true)
371    }
372    .ok_or(c)?;
373    let (lead, trail) = (p / 157, p % 157);
374    out.push((lead + 0x81) as u8);
375    out.push((trail + if trail < 0x3F { 0x40 } else { 0x62 }) as u8);
376    Ok(())
377}
378
379fn euc_kr(c: char, out: &mut Vec<u8>) -> Result<(), char> {
380    let p = pointer(cjk::EUC_KR_ORDER, |p| cjk::EUC_KR.get(p) as u32, c as u32, |_| true).ok_or(c)?;
381    out.push((p / 190 + 0x81) as u8);
382    out.push((p % 190 + 0x41) as u8);
383    Ok(())
384}