1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Character manipulation.
13 //! For more details, see ::std_unicode::char (a.k.a. std::char)
15 #![allow(non_snake_case)]
16 #![stable(feature = "core_char", since = "1.2.0")]
18 use char_private::is_printable;
20 use fmt::{self, Write};
22 use iter::FusedIterator;
25 // UTF-8 ranges and tags for encoding characters
26 const TAG_CONT: u8 = 0b1000_0000;
27 const TAG_TWO_B: u8 = 0b1100_0000;
28 const TAG_THREE_B: u8 = 0b1110_0000;
29 const TAG_FOUR_B: u8 = 0b1111_0000;
30 const MAX_ONE_B: u32 = 0x80;
31 const MAX_TWO_B: u32 = 0x800;
32 const MAX_THREE_B: u32 = 0x10000;
35 Lu Uppercase_Letter an uppercase letter
36 Ll Lowercase_Letter a lowercase letter
37 Lt Titlecase_Letter a digraphic character, with first part uppercase
38 Lm Modifier_Letter a modifier letter
39 Lo Other_Letter other letters, including syllables and ideographs
40 Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
41 Mc Spacing_Mark a spacing combining mark (positive advance width)
42 Me Enclosing_Mark an enclosing combining mark
43 Nd Decimal_Number a decimal digit
44 Nl Letter_Number a letterlike numeric character
45 No Other_Number a numeric character of other type
46 Pc Connector_Punctuation a connecting punctuation mark, like a tie
47 Pd Dash_Punctuation a dash or hyphen punctuation mark
48 Ps Open_Punctuation an opening punctuation mark (of a pair)
49 Pe Close_Punctuation a closing punctuation mark (of a pair)
50 Pi Initial_Punctuation an initial quotation mark
51 Pf Final_Punctuation a final quotation mark
52 Po Other_Punctuation a punctuation mark of other type
53 Sm Math_Symbol a symbol of primarily mathematical use
54 Sc Currency_Symbol a currency sign
55 Sk Modifier_Symbol a non-letterlike modifier symbol
56 So Other_Symbol a symbol of other type
57 Zs Space_Separator a space character (of various non-zero widths)
58 Zl Line_Separator U+2028 LINE SEPARATOR only
59 Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only
60 Cc Control a C0 or C1 control code
61 Cf Format a format control character
62 Cs Surrogate a surrogate code point
63 Co Private_Use a private-use character
64 Cn Unassigned a reserved unassigned code point or a noncharacter
67 /// The highest valid code point a `char` can have.
69 /// A [`char`] is a [Unicode Scalar Value], which means that it is a [Code
70 /// Point], but only ones within a certain range. `MAX` is the highest valid
71 /// code point that's a valid [Unicode Scalar Value].
73 /// [`char`]: ../../std/primitive.char.html
74 /// [Unicode Scalar Value]: http://www.unicode.org/glossary/#unicode_scalar_value
75 /// [Code Point]: http://www.unicode.org/glossary/#code_point
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub const MAX: char = '\u{10ffff}';
79 /// Converts a `u32` to a `char`.
81 /// Note that all [`char`]s are valid [`u32`]s, and can be casted to one with
88 /// assert_eq!(128175, i);
91 /// However, the reverse is not true: not all valid [`u32`]s are valid
92 /// [`char`]s. `from_u32()` will return `None` if the input is not a valid value
95 /// [`char`]: ../../std/primitive.char.html
96 /// [`u32`]: ../../std/primitive.u32.html
97 /// [`as`]: ../../book/casting-between-types.html#as
99 /// For an unsafe version of this function which ignores these checks, see
100 /// [`from_u32_unchecked()`].
102 /// [`from_u32_unchecked()`]: fn.from_u32_unchecked.html
111 /// let c = char::from_u32(0x2764);
113 /// assert_eq!(Some('❤'), c);
116 /// Returning `None` when the input is not a valid [`char`]:
121 /// let c = char::from_u32(0x110000);
123 /// assert_eq!(None, c);
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub fn from_u32(i: u32) -> Option<char> {
128 char::try_from(i).ok()
131 /// Converts a `u32` to a `char`, ignoring validity.
133 /// Note that all [`char`]s are valid [`u32`]s, and can be casted to one with
138 /// let i = c as u32;
140 /// assert_eq!(128175, i);
143 /// However, the reverse is not true: not all valid [`u32`]s are valid
144 /// [`char`]s. `from_u32_unchecked()` will ignore this, and blindly cast to
145 /// [`char`], possibly creating an invalid one.
147 /// [`char`]: ../../std/primitive.char.html
148 /// [`u32`]: ../../std/primitive.u32.html
149 /// [`as`]: ../../book/casting-between-types.html#as
153 /// This function is unsafe, as it may construct invalid `char` values.
155 /// For a safe version of this function, see the [`from_u32()`] function.
157 /// [`from_u32()`]: fn.from_u32.html
166 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
168 /// assert_eq!('❤', c);
171 #[stable(feature = "char_from_unchecked", since = "1.5.0")]
172 pub unsafe fn from_u32_unchecked(i: u32) -> char {
176 #[stable(feature = "char_convert", since = "1.13.0")]
177 impl From<char> for u32 {
179 fn from(c: char) -> Self {
184 /// Maps a byte in 0x00...0xFF to a `char` whose code point has the same value, in U+0000 to U+00FF.
186 /// Unicode is designed such that this effectively decodes bytes
187 /// with the character encoding that IANA calls ISO-8859-1.
188 /// This encoding is compatible with ASCII.
190 /// Note that this is different from ISO/IEC 8859-1 a.k.a. ISO 8859-1 (with one less hypen),
191 /// which leaves some "blanks", byte values that are not assigned to any character.
192 /// ISO-8859-1 (the IANA one) assigns them to the C0 and C1 control codes.
194 /// Note that this is *also* different from Windows-1252 a.k.a. code page 1252,
195 /// which is a superset ISO/IEC 8859-1 that assigns some (not all!) blanks
196 /// to punctuation and various Latin characters.
198 /// To confuse things further, [on the Web](https://encoding.spec.whatwg.org/)
199 /// `ascii`, `iso-8859-1`, and `windows-1252` are all aliases
200 /// for a superset of Windows-1252 that fills the remaining blanks with corresponding
201 /// C0 and C1 control codes.
202 #[stable(feature = "char_convert", since = "1.13.0")]
203 impl From<u8> for char {
205 fn from(i: u8) -> Self {
210 #[unstable(feature = "try_from", issue = "33417")]
211 impl TryFrom<u32> for char {
212 type Err = CharTryFromError;
215 fn try_from(i: u32) -> Result<Self, Self::Err> {
216 if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
217 Err(CharTryFromError(()))
219 Ok(unsafe { from_u32_unchecked(i) })
224 /// The error type returned when a conversion from u32 to char fails.
225 #[unstable(feature = "try_from", issue = "33417")]
226 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
227 pub struct CharTryFromError(());
229 #[unstable(feature = "try_from", issue = "33417")]
230 impl fmt::Display for CharTryFromError {
231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
232 "converted integer out of range for `char`".fmt(f)
236 /// Converts a digit in the given radix to a `char`.
238 /// A 'radix' here is sometimes also called a 'base'. A radix of two
239 /// indicates a binary number, a radix of ten, decimal, and a radix of
240 /// sixteen, hexadecimal, to give some common values. Arbitrary
241 /// radices are supported.
243 /// `from_digit()` will return `None` if the input is not a digit in
248 /// Panics if given a radix larger than 36.
257 /// let c = char::from_digit(4, 10);
259 /// assert_eq!(Some('4'), c);
261 /// // Decimal 11 is a single digit in base 16
262 /// let c = char::from_digit(11, 16);
264 /// assert_eq!(Some('b'), c);
267 /// Returning `None` when the input is not a digit:
272 /// let c = char::from_digit(20, 10);
274 /// assert_eq!(None, c);
277 /// Passing a large radix, causing a panic:
283 /// let result = thread::spawn(|| {
285 /// let c = char::from_digit(1, 37);
288 /// assert!(result.is_err());
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn from_digit(num: u32, radix: u32) -> Option<char> {
294 panic!("from_digit: radix is too high (maximum 36)");
299 Some((b'0' + num) as char)
301 Some((b'a' + num - 10) as char)
308 // NB: the stabilization and documentation for this trait is in
309 // unicode/char.rs, not here
310 #[allow(missing_docs)] // docs in libunicode/u_char.rs
312 #[unstable(feature = "core_char_ext",
313 reason = "the stable interface is `impl char` in later crate",
316 #[stable(feature = "core", since = "1.6.0")]
317 fn is_digit(self, radix: u32) -> bool;
318 #[stable(feature = "core", since = "1.6.0")]
319 fn to_digit(self, radix: u32) -> Option<u32>;
320 #[stable(feature = "core", since = "1.6.0")]
321 fn escape_unicode(self) -> EscapeUnicode;
322 #[stable(feature = "core", since = "1.6.0")]
323 fn escape_default(self) -> EscapeDefault;
324 #[unstable(feature = "char_escape_debug", issue = "35068")]
325 fn escape_debug(self) -> EscapeDebug;
326 #[stable(feature = "core", since = "1.6.0")]
327 fn len_utf8(self) -> usize;
328 #[stable(feature = "core", since = "1.6.0")]
329 fn len_utf16(self) -> usize;
330 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
331 fn encode_utf8(self, dst: &mut [u8]) -> &mut str;
332 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
333 fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16];
336 #[stable(feature = "core", since = "1.6.0")]
337 impl CharExt for char {
339 fn is_digit(self, radix: u32) -> bool {
340 self.to_digit(radix).is_some()
344 fn to_digit(self, radix: u32) -> Option<u32> {
346 panic!("to_digit: radix is too high (maximum 36)");
348 let val = match self {
349 '0' ... '9' => self as u32 - '0' as u32,
350 'a' ... 'z' => self as u32 - 'a' as u32 + 10,
351 'A' ... 'Z' => self as u32 - 'A' as u32 + 10,
354 if val < radix { Some(val) }
359 fn escape_unicode(self) -> EscapeUnicode {
362 // or-ing 1 ensures that for c==0 the code computes that one
363 // digit should be printed and (which is the same) avoids the
364 // (31 - 32) underflow
365 let msb = 31 - (c | 1).leading_zeros();
367 // the index of the most significant hex digit
368 let ms_hex_digit = msb / 4;
371 state: EscapeUnicodeState::Backslash,
372 hex_digit_idx: ms_hex_digit as usize,
377 fn escape_default(self) -> EscapeDefault {
378 let init_state = match self {
379 '\t' => EscapeDefaultState::Backslash('t'),
380 '\r' => EscapeDefaultState::Backslash('r'),
381 '\n' => EscapeDefaultState::Backslash('n'),
382 '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
383 '\x20' ... '\x7e' => EscapeDefaultState::Char(self),
384 _ => EscapeDefaultState::Unicode(self.escape_unicode())
386 EscapeDefault { state: init_state }
390 fn escape_debug(self) -> EscapeDebug {
391 let init_state = match self {
392 '\t' => EscapeDefaultState::Backslash('t'),
393 '\r' => EscapeDefaultState::Backslash('r'),
394 '\n' => EscapeDefaultState::Backslash('n'),
395 '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
396 c if is_printable(c) => EscapeDefaultState::Char(c),
397 c => EscapeDefaultState::Unicode(c.escape_unicode()),
399 EscapeDebug(EscapeDefault { state: init_state })
403 fn len_utf8(self) -> usize {
404 let code = self as u32;
405 if code < MAX_ONE_B {
407 } else if code < MAX_TWO_B {
409 } else if code < MAX_THREE_B {
417 fn len_utf16(self) -> usize {
418 let ch = self as u32;
419 if (ch & 0xFFFF) == ch { 1 } else { 2 }
423 fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
424 let code = self as u32;
427 if code < MAX_ONE_B && !dst.is_empty() {
428 *dst.get_unchecked_mut(0) = code as u8;
430 } else if code < MAX_TWO_B && dst.len() >= 2 {
431 *dst.get_unchecked_mut(0) = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
432 *dst.get_unchecked_mut(1) = (code & 0x3F) as u8 | TAG_CONT;
434 } else if code < MAX_THREE_B && dst.len() >= 3 {
435 *dst.get_unchecked_mut(0) = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
436 *dst.get_unchecked_mut(1) = (code >> 6 & 0x3F) as u8 | TAG_CONT;
437 *dst.get_unchecked_mut(2) = (code & 0x3F) as u8 | TAG_CONT;
439 } else if dst.len() >= 4 {
440 *dst.get_unchecked_mut(0) = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
441 *dst.get_unchecked_mut(1) = (code >> 12 & 0x3F) as u8 | TAG_CONT;
442 *dst.get_unchecked_mut(2) = (code >> 6 & 0x3F) as u8 | TAG_CONT;
443 *dst.get_unchecked_mut(3) = (code & 0x3F) as u8 | TAG_CONT;
446 panic!("encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
447 from_u32_unchecked(code).len_utf8(),
451 transmute(slice::from_raw_parts_mut(dst.as_mut_ptr(), len))
456 fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
457 let mut code = self as u32;
459 if (code & 0xFFFF) == code && !dst.is_empty() {
460 // The BMP falls through (assuming non-surrogate, as it should)
461 *dst.get_unchecked_mut(0) = code as u16;
462 slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
463 } else if dst.len() >= 2 {
464 // Supplementary planes break into surrogates.
466 *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
467 *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
468 slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
470 panic!("encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
471 from_u32_unchecked(code).len_utf16(),
479 /// Returns an iterator that yields the hexadecimal Unicode escape of a
480 /// character, as `char`s.
482 /// This `struct` is created by the [`escape_unicode()`] method on [`char`]. See
483 /// its documentation for more.
485 /// [`escape_unicode()`]: ../../std/primitive.char.html#method.escape_unicode
486 /// [`char`]: ../../std/primitive.char.html
487 #[derive(Clone, Debug)]
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub struct EscapeUnicode {
491 state: EscapeUnicodeState,
493 // The index of the next hex digit to be printed (0 if none),
494 // i.e. the number of remaining hex digits to be printed;
495 // increasing from the least significant digit: 0x543210
496 hex_digit_idx: usize,
499 // The enum values are ordered so that their representation is the
500 // same as the remaining length (besides the hexadecimal digits). This
501 // likely makes `len()` a single load from memory) and inline-worth.
502 #[derive(Clone, Debug)]
503 enum EscapeUnicodeState {
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl Iterator for EscapeUnicode {
516 fn next(&mut self) -> Option<char> {
518 EscapeUnicodeState::Backslash => {
519 self.state = EscapeUnicodeState::Type;
522 EscapeUnicodeState::Type => {
523 self.state = EscapeUnicodeState::LeftBrace;
526 EscapeUnicodeState::LeftBrace => {
527 self.state = EscapeUnicodeState::Value;
530 EscapeUnicodeState::Value => {
531 let hex_digit = ((self.c as u32) >> (self.hex_digit_idx * 4)) & 0xf;
532 let c = from_digit(hex_digit, 16).unwrap();
533 if self.hex_digit_idx == 0 {
534 self.state = EscapeUnicodeState::RightBrace;
536 self.hex_digit_idx -= 1;
540 EscapeUnicodeState::RightBrace => {
541 self.state = EscapeUnicodeState::Done;
544 EscapeUnicodeState::Done => None,
549 fn size_hint(&self) -> (usize, Option<usize>) {
555 fn count(self) -> usize {
559 fn last(self) -> Option<char> {
561 EscapeUnicodeState::Done => None,
563 EscapeUnicodeState::RightBrace |
564 EscapeUnicodeState::Value |
565 EscapeUnicodeState::LeftBrace |
566 EscapeUnicodeState::Type |
567 EscapeUnicodeState::Backslash => Some('}'),
572 #[stable(feature = "exact_size_escape", since = "1.11.0")]
573 impl ExactSizeIterator for EscapeUnicode {
575 fn len(&self) -> usize {
576 // The match is a single memory access with no branching
577 self.hex_digit_idx + match self.state {
578 EscapeUnicodeState::Done => 0,
579 EscapeUnicodeState::RightBrace => 1,
580 EscapeUnicodeState::Value => 2,
581 EscapeUnicodeState::LeftBrace => 3,
582 EscapeUnicodeState::Type => 4,
583 EscapeUnicodeState::Backslash => 5,
588 #[unstable(feature = "fused", issue = "35602")]
589 impl FusedIterator for EscapeUnicode {}
591 #[stable(feature = "char_struct_display", since = "1.16.0")]
592 impl fmt::Display for EscapeUnicode {
593 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
594 for c in self.clone() {
601 /// An iterator that yields the literal escape code of a `char`.
603 /// This `struct` is created by the [`escape_default()`] method on [`char`]. See
604 /// its documentation for more.
606 /// [`escape_default()`]: ../../std/primitive.char.html#method.escape_default
607 /// [`char`]: ../../std/primitive.char.html
608 #[derive(Clone, Debug)]
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub struct EscapeDefault {
611 state: EscapeDefaultState
614 #[derive(Clone, Debug)]
615 enum EscapeDefaultState {
619 Unicode(EscapeUnicode),
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl Iterator for EscapeDefault {
626 fn next(&mut self) -> Option<char> {
628 EscapeDefaultState::Backslash(c) => {
629 self.state = EscapeDefaultState::Char(c);
632 EscapeDefaultState::Char(c) => {
633 self.state = EscapeDefaultState::Done;
636 EscapeDefaultState::Done => None,
637 EscapeDefaultState::Unicode(ref mut iter) => iter.next(),
642 fn size_hint(&self) -> (usize, Option<usize>) {
648 fn count(self) -> usize {
652 fn nth(&mut self, n: usize) -> Option<char> {
654 EscapeDefaultState::Backslash(c) if n == 0 => {
655 self.state = EscapeDefaultState::Char(c);
658 EscapeDefaultState::Backslash(c) if n == 1 => {
659 self.state = EscapeDefaultState::Done;
662 EscapeDefaultState::Backslash(_) => {
663 self.state = EscapeDefaultState::Done;
666 EscapeDefaultState::Char(c) => {
667 self.state = EscapeDefaultState::Done;
675 EscapeDefaultState::Done => return None,
676 EscapeDefaultState::Unicode(ref mut i) => return i.nth(n),
680 fn last(self) -> Option<char> {
682 EscapeDefaultState::Unicode(iter) => iter.last(),
683 EscapeDefaultState::Done => None,
684 EscapeDefaultState::Backslash(c) | EscapeDefaultState::Char(c) => Some(c),
689 #[stable(feature = "exact_size_escape", since = "1.11.0")]
690 impl ExactSizeIterator for EscapeDefault {
691 fn len(&self) -> usize {
693 EscapeDefaultState::Done => 0,
694 EscapeDefaultState::Char(_) => 1,
695 EscapeDefaultState::Backslash(_) => 2,
696 EscapeDefaultState::Unicode(ref iter) => iter.len(),
701 #[unstable(feature = "fused", issue = "35602")]
702 impl FusedIterator for EscapeDefault {}
704 #[stable(feature = "char_struct_display", since = "1.16.0")]
705 impl fmt::Display for EscapeDefault {
706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
707 for c in self.clone() {
714 /// An iterator that yields the literal escape code of a `char`.
716 /// This `struct` is created by the [`escape_debug()`] method on [`char`]. See its
717 /// documentation for more.
719 /// [`escape_debug()`]: ../../std/primitive.char.html#method.escape_debug
720 /// [`char`]: ../../std/primitive.char.html
721 #[unstable(feature = "char_escape_debug", issue = "35068")]
722 #[derive(Clone, Debug)]
723 pub struct EscapeDebug(EscapeDefault);
725 #[unstable(feature = "char_escape_debug", issue = "35068")]
726 impl Iterator for EscapeDebug {
728 fn next(&mut self) -> Option<char> { self.0.next() }
729 fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
732 #[unstable(feature = "char_escape_debug", issue = "35068")]
733 impl ExactSizeIterator for EscapeDebug { }
735 #[unstable(feature = "fused", issue = "35602")]
736 impl FusedIterator for EscapeDebug {}
738 #[unstable(feature = "char_escape_debug", issue = "35068")]
739 impl fmt::Display for EscapeDebug {
740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
741 fmt::Display::fmt(&self.0, f)
747 /// An iterator over an iterator of bytes of the characters the bytes represent
749 #[unstable(feature = "decode_utf8", issue = "33906")]
750 #[derive(Clone, Debug)]
751 pub struct DecodeUtf8<I: Iterator<Item = u8>>(::iter::Peekable<I>);
753 /// Decodes an `Iterator` of bytes as UTF-8.
754 #[unstable(feature = "decode_utf8", issue = "33906")]
756 pub fn decode_utf8<I: IntoIterator<Item = u8>>(i: I) -> DecodeUtf8<I::IntoIter> {
757 DecodeUtf8(i.into_iter().peekable())
760 /// `<DecodeUtf8 as Iterator>::next` returns this for an invalid input sequence.
761 #[unstable(feature = "decode_utf8", issue = "33906")]
762 #[derive(PartialEq, Eq, Debug)]
763 pub struct InvalidSequence(());
765 #[unstable(feature = "decode_utf8", issue = "33906")]
766 impl<I: Iterator<Item = u8>> Iterator for DecodeUtf8<I> {
767 type Item = Result<char, InvalidSequence>;
770 fn next(&mut self) -> Option<Result<char, InvalidSequence>> {
771 self.0.next().map(|first_byte| {
772 // Emit InvalidSequence according to
773 // Unicode §5.22 Best Practice for U+FFFD Substitution
774 // http://www.unicode.org/versions/Unicode9.0.0/ch05.pdf#G40630
776 // Roughly: consume at least one byte,
777 // then validate one byte at a time and stop before the first unexpected byte
778 // (which might be the valid start of the next byte sequence).
781 macro_rules! first_byte {
783 code_point = u32::from(first_byte & $mask)
786 macro_rules! continuation_byte {
787 () => { continuation_byte!(0x80...0xBF) };
789 match self.0.peek() {
790 Some(&byte @ $range) => {
791 code_point = (code_point << 6) | u32::from(byte & 0b0011_1111);
794 _ => return Err(InvalidSequence(()))
801 first_byte!(0b1111_1111);
804 first_byte!(0b0001_1111);
805 continuation_byte!();
808 first_byte!(0b0000_1111);
809 continuation_byte!(0xA0...0xBF); // 0x80...0x9F here are overlong
810 continuation_byte!();
812 0xE1...0xEC | 0xEE...0xEF => {
813 first_byte!(0b0000_1111);
814 continuation_byte!();
815 continuation_byte!();
818 first_byte!(0b0000_1111);
819 continuation_byte!(0x80...0x9F); // 0xA0..0xBF here are surrogates
820 continuation_byte!();
823 first_byte!(0b0000_0111);
824 continuation_byte!(0x90...0xBF); // 0x80..0x8F here are overlong
825 continuation_byte!();
826 continuation_byte!();
829 first_byte!(0b0000_0111);
830 continuation_byte!();
831 continuation_byte!();
832 continuation_byte!();
835 first_byte!(0b0000_0111);
836 continuation_byte!(0x80...0x8F); // 0x90..0xBF here are beyond char::MAX
837 continuation_byte!();
838 continuation_byte!();
840 _ => return Err(InvalidSequence(())) // Illegal first byte, overlong, or beyond MAX
843 Ok(from_u32_unchecked(code_point))
849 #[unstable(feature = "fused", issue = "35602")]
850 impl<I: FusedIterator<Item = u8>> FusedIterator for DecodeUtf8<I> {}