Skip to main content

formats/
decode.rs

1// decode -- formats::encoding's Decoder: the decoders of the WHATWG Encoding Standard for input in pieces,
2// UTF-8, UTF-16, the single-byte sets, the replacement encoding and the multi-byte encodings, each the
3// standard's algorithm byte by byte (with a fast path for ASCII where no sequence is open).
4//
5// The standard lets a decoder "restore" bytes it has read: they are read again, before the rest of the input.
6// They wait in a small queue here, so a sequence may end in one piece of input and be read again from the next.
7use alloc::string::String;
8
9use crate::cjk;
10use crate::encoding::Label;
11use crate::multibyte::{big5_code_point, gb18030_range_code_point, MultiByte};
12
13/// A decoder for input in pieces: `decode(piece, last, out)` appends the text of each piece to `out`; a
14/// sequence cut between two pieces is finished by the next one.  The output is the same as decoding the whole
15/// input at once with `decode_label` (without its byte-order mark rule; see `Decoder::sniffing`).  Shift_JIS's
16/// "あ" in two pieces, 0x82 and then 0xA0 with `last`, gives "あ".
17#[derive(Clone, Debug)]
18pub struct Decoder {
19    label: Label,
20    state: State,
21    queue: Queue,
22    // the byte-order mark rule: Some(bytes read so far) until it is decided
23    sniff: Option<([u8; 3], u8)>,
24    malformed: bool,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28enum State {
29    Utf8 { cp: u32, seen: u8, need: u8, lower: u8, upper: u8 },
30    Utf16 { le: bool, lead: Option<u8>, surrogate: Option<u16> },
31    Single,
32    Replacement { done: bool },
33    ShiftJis { lead: u8 },
34    EucJp { lead: u8, jis0212: bool },
35    Iso2022Jp { state: Jp, output: Jp, lead: u8, flag: bool },
36    Gb18030 { first: u8, second: u8, third: u8 },
37    Big5 { lead: u8 },
38    EucKr { lead: u8 },
39}
40
41// the states of the ISO-2022-JP decoder
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43enum Jp {
44    Ascii,
45    Roman,
46    Katakana,
47    LeadByte,
48    TrailByte,
49    EscapeStart,
50    Escape,
51}
52
53// what a step gives
54enum Out {
55    Continue,
56    Finished,
57    Error,
58    Char(u32),
59    Pair(u32, u32),
60}
61
62// bytes restored by a step, read before the rest of the input (front first)
63#[derive(Clone, Copy, Debug, Default)]
64struct Queue {
65    b: [u8; 8],
66    n: u8,
67}
68
69impl Queue {
70    fn pop(&mut self) -> Option<u8> {
71        if self.n == 0 {
72            return None;
73        }
74        let x = self.b[0];
75        self.b.copy_within(1..self.n as usize, 0);
76        self.n -= 1;
77        Some(x)
78    }
79
80    // put bytes in front of the queue (at most 3 at a time; the queue never holds more than 6)
81    fn restore(&mut self, bytes: &[u8]) {
82        let (n, k) = (self.n as usize, bytes.len());
83        debug_assert!(n + k <= self.b.len());
84        if n + k > self.b.len() {
85            return;
86        }
87        self.b.copy_within(0..n, k);
88        self.b[..k].copy_from_slice(bytes);
89        self.n += k as u8;
90    }
91}
92
93fn fresh(label: Label) -> State {
94    match label {
95        Label::Utf8 => State::Utf8 { cp: 0, seen: 0, need: 0, lower: 0x80, upper: 0xBF },
96        Label::Utf16Le => State::Utf16 { le: true, lead: None, surrogate: None },
97        Label::Utf16Be => State::Utf16 { le: false, lead: None, surrogate: None },
98        Label::Single(_) => State::Single,
99        Label::Replacement => State::Replacement { done: false },
100        Label::Multi(m) => match m {
101            MultiByte::ShiftJis => State::ShiftJis { lead: 0 },
102            MultiByte::EucJp => State::EucJp { lead: 0, jis0212: false },
103            MultiByte::Iso2022Jp => State::Iso2022Jp { state: Jp::Ascii, output: Jp::Ascii, lead: 0, flag: false },
104            MultiByte::Gbk | MultiByte::Gb18030 => State::Gb18030 { first: 0, second: 0, third: 0 },
105            MultiByte::Big5 => State::Big5 { lead: 0 },
106            MultiByte::EucKr => State::EucKr { lead: 0 },
107        },
108    }
109}
110
111impl Decoder {
112    /// A decoder of the encoding a label names (`encoding::label`).
113    pub fn new(label: Label) -> Decoder {
114        Decoder { label, state: fresh(label), queue: Queue::default(), sniff: None, malformed: false }
115    }
116
117    /// A decoder with the standard's byte-order mark rule (its "decode"): a UTF-8, UTF-16LE or UTF-16BE
118    /// byte-order mark at the start wins over the label and is dropped.
119    pub fn sniffing(label: Label) -> Decoder {
120        Decoder { sniff: Some(([0; 3], 0)), ..Decoder::new(label) }
121    }
122
123    /// The encoding decoded: the label's, or the byte-order mark's once one was found.
124    pub fn label(&self) -> Label {
125        self.label
126    }
127
128    /// Whether some input was malformed (a U+FFFD in the output came from an error, not from the input).
129    pub fn malformed(&self) -> bool {
130        self.malformed
131    }
132
133    /// Append the text of `input` to `out`.  `last`: no more input follows; an open sequence becomes U+FFFD,
134    /// and a following call starts a new input in the encoding `label` names (a byte-order mark is not looked
135    /// for again).  The output grows by at most three bytes per input byte, and by six for what an earlier
136    /// piece left open.
137    pub fn decode(&mut self, input: &[u8], last: bool, out: &mut String) {
138        let mut input = input;
139        // the byte-order mark: hold the first bytes while they may still become one
140        let mut held = [0u8; 3];
141        let mut held_n = 0;
142        if let Some((mut b, mut n)) = self.sniff {
143            while (n as usize) < 3 && !input.is_empty() && maybe_bom(&b[..n as usize]) {
144                b[n as usize] = input[0];
145                n += 1;
146                input = &input[1..];
147            }
148            let s = &b[..n as usize];
149            let bom = if s.starts_with(&[0xEF, 0xBB, 0xBF]) {
150                Some((Label::Utf8, 3))
151            } else if s.starts_with(&[0xFF, 0xFE]) {
152                Some((Label::Utf16Le, 2))
153            } else if s.starts_with(&[0xFE, 0xFF]) {
154                Some((Label::Utf16Be, 2))
155            } else {
156                None
157            };
158            if bom.is_none() && maybe_bom(s) && !last {
159                self.sniff = Some((b, n));
160                return;
161            }
162            self.sniff = None;
163            let skip = match bom {
164                Some((l, k)) => {
165                    self.label = l;
166                    self.state = fresh(l);
167                    k
168                }
169                None => 0,
170            };
171            held_n = s.len() - skip;
172            held[..held_n].copy_from_slice(&s[skip..]);
173        }
174        if held_n > 0 {
175            self.run(&held[..held_n], last && input.is_empty(), out);
176        }
177        if !input.is_empty() || held_n == 0 {
178            self.run(input, last, out);
179        }
180    }
181
182    fn run(&mut self, input: &[u8], last: bool, out: &mut String) {
183        if let Label::Single(c) = self.label {
184            for &b in input {
185                let ch = c.decode_char(b);
186                self.malformed |= ch.is_none();
187                out.push(ch.unwrap_or(char::REPLACEMENT_CHARACTER));
188            }
189            return;
190        }
191        if let State::Replacement { done } = &mut self.state {
192            if !*done && !input.is_empty() {
193                *done = true;
194                self.malformed = true;
195                out.push(char::REPLACEMENT_CHARACTER);
196            }
197            if last {
198                self.state = State::Replacement { done: false };
199            }
200            return;
201        }
202        out.reserve(input.len());
203        let mut i = 0;
204        loop {
205            let b = if let Some(b) = self.queue.pop() {
206                Some(b)
207            } else if i < input.len() {
208                // where no sequence is open: valid UTF-8 at once, ASCII as itself (in ISO-2022-JP's ASCII state
209                // but SO, SI and ESC)
210                let run = match self.state {
211                    State::Utf8 { need: 0, .. } => match core::str::from_utf8(&input[i..]) {
212                        Ok(s) => s.len(),
213                        Err(e) => e.valid_up_to(),
214                    },
215                    State::Iso2022Jp { state: Jp::Ascii, ref mut flag, .. } => {
216                        let n = input[i..].iter().position(|&x| x >= 0x80 || matches!(x, 0x0E | 0x0F | 0x1B)).unwrap_or(input.len() - i);
217                        if n > 0 {
218                            *flag = false;
219                        }
220                        n
221                    }
222                    _ if self.idle() => input[i..].iter().position(|&x| x >= 0x80).unwrap_or(input.len() - i),
223                    _ => 0,
224                };
225                if run > 0 {
226                    out.push_str(core::str::from_utf8(&input[i..i + run]).unwrap_or(""));
227                    i += run;
228                    continue;
229                }
230                i += 1;
231                Some(input[i - 1])
232            } else if last {
233                None
234            } else {
235                return;
236            };
237            match self.step(b) {
238                Out::Continue => {}
239                Out::Finished => {
240                    self.state = fresh(self.label);
241                    return;
242                }
243                Out::Error => {
244                    self.malformed = true;
245                    out.push(char::REPLACEMENT_CHARACTER);
246                }
247                Out::Char(c) => out.push(char::from_u32(c).unwrap_or(char::REPLACEMENT_CHARACTER)),
248                Out::Pair(a, c) => {
249                    out.push(char::from_u32(a).unwrap_or(char::REPLACEMENT_CHARACTER));
250                    out.push(char::from_u32(c).unwrap_or(char::REPLACEMENT_CHARACTER));
251                }
252            }
253        }
254    }
255
256    // no sequence open, ASCII is ASCII
257    fn idle(&self) -> bool {
258        match self.state {
259            State::Utf8 { need, .. } => need == 0,
260            State::ShiftJis { lead } | State::Big5 { lead } | State::EucKr { lead } | State::EucJp { lead, .. } => lead == 0,
261            State::Gb18030 { first, .. } => first == 0,
262            _ => false,
263        }
264    }
265
266    // one step of the standard's decoder: a byte, or None for the end of the input
267    fn step(&mut self, byte: Option<u8>) -> Out {
268        let q = &mut self.queue;
269        match &mut self.state {
270            State::Utf8 { cp, seen, need, lower, upper } => {
271                let Some(b) = byte else {
272                    if *need != 0 {
273                        *need = 0;
274                        return Out::Error;
275                    }
276                    return Out::Finished;
277                };
278                if *need == 0 {
279                    match b {
280                        0x00..=0x7F => return Out::Char(b as u32),
281                        0xC2..=0xDF => {
282                            *need = 1;
283                            *cp = (b & 0x1F) as u32;
284                        }
285                        0xE0..=0xEF => {
286                            if b == 0xE0 {
287                                *lower = 0xA0;
288                            }
289                            if b == 0xED {
290                                *upper = 0x9F;
291                            }
292                            *need = 2;
293                            *cp = (b & 0xF) as u32;
294                        }
295                        0xF0..=0xF4 => {
296                            if b == 0xF0 {
297                                *lower = 0x90;
298                            }
299                            if b == 0xF4 {
300                                *upper = 0x8F;
301                            }
302                            *need = 3;
303                            *cp = (b & 0x7) as u32;
304                        }
305                        _ => return Out::Error,
306                    }
307                    return Out::Continue;
308                }
309                if b < *lower || b > *upper {
310                    (*cp, *need, *seen, *lower, *upper) = (0, 0, 0, 0x80, 0xBF);
311                    q.restore(&[b]);
312                    return Out::Error;
313                }
314                (*lower, *upper) = (0x80, 0xBF);
315                *cp = (*cp << 6) | (b & 0x3F) as u32;
316                *seen += 1;
317                if seen != need {
318                    return Out::Continue;
319                }
320                let c = *cp;
321                (*cp, *need, *seen) = (0, 0, 0);
322                Out::Char(c)
323            }
324            State::Utf16 { le, lead, surrogate } => {
325                let Some(b) = byte else {
326                    if lead.is_some() || surrogate.is_some() {
327                        (*lead, *surrogate) = (None, None);
328                        return Out::Error;
329                    }
330                    return Out::Finished;
331                };
332                let Some(l) = lead.take() else {
333                    *lead = Some(b);
334                    return Out::Continue;
335                };
336                let unit = if *le { (b as u16) << 8 | l as u16 } else { (l as u16) << 8 | b as u16 };
337                if let Some(s) = surrogate.take() {
338                    if (0xDC00..=0xDFFF).contains(&unit) {
339                        return Out::Char(0x10000 + ((s as u32 - 0xD800) << 10) + (unit as u32 - 0xDC00));
340                    }
341                    let (hi, lo) = ((unit >> 8) as u8, unit as u8);
342                    q.restore(&if *le { [lo, hi] } else { [hi, lo] });
343                    return Out::Error;
344                }
345                match unit {
346                    0xD800..=0xDBFF => {
347                        *surrogate = Some(unit);
348                        Out::Continue
349                    }
350                    0xDC00..=0xDFFF => Out::Error,
351                    _ => Out::Char(unit as u32),
352                }
353            }
354            State::Single | State::Replacement { .. } => Out::Finished,
355            State::ShiftJis { lead } => {
356                let Some(b) = byte else {
357                    return end(lead);
358                };
359                if *lead != 0 {
360                    let l = core::mem::take(lead) as usize;
361                    let offset = if b < 0x7F { 0x40 } else { 0x41 };
362                    let lead_offset = if l < 0xA0 { 0x81 } else { 0xC1 };
363                    if matches!(b, 0x40..=0x7E | 0x80..=0xFC) {
364                        let p = (l - lead_offset) * 188 + b as usize - offset;
365                        if (8836..=10715).contains(&p) {
366                            return Out::Char(0xE000 - 8836 + p as u32);
367                        }
368                        let c = cjk::JIS0208.get(p);
369                        if c != 0 {
370                            return Out::Char(c as u32);
371                        }
372                    }
373                    return error_keep_ascii(b, q);
374                }
375                match b {
376                    0x00..=0x80 => Out::Char(b as u32),
377                    0xA1..=0xDF => Out::Char(0xFF61 - 0xA1 + b as u32),
378                    0x81..=0x9F | 0xE0..=0xFC => {
379                        *lead = b;
380                        Out::Continue
381                    }
382                    _ => Out::Error,
383                }
384            }
385            State::EucJp { lead, jis0212 } => {
386                let Some(b) = byte else {
387                    return end(lead);
388                };
389                if *lead == 0x8E && (0xA1..=0xDF).contains(&b) {
390                    *lead = 0;
391                    return Out::Char(0xFF61 - 0xA1 + b as u32);
392                }
393                if *lead == 0x8F && (0xA1..=0xFE).contains(&b) {
394                    *jis0212 = true;
395                    *lead = b;
396                    return Out::Continue;
397                }
398                if *lead != 0 {
399                    let l = core::mem::take(lead);
400                    let mut c = 0;
401                    if (0xA1..=0xFE).contains(&l) && (0xA1..=0xFE).contains(&b) {
402                        let p = (l - 0xA1) as usize * 94 + (b - 0xA1) as usize;
403                        c = if *jis0212 { cjk::JIS0212.get(p) } else { cjk::JIS0208.get(p) };
404                    }
405                    *jis0212 = false;
406                    if c != 0 {
407                        return Out::Char(c as u32);
408                    }
409                    return error_keep_ascii(b, q);
410                }
411                match b {
412                    0x00..=0x7F => Out::Char(b as u32),
413                    0x8E | 0x8F | 0xA1..=0xFE => {
414                        *lead = b;
415                        Out::Continue
416                    }
417                    _ => Out::Error,
418                }
419            }
420            State::Iso2022Jp { state, output, lead, flag } => iso2022jp(state, output, lead, flag, byte, q),
421            State::Gb18030 { first, second, third } => {
422                let Some(b) = byte else {
423                    if *first == 0 && *second == 0 && *third == 0 {
424                        return Out::Finished;
425                    }
426                    (*first, *second, *third) = (0, 0, 0);
427                    return Out::Error;
428                };
429                if *third != 0 {
430                    if !b.is_ascii_digit() {
431                        q.restore(&[*second, *third, b]);
432                        (*first, *second, *third) = (0, 0, 0);
433                        return Out::Error;
434                    }
435                    let p = (*first as u32 - 0x81) * 12600 + (*second as u32 - 0x30) * 1260 + (*third as u32 - 0x81) * 10 + b as u32 - 0x30;
436                    (*first, *second, *third) = (0, 0, 0);
437                    return match gb18030_range_code_point(p) {
438                        Some(c) => Out::Char(c),
439                        None => Out::Error,
440                    };
441                }
442                if *second != 0 {
443                    if (0x81..=0xFE).contains(&b) {
444                        *third = b;
445                        return Out::Continue;
446                    }
447                    q.restore(&[*second, b]);
448                    (*first, *second) = (0, 0);
449                    return Out::Error;
450                }
451                if *first != 0 {
452                    if b.is_ascii_digit() {
453                        *second = b;
454                        return Out::Continue;
455                    }
456                    let l = core::mem::take(first) as usize;
457                    let offset = if b < 0x7F { 0x40 } else { 0x41 };
458                    if matches!(b, 0x40..=0x7E | 0x80..=0xFE) {
459                        let c = cjk::GB18030.get((l - 0x81) * 190 + b as usize - offset);
460                        if c != 0 {
461                            return Out::Char(c as u32);
462                        }
463                    }
464                    return error_keep_ascii(b, q);
465                }
466                match b {
467                    0x00..=0x7F => Out::Char(b as u32),
468                    0x80 => Out::Char(0x20AC),
469                    0x81..=0xFE => {
470                        *first = b;
471                        Out::Continue
472                    }
473                    _ => Out::Error,
474                }
475            }
476            State::Big5 { lead } => {
477                let Some(b) = byte else {
478                    return end(lead);
479                };
480                if *lead != 0 {
481                    let l = core::mem::take(lead) as usize;
482                    let offset = if b < 0x7F { 0x40 } else { 0x62 };
483                    if matches!(b, 0x40..=0x7E | 0xA1..=0xFE) {
484                        let p = (l - 0x81) * 157 + b as usize - offset;
485                        match p {
486                            1133 => return Out::Pair(0x00CA, 0x0304),
487                            1135 => return Out::Pair(0x00CA, 0x030C),
488                            1164 => return Out::Pair(0x00EA, 0x0304),
489                            1166 => return Out::Pair(0x00EA, 0x030C),
490                            _ => {}
491                        }
492                        let c = big5_code_point(p);
493                        if c != 0 {
494                            return Out::Char(c);
495                        }
496                    }
497                    return error_keep_ascii(b, q);
498                }
499                match b {
500                    0x00..=0x7F => Out::Char(b as u32),
501                    0x81..=0xFE => {
502                        *lead = b;
503                        Out::Continue
504                    }
505                    _ => Out::Error,
506                }
507            }
508            State::EucKr { lead } => {
509                let Some(b) = byte else {
510                    return end(lead);
511                };
512                if *lead != 0 {
513                    let l = core::mem::take(lead) as usize;
514                    if (0x41..=0xFE).contains(&b) {
515                        let c = cjk::EUC_KR.get((l - 0x81) * 190 + b as usize - 0x41);
516                        if c != 0 {
517                            return Out::Char(c as u32);
518                        }
519                    }
520                    return error_keep_ascii(b, q);
521                }
522                match b {
523                    0x00..=0x7F => Out::Char(b as u32),
524                    0x81..=0xFE => {
525                        *lead = b;
526                        Out::Continue
527                    }
528                    _ => Out::Error,
529                }
530            }
531        }
532    }
533}
534
535// whether these first bytes may still become a byte-order mark (a proper beginning of one)
536fn maybe_bom(s: &[u8]) -> bool {
537    s.len() < 3 && [0xEF, 0xBB, 0xBF].starts_with(s) || s.len() < 2 && ([0xFF, 0xFE].starts_with(s) || [0xFE, 0xFF].starts_with(s))
538}
539
540// the end of the input with a lead byte open (an error) or not (finished)
541fn end(lead: &mut u8) -> Out {
542    if core::mem::take(lead) != 0 { Out::Error } else { Out::Finished }
543}
544
545// a lead byte without a character: an ASCII byte after it is read again
546fn error_keep_ascii(b: u8, q: &mut Queue) -> Out {
547    if b < 0x80 {
548        q.restore(&[b]);
549    }
550    Out::Error
551}
552
553fn iso2022jp(state: &mut Jp, output: &mut Jp, lead: &mut u8, flag: &mut bool, byte: Option<u8>, q: &mut Queue) -> Out {
554    let esc = |state: &mut Jp| {
555        *state = Jp::EscapeStart;
556        Out::Continue
557    };
558    match *state {
559        Jp::Ascii => match byte {
560            Some(0x1B) => esc(state),
561            Some(b @ 0x00..=0x7F) if b != 0x0E && b != 0x0F => {
562                *flag = false;
563                Out::Char(b as u32)
564            }
565            None => Out::Finished,
566            _ => {
567                *flag = false;
568                Out::Error
569            }
570        },
571        Jp::Roman => match byte {
572            Some(0x1B) => esc(state),
573            Some(0x5C) => {
574                *flag = false;
575                Out::Char(0xA5)
576            }
577            Some(0x7E) => {
578                *flag = false;
579                Out::Char(0x203E)
580            }
581            Some(b @ 0x00..=0x7F) if b != 0x0E && b != 0x0F => {
582                *flag = false;
583                Out::Char(b as u32)
584            }
585            None => Out::Finished,
586            _ => {
587                *flag = false;
588                Out::Error
589            }
590        },
591        Jp::Katakana => match byte {
592            Some(0x1B) => esc(state),
593            Some(b @ 0x21..=0x5F) => {
594                *flag = false;
595                Out::Char(0xFF61 - 0x21 + b as u32)
596            }
597            None => Out::Finished,
598            _ => {
599                *flag = false;
600                Out::Error
601            }
602        },
603        Jp::LeadByte => match byte {
604            Some(0x1B) => esc(state),
605            Some(b @ 0x21..=0x7E) => {
606                *flag = false;
607                *lead = b;
608                *state = Jp::TrailByte;
609                Out::Continue
610            }
611            None => Out::Finished,
612            _ => {
613                *flag = false;
614                Out::Error
615            }
616        },
617        Jp::TrailByte => match byte {
618            Some(0x1B) => {
619                *state = Jp::EscapeStart;
620                Out::Error
621            }
622            Some(b @ 0x21..=0x7E) => {
623                *state = Jp::LeadByte;
624                let c = cjk::JIS0208.get((*lead - 0x21) as usize * 94 + (b - 0x21) as usize);
625                if c == 0 { Out::Error } else { Out::Char(c as u32) }
626            }
627            // (the end of the input is read again in the lead byte state: finished)
628            _ => {
629                *state = Jp::LeadByte;
630                Out::Error
631            }
632        },
633        Jp::EscapeStart => {
634            if let Some(b @ (0x24 | 0x28)) = byte {
635                *lead = b;
636                *state = Jp::Escape;
637                return Out::Continue;
638            }
639            if let Some(b) = byte {
640                q.restore(&[b]);
641            }
642            *flag = false;
643            *state = *output;
644            Out::Error
645        }
646        Jp::Escape => {
647            let l = core::mem::take(lead);
648            let next = match (l, byte) {
649                (0x28, Some(0x42)) => Some(Jp::Ascii),
650                (0x28, Some(0x4A)) => Some(Jp::Roman),
651                (0x28, Some(0x49)) => Some(Jp::Katakana),
652                (0x24, Some(0x40 | 0x42)) => Some(Jp::LeadByte),
653                _ => None,
654            };
655            if let Some(s) = next {
656                *state = s;
657                *output = s;
658                let was = core::mem::replace(flag, true);
659                return if was { Out::Error } else { Out::Continue };
660            }
661            match byte {
662                Some(b) => q.restore(&[l, b]),
663                None => q.restore(&[l]),
664            }
665            *flag = false;
666            *state = *output;
667            Out::Error
668        }
669    }
670}