Skip to main content

encoding_rs/
utf_8.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::ascii::ascii_to_basic_latin;
12use crate::ascii::basic_latin_to_ascii;
13use crate::ascii::validate_ascii;
14use crate::handles::*;
15use crate::mem::convert_utf16_to_utf8_partial;
16use crate::variant::*;
17
18cfg_if! {
19    if #[cfg(feature = "simd-accel")] {
20        use ::core::intrinsics::unlikely;
21        use ::core::intrinsics::likely;
22    } else {
23        #[inline(always)]
24        fn unlikely(b: bool) -> bool {
25            b
26        }
27        #[inline(always)]
28        fn likely(b: bool) -> bool {
29            b
30        }
31    }
32}
33
34#[repr(align(64))] // Align to cache lines
35pub struct Utf8Data {
36    pub table: [u8; 384],
37}
38
39// BEGIN GENERATED CODE. PLEASE DO NOT EDIT.
40// Instead, please regenerate using generate-encoding-data.py
41
42pub static UTF8_DATA: Utf8Data = Utf8Data {
43    table: [
44        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
45        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
46        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
47        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
48        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
49        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
50        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
51        252, 252, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 148, 148, 148,
52        148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 164, 164, 164, 164, 164,
53        164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164,
54        164, 164, 164, 164, 164, 164, 164, 164, 164, 252, 252, 252, 252, 252, 252, 252, 252, 252,
55        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
56        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
57        252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
58        252, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
59        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
60        4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
61        8, 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 32, 8, 8, 64, 8, 8, 8, 128, 4,
62        4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
63    ],
64};
65
66// END GENERATED CODE
67
68// The UTF-8 validation code provided by this crate is faster than the UTF-8 validation code
69// provided by the standard library. When SIMD is used, the simdutf8 crate is much faster
70// than the code here. However, when SIMD isn't used, simdutf8 delegates to the standard
71// library and not here. To use the code here when SSE 4.2 isn't available for simdutf8
72// to use, let's implement custom dispatch here. As a bonus, the `core_detect` crate
73// works without `std`.
74
75cfg_if! {
76    if #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] {
77        #[inline(always)]
78        fn fast_utf8_valid_up_to(src: &[u8]) -> Option<usize> {
79            if src.len() >= 64 {
80                // SAFETY: The cfg check above ensures that the precondition, NEON availability on aarch64, is satisfied.
81                Some(match unsafe { simdutf8::compat::imp::aarch64::neon::validate_utf8(src) } {
82                    Ok(_) => src.len(),
83                    Err(e) => e.valid_up_to(),
84                })
85            } else {
86                None
87            }
88        }
89    } else if #[cfg(target_feature = "avx2")] {
90        #[inline(always)]
91        fn fast_utf8_valid_up_to(src: &[u8]) -> Option<usize> {
92            if src.len() >= 64 {
93                // SAFETY: The cfg check above ensures that the precondition, AVX2 availability, is satisfied.
94                Some(match unsafe { simdutf8::compat::imp::x86::avx2::validate_utf8(src) } {
95                    Ok(_) => src.len(),
96                    Err(e) => e.valid_up_to(),
97                })
98            } else {
99                None
100            }
101        }
102    } else if #[cfg(target_feature = "sse4.2")] {
103        #[inline(always)]
104        fn fast_utf8_valid_up_to(src: &[u8]) -> Option<usize> {
105            if src.len() >= 64 {
106                if core_detect::is_x86_feature_detected!("avx2") {
107                    // SAFETY: The dynamic check above ensures that the precondition, AVX2 availability, is satisfied.
108                    Some(match unsafe { simdutf8::compat::imp::x86::avx2::validate_utf8(src) } {
109                        Ok(_) => src.len(),
110                        Err(e) => e.valid_up_to(),
111                    })
112                } else {
113                    // SAFETY: The cfg check above ensures that the precondition, SSE 4.2 availability, is satisfied.
114                    Some(match unsafe { simdutf8::compat::imp::x86::sse42::validate_utf8(src) } {
115                        Ok(_) => src.len(),
116                        Err(e) => e.valid_up_to(),
117                    })
118                }
119            } else {
120                None
121            }
122        }
123    } else if #[cfg(target_feature = "sse")] { // "sse" stands in for cpuid availability
124        #[inline(always)]
125        fn fast_utf8_valid_up_to(src: &[u8]) -> Option<usize> {
126            if src.len() >= 64 {
127                if core_detect::is_x86_feature_detected!("avx2") {
128                    // SAFETY: The dynamic check above ensures that the precondition, AVX2 availability, is satisfied.
129                    Some(match unsafe { simdutf8::compat::imp::x86::avx2::validate_utf8(src) } {
130                        Ok(_) => src.len(),
131                        Err(e) => e.valid_up_to(),
132                    })
133                } else if core_detect::is_x86_feature_detected!("sse4.2") {
134                    // SAFETY: The dynamic check above ensures that the precondition, SSE 4.2 availability, is satisfied.
135                    Some(match unsafe { simdutf8::compat::imp::x86::sse42::validate_utf8(src) } {
136                        Ok(_) => src.len(),
137                        Err(e) => e.valid_up_to(),
138                    })
139                } else {
140                    None
141                }
142            } else {
143                None
144            }
145        }
146    } else if #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))] {
147        #[inline(always)]
148        fn fast_utf8_valid_up_to(src: &[u8]) -> Option<usize> {
149            if src.len() >= 64 {
150                // SAFETY: The cfg check above ensures that the precondition, simd128 availability on wasm32, is satisfied.
151                Some(match unsafe { simdutf8::compat::imp::wasm32::simd128::validate_utf8(src) } {
152                    Ok(_) => src.len(),
153                    Err(e) => e.valid_up_to(),
154                })
155            } else {
156                None
157            }
158        }
159    } else {
160        #[inline(always)]
161        fn fast_utf8_valid_up_to(_src: &[u8]) -> Option<usize> {
162            None
163        }
164    }
165}
166
167pub fn utf8_valid_up_to(src: &[u8]) -> usize {
168    if let Some(up_to) = fast_utf8_valid_up_to(src) {
169        return up_to;
170    }
171
172    let mut read = 0;
173    'outer: loop {
174        let mut byte = {
175            let src_remaining = &src[read..];
176            match validate_ascii(src_remaining) {
177                None => {
178                    return src.len();
179                }
180                Some((non_ascii, consumed)) => {
181                    read += consumed;
182                    non_ascii
183                }
184            }
185        };
186        // Check for the longest sequence to avoid checking twice for the
187        // multi-byte sequences. This can't overflow with 64-bit address space,
188        // because full 64 bits aren't in use. In the 32-bit PAE case, for this
189        // to overflow would mean that the source slice would be so large that
190        // the address space of the process would not have space for any code.
191        // Therefore, the slice cannot be so long that this would overflow.
192        if likely(read + 4 <= src.len()) {
193            'inner: loop {
194                // At this point, `byte` is not included in `read`, because we
195                // don't yet know that a) the UTF-8 sequence is valid and b) that there
196                // is output space if it is an astral sequence.
197                // Inspecting the lead byte directly is faster than what the
198                // std lib does!
199                if likely(in_inclusive_range8(byte, 0xC2, 0xDF)) {
200                    // Two-byte
201                    let second = unsafe { *(src.get_unchecked(read + 1)) };
202                    if !in_inclusive_range8(second, 0x80, 0xBF) {
203                        break 'outer;
204                    }
205                    read += 2;
206
207                    // Next lead (manually inlined)
208                    if likely(read + 4 <= src.len()) {
209                        byte = unsafe { *(src.get_unchecked(read)) };
210                        if byte < 0x80 {
211                            read += 1;
212                            continue 'outer;
213                        }
214                        continue 'inner;
215                    }
216                    break 'inner;
217                }
218                if likely(byte < 0xF0) {
219                    'three: loop {
220                        // Three-byte
221                        let second = unsafe { *(src.get_unchecked(read + 1)) };
222                        let third = unsafe { *(src.get_unchecked(read + 2)) };
223                        if ((UTF8_DATA.table[usize::from(second)]
224                            & unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
225                            | (third >> 6))
226                            != 2
227                        {
228                            break 'outer;
229                        }
230                        read += 3;
231
232                        // Next lead (manually inlined)
233                        if likely(read + 4 <= src.len()) {
234                            byte = unsafe { *(src.get_unchecked(read)) };
235                            if in_inclusive_range8(byte, 0xE0, 0xEF) {
236                                continue 'three;
237                            }
238                            if likely(byte < 0x80) {
239                                read += 1;
240                                continue 'outer;
241                            }
242                            continue 'inner;
243                        }
244                        break 'inner;
245                    }
246                }
247                // Four-byte
248                let second = unsafe { *(src.get_unchecked(read + 1)) };
249                let third = unsafe { *(src.get_unchecked(read + 2)) };
250                let fourth = unsafe { *(src.get_unchecked(read + 3)) };
251                if (u16::from(
252                    UTF8_DATA.table[usize::from(second)]
253                        & unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) },
254                ) | u16::from(third >> 6)
255                    | (u16::from(fourth & 0xC0) << 2))
256                    != 0x202
257                {
258                    break 'outer;
259                }
260                read += 4;
261
262                // Next lead
263                if likely(read + 4 <= src.len()) {
264                    byte = unsafe { *(src.get_unchecked(read)) };
265                    if byte < 0x80 {
266                        read += 1;
267                        continue 'outer;
268                    }
269                    continue 'inner;
270                }
271                break 'inner;
272            }
273        }
274        // We can't have a complete 4-byte sequence, but we could still have
275        // one to three shorter sequences.
276        'tail: loop {
277            // >= is better for bound check elision than ==
278            if read >= src.len() {
279                break 'outer;
280            }
281            byte = src[read];
282            // At this point, `byte` is not included in `read`, because we
283            // don't yet know that a) the UTF-8 sequence is valid and b) that there
284            // is output space if it is an astral sequence.
285            // Inspecting the lead byte directly is faster than what the
286            // std lib does!
287            if byte < 0x80 {
288                read += 1;
289                continue 'tail;
290            }
291            if in_inclusive_range8(byte, 0xC2, 0xDF) {
292                // Two-byte
293                let new_read = read + 2;
294                if new_read > src.len() {
295                    break 'outer;
296                }
297                let second = src[read + 1];
298                if !in_inclusive_range8(second, 0x80, 0xBF) {
299                    break 'outer;
300                }
301                read += 2;
302                continue 'tail;
303            }
304            // We need to exclude valid four byte lead bytes, because
305            // `UTF8_DATA.second_mask` covers
306            if byte < 0xF0 {
307                // Three-byte
308                let new_read = read + 3;
309                if new_read > src.len() {
310                    break 'outer;
311                }
312                let second = src[read + 1];
313                let third = src[read + 2];
314                if ((UTF8_DATA.table[usize::from(second)]
315                    & unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
316                    | (third >> 6))
317                    != 2
318                {
319                    break 'outer;
320                }
321                read += 3;
322                // `'tail` handles sequences shorter than 4, so
323                // there can't be another sequence after this one.
324                break 'outer;
325            }
326            break 'outer;
327        }
328    }
329    read
330}
331
332#[inline(always)]
333#[allow(clippy::never_loop, clippy::cognitive_complexity)]
334pub fn convert_utf8_to_utf16_up_to_invalid(src: &[u8], dst: &mut [u16]) -> (usize, usize) {
335    let mut read = 0;
336    let mut written = 0;
337    'outer: loop {
338        let mut byte = {
339            let src_remaining = &src[read..];
340            let dst_remaining = &mut dst[written..];
341            let length = ::core::cmp::min(src_remaining.len(), dst_remaining.len());
342            match ascii_to_basic_latin(src_remaining, dst_remaining) {
343                None => {
344                    read += length;
345                    written += length;
346                    break 'outer;
347                }
348                Some((non_ascii, consumed)) => {
349                    read += consumed;
350                    written += consumed;
351                    non_ascii
352                }
353            }
354        };
355        // Check for the longest sequence to avoid checking twice for the
356        // multi-byte sequences. This can't overflow with 64-bit address space,
357        // because full 64 bits aren't in use. In the 32-bit PAE case, for this
358        // to overflow would mean that the source slice would be so large that
359        // the address space of the process would not have space for any code.
360        // Therefore, the slice cannot be so long that this would overflow.
361        if likely(read + 4 <= src.len()) {
362            'inner: loop {
363                // At this point, `byte` is not included in `read`, because we
364                // don't yet know that a) the UTF-8 sequence is valid and b) that there
365                // is output space if it is an astral sequence.
366                // We know, thanks to `ascii_to_basic_latin` that there is output
367                // space for at least one UTF-16 code unit, so no need to check
368                // for output space in the BMP cases.
369                // Inspecting the lead byte directly is faster than what the
370                // std lib does!
371                if likely(in_inclusive_range8(byte, 0xC2, 0xDF)) {
372                    // Two-byte
373                    let second = unsafe { *(src.get_unchecked(read + 1)) };
374                    if !in_inclusive_range8(second, 0x80, 0xBF) {
375                        break 'outer;
376                    }
377                    unsafe {
378                        *(dst.get_unchecked_mut(written)) =
379                            ((u16::from(byte) & 0x1F) << 6) | (u16::from(second) & 0x3F)
380                    };
381                    read += 2;
382                    written += 1;
383
384                    // Next lead (manually inlined)
385                    if written == dst.len() {
386                        break 'outer;
387                    }
388                    if likely(read + 4 <= src.len()) {
389                        byte = unsafe { *(src.get_unchecked(read)) };
390                        if byte < 0x80 {
391                            unsafe { *(dst.get_unchecked_mut(written)) = u16::from(byte) };
392                            read += 1;
393                            written += 1;
394                            continue 'outer;
395                        }
396                        continue 'inner;
397                    }
398                    break 'inner;
399                }
400                if likely(byte < 0xF0) {
401                    'three: loop {
402                        // Three-byte
403                        let second = unsafe { *(src.get_unchecked(read + 1)) };
404                        let third = unsafe { *(src.get_unchecked(read + 2)) };
405                        if ((UTF8_DATA.table[usize::from(second)]
406                            & unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
407                            | (third >> 6))
408                            != 2
409                        {
410                            break 'outer;
411                        }
412                        let point = ((u16::from(byte) & 0xF) << 12)
413                            | ((u16::from(second) & 0x3F) << 6)
414                            | (u16::from(third) & 0x3F);
415                        unsafe { *(dst.get_unchecked_mut(written)) = point };
416                        read += 3;
417                        written += 1;
418
419                        // Next lead (manually inlined)
420                        if written == dst.len() {
421                            break 'outer;
422                        }
423                        if likely(read + 4 <= src.len()) {
424                            byte = unsafe { *(src.get_unchecked(read)) };
425                            if in_inclusive_range8(byte, 0xE0, 0xEF) {
426                                continue 'three;
427                            }
428                            if likely(byte < 0x80) {
429                                unsafe { *(dst.get_unchecked_mut(written)) = u16::from(byte) };
430                                read += 1;
431                                written += 1;
432                                continue 'outer;
433                            }
434                            continue 'inner;
435                        }
436                        break 'inner;
437                    }
438                }
439                // Four-byte
440                if written + 1 == dst.len() {
441                    break 'outer;
442                }
443                let second = unsafe { *(src.get_unchecked(read + 1)) };
444                let third = unsafe { *(src.get_unchecked(read + 2)) };
445                let fourth = unsafe { *(src.get_unchecked(read + 3)) };
446                if (u16::from(
447                    UTF8_DATA.table[usize::from(second)]
448                        & unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) },
449                ) | u16::from(third >> 6)
450                    | (u16::from(fourth & 0xC0) << 2))
451                    != 0x202
452                {
453                    break 'outer;
454                }
455                let point = ((u32::from(byte) & 0x7) << 18)
456                    | ((u32::from(second) & 0x3F) << 12)
457                    | ((u32::from(third) & 0x3F) << 6)
458                    | (u32::from(fourth) & 0x3F);
459                unsafe { *(dst.get_unchecked_mut(written)) = (0xD7C0 + (point >> 10)) as u16 };
460                unsafe {
461                    *(dst.get_unchecked_mut(written + 1)) = (0xDC00 + (point & 0x3FF)) as u16
462                };
463                read += 4;
464                written += 2;
465
466                // Next lead
467                if written == dst.len() {
468                    break 'outer;
469                }
470                if likely(read + 4 <= src.len()) {
471                    byte = unsafe { *(src.get_unchecked(read)) };
472                    if byte < 0x80 {
473                        unsafe { *(dst.get_unchecked_mut(written)) = u16::from(byte) };
474                        read += 1;
475                        written += 1;
476                        // See `u8u16punct` branch for punctuation loop here.
477                        continue 'outer;
478                    }
479                    continue 'inner;
480                }
481                break 'inner;
482            }
483        }
484        // We can't have a complete 4-byte sequence, but we could still have
485        // one to three shorter sequences.
486        'tail: loop {
487            // >= is better for bound check elision than ==
488            if read >= src.len() || written >= dst.len() {
489                break 'outer;
490            }
491            byte = src[read];
492            // At this point, `byte` is not included in `read`, because we
493            // don't yet know that a) the UTF-8 sequence is valid and b) that there
494            // is output space if it is an astral sequence.
495            // Inspecting the lead byte directly is faster than what the
496            // std lib does!
497            if byte < 0x80 {
498                dst[written] = u16::from(byte);
499                read += 1;
500                written += 1;
501                continue 'tail;
502            }
503            if in_inclusive_range8(byte, 0xC2, 0xDF) {
504                // Two-byte
505                let new_read = read + 2;
506                if new_read > src.len() {
507                    break 'outer;
508                }
509                let second = src[read + 1];
510                if !in_inclusive_range8(second, 0x80, 0xBF) {
511                    break 'outer;
512                }
513                dst[written] = ((u16::from(byte) & 0x1F) << 6) | (u16::from(second) & 0x3F);
514                read += 2;
515                written += 1;
516                continue 'tail;
517            }
518            // We need to exclude valid four byte lead bytes, because
519            // `UTF8_DATA.second_mask` covers
520            if byte < 0xF0 {
521                // Three-byte
522                let new_read = read + 3;
523                if new_read > src.len() {
524                    break 'outer;
525                }
526                let second = src[read + 1];
527                let third = src[read + 2];
528                if ((UTF8_DATA.table[usize::from(second)]
529                    & unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
530                    | (third >> 6))
531                    != 2
532                {
533                    break 'outer;
534                }
535                let point = ((u16::from(byte) & 0xF) << 12)
536                    | ((u16::from(second) & 0x3F) << 6)
537                    | (u16::from(third) & 0x3F);
538                dst[written] = point;
539                read += 3;
540                written += 1;
541                // `'tail` handles sequences shorter than 4, so
542                // there can't be another sequence after this one.
543                break 'outer;
544            }
545            break 'outer;
546        }
547    }
548    (read, written)
549}
550
551pub struct Utf8Decoder {
552    code_point: u32,
553    bytes_seen: usize,   // 1, 2 or 3: counts continuations only
554    bytes_needed: usize, // 1, 2 or 3: counts continuations only
555    lower_boundary: u8,
556    upper_boundary: u8,
557}
558
559impl Utf8Decoder {
560    pub fn new_inner() -> Utf8Decoder {
561        Utf8Decoder {
562            code_point: 0,
563            bytes_seen: 0,
564            bytes_needed: 0,
565            lower_boundary: 0x80u8,
566            upper_boundary: 0xBFu8,
567        }
568    }
569
570    pub fn new() -> VariantDecoder {
571        VariantDecoder::Utf8(Utf8Decoder::new_inner())
572    }
573
574    pub fn in_neutral_state(&self) -> bool {
575        self.bytes_needed == 0
576    }
577
578    fn extra_from_state(&self) -> usize {
579        if self.bytes_needed == 0 {
580            0
581        } else {
582            self.bytes_seen + 1
583        }
584    }
585
586    pub fn max_utf16_buffer_length(&self, byte_length: usize) -> Option<usize> {
587        byte_length.checked_add(1 + self.extra_from_state())
588    }
589
590    pub fn max_utf8_buffer_length_without_replacement(&self, byte_length: usize) -> Option<usize> {
591        byte_length.checked_add(3 + self.extra_from_state())
592    }
593
594    pub fn max_utf8_buffer_length(&self, byte_length: usize) -> Option<usize> {
595        checked_add(
596            3,
597            checked_mul(3, byte_length.checked_add(self.extra_from_state())),
598        )
599    }
600
601    decoder_functions!(
602        preamble = {},
603        loop_preamble = {
604            // This is the fast path. The rest runs only at the
605            // start and end for partial sequences.
606            if self.bytes_needed == 0 {
607                dest.copy_utf8_up_to_invalid_from(&mut source);
608            }
609        },
610        eof = {
611            if self.bytes_needed != 0 {
612                let bad_bytes = (self.bytes_seen + 1) as u8;
613                self.code_point = 0;
614                self.bytes_needed = 0;
615                self.bytes_seen = 0;
616                return (
617                    DecoderResult::Malformed(bad_bytes, 0),
618                    src_consumed,
619                    dest.written(),
620                );
621            }
622        },
623        body = {
624            if self.bytes_needed == 0 {
625                if b < 0x80u8 {
626                    destination_handle.write_ascii(b);
627                    continue;
628                }
629                if b < 0xC2u8 {
630                    return (
631                        DecoderResult::Malformed(1, 0),
632                        unread_handle.consumed(),
633                        destination_handle.written(),
634                    );
635                }
636                if b < 0xE0u8 {
637                    self.bytes_needed = 1;
638                    self.code_point = u32::from(b) & 0x1F;
639                    continue;
640                }
641                if b < 0xF0u8 {
642                    if b == 0xE0u8 {
643                        self.lower_boundary = 0xA0u8;
644                    } else if b == 0xEDu8 {
645                        self.upper_boundary = 0x9Fu8;
646                    }
647                    self.bytes_needed = 2;
648                    self.code_point = u32::from(b) & 0xF;
649                    continue;
650                }
651                if b < 0xF5u8 {
652                    if b == 0xF0u8 {
653                        self.lower_boundary = 0x90u8;
654                    } else if b == 0xF4u8 {
655                        self.upper_boundary = 0x8Fu8;
656                    }
657                    self.bytes_needed = 3;
658                    self.code_point = u32::from(b) & 0x7;
659                    continue;
660                }
661                return (
662                    DecoderResult::Malformed(1, 0),
663                    unread_handle.consumed(),
664                    destination_handle.written(),
665                );
666            }
667            // self.bytes_needed != 0
668            if !(b >= self.lower_boundary && b <= self.upper_boundary) {
669                let bad_bytes = (self.bytes_seen + 1) as u8;
670                self.code_point = 0;
671                self.bytes_needed = 0;
672                self.bytes_seen = 0;
673                self.lower_boundary = 0x80u8;
674                self.upper_boundary = 0xBFu8;
675                return (
676                    DecoderResult::Malformed(bad_bytes, 0),
677                    unread_handle.unread(),
678                    destination_handle.written(),
679                );
680            }
681            self.lower_boundary = 0x80u8;
682            self.upper_boundary = 0xBFu8;
683            self.code_point = (self.code_point << 6) | (u32::from(b) & 0x3F);
684            self.bytes_seen += 1;
685            if self.bytes_seen != self.bytes_needed {
686                continue;
687            }
688            if self.bytes_needed == 3 {
689                destination_handle.write_astral(self.code_point);
690            } else {
691                destination_handle.write_bmp_excl_ascii(self.code_point as u16);
692            }
693            self.code_point = 0;
694            self.bytes_needed = 0;
695            self.bytes_seen = 0;
696            continue;
697        },
698        self = self,
699        src_consumed = src_consumed,
700        dest = dest,
701        source = source,
702        byte = b,
703        destination_handle = destination_handle,
704        unread_handle = unread_handle,
705        destination_check = check_space_astral
706    );
707}
708
709#[allow(clippy::never_loop)]
710#[inline(never)]
711#[crate::multiversion(targets("x86_64+avx2+bmi1", "x86+avx2+bmi1"))]
712pub fn convert_utf16_to_utf8_partial_inner(src: &[u16], dst: &mut [u8]) -> (usize, usize) {
713    let mut read = 0;
714    let mut written = 0;
715    'outer: loop {
716        let mut unit = {
717            // `basic_latin_to_ascii` may write garbage beyond the logical number
718            // of read and written code units. If `dst` was longer than necessary,
719            // this would not be a problem, since we know that every code unit
720            // in input will result in at least one code unit in output, so the
721            // garbage would get subsequently overwritten. However, when the
722            // conversion here ends due to running out of output space, we
723            // may have a situation where we have written a byte of garbage
724            // to output, but we don't overwrite it, because there is not
725            // enough space in the output for every possible scalar (4 bytes).
726            //
727            // Therefore, let's make the destination slice that this function
728            // operates on 3 bytes shorter to make the SIMD code stop a bit
729            // earlier and then `convert_utf16_to_utf8_partial_tail` will
730            // handle the part that this function does not.
731            let capped_dst_len = dst.len().saturating_sub(3);
732            if written >= capped_dst_len {
733                return (read, written);
734            }
735            let src_remaining = &src[read..];
736            let dst_remaining = &mut dst[written..capped_dst_len];
737            let length = if dst_remaining.len() < src_remaining.len() {
738                dst_remaining.len()
739            } else {
740                src_remaining.len()
741            };
742            match basic_latin_to_ascii(src_remaining, dst_remaining) {
743                None => {
744                    read += length;
745                    written += length;
746                    return (read, written);
747                }
748                Some((non_ascii, consumed)) => {
749                    read += consumed;
750                    written += consumed;
751                    non_ascii
752                }
753            }
754        };
755        'inner: loop {
756            // The following loop is only broken out of as a goto forward.
757            loop {
758                // Unfortunately, this check isn't enough for the compiler to elide
759                // the bound checks on writes to dst, which is why they are manually
760                // elided, which makes a measurable difference.
761                if written.checked_add(4).unwrap() > dst.len() {
762                    return (read, written);
763                }
764                read += 1;
765                if unit < 0x800 {
766                    unsafe {
767                        *(dst.get_unchecked_mut(written)) = (unit >> 6) as u8 | 0xC0u8;
768                        written += 1;
769                        *(dst.get_unchecked_mut(written)) = (unit & 0x3F) as u8 | 0x80u8;
770                        written += 1;
771                    }
772                    break;
773                }
774                let unit_minus_surrogate_start = unit.wrapping_sub(0xD800);
775                if likely(unit_minus_surrogate_start > (0xDFFF - 0xD800)) {
776                    unsafe {
777                        *(dst.get_unchecked_mut(written)) = (unit >> 12) as u8 | 0xE0u8;
778                        written += 1;
779                        *(dst.get_unchecked_mut(written)) = ((unit & 0xFC0) >> 6) as u8 | 0x80u8;
780                        written += 1;
781                        *(dst.get_unchecked_mut(written)) = (unit & 0x3F) as u8 | 0x80u8;
782                        written += 1;
783                    }
784                    break;
785                }
786                if likely(unit_minus_surrogate_start <= (0xDBFF - 0xD800)) {
787                    // high surrogate
788                    // read > src.len() is impossible, but using
789                    // >= instead of == allows the compiler to elide a bound check.
790                    if read >= src.len() {
791                        debug_assert_eq!(read, src.len());
792                        // Unpaired surrogate at the end of the buffer.
793                        unsafe {
794                            *(dst.get_unchecked_mut(written)) = 0xEFu8;
795                            written += 1;
796                            *(dst.get_unchecked_mut(written)) = 0xBFu8;
797                            written += 1;
798                            *(dst.get_unchecked_mut(written)) = 0xBDu8;
799                            written += 1;
800                        }
801                        return (read, written);
802                    }
803                    let second = src[read];
804                    let second_minus_low_surrogate_start = second.wrapping_sub(0xDC00);
805                    if likely(second_minus_low_surrogate_start <= (0xDFFF - 0xDC00)) {
806                        // The next code unit is a low surrogate. Advance position.
807                        read += 1;
808                        let astral = (u32::from(unit) << 10) + u32::from(second)
809                            - (((0xD800u32 << 10) - 0x10000u32) + 0xDC00u32);
810                        unsafe {
811                            *(dst.get_unchecked_mut(written)) = (astral >> 18) as u8 | 0xF0u8;
812                            written += 1;
813                            *(dst.get_unchecked_mut(written)) =
814                                ((astral & 0x3F000u32) >> 12) as u8 | 0x80u8;
815                            written += 1;
816                            *(dst.get_unchecked_mut(written)) =
817                                ((astral & 0xFC0u32) >> 6) as u8 | 0x80u8;
818                            written += 1;
819                            *(dst.get_unchecked_mut(written)) = (astral & 0x3F) as u8 | 0x80u8;
820                            written += 1;
821                        }
822                        break;
823                    }
824                    // The next code unit is not a low surrogate. Don't advance
825                    // position and treat the high surrogate as unpaired.
826                    // Fall through
827                }
828                // Unpaired low surrogate
829                unsafe {
830                    *(dst.get_unchecked_mut(written)) = 0xEFu8;
831                    written += 1;
832                    *(dst.get_unchecked_mut(written)) = 0xBFu8;
833                    written += 1;
834                    *(dst.get_unchecked_mut(written)) = 0xBDu8;
835                    written += 1;
836                }
837                break;
838            }
839            'punctuation: loop {
840                // Now see if the next unit is Basic Latin
841                // read > src.len() is impossible, but using
842                // >= instead of == allows the compiler to elide a bound check.
843                if read >= src.len() {
844                    debug_assert_eq!(read, src.len());
845                    return (read, written);
846                }
847                unit = src[read];
848                if unlikely(unit < 0x80) {
849                    // written > dst.len() is impossible, but using
850                    // >= instead of == allows the compiler to elide a bound check.
851                    if written >= dst.len() {
852                        debug_assert_eq!(written, dst.len());
853                        return (read, written);
854                    }
855                    dst[written] = unit as u8;
856                    read += 1;
857                    written += 1;
858                    // A punctuation check was slower in 2018 but makes sense in 2026.
859                    if unit < 0x3C {
860                        continue 'punctuation;
861                    }
862                    continue 'outer;
863                }
864                continue 'inner;
865            }
866        }
867    }
868}
869
870#[inline(never)]
871pub fn convert_utf16_to_utf8_partial_tail(src: &[u16], dst: &mut [u8]) -> (usize, usize) {
872    // Everything below is cold code!
873    let mut read = 0;
874    let mut written = 0;
875    let mut unit = src[read];
876    // We now have up to 3 output slots, so an astral character
877    // will not fit.
878    if unit < 0x800 {
879        loop {
880            if unit < 0x80 {
881                if written >= dst.len() {
882                    return (read, written);
883                }
884                read += 1;
885                dst[written] = unit as u8;
886                written += 1;
887            } else if unit < 0x800 {
888                if written + 2 > dst.len() {
889                    return (read, written);
890                }
891                read += 1;
892                dst[written] = (unit >> 6) as u8 | 0xC0u8;
893                written += 1;
894                dst[written] = (unit & 0x3F) as u8 | 0x80u8;
895                written += 1;
896            } else {
897                return (read, written);
898            }
899            // read > src.len() is impossible, but using
900            // >= instead of == allows the compiler to elide a bound check.
901            if read >= src.len() {
902                debug_assert_eq!(read, src.len());
903                return (read, written);
904            }
905            unit = src[read];
906        }
907    }
908    // Could be an unpaired surrogate, but we'll need 3 output
909    // slots in any case.
910    if written + 3 > dst.len() {
911        return (read, written);
912    }
913    read += 1;
914    let unit_minus_surrogate_start = unit.wrapping_sub(0xD800);
915    if unit_minus_surrogate_start <= (0xDFFF - 0xD800) {
916        // Got surrogate
917        if unit_minus_surrogate_start <= (0xDBFF - 0xD800) {
918            // Got high surrogate
919            #[allow(clippy::branches_sharing_code)]
920            if read >= src.len() {
921                // Unpaired high surrogate
922                unit = 0xFFFD;
923            } else {
924                let second = src[read];
925                if in_inclusive_range16(second, 0xDC00, 0xDFFF) {
926                    // Valid surrogate pair, but we know it won't fit.
927                    read -= 1;
928                    return (read, written);
929                }
930                // Unpaired high
931                unit = 0xFFFD;
932            }
933        } else {
934            // Unpaired low
935            unit = 0xFFFD;
936        }
937    }
938    dst[written] = (unit >> 12) as u8 | 0xE0u8;
939    written += 1;
940    dst[written] = ((unit & 0xFC0) >> 6) as u8 | 0x80u8;
941    written += 1;
942    dst[written] = (unit & 0x3F) as u8 | 0x80u8;
943    written += 1;
944    debug_assert_eq!(written, dst.len());
945    (read, written)
946}
947
948pub struct Utf8Encoder;
949
950impl Utf8Encoder {
951    pub fn new(encoding: &'static Encoding) -> Encoder {
952        Encoder::new(encoding, VariantEncoder::Utf8(Utf8Encoder))
953    }
954
955    pub fn max_buffer_length_from_utf16_without_replacement(
956        &self,
957        u16_length: usize,
958    ) -> Option<usize> {
959        u16_length.checked_mul(3)
960    }
961
962    pub fn max_buffer_length_from_utf8_without_replacement(
963        &self,
964        byte_length: usize,
965    ) -> Option<usize> {
966        Some(byte_length)
967    }
968
969    pub fn encode_from_utf16_raw(
970        &mut self,
971        src: &[u16],
972        dst: &mut [u8],
973        _last: bool,
974    ) -> (EncoderResult, usize, usize) {
975        let (read, written) = convert_utf16_to_utf8_partial(src, dst);
976        (
977            if read == src.len() {
978                EncoderResult::InputEmpty
979            } else {
980                EncoderResult::OutputFull
981            },
982            read,
983            written,
984        )
985    }
986
987    pub fn encode_from_utf8_raw(
988        &mut self,
989        src: &str,
990        dst: &mut [u8],
991        _last: bool,
992    ) -> (EncoderResult, usize, usize) {
993        let bytes = src.as_bytes();
994        let mut to_write = bytes.len();
995        if to_write <= dst.len() {
996            dst[..to_write].copy_from_slice(bytes);
997            return (EncoderResult::InputEmpty, to_write, to_write);
998        }
999        to_write = dst.len();
1000        // Move back until we find a UTF-8 sequence boundary.
1001        while (bytes[to_write] & 0xC0) == 0x80 {
1002            to_write -= 1;
1003        }
1004        dst[..to_write].copy_from_slice(&bytes[..to_write]);
1005        (EncoderResult::OutputFull, to_write, to_write)
1006    }
1007}
1008
1009// Any copyright to the test code below this comment is dedicated to the
1010// Public Domain. http://creativecommons.org/publicdomain/zero/1.0/
1011
1012#[cfg(all(test, feature = "alloc"))]
1013mod tests {
1014    use super::super::testing::*;
1015    use super::super::*;
1016
1017    //    fn decode_utf8_to_utf16(bytes: &[u8], expect: &[u16]) {
1018    //        decode_to_utf16_without_replacement(UTF_8, bytes, expect);
1019    //    }
1020
1021    fn decode_utf8_to_utf8(bytes: &[u8], expect: &str) {
1022        decode_to_utf8(UTF_8, bytes, expect);
1023    }
1024
1025    fn decode_valid_utf8(string: &str) {
1026        decode_utf8_to_utf8(string.as_bytes(), string);
1027    }
1028
1029    fn encode_utf8_from_utf16(string: &[u16], expect: &[u8]) {
1030        encode_from_utf16(UTF_8, string, expect);
1031    }
1032
1033    fn encode_utf8_from_utf8(string: &str, expect: &[u8]) {
1034        encode_from_utf8(UTF_8, string, expect);
1035    }
1036
1037    fn encode_utf8_from_utf16_with_output_limit(
1038        string: &[u16],
1039        expect: &str,
1040        limit: usize,
1041        expect_result: EncoderResult,
1042    ) {
1043        let mut dst = Vec::new();
1044        {
1045            dst.resize(limit, 0u8);
1046            let mut encoder = UTF_8.new_encoder();
1047            let (result, read, written) =
1048                encoder.encode_from_utf16_without_replacement(string, &mut dst, false);
1049            assert_eq!(result, expect_result);
1050            if expect_result == EncoderResult::InputEmpty {
1051                assert_eq!(read, string.len());
1052            }
1053            assert_eq!(&dst[..written], expect.as_bytes());
1054        }
1055        {
1056            dst.resize(64, 0u8);
1057            for (i, elem) in dst.iter_mut().enumerate() {
1058                *elem = i as u8;
1059            }
1060            let mut encoder = UTF_8.new_encoder();
1061            let (_, _, mut j) =
1062                encoder.encode_from_utf16_without_replacement(string, &mut dst, false);
1063            while j < dst.len() {
1064                assert_eq!(usize::from(dst[j]), j);
1065                j += 1;
1066            }
1067        }
1068    }
1069
1070    #[test]
1071    fn test_utf8_decode() {
1072        // Empty
1073        decode_valid_utf8("");
1074        // ASCII
1075        decode_valid_utf8("ab");
1076        // Low BMP
1077        decode_valid_utf8("a\u{E4}Z");
1078        // High BMP
1079        decode_valid_utf8("a\u{2603}Z");
1080        // Astral
1081        decode_valid_utf8("a\u{1F4A9}Z");
1082        // Low BMP with last byte missing
1083        decode_utf8_to_utf8(b"a\xC3Z", "a\u{FFFD}Z");
1084        decode_utf8_to_utf8(b"a\xC3", "a\u{FFFD}");
1085        // High BMP with last byte missing
1086        decode_utf8_to_utf8(b"a\xE2\x98Z", "a\u{FFFD}Z");
1087        decode_utf8_to_utf8(b"a\xE2\x98", "a\u{FFFD}");
1088        // Astral with last byte missing
1089        decode_utf8_to_utf8(b"a\xF0\x9F\x92Z", "a\u{FFFD}Z");
1090        decode_utf8_to_utf8(b"a\xF0\x9F\x92", "a\u{FFFD}");
1091        // Lone highest continuation
1092        decode_utf8_to_utf8(b"a\xBFZ", "a\u{FFFD}Z");
1093        decode_utf8_to_utf8(b"a\xBF", "a\u{FFFD}");
1094        // Two lone highest continuations
1095        decode_utf8_to_utf8(b"a\xBF\xBFZ", "a\u{FFFD}\u{FFFD}Z");
1096        decode_utf8_to_utf8(b"a\xBF\xBF", "a\u{FFFD}\u{FFFD}");
1097        // Low BMP followed by lowest lone continuation
1098        decode_utf8_to_utf8(b"a\xC3\xA4\x80Z", "a\u{E4}\u{FFFD}Z");
1099        decode_utf8_to_utf8(b"a\xC3\xA4\x80", "a\u{E4}\u{FFFD}");
1100        // Low BMP followed by highest lone continuation
1101        decode_utf8_to_utf8(b"a\xC3\xA4\xBFZ", "a\u{E4}\u{FFFD}Z");
1102        decode_utf8_to_utf8(b"a\xC3\xA4\xBF", "a\u{E4}\u{FFFD}");
1103        // High BMP followed by lowest lone continuation
1104        decode_utf8_to_utf8(b"a\xE2\x98\x83\x80Z", "a\u{2603}\u{FFFD}Z");
1105        decode_utf8_to_utf8(b"a\xE2\x98\x83\x80", "a\u{2603}\u{FFFD}");
1106        // High BMP followed by highest lone continuation
1107        decode_utf8_to_utf8(b"a\xE2\x98\x83\xBFZ", "a\u{2603}\u{FFFD}Z");
1108        decode_utf8_to_utf8(b"a\xE2\x98\x83\xBF", "a\u{2603}\u{FFFD}");
1109        // Astral followed by lowest lone continuation
1110        decode_utf8_to_utf8(b"a\xF0\x9F\x92\xA9\x80Z", "a\u{1F4A9}\u{FFFD}Z");
1111        decode_utf8_to_utf8(b"a\xF0\x9F\x92\xA9\x80", "a\u{1F4A9}\u{FFFD}");
1112        // Astral followed by highest lone continuation
1113        decode_utf8_to_utf8(b"a\xF0\x9F\x92\xA9\xBFZ", "a\u{1F4A9}\u{FFFD}Z");
1114        decode_utf8_to_utf8(b"a\xF0\x9F\x92\xA9\xBF", "a\u{1F4A9}\u{FFFD}");
1115
1116        // Boundary conditions
1117        // Lowest single-byte
1118        decode_valid_utf8("Z\x00");
1119        decode_valid_utf8("Z\x00Z");
1120        // Lowest single-byte as two-byte overlong sequence
1121        decode_utf8_to_utf8(b"a\xC0\x80", "a\u{FFFD}\u{FFFD}");
1122        decode_utf8_to_utf8(b"a\xC0\x80Z", "a\u{FFFD}\u{FFFD}Z");
1123        // Lowest single-byte as three-byte overlong sequence
1124        decode_utf8_to_utf8(b"a\xE0\x80\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}");
1125        decode_utf8_to_utf8(b"a\xE0\x80\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}Z");
1126        // Lowest single-byte as four-byte overlong sequence
1127        decode_utf8_to_utf8(b"a\xF0\x80\x80\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1128        decode_utf8_to_utf8(b"a\xF0\x80\x80\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1129        // One below lowest single-byte
1130        decode_utf8_to_utf8(b"a\xFF", "a\u{FFFD}");
1131        decode_utf8_to_utf8(b"a\xFFZ", "a\u{FFFD}Z");
1132        // Highest single-byte
1133        decode_valid_utf8("a\x7F");
1134        decode_valid_utf8("a\x7FZ");
1135        // Highest single-byte as two-byte overlong sequence
1136        decode_utf8_to_utf8(b"a\xC1\xBF", "a\u{FFFD}\u{FFFD}");
1137        decode_utf8_to_utf8(b"a\xC1\xBFZ", "a\u{FFFD}\u{FFFD}Z");
1138        // Highest single-byte as three-byte overlong sequence
1139        decode_utf8_to_utf8(b"a\xE0\x81\xBF", "a\u{FFFD}\u{FFFD}\u{FFFD}");
1140        decode_utf8_to_utf8(b"a\xE0\x81\xBFZ", "a\u{FFFD}\u{FFFD}\u{FFFD}Z");
1141        // Highest single-byte as four-byte overlong sequence
1142        decode_utf8_to_utf8(b"a\xF0\x80\x81\xBF", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1143        decode_utf8_to_utf8(b"a\xF0\x80\x81\xBFZ", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1144        // One past highest single byte (also lone continuation)
1145        decode_utf8_to_utf8(b"a\x80Z", "a\u{FFFD}Z");
1146        decode_utf8_to_utf8(b"a\x80", "a\u{FFFD}");
1147        // Two lone continuations
1148        decode_utf8_to_utf8(b"a\x80\x80Z", "a\u{FFFD}\u{FFFD}Z");
1149        decode_utf8_to_utf8(b"a\x80\x80", "a\u{FFFD}\u{FFFD}");
1150        // Three lone continuations
1151        decode_utf8_to_utf8(b"a\x80\x80\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}Z");
1152        decode_utf8_to_utf8(b"a\x80\x80\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}");
1153        // Four lone continuations
1154        decode_utf8_to_utf8(b"a\x80\x80\x80\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1155        decode_utf8_to_utf8(b"a\x80\x80\x80\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1156        // Lowest two-byte
1157        decode_utf8_to_utf8(b"a\xC2\x80", "a\u{0080}");
1158        decode_utf8_to_utf8(b"a\xC2\x80Z", "a\u{0080}Z");
1159        // Lowest two-byte as three-byte overlong sequence
1160        decode_utf8_to_utf8(b"a\xE0\x82\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}");
1161        decode_utf8_to_utf8(b"a\xE0\x82\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}Z");
1162        // Lowest two-byte as four-byte overlong sequence
1163        decode_utf8_to_utf8(b"a\xF0\x80\x82\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1164        decode_utf8_to_utf8(b"a\xF0\x80\x82\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1165        // Lead one below lowest two-byte
1166        decode_utf8_to_utf8(b"a\xC1\x80", "a\u{FFFD}\u{FFFD}");
1167        decode_utf8_to_utf8(b"a\xC1\x80Z", "a\u{FFFD}\u{FFFD}Z");
1168        // Trail one below lowest two-byte
1169        decode_utf8_to_utf8(b"a\xC2\x7F", "a\u{FFFD}\u{007F}");
1170        decode_utf8_to_utf8(b"a\xC2\x7FZ", "a\u{FFFD}\u{007F}Z");
1171        // Highest two-byte
1172        decode_utf8_to_utf8(b"a\xDF\xBF", "a\u{07FF}");
1173        decode_utf8_to_utf8(b"a\xDF\xBFZ", "a\u{07FF}Z");
1174        // Highest two-byte as three-byte overlong sequence
1175        decode_utf8_to_utf8(b"a\xE0\x9F\xBF", "a\u{FFFD}\u{FFFD}\u{FFFD}");
1176        decode_utf8_to_utf8(b"a\xE0\x9F\xBFZ", "a\u{FFFD}\u{FFFD}\u{FFFD}Z");
1177        // Highest two-byte as four-byte overlong sequence
1178        decode_utf8_to_utf8(b"a\xF0\x80\x9F\xBF", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1179        decode_utf8_to_utf8(b"a\xF0\x80\x9F\xBFZ", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1180        // Lowest three-byte
1181        decode_utf8_to_utf8(b"a\xE0\xA0\x80", "a\u{0800}");
1182        decode_utf8_to_utf8(b"a\xE0\xA0\x80Z", "a\u{0800}Z");
1183        // Lowest three-byte as four-byte overlong sequence
1184        decode_utf8_to_utf8(b"a\xF0\x80\xA0\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1185        decode_utf8_to_utf8(b"a\xF0\x80\xA0\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1186        // Highest below surrogates
1187        decode_utf8_to_utf8(b"a\xED\x9F\xBF", "a\u{D7FF}");
1188        decode_utf8_to_utf8(b"a\xED\x9F\xBFZ", "a\u{D7FF}Z");
1189        // Highest below surrogates as four-byte overlong sequence
1190        decode_utf8_to_utf8(b"a\xF0\x8D\x9F\xBF", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1191        decode_utf8_to_utf8(b"a\xF0\x8D\x9F\xBFZ", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1192        // First surrogate
1193        decode_utf8_to_utf8(b"a\xED\xA0\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}");
1194        decode_utf8_to_utf8(b"a\xED\xA0\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}Z");
1195        // First surrogate as four-byte overlong sequence
1196        decode_utf8_to_utf8(b"a\xF0\x8D\xA0\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1197        decode_utf8_to_utf8(b"a\xF0\x8D\xA0\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1198        // Last surrogate
1199        decode_utf8_to_utf8(b"a\xED\xBF\xBF", "a\u{FFFD}\u{FFFD}\u{FFFD}");
1200        decode_utf8_to_utf8(b"a\xED\xBF\xBFZ", "a\u{FFFD}\u{FFFD}\u{FFFD}Z");
1201        // Last surrogate as four-byte overlong sequence
1202        decode_utf8_to_utf8(b"a\xF0\x8D\xBF\xBF", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1203        decode_utf8_to_utf8(b"a\xF0\x8D\xBF\xBFZ", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1204        // Lowest above surrogates
1205        decode_utf8_to_utf8(b"a\xEE\x80\x80", "a\u{E000}");
1206        decode_utf8_to_utf8(b"a\xEE\x80\x80Z", "a\u{E000}Z");
1207        // Lowest above surrogates as four-byte overlong sequence
1208        decode_utf8_to_utf8(b"a\xF0\x8E\x80\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1209        decode_utf8_to_utf8(b"a\xF0\x8E\x80\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1210        // Highest three-byte
1211        decode_utf8_to_utf8(b"a\xEF\xBF\xBF", "a\u{FFFF}");
1212        decode_utf8_to_utf8(b"a\xEF\xBF\xBFZ", "a\u{FFFF}Z");
1213        // Highest three-byte as four-byte overlong sequence
1214        decode_utf8_to_utf8(b"a\xF0\x8F\xBF\xBF", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1215        decode_utf8_to_utf8(b"a\xF0\x8F\xBF\xBFZ", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1216        // Lowest four-byte
1217        decode_utf8_to_utf8(b"a\xF0\x90\x80\x80", "a\u{10000}");
1218        decode_utf8_to_utf8(b"a\xF0\x90\x80\x80Z", "a\u{10000}Z");
1219        // Highest four-byte
1220        decode_utf8_to_utf8(b"a\xF4\x8F\xBF\xBF", "a\u{10FFFF}");
1221        decode_utf8_to_utf8(b"a\xF4\x8F\xBF\xBFZ", "a\u{10FFFF}Z");
1222        // One past highest four-byte
1223        decode_utf8_to_utf8(b"a\xF4\x90\x80\x80", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}");
1224        decode_utf8_to_utf8(b"a\xF4\x90\x80\x80Z", "a\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}Z");
1225
1226        // Highest four-byte with last byte replaced with 0xFF
1227        decode_utf8_to_utf8(b"a\xF4\x8F\xBF\xFF", "a\u{FFFD}\u{FFFD}");
1228        decode_utf8_to_utf8(b"a\xF4\x8F\xBF\xFFZ", "a\u{FFFD}\u{FFFD}Z");
1229    }
1230
1231    #[test]
1232    fn test_utf8_encode() {
1233        // Empty
1234        encode_utf8_from_utf16(&[], b"");
1235        encode_utf8_from_utf8("", b"");
1236
1237        encode_utf8_from_utf16(&[0x0000], "\u{0000}".as_bytes());
1238        encode_utf8_from_utf16(&[0x007F], "\u{007F}".as_bytes());
1239        encode_utf8_from_utf16(&[0x0080], "\u{0080}".as_bytes());
1240        encode_utf8_from_utf16(&[0x07FF], "\u{07FF}".as_bytes());
1241        encode_utf8_from_utf16(&[0x0800], "\u{0800}".as_bytes());
1242        encode_utf8_from_utf16(&[0xD7FF], "\u{D7FF}".as_bytes());
1243        encode_utf8_from_utf16(&[0xD800], "\u{FFFD}".as_bytes());
1244        encode_utf8_from_utf16(&[0xD800, 0x0062], "\u{FFFD}\u{0062}".as_bytes());
1245        encode_utf8_from_utf16(&[0xDFFF], "\u{FFFD}".as_bytes());
1246        encode_utf8_from_utf16(&[0xDFFF, 0x0062], "\u{FFFD}\u{0062}".as_bytes());
1247        encode_utf8_from_utf16(&[0xE000], "\u{E000}".as_bytes());
1248        encode_utf8_from_utf16(&[0xFFFF], "\u{FFFF}".as_bytes());
1249        encode_utf8_from_utf16(&[0xD800, 0xDC00], "\u{10000}".as_bytes());
1250        encode_utf8_from_utf16(&[0xDBFF, 0xDFFF], "\u{10FFFF}".as_bytes());
1251        encode_utf8_from_utf16(&[0xDC00, 0xDEDE], "\u{FFFD}\u{FFFD}".as_bytes());
1252    }
1253
1254    #[test]
1255    fn test_encode_utf8_from_utf16_with_output_limit() {
1256        encode_utf8_from_utf16_with_output_limit(&[0x0062], "\u{62}", 1, EncoderResult::InputEmpty);
1257        encode_utf8_from_utf16_with_output_limit(&[0x00A7], "\u{A7}", 2, EncoderResult::InputEmpty);
1258        encode_utf8_from_utf16_with_output_limit(
1259            &[0x2603],
1260            "\u{2603}",
1261            3,
1262            EncoderResult::InputEmpty,
1263        );
1264        encode_utf8_from_utf16_with_output_limit(
1265            &[0xD83D, 0xDCA9],
1266            "\u{1F4A9}",
1267            4,
1268            EncoderResult::InputEmpty,
1269        );
1270
1271        encode_utf8_from_utf16_with_output_limit(&[0x00A7], "", 1, EncoderResult::OutputFull);
1272        encode_utf8_from_utf16_with_output_limit(&[0x2603], "", 2, EncoderResult::OutputFull);
1273        encode_utf8_from_utf16_with_output_limit(
1274            &[0xD83D, 0xDCA9],
1275            "",
1276            3,
1277            EncoderResult::OutputFull,
1278        );
1279
1280        encode_utf8_from_utf16_with_output_limit(
1281            &[0x0063, 0x0062],
1282            "\u{63}\u{62}",
1283            2,
1284            EncoderResult::InputEmpty,
1285        );
1286        encode_utf8_from_utf16_with_output_limit(
1287            &[0x0063, 0x00A7],
1288            "\u{63}\u{A7}",
1289            3,
1290            EncoderResult::InputEmpty,
1291        );
1292        encode_utf8_from_utf16_with_output_limit(
1293            &[0x0063, 0x2603],
1294            "\u{63}\u{2603}",
1295            4,
1296            EncoderResult::InputEmpty,
1297        );
1298        encode_utf8_from_utf16_with_output_limit(
1299            &[0x0063, 0xD83D, 0xDCA9],
1300            "\u{63}\u{1F4A9}",
1301            5,
1302            EncoderResult::InputEmpty,
1303        );
1304
1305        encode_utf8_from_utf16_with_output_limit(
1306            &[0x0063, 0x00A7],
1307            "\u{63}",
1308            2,
1309            EncoderResult::OutputFull,
1310        );
1311        encode_utf8_from_utf16_with_output_limit(
1312            &[0x0063, 0x2603],
1313            "\u{63}",
1314            3,
1315            EncoderResult::OutputFull,
1316        );
1317        encode_utf8_from_utf16_with_output_limit(
1318            &[0x0063, 0xD83D, 0xDCA9],
1319            "\u{63}",
1320            4,
1321            EncoderResult::OutputFull,
1322        );
1323
1324        encode_utf8_from_utf16_with_output_limit(
1325            &[0x00B6, 0x0062],
1326            "\u{B6}\u{62}",
1327            3,
1328            EncoderResult::InputEmpty,
1329        );
1330        encode_utf8_from_utf16_with_output_limit(
1331            &[0x00B6, 0x00A7],
1332            "\u{B6}\u{A7}",
1333            4,
1334            EncoderResult::InputEmpty,
1335        );
1336        encode_utf8_from_utf16_with_output_limit(
1337            &[0x00B6, 0x2603],
1338            "\u{B6}\u{2603}",
1339            5,
1340            EncoderResult::InputEmpty,
1341        );
1342        encode_utf8_from_utf16_with_output_limit(
1343            &[0x00B6, 0xD83D, 0xDCA9],
1344            "\u{B6}\u{1F4A9}",
1345            6,
1346            EncoderResult::InputEmpty,
1347        );
1348
1349        encode_utf8_from_utf16_with_output_limit(
1350            &[0x00B6, 0x00A7],
1351            "\u{B6}",
1352            3,
1353            EncoderResult::OutputFull,
1354        );
1355        encode_utf8_from_utf16_with_output_limit(
1356            &[0x00B6, 0x2603],
1357            "\u{B6}",
1358            4,
1359            EncoderResult::OutputFull,
1360        );
1361        encode_utf8_from_utf16_with_output_limit(
1362            &[0x00B6, 0xD83D, 0xDCA9],
1363            "\u{B6}",
1364            5,
1365            EncoderResult::OutputFull,
1366        );
1367
1368        encode_utf8_from_utf16_with_output_limit(
1369            &[0x263A, 0x0062],
1370            "\u{263A}\u{62}",
1371            4,
1372            EncoderResult::InputEmpty,
1373        );
1374        encode_utf8_from_utf16_with_output_limit(
1375            &[0x263A, 0x00A7],
1376            "\u{263A}\u{A7}",
1377            5,
1378            EncoderResult::InputEmpty,
1379        );
1380        encode_utf8_from_utf16_with_output_limit(
1381            &[0x263A, 0x2603],
1382            "\u{263A}\u{2603}",
1383            6,
1384            EncoderResult::InputEmpty,
1385        );
1386        encode_utf8_from_utf16_with_output_limit(
1387            &[0x263A, 0xD83D, 0xDCA9],
1388            "\u{263A}\u{1F4A9}",
1389            7,
1390            EncoderResult::InputEmpty,
1391        );
1392
1393        encode_utf8_from_utf16_with_output_limit(
1394            &[0x263A, 0x00A7],
1395            "\u{263A}",
1396            4,
1397            EncoderResult::OutputFull,
1398        );
1399        encode_utf8_from_utf16_with_output_limit(
1400            &[0x263A, 0x2603],
1401            "\u{263A}",
1402            5,
1403            EncoderResult::OutputFull,
1404        );
1405        encode_utf8_from_utf16_with_output_limit(
1406            &[0x263A, 0xD83D, 0xDCA9],
1407            "\u{263A}",
1408            6,
1409            EncoderResult::OutputFull,
1410        );
1411
1412        encode_utf8_from_utf16_with_output_limit(
1413            &[0xD83D, 0xDE0E, 0x0062],
1414            "\u{1F60E}\u{62}",
1415            5,
1416            EncoderResult::InputEmpty,
1417        );
1418        encode_utf8_from_utf16_with_output_limit(
1419            &[0xD83D, 0xDE0E, 0x00A7],
1420            "\u{1F60E}\u{A7}",
1421            6,
1422            EncoderResult::InputEmpty,
1423        );
1424        encode_utf8_from_utf16_with_output_limit(
1425            &[0xD83D, 0xDE0E, 0x2603],
1426            "\u{1F60E}\u{2603}",
1427            7,
1428            EncoderResult::InputEmpty,
1429        );
1430        encode_utf8_from_utf16_with_output_limit(
1431            &[0xD83D, 0xDE0E, 0xD83D, 0xDCA9],
1432            "\u{1F60E}\u{1F4A9}",
1433            8,
1434            EncoderResult::InputEmpty,
1435        );
1436
1437        encode_utf8_from_utf16_with_output_limit(
1438            &[0xD83D, 0xDE0E, 0x00A7],
1439            "\u{1F60E}",
1440            5,
1441            EncoderResult::OutputFull,
1442        );
1443        encode_utf8_from_utf16_with_output_limit(
1444            &[0xD83D, 0xDE0E, 0x2603],
1445            "\u{1F60E}",
1446            6,
1447            EncoderResult::OutputFull,
1448        );
1449        encode_utf8_from_utf16_with_output_limit(
1450            &[0xD83D, 0xDE0E, 0xD83D, 0xDCA9],
1451            "\u{1F60E}",
1452            7,
1453            EncoderResult::OutputFull,
1454        );
1455
1456        encode_utf8_from_utf16_with_output_limit(
1457            &[0x0063, 0x00B6, 0x0062, 0x0062],
1458            "\u{63}\u{B6}\u{62}\u{62}",
1459            5,
1460            EncoderResult::InputEmpty,
1461        );
1462        encode_utf8_from_utf16_with_output_limit(
1463            &[0x0063, 0x00B6, 0x0062, 0x0062],
1464            "\u{63}\u{B6}\u{62}",
1465            4,
1466            EncoderResult::OutputFull,
1467        );
1468
1469        encode_utf8_from_utf16_with_output_limit(
1470            &[0x0063, 0x00B6, 0x0062, 0x0062, 0x0062],
1471            "\u{63}\u{B6}\u{62}\u{62}\u{62}",
1472            6,
1473            EncoderResult::InputEmpty,
1474        );
1475        encode_utf8_from_utf16_with_output_limit(
1476            &[0x0063, 0x00B6, 0x0062, 0x0062, 0x0062],
1477            "\u{63}\u{B6}\u{62}\u{62}",
1478            5,
1479            EncoderResult::OutputFull,
1480        );
1481
1482        encode_utf8_from_utf16_with_output_limit(
1483            &[0x263A, 0x0062, 0x0062],
1484            "\u{263A}\u{62}\u{62}",
1485            5,
1486            EncoderResult::InputEmpty,
1487        );
1488        encode_utf8_from_utf16_with_output_limit(
1489            &[0x263A, 0x0062, 0x0062],
1490            "\u{263A}\u{62}",
1491            4,
1492            EncoderResult::OutputFull,
1493        );
1494
1495        encode_utf8_from_utf16_with_output_limit(
1496            &[0x263A, 0x0062, 0x0062, 0x0062],
1497            "\u{263A}\u{62}\u{62}\u{62}",
1498            6,
1499            EncoderResult::InputEmpty,
1500        );
1501        encode_utf8_from_utf16_with_output_limit(
1502            &[0x263A, 0x0062, 0x0062, 0x0062],
1503            "\u{263A}\u{62}\u{62}",
1504            5,
1505            EncoderResult::OutputFull,
1506        );
1507
1508        encode_utf8_from_utf16_with_output_limit(
1509            &[0x0063, 0x00B6, 0x00A7],
1510            "\u{63}\u{B6}\u{A7}",
1511            5,
1512            EncoderResult::InputEmpty,
1513        );
1514        encode_utf8_from_utf16_with_output_limit(
1515            &[0x0063, 0x00B6, 0x00A7],
1516            "\u{63}\u{B6}",
1517            4,
1518            EncoderResult::OutputFull,
1519        );
1520
1521        encode_utf8_from_utf16_with_output_limit(
1522            &[0x0063, 0x00B6, 0x00A7, 0x0062],
1523            "\u{63}\u{B6}\u{A7}\u{62}",
1524            6,
1525            EncoderResult::InputEmpty,
1526        );
1527        encode_utf8_from_utf16_with_output_limit(
1528            &[0x0063, 0x00B6, 0x00A7, 0x0062],
1529            "\u{63}\u{B6}\u{A7}",
1530            5,
1531            EncoderResult::OutputFull,
1532        );
1533
1534        encode_utf8_from_utf16_with_output_limit(
1535            &[0x263A, 0x00A7, 0x0062],
1536            "\u{263A}\u{A7}\u{62}",
1537            6,
1538            EncoderResult::InputEmpty,
1539        );
1540        encode_utf8_from_utf16_with_output_limit(
1541            &[0x263A, 0x00A7, 0x0062],
1542            "\u{263A}\u{A7}",
1543            5,
1544            EncoderResult::OutputFull,
1545        );
1546
1547        encode_utf8_from_utf16_with_output_limit(
1548            &[0x0063, 0x00B6, 0x0062, 0x00A7],
1549            "\u{63}\u{B6}\u{62}\u{A7}",
1550            6,
1551            EncoderResult::InputEmpty,
1552        );
1553        encode_utf8_from_utf16_with_output_limit(
1554            &[0x0063, 0x00B6, 0x0062, 0x00A7],
1555            "\u{63}\u{B6}\u{62}",
1556            5,
1557            EncoderResult::OutputFull,
1558        );
1559
1560        encode_utf8_from_utf16_with_output_limit(
1561            &[0x263A, 0x0062, 0x00A7],
1562            "\u{263A}\u{62}\u{A7}",
1563            6,
1564            EncoderResult::InputEmpty,
1565        );
1566        encode_utf8_from_utf16_with_output_limit(
1567            &[0x263A, 0x0062, 0x00A7],
1568            "\u{263A}\u{62}",
1569            5,
1570            EncoderResult::OutputFull,
1571        );
1572
1573        encode_utf8_from_utf16_with_output_limit(
1574            &[0x0063, 0x00B6, 0x2603],
1575            "\u{63}\u{B6}\u{2603}",
1576            6,
1577            EncoderResult::InputEmpty,
1578        );
1579        encode_utf8_from_utf16_with_output_limit(
1580            &[0x0063, 0x00B6, 0x2603],
1581            "\u{63}\u{B6}",
1582            5,
1583            EncoderResult::OutputFull,
1584        );
1585
1586        encode_utf8_from_utf16_with_output_limit(
1587            &[0x263A, 0x2603],
1588            "\u{263A}\u{2603}",
1589            6,
1590            EncoderResult::InputEmpty,
1591        );
1592        encode_utf8_from_utf16_with_output_limit(
1593            &[0x263A, 0x2603],
1594            "\u{263A}",
1595            5,
1596            EncoderResult::OutputFull,
1597        );
1598
1599        encode_utf8_from_utf16_with_output_limit(
1600            &[0x0063, 0x00B6, 0xD83D],
1601            "\u{63}\u{B6}\u{FFFD}",
1602            6,
1603            EncoderResult::InputEmpty,
1604        );
1605        encode_utf8_from_utf16_with_output_limit(
1606            &[0x0063, 0x00B6, 0xD83D],
1607            "\u{63}\u{B6}",
1608            5,
1609            EncoderResult::OutputFull,
1610        );
1611
1612        encode_utf8_from_utf16_with_output_limit(
1613            &[0x263A, 0xD83D],
1614            "\u{263A}\u{FFFD}",
1615            6,
1616            EncoderResult::InputEmpty,
1617        );
1618        encode_utf8_from_utf16_with_output_limit(
1619            &[0x263A, 0xD83D],
1620            "\u{263A}",
1621            5,
1622            EncoderResult::OutputFull,
1623        );
1624
1625        encode_utf8_from_utf16_with_output_limit(
1626            &[0x0063, 0x00B6, 0xDCA9],
1627            "\u{63}\u{B6}\u{FFFD}",
1628            6,
1629            EncoderResult::InputEmpty,
1630        );
1631        encode_utf8_from_utf16_with_output_limit(
1632            &[0x0063, 0x00B6, 0xDCA9],
1633            "\u{63}\u{B6}",
1634            5,
1635            EncoderResult::OutputFull,
1636        );
1637
1638        encode_utf8_from_utf16_with_output_limit(
1639            &[0x263A, 0xDCA9],
1640            "\u{263A}\u{FFFD}",
1641            6,
1642            EncoderResult::InputEmpty,
1643        );
1644        encode_utf8_from_utf16_with_output_limit(
1645            &[0x263A, 0xDCA9],
1646            "\u{263A}",
1647            5,
1648            EncoderResult::OutputFull,
1649        );
1650    }
1651
1652    #[test]
1653    fn test_utf8_max_length_from_utf16() {
1654        let mut encoder = UTF_8.new_encoder();
1655        let mut output = [0u8; 13];
1656        let input = &[0x2C9Fu16, 0x2CA9u16, 0x2CA3u16, 0x2C9Fu16];
1657        let needed = encoder
1658            .max_buffer_length_from_utf16_without_replacement(input.len())
1659            .unwrap();
1660        let (result, _, _) =
1661            encoder.encode_from_utf16_without_replacement(input, &mut output[..needed], true);
1662        assert_eq!(result, EncoderResult::InputEmpty);
1663    }
1664
1665    #[test]
1666    fn test_decode_bom_prefixed_split_byte_triple() {
1667        let mut output = [0u16; 20];
1668        let mut decoder = UTF_8.new_decoder();
1669        {
1670            let needed = decoder.max_utf16_buffer_length(1).unwrap();
1671            let (result, read, written, had_errors) =
1672                decoder.decode_to_utf16(b"\xEF", &mut output[..needed], false);
1673            assert_eq!(result, CoderResult::InputEmpty);
1674            assert_eq!(read, 1);
1675            assert_eq!(written, 0);
1676            assert!(!had_errors);
1677        }
1678        {
1679            let needed = decoder.max_utf16_buffer_length(1).unwrap();
1680            let (result, read, written, had_errors) =
1681                decoder.decode_to_utf16(b"\xBF", &mut output[..needed], false);
1682            assert_eq!(result, CoderResult::InputEmpty);
1683            assert_eq!(read, 1);
1684            assert_eq!(written, 0);
1685            assert!(!had_errors);
1686        }
1687        {
1688            let needed = decoder.max_utf16_buffer_length(1).unwrap();
1689            let (result, read, written, had_errors) =
1690                decoder.decode_to_utf16(b"\xBE", &mut output[..needed], true);
1691            assert_eq!(result, CoderResult::InputEmpty);
1692            assert_eq!(read, 1);
1693            assert_eq!(written, 1);
1694            assert!(!had_errors);
1695            assert_eq!(output[0], 0xFFFE);
1696        }
1697    }
1698
1699    #[test]
1700    fn test_decode_bom_prefixed_split_byte_pair() {
1701        let mut output = [0u16; 20];
1702        let mut decoder = UTF_8.new_decoder();
1703        {
1704            let needed = decoder.max_utf16_buffer_length(1).unwrap();
1705            let (result, read, written, had_errors) =
1706                decoder.decode_to_utf16(b"\xEF", &mut output[..needed], false);
1707            assert_eq!(result, CoderResult::InputEmpty);
1708            assert_eq!(read, 1);
1709            assert_eq!(written, 0);
1710            assert!(!had_errors);
1711        }
1712        {
1713            let needed = decoder.max_utf16_buffer_length(1).unwrap();
1714            let (result, read, written, had_errors) =
1715                decoder.decode_to_utf16(b"\xBC", &mut output[..needed], true);
1716            assert_eq!(result, CoderResult::InputEmpty);
1717            assert_eq!(read, 1);
1718            assert_eq!(written, 1);
1719            assert!(had_errors);
1720            assert_eq!(output[0], 0xFFFD);
1721        }
1722    }
1723
1724    #[test]
1725    fn test_decode_bom_prefix() {
1726        let mut output = [0u16; 20];
1727        let mut decoder = UTF_8.new_decoder();
1728        {
1729            let needed = decoder.max_utf16_buffer_length(1).unwrap();
1730            let (result, read, written, had_errors) =
1731                decoder.decode_to_utf16(b"\xEF", &mut output[..needed], true);
1732            assert_eq!(result, CoderResult::InputEmpty);
1733            assert_eq!(read, 1);
1734            assert_eq!(written, 1);
1735            assert!(had_errors);
1736            assert_eq!(output[0], 0xFFFD);
1737        }
1738    }
1739
1740    #[test]
1741    fn test_tail() {
1742        let mut output = [0u16; 1];
1743        let mut decoder = UTF_8.new_decoder_without_bom_handling();
1744        {
1745            let (result, read, written, had_errors) =
1746                decoder.decode_to_utf16("\u{E4}a".as_bytes(), &mut output[..], false);
1747            assert_eq!(result, CoderResult::OutputFull);
1748            assert_eq!(read, 2);
1749            assert_eq!(written, 1);
1750            assert!(!had_errors);
1751            assert_eq!(output[0], 0x00E4);
1752        }
1753    }
1754}