]> git.lizzy.rs Git - rust.git/blob - src/libcore/char.rs
add inline attributes to stage 0 methods
[rust.git] / src / libcore / char.rs
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.
4 //
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.
10
11 //! Character manipulation.
12 //!
13 //! For more details, see ::std_unicode::char (a.k.a. std::char)
14
15 #![allow(non_snake_case)]
16 #![stable(feature = "core_char", since = "1.2.0")]
17
18 use char_private::is_printable;
19 use convert::TryFrom;
20 use fmt::{self, Write};
21 use slice;
22 use iter::FusedIterator;
23 use mem::transmute;
24
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;
33
34 /*
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
65 */
66
67 /// The highest valid code point a `char` can have.
68 ///
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].
72 ///
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}';
78
79 /// Converts a `u32` to a `char`.
80 ///
81 /// Note that all [`char`]s are valid [`u32`]s, and can be casted to one with
82 /// [`as`]:
83 ///
84 /// ```
85 /// let c = '💯';
86 /// let i = c as u32;
87 ///
88 /// assert_eq!(128175, i);
89 /// ```
90 ///
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
93 /// for a [`char`].
94 ///
95 /// [`char`]: ../../std/primitive.char.html
96 /// [`u32`]: ../../std/primitive.u32.html
97 /// [`as`]: ../../book/casting-between-types.html#as
98 ///
99 /// For an unsafe version of this function which ignores these checks, see
100 /// [`from_u32_unchecked()`].
101 ///
102 /// [`from_u32_unchecked()`]: fn.from_u32_unchecked.html
103 ///
104 /// # Examples
105 ///
106 /// Basic usage:
107 ///
108 /// ```
109 /// use std::char;
110 ///
111 /// let c = char::from_u32(0x2764);
112 ///
113 /// assert_eq!(Some('❤'), c);
114 /// ```
115 ///
116 /// Returning `None` when the input is not a valid [`char`]:
117 ///
118 /// ```
119 /// use std::char;
120 ///
121 /// let c = char::from_u32(0x110000);
122 ///
123 /// assert_eq!(None, c);
124 /// ```
125 #[inline]
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub fn from_u32(i: u32) -> Option<char> {
128     char::try_from(i).ok()
129 }
130
131 /// Converts a `u32` to a `char`, ignoring validity.
132 ///
133 /// Note that all [`char`]s are valid [`u32`]s, and can be casted to one with
134 /// [`as`]:
135 ///
136 /// ```
137 /// let c = '💯';
138 /// let i = c as u32;
139 ///
140 /// assert_eq!(128175, i);
141 /// ```
142 ///
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.
146 ///
147 /// [`char`]: ../../std/primitive.char.html
148 /// [`u32`]: ../../std/primitive.u32.html
149 /// [`as`]: ../../book/casting-between-types.html#as
150 ///
151 /// # Safety
152 ///
153 /// This function is unsafe, as it may construct invalid `char` values.
154 ///
155 /// For a safe version of this function, see the [`from_u32()`] function.
156 ///
157 /// [`from_u32()`]: fn.from_u32.html
158 ///
159 /// # Examples
160 ///
161 /// Basic usage:
162 ///
163 /// ```
164 /// use std::char;
165 ///
166 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
167 ///
168 /// assert_eq!('❤', c);
169 /// ```
170 #[inline]
171 #[stable(feature = "char_from_unchecked", since = "1.5.0")]
172 pub unsafe fn from_u32_unchecked(i: u32) -> char {
173     transmute(i)
174 }
175
176 #[stable(feature = "char_convert", since = "1.13.0")]
177 impl From<char> for u32 {
178     #[inline]
179     fn from(c: char) -> Self {
180         c as u32
181     }
182 }
183
184 /// Maps a byte in 0x00...0xFF to a `char` whose code point has the same value, in U+0000 to U+00FF.
185 ///
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.
189 ///
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.
193 ///
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.
197 ///
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 {
204     #[inline]
205     fn from(i: u8) -> Self {
206         i as char
207     }
208 }
209
210 #[unstable(feature = "try_from", issue = "33417")]
211 impl TryFrom<u32> for char {
212     type Err = CharTryFromError;
213
214     #[inline]
215     fn try_from(i: u32) -> Result<Self, Self::Err> {
216         if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
217             Err(CharTryFromError(()))
218         } else {
219             Ok(unsafe { from_u32_unchecked(i) })
220         }
221     }
222 }
223
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(());
228
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)
233     }
234 }
235
236 /// Converts a digit in the given radix to a `char`.
237 ///
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.
242 ///
243 /// `from_digit()` will return `None` if the input is not a digit in
244 /// the given radix.
245 ///
246 /// # Panics
247 ///
248 /// Panics if given a radix larger than 36.
249 ///
250 /// # Examples
251 ///
252 /// Basic usage:
253 ///
254 /// ```
255 /// use std::char;
256 ///
257 /// let c = char::from_digit(4, 10);
258 ///
259 /// assert_eq!(Some('4'), c);
260 ///
261 /// // Decimal 11 is a single digit in base 16
262 /// let c = char::from_digit(11, 16);
263 ///
264 /// assert_eq!(Some('b'), c);
265 /// ```
266 ///
267 /// Returning `None` when the input is not a digit:
268 ///
269 /// ```
270 /// use std::char;
271 ///
272 /// let c = char::from_digit(20, 10);
273 ///
274 /// assert_eq!(None, c);
275 /// ```
276 ///
277 /// Passing a large radix, causing a panic:
278 ///
279 /// ```
280 /// use std::thread;
281 /// use std::char;
282 ///
283 /// let result = thread::spawn(|| {
284 ///     // this panics
285 ///     let c = char::from_digit(1, 37);
286 /// }).join();
287 ///
288 /// assert!(result.is_err());
289 /// ```
290 #[inline]
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn from_digit(num: u32, radix: u32) -> Option<char> {
293     if radix > 36 {
294         panic!("from_digit: radix is too high (maximum 36)");
295     }
296     if num < radix {
297         let num = num as u8;
298         if num < 10 {
299             Some((b'0' + num) as char)
300         } else {
301             Some((b'a' + num - 10) as char)
302         }
303     } else {
304         None
305     }
306 }
307
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
311 #[doc(hidden)]
312 #[unstable(feature = "core_char_ext",
313            reason = "the stable interface is `impl char` in later crate",
314            issue = "32110")]
315 pub trait CharExt {
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];
334 }
335
336 #[stable(feature = "core", since = "1.6.0")]
337 impl CharExt for char {
338     #[inline]
339     fn is_digit(self, radix: u32) -> bool {
340         self.to_digit(radix).is_some()
341     }
342
343     #[inline]
344     fn to_digit(self, radix: u32) -> Option<u32> {
345         if radix > 36 {
346             panic!("to_digit: radix is too high (maximum 36)");
347         }
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,
352           _ => return None,
353         };
354         if val < radix { Some(val) }
355         else { None }
356     }
357
358     #[inline]
359     fn escape_unicode(self) -> EscapeUnicode {
360         let c = self as u32;
361
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();
366
367         // the index of the most significant hex digit
368         let ms_hex_digit = msb / 4;
369         EscapeUnicode {
370             c: self,
371             state: EscapeUnicodeState::Backslash,
372             hex_digit_idx: ms_hex_digit as usize,
373         }
374     }
375
376     #[inline]
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())
385         };
386         EscapeDefault { state: init_state }
387     }
388
389     #[inline]
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()),
398         };
399         EscapeDebug(EscapeDefault { state: init_state })
400     }
401
402     #[inline]
403     fn len_utf8(self) -> usize {
404         let code = self as u32;
405         if code < MAX_ONE_B {
406             1
407         } else if code < MAX_TWO_B {
408             2
409         } else if code < MAX_THREE_B {
410             3
411         } else {
412             4
413         }
414     }
415
416     #[inline]
417     fn len_utf16(self) -> usize {
418         let ch = self as u32;
419         if (ch & 0xFFFF) == ch { 1 } else { 2 }
420     }
421
422     #[inline]
423     fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
424         let code = self as u32;
425         unsafe {
426             let len =
427             if code < MAX_ONE_B && !dst.is_empty() {
428                 *dst.get_unchecked_mut(0) = code as u8;
429                 1
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;
433                 2
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;
438                 3
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;
444                 4
445             } else {
446                 panic!("encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
447                     from_u32_unchecked(code).len_utf8(),
448                     code,
449                     dst.len())
450             };
451             transmute(slice::from_raw_parts_mut(dst.as_mut_ptr(), len))
452         }
453     }
454
455     #[inline]
456     fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
457         let mut code = self as u32;
458         unsafe {
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.
465                 code -= 0x1_0000;
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)
469             } else {
470                 panic!("encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
471                     from_u32_unchecked(code).len_utf16(),
472                     code,
473                     dst.len())
474             }
475         }
476     }
477 }
478
479 /// Returns an iterator that yields the hexadecimal Unicode escape of a
480 /// character, as `char`s.
481 ///
482 /// This `struct` is created by the [`escape_unicode()`] method on [`char`]. See
483 /// its documentation for more.
484 ///
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 {
490     c: char,
491     state: EscapeUnicodeState,
492
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,
497 }
498
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 {
504     Done,
505     RightBrace,
506     Value,
507     LeftBrace,
508     Type,
509     Backslash,
510 }
511
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl Iterator for EscapeUnicode {
514     type Item = char;
515
516     fn next(&mut self) -> Option<char> {
517         match self.state {
518             EscapeUnicodeState::Backslash => {
519                 self.state = EscapeUnicodeState::Type;
520                 Some('\\')
521             }
522             EscapeUnicodeState::Type => {
523                 self.state = EscapeUnicodeState::LeftBrace;
524                 Some('u')
525             }
526             EscapeUnicodeState::LeftBrace => {
527                 self.state = EscapeUnicodeState::Value;
528                 Some('{')
529             }
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;
535                 } else {
536                     self.hex_digit_idx -= 1;
537                 }
538                 Some(c)
539             }
540             EscapeUnicodeState::RightBrace => {
541                 self.state = EscapeUnicodeState::Done;
542                 Some('}')
543             }
544             EscapeUnicodeState::Done => None,
545         }
546     }
547
548     #[inline]
549     fn size_hint(&self) -> (usize, Option<usize>) {
550         let n = self.len();
551         (n, Some(n))
552     }
553
554     #[inline]
555     fn count(self) -> usize {
556         self.len()
557     }
558
559     fn last(self) -> Option<char> {
560         match self.state {
561             EscapeUnicodeState::Done => None,
562
563             EscapeUnicodeState::RightBrace |
564             EscapeUnicodeState::Value |
565             EscapeUnicodeState::LeftBrace |
566             EscapeUnicodeState::Type |
567             EscapeUnicodeState::Backslash => Some('}'),
568         }
569     }
570 }
571
572 #[stable(feature = "exact_size_escape", since = "1.11.0")]
573 impl ExactSizeIterator for EscapeUnicode {
574     #[inline]
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,
584         }
585     }
586 }
587
588 #[unstable(feature = "fused", issue = "35602")]
589 impl FusedIterator for EscapeUnicode {}
590
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() {
595             f.write_char(c)?;
596         }
597         Ok(())
598     }
599 }
600
601 /// An iterator that yields the literal escape code of a `char`.
602 ///
603 /// This `struct` is created by the [`escape_default()`] method on [`char`]. See
604 /// its documentation for more.
605 ///
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
612 }
613
614 #[derive(Clone, Debug)]
615 enum EscapeDefaultState {
616     Done,
617     Char(char),
618     Backslash(char),
619     Unicode(EscapeUnicode),
620 }
621
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl Iterator for EscapeDefault {
624     type Item = char;
625
626     fn next(&mut self) -> Option<char> {
627         match self.state {
628             EscapeDefaultState::Backslash(c) => {
629                 self.state = EscapeDefaultState::Char(c);
630                 Some('\\')
631             }
632             EscapeDefaultState::Char(c) => {
633                 self.state = EscapeDefaultState::Done;
634                 Some(c)
635             }
636             EscapeDefaultState::Done => None,
637             EscapeDefaultState::Unicode(ref mut iter) => iter.next(),
638         }
639     }
640
641     #[inline]
642     fn size_hint(&self) -> (usize, Option<usize>) {
643         let n = self.len();
644         (n, Some(n))
645     }
646
647     #[inline]
648     fn count(self) -> usize {
649         self.len()
650     }
651
652     fn nth(&mut self, n: usize) -> Option<char> {
653         match self.state {
654             EscapeDefaultState::Backslash(c) if n == 0 => {
655                 self.state = EscapeDefaultState::Char(c);
656                 Some('\\')
657             },
658             EscapeDefaultState::Backslash(c) if n == 1 => {
659                 self.state = EscapeDefaultState::Done;
660                 Some(c)
661             },
662             EscapeDefaultState::Backslash(_) => {
663                 self.state = EscapeDefaultState::Done;
664                 None
665             },
666             EscapeDefaultState::Char(c) => {
667                 self.state = EscapeDefaultState::Done;
668
669                 if n == 0 {
670                     Some(c)
671                 } else {
672                     None
673                 }
674             },
675             EscapeDefaultState::Done => return None,
676             EscapeDefaultState::Unicode(ref mut i) => return i.nth(n),
677         }
678     }
679
680     fn last(self) -> Option<char> {
681         match self.state {
682             EscapeDefaultState::Unicode(iter) => iter.last(),
683             EscapeDefaultState::Done => None,
684             EscapeDefaultState::Backslash(c) | EscapeDefaultState::Char(c) => Some(c),
685         }
686     }
687 }
688
689 #[stable(feature = "exact_size_escape", since = "1.11.0")]
690 impl ExactSizeIterator for EscapeDefault {
691     fn len(&self) -> usize {
692         match self.state {
693             EscapeDefaultState::Done => 0,
694             EscapeDefaultState::Char(_) => 1,
695             EscapeDefaultState::Backslash(_) => 2,
696             EscapeDefaultState::Unicode(ref iter) => iter.len(),
697         }
698     }
699 }
700
701 #[unstable(feature = "fused", issue = "35602")]
702 impl FusedIterator for EscapeDefault {}
703
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() {
708             f.write_char(c)?;
709         }
710         Ok(())
711     }
712 }
713
714 /// An iterator that yields the literal escape code of a `char`.
715 ///
716 /// This `struct` is created by the [`escape_debug()`] method on [`char`]. See its
717 /// documentation for more.
718 ///
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);
724
725 #[unstable(feature = "char_escape_debug", issue = "35068")]
726 impl Iterator for EscapeDebug {
727     type Item = char;
728     fn next(&mut self) -> Option<char> { self.0.next() }
729     fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
730 }
731
732 #[unstable(feature = "char_escape_debug", issue = "35068")]
733 impl ExactSizeIterator for EscapeDebug { }
734
735 #[unstable(feature = "fused", issue = "35602")]
736 impl FusedIterator for EscapeDebug {}
737
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)
742     }
743 }
744
745
746
747 /// An iterator over an iterator of bytes of the characters the bytes represent
748 /// as UTF-8
749 #[unstable(feature = "decode_utf8", issue = "33906")]
750 #[derive(Clone, Debug)]
751 pub struct DecodeUtf8<I: Iterator<Item = u8>>(::iter::Peekable<I>);
752
753 /// Decodes an `Iterator` of bytes as UTF-8.
754 #[unstable(feature = "decode_utf8", issue = "33906")]
755 #[inline]
756 pub fn decode_utf8<I: IntoIterator<Item = u8>>(i: I) -> DecodeUtf8<I::IntoIter> {
757     DecodeUtf8(i.into_iter().peekable())
758 }
759
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(());
764
765 #[unstable(feature = "decode_utf8", issue = "33906")]
766 impl<I: Iterator<Item = u8>> Iterator for DecodeUtf8<I> {
767     type Item = Result<char, InvalidSequence>;
768     #[inline]
769
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
775
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).
779
780             let mut code_point;
781             macro_rules! first_byte {
782                 ($mask: expr) => {
783                     code_point = u32::from(first_byte & $mask)
784                 }
785             }
786             macro_rules! continuation_byte {
787                 () => { continuation_byte!(0x80...0xBF) };
788                 ($range: pat) => {
789                     match self.0.peek() {
790                         Some(&byte @ $range) => {
791                             code_point = (code_point << 6) | u32::from(byte & 0b0011_1111);
792                             self.0.next();
793                         }
794                         _ => return Err(InvalidSequence(()))
795                     }
796                 }
797             }
798
799             match first_byte {
800                 0x00...0x7F => {
801                     first_byte!(0b1111_1111);
802                 }
803                 0xC2...0xDF => {
804                     first_byte!(0b0001_1111);
805                     continuation_byte!();
806                 }
807                 0xE0 => {
808                     first_byte!(0b0000_1111);
809                     continuation_byte!(0xA0...0xBF);  // 0x80...0x9F here are overlong
810                     continuation_byte!();
811                 }
812                 0xE1...0xEC | 0xEE...0xEF => {
813                     first_byte!(0b0000_1111);
814                     continuation_byte!();
815                     continuation_byte!();
816                 }
817                 0xED => {
818                     first_byte!(0b0000_1111);
819                     continuation_byte!(0x80...0x9F);  // 0xA0..0xBF here are surrogates
820                     continuation_byte!();
821                 }
822                 0xF0 => {
823                     first_byte!(0b0000_0111);
824                     continuation_byte!(0x90...0xBF);  // 0x80..0x8F here are overlong
825                     continuation_byte!();
826                     continuation_byte!();
827                 }
828                 0xF1...0xF3 => {
829                     first_byte!(0b0000_0111);
830                     continuation_byte!();
831                     continuation_byte!();
832                     continuation_byte!();
833                 }
834                 0xF4 => {
835                     first_byte!(0b0000_0111);
836                     continuation_byte!(0x80...0x8F);  // 0x90..0xBF here are beyond char::MAX
837                     continuation_byte!();
838                     continuation_byte!();
839                 }
840                 _ => return Err(InvalidSequence(()))  // Illegal first byte, overlong, or beyond MAX
841             }
842             unsafe {
843                 Ok(from_u32_unchecked(code_point))
844             }
845         })
846     }
847 }
848
849 #[unstable(feature = "fused", issue = "35602")]
850 impl<I: FusedIterator<Item = u8>> FusedIterator for DecodeUtf8<I> {}