Skip to main content

encoding_rs/
utf_16.rs

1// Copyright Mozilla Foundation. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10use super::*;
11use crate::handles::*;
12use crate::variant::*;
13
14pub struct Utf16Decoder {
15    lead_surrogate: u16, // If non-zero and pending_bmp == false, a pending lead surrogate
16    lead_byte: Option<u8>,
17    be: bool,
18    pending_bmp: bool, // if true, lead_surrogate is actually pending BMP
19}
20
21impl Utf16Decoder {
22    pub fn new(big_endian: bool) -> VariantDecoder {
23        VariantDecoder::Utf16(Utf16Decoder {
24            lead_surrogate: 0,
25            lead_byte: None,
26            be: big_endian,
27            pending_bmp: false,
28        })
29    }
30
31    pub fn additional_from_state(&self) -> usize {
32        // A pending BMP code unit is stored in `lead_surrogate` and may be zero.
33        1 + if self.lead_byte.is_some() { 1 } else { 0 }
34            + if self.lead_surrogate == 0 && !self.pending_bmp {
35                0
36            } else {
37                2
38            }
39    }
40
41    pub fn max_utf16_buffer_length(&self, byte_length: usize) -> Option<usize> {
42        checked_add(
43            1,
44            checked_div(byte_length.checked_add(self.additional_from_state()), 2),
45        )
46    }
47
48    pub fn max_utf8_buffer_length_without_replacement(&self, byte_length: usize) -> Option<usize> {
49        checked_add(
50            1,
51            checked_mul(
52                3,
53                checked_div(byte_length.checked_add(self.additional_from_state()), 2),
54            ),
55        )
56    }
57
58    pub fn max_utf8_buffer_length(&self, byte_length: usize) -> Option<usize> {
59        checked_add(
60            1,
61            checked_mul(
62                3,
63                checked_div(byte_length.checked_add(self.additional_from_state()), 2),
64            ),
65        )
66    }
67
68    decoder_functions!(
69        preamble = {
70            if self.pending_bmp {
71                match dest.check_space_bmp() {
72                    Space::Full(_) => {
73                        return (DecoderResult::OutputFull, 0, 0);
74                    }
75                    Space::Available(destination_handle) => {
76                        destination_handle.write_bmp(self.lead_surrogate);
77                        self.pending_bmp = false;
78                        self.lead_surrogate = 0;
79                    }
80                }
81            }
82        },
83        loop_preamble = {
84            // This is the fast path. The rest runs only at the
85            // start and end for partial sequences.
86            if self.lead_byte.is_none()
87                && self.lead_surrogate == 0
88                && let Some((read, written)) = if self.be {
89                    dest.copy_utf16_from::<BigEndian>(&mut source)
90                } else {
91                    dest.copy_utf16_from::<LittleEndian>(&mut source)
92                }
93            {
94                return (DecoderResult::Malformed(2, 0), read, written);
95            }
96        },
97        eof = {
98            debug_assert!(!self.pending_bmp);
99            if self.lead_surrogate != 0 || self.lead_byte.is_some() {
100                // We need to check space without intent to write in order to
101                // make sure that there is space for the replacement character.
102                match dest.check_space_bmp() {
103                    Space::Full(_) => {
104                        return (DecoderResult::OutputFull, 0, 0);
105                    }
106                    Space::Available(_) => {
107                        if self.lead_surrogate != 0 {
108                            self.lead_surrogate = 0;
109                            match self.lead_byte {
110                                None => {
111                                    return (
112                                        DecoderResult::Malformed(2, 0),
113                                        src_consumed,
114                                        dest.written(),
115                                    );
116                                }
117                                Some(_) => {
118                                    self.lead_byte = None;
119                                    return (
120                                        DecoderResult::Malformed(3, 0),
121                                        src_consumed,
122                                        dest.written(),
123                                    );
124                                }
125                            }
126                        }
127                        debug_assert!(self.lead_byte.is_some());
128                        self.lead_byte = None;
129                        return (DecoderResult::Malformed(1, 0), src_consumed, dest.written());
130                    }
131                }
132            }
133        },
134        body = {
135            match self.lead_byte {
136                None => {
137                    self.lead_byte = Some(b);
138                    continue;
139                }
140                Some(lead) => {
141                    self.lead_byte = None;
142                    let code_unit = if self.be {
143                        u16::from(lead) << 8 | u16::from(b)
144                    } else {
145                        u16::from(b) << 8 | u16::from(lead)
146                    };
147                    let high_bits = code_unit & 0xFC00u16;
148                    if high_bits == 0xD800u16 {
149                        // high surrogate
150                        if self.lead_surrogate != 0 {
151                            // The previous high surrogate was in
152                            // error and this one becomes the new
153                            // pending one.
154                            self.lead_surrogate = code_unit;
155                            return (
156                                DecoderResult::Malformed(2, 2),
157                                unread_handle.consumed(),
158                                destination_handle.written(),
159                            );
160                        }
161                        self.lead_surrogate = code_unit;
162                        continue;
163                    }
164                    if high_bits == 0xDC00u16 {
165                        // low surrogate
166                        if self.lead_surrogate == 0 {
167                            return (
168                                DecoderResult::Malformed(2, 0),
169                                unread_handle.consumed(),
170                                destination_handle.written(),
171                            );
172                        }
173                        destination_handle.write_surrogate_pair(self.lead_surrogate, code_unit);
174                        self.lead_surrogate = 0;
175                        continue;
176                    }
177                    // bmp
178                    if self.lead_surrogate != 0 {
179                        // The previous high surrogate was in
180                        // error and this code unit becomes a
181                        // pending BMP character.
182                        self.lead_surrogate = code_unit;
183                        self.pending_bmp = true;
184                        return (
185                            DecoderResult::Malformed(2, 2),
186                            unread_handle.consumed(),
187                            destination_handle.written(),
188                        );
189                    }
190                    destination_handle.write_bmp(code_unit);
191                    continue;
192                }
193            }
194        },
195        self = self,
196        src_consumed = src_consumed,
197        dest = dest,
198        source = source,
199        byte = b,
200        destination_handle = destination_handle,
201        unread_handle = unread_handle,
202        destination_check = check_space_astral
203    );
204}
205
206// Any copyright to the test code below this comment is dedicated to the
207// Public Domain. http://creativecommons.org/publicdomain/zero/1.0/
208
209#[cfg(all(test, feature = "alloc"))]
210mod tests {
211    use super::super::testing::*;
212    use super::super::*;
213
214    fn decode_utf_16le(bytes: &[u8], expect: &str) {
215        decode_without_padding(UTF_16LE, bytes, expect);
216    }
217
218    fn decode_utf_16be(bytes: &[u8], expect: &str) {
219        decode_without_padding(UTF_16BE, bytes, expect);
220    }
221
222    fn encode_utf_16le(string: &str, expect: &[u8]) {
223        encode(UTF_16LE, string, expect);
224    }
225
226    fn encode_utf_16be(string: &str, expect: &[u8]) {
227        encode(UTF_16BE, string, expect);
228    }
229
230    #[test]
231    fn test_utf_16_decode() {
232        decode_utf_16le(b"", "");
233        decode_utf_16be(b"", "");
234
235        decode_utf_16le(b"\x61\x00\x62\x00", "\u{0061}\u{0062}");
236        decode_utf_16be(b"\x00\x61\x00\x62", "\u{0061}\u{0062}");
237
238        decode_utf_16le(b"\xFE\xFF\x00\x61\x00\x62", "\u{0061}\u{0062}");
239        decode_utf_16be(b"\xFF\xFE\x61\x00\x62\x00", "\u{0061}\u{0062}");
240
241        decode_utf_16le(b"\x61\x00\x62", "\u{0061}\u{FFFD}");
242        decode_utf_16be(b"\x00\x61\x00", "\u{0061}\u{FFFD}");
243
244        decode_utf_16le(b"\x3D\xD8\xA9", "\u{FFFD}");
245        decode_utf_16be(b"\xD8\x3D\xDC", "\u{FFFD}");
246
247        decode_utf_16le(b"\x3D\xD8\xA9\xDC\x03\x26", "\u{1F4A9}\u{2603}");
248        decode_utf_16be(b"\xD8\x3D\xDC\xA9\x26\x03", "\u{1F4A9}\u{2603}");
249
250        decode_utf_16le(b"\xA9\xDC\x03\x26", "\u{FFFD}\u{2603}");
251        decode_utf_16be(b"\xDC\xA9\x26\x03", "\u{FFFD}\u{2603}");
252
253        decode_utf_16le(b"\x3D\xD8\x03\x26", "\u{FFFD}\u{2603}");
254        decode_utf_16be(b"\xD8\x3D\x26\x03", "\u{FFFD}\u{2603}");
255
256        // The \xFF makes sure that the parts before and after have different alignment
257        let long_le = b"\x00\x00\x00\x00\x00\x00\x00\x00\x3D\xD8\xA9\xDC\x00\x00\x00\x00\x00\x00\x00\x00\x3D\xD8\x00\x00\x00\x00\x00\x00\x00\x00\xA9\xDC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x3D\xD8\xFF\x00\x00\x00\x00\x00\x00\x00\x00\x3D\xD8\xA9\xDC\x00\x00\x00\x00\x00\x00\x00\x00\x3D\xD8\x00\x00\x00\x00\x00\x00\x00\x00\xA9\xDC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x3D\xD8";
258        let long_be = b"\x00\x00\x00\x00\x00\x00\x00\x00\xD8\x3D\xDC\xA9\x00\x00\x00\x00\x00\x00\x00\x00\xD8\x3D\x00\x00\x00\x00\x00\x00\x00\x00\xDC\xA9\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xD8\x3D\xFF\x00\x00\x00\x00\x00\x00\x00\x00\xD8\x3D\xDC\xA9\x00\x00\x00\x00\x00\x00\x00\x00\xD8\x3D\x00\x00\x00\x00\x00\x00\x00\x00\xDC\xA9\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xD8\x3D";
259        let long_expect = "\x00\x00\x00\x00\u{1F4A9}\x00\x00\x00\x00\u{FFFD}\x00\x00\x00\x00\u{FFFD}\x00\x00\x00\x00\x00\x00\x00\x00\u{FFFD}";
260        decode_utf_16le(&long_le[..long_le.len() / 2], long_expect);
261        decode_utf_16be(&long_be[..long_be.len() / 2], long_expect);
262        decode_utf_16le(&long_le[long_le.len() / 2 + 1..], long_expect);
263        decode_utf_16be(&long_be[long_be.len() / 2 + 1..], long_expect);
264    }
265
266    #[test]
267    fn test_utf_16_encode() {
268        // Empty
269        encode_utf_16be("", b"");
270        encode_utf_16le("", b"");
271
272        // Encodes as UTF-8
273        assert_eq!(UTF_16LE.new_encoder().encoding(), UTF_8);
274        assert_eq!(UTF_16BE.new_encoder().encoding(), UTF_8);
275        encode_utf_16le("\u{1F4A9}\u{2603}", "\u{1F4A9}\u{2603}".as_bytes());
276        encode_utf_16be("\u{1F4A9}\u{2603}", "\u{1F4A9}\u{2603}".as_bytes());
277    }
278
279    #[test]
280    fn test_utf_16be_decode_one_by_one() {
281        let input = b"\x00\x61\x00\xE4\x26\x03\xD8\x3D\xDC\xA9";
282        let mut output = [0u16; 20];
283        let mut decoder = UTF_16BE.new_decoder();
284        for b in input.chunks(1) {
285            assert_eq!(b.len(), 1);
286            let needed = decoder.max_utf16_buffer_length(b.len()).unwrap();
287            let (result, read, _, had_errors) =
288                decoder.decode_to_utf16(b, &mut output[..needed], false);
289            assert_eq!(result, CoderResult::InputEmpty);
290            assert_eq!(read, 1);
291            assert!(!had_errors);
292        }
293    }
294
295    #[test]
296    fn test_utf_16le_decode_one_by_one() {
297        let input = b"\x61\x00\xE4\x00\x03\x26\x3D\xD8\xA9\xDC";
298        let mut output = [0u16; 20];
299        let mut decoder = UTF_16LE.new_decoder();
300        for b in input.chunks(1) {
301            assert_eq!(b.len(), 1);
302            let needed = decoder.max_utf16_buffer_length(b.len()).unwrap();
303            let (result, read, _, had_errors) =
304                decoder.decode_to_utf16(b, &mut output[..needed], false);
305            assert_eq!(result, CoderResult::InputEmpty);
306            assert_eq!(read, 1);
307            assert!(!had_errors);
308        }
309    }
310
311    #[test]
312    fn test_utf_16be_decode_three_at_a_time() {
313        let input = b"\x00\xE4\x26\x03\xD8\x3D\xDC\xA9\x00\x61\x00\xE4";
314        let mut output = [0u16; 20];
315        let mut decoder = UTF_16BE.new_decoder();
316        for b in input.chunks(3) {
317            assert_eq!(b.len(), 3);
318            let needed = decoder.max_utf16_buffer_length(b.len()).unwrap();
319            let (result, read, _, had_errors) =
320                decoder.decode_to_utf16(b, &mut output[..needed], false);
321            assert_eq!(result, CoderResult::InputEmpty);
322            assert_eq!(read, b.len());
323            assert!(!had_errors);
324        }
325    }
326
327    #[test]
328    fn test_utf_16le_decode_three_at_a_time() {
329        let input = b"\xE4\x00\x03\x26\x3D\xD8\xA9\xDC\x61\x00\xE4\x00";
330        let mut output = [0u16; 20];
331        let mut decoder = UTF_16LE.new_decoder();
332        for b in input.chunks(3) {
333            assert_eq!(b.len(), 3);
334            let needed = decoder.max_utf16_buffer_length(b.len()).unwrap();
335            let (result, read, _, had_errors) =
336                decoder.decode_to_utf16(b, &mut output[..needed], false);
337            assert_eq!(result, CoderResult::InputEmpty);
338            assert_eq!(read, b.len());
339            assert!(!had_errors);
340        }
341    }
342
343    #[test]
344    fn test_utf_16le_decode_bom_prefixed_split_byte_pair() {
345        let mut output = [0u16; 20];
346        let mut decoder = UTF_16LE.new_decoder();
347        {
348            let needed = decoder.max_utf16_buffer_length(1).unwrap();
349            let (result, read, written, had_errors) =
350                decoder.decode_to_utf16(b"\xFF", &mut output[..needed], false);
351            assert_eq!(result, CoderResult::InputEmpty);
352            assert_eq!(read, 1);
353            assert_eq!(written, 0);
354            assert!(!had_errors);
355        }
356        {
357            let needed = decoder.max_utf16_buffer_length(1).unwrap();
358            let (result, read, written, had_errors) =
359                decoder.decode_to_utf16(b"\xFD", &mut output[..needed], true);
360            assert_eq!(result, CoderResult::InputEmpty);
361            assert_eq!(read, 1);
362            assert_eq!(written, 1);
363            assert!(!had_errors);
364            assert_eq!(output[0], 0xFDFF);
365        }
366    }
367
368    #[test]
369    fn test_utf_16be_decode_bom_prefixed_split_byte_pair() {
370        let mut output = [0u16; 20];
371        let mut decoder = UTF_16BE.new_decoder();
372        {
373            let needed = decoder.max_utf16_buffer_length(1).unwrap();
374            let (result, read, written, had_errors) =
375                decoder.decode_to_utf16(b"\xFE", &mut output[..needed], false);
376            assert_eq!(result, CoderResult::InputEmpty);
377            assert_eq!(read, 1);
378            assert_eq!(written, 0);
379            assert!(!had_errors);
380        }
381        {
382            let needed = decoder.max_utf16_buffer_length(1).unwrap();
383            let (result, read, written, had_errors) =
384                decoder.decode_to_utf16(b"\xFD", &mut output[..needed], true);
385            assert_eq!(result, CoderResult::InputEmpty);
386            assert_eq!(read, 1);
387            assert_eq!(written, 1);
388            assert!(!had_errors);
389            assert_eq!(output[0], 0xFEFD);
390        }
391    }
392
393    #[test]
394    fn test_utf_16le_decode_bom_prefix() {
395        let mut output = [0u16; 20];
396        let mut decoder = UTF_16LE.new_decoder();
397        {
398            let needed = decoder.max_utf16_buffer_length(1).unwrap();
399            let (result, read, written, had_errors) =
400                decoder.decode_to_utf16(b"\xFF", &mut output[..needed], true);
401            assert_eq!(result, CoderResult::InputEmpty);
402            assert_eq!(read, 1);
403            assert_eq!(written, 1);
404            assert!(had_errors);
405            assert_eq!(output[0], 0xFFFD);
406        }
407    }
408
409    #[test]
410    fn test_utf_16be_decode_bom_prefix() {
411        let mut output = [0u16; 20];
412        let mut decoder = UTF_16BE.new_decoder();
413        {
414            let needed = decoder.max_utf16_buffer_length(1).unwrap();
415            let (result, read, written, had_errors) =
416                decoder.decode_to_utf16(b"\xFE", &mut output[..needed], true);
417            assert_eq!(result, CoderResult::InputEmpty);
418            assert_eq!(read, 1);
419            assert_eq!(written, 1);
420            assert!(had_errors);
421            assert_eq!(output[0], 0xFFFD);
422        }
423    }
424
425    #[test]
426    fn test_utf_16le_decode_near_end() {
427        let mut output = [0u8; 4];
428        let mut decoder = UTF_16LE.new_decoder();
429        {
430            let (result, read, written, had_errors) =
431                decoder.decode_to_utf8(&[0x03], &mut output[..], false);
432            assert_eq!(result, CoderResult::InputEmpty);
433            assert_eq!(read, 1);
434            assert_eq!(written, 0);
435            assert!(!had_errors);
436            assert_eq!(output[0], 0x0);
437        }
438        {
439            let (result, read, written, had_errors) =
440                decoder.decode_to_utf8(&[0x26, 0x03, 0x26], &mut output[..], false);
441            assert_eq!(result, CoderResult::OutputFull);
442            assert_eq!(read, 1);
443            assert_eq!(written, 3);
444            assert!(!had_errors);
445            assert_eq!(output[0], 0xE2);
446            assert_eq!(output[1], 0x98);
447            assert_eq!(output[2], 0x83);
448            assert_eq!(output[3], 0x00);
449        }
450    }
451
452    #[test]
453    fn test_utf_16le_pending_nul_max_length() {
454        // An unpaired high surrogate followed by U+0000 leaves U+0000 pending.
455        // The max length queries must count it like any other pending code unit.
456        let mut decoder = UTF_16LE.new_decoder_without_bom_handling();
457        let mut output = [0u8; 16];
458        let (result, _, _) =
459            decoder.decode_to_utf8_without_replacement(&[0x00, 0xD8], &mut output[..], false);
460        assert_eq!(result, DecoderResult::InputEmpty);
461        let (result, read, _) = decoder.decode_to_utf8_without_replacement(
462            &[0x00, 0x00, 0x00, 0x4E, 0x00, 0x4E],
463            &mut output[..],
464            false,
465        );
466        assert_eq!(result, DecoderResult::Malformed(2, 2));
467        assert_eq!(read, 2);
468        let rest = [0x00, 0x4E, 0x00, 0x4E];
469        let max = decoder
470            .max_utf8_buffer_length_without_replacement(rest.len())
471            .unwrap();
472        let mut output = vec![0u8; max];
473        let (result, read, written) =
474            decoder.decode_to_utf8_without_replacement(&rest, &mut output[..], true);
475        assert_eq!(result, DecoderResult::InputEmpty);
476        assert_eq!(read, 4);
477        assert_eq!(&output[..written], "\u{0000}\u{4E00}\u{4E00}".as_bytes());
478    }
479
480    #[test]
481    fn test_utf_16be_decode_near_end() {
482        let mut output = [0u8; 4];
483        let mut decoder = UTF_16BE.new_decoder();
484        {
485            let (result, read, written, had_errors) =
486                decoder.decode_to_utf8(&[0x26], &mut output[..], false);
487            assert_eq!(result, CoderResult::InputEmpty);
488            assert_eq!(read, 1);
489            assert_eq!(written, 0);
490            assert!(!had_errors);
491            assert_eq!(output[0], 0x0);
492        }
493        {
494            let (result, read, written, had_errors) =
495                decoder.decode_to_utf8(&[0x03, 0x26, 0x03], &mut output[..], false);
496            assert_eq!(result, CoderResult::OutputFull);
497            assert_eq!(read, 1);
498            assert_eq!(written, 3);
499            assert!(!had_errors);
500            assert_eq!(output[0], 0xE2);
501            assert_eq!(output[1], 0x98);
502            assert_eq!(output[2], 0x83);
503            assert_eq!(output[3], 0x00);
504        }
505    }
506}