]> git.lizzy.rs Git - rust.git/blob - src/libstd_unicode/char.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / libstd_unicode / 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 //! A character type.
12 //!
13 //! The `char` type represents a single character. More specifically, since
14 //! 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
15 //! scalar value]', which is similar to, but not the same as, a '[Unicode code
16 //! point]'.
17 //!
18 //! [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
19 //! [Unicode code point]: http://www.unicode.org/glossary/#code_point
20 //!
21 //! This module exists for technical reasons, the primary documentation for
22 //! `char` is directly on [the `char` primitive type](../../std/primitive.char.html)
23 //! itself.
24 //!
25 //! This module is the home of the iterator implementations for the iterators
26 //! implemented on `char`, as well as some useful constants and conversion
27 //! functions that convert various types to `char`.
28
29 #![stable(feature = "rust1", since = "1.0.0")]
30
31 use core::char::CharExt as C;
32 use core::iter::FusedIterator;
33 use core::fmt::{self, Write};
34 use tables::{conversions, derived_property, general_category, property};
35
36 // stable reexports
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use core::char::{MAX, from_digit, from_u32, from_u32_unchecked};
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub use core::char::{EscapeDebug, EscapeDefault, EscapeUnicode};
41
42 // unstable reexports
43 #[unstable(feature = "try_from", issue = "33417")]
44 pub use core::char::CharTryFromError;
45 #[unstable(feature = "decode_utf8", issue = "33906")]
46 pub use core::char::{DecodeUtf8, decode_utf8};
47 #[unstable(feature = "unicode", issue = "27783")]
48 pub use tables::UNICODE_VERSION;
49
50 /// Returns an iterator that yields the lowercase equivalent of a `char`.
51 ///
52 /// This `struct` is created by the [`to_lowercase`] method on [`char`]. See
53 /// its documentation for more.
54 ///
55 /// [`to_lowercase`]: ../../std/primitive.char.html#method.to_lowercase
56 /// [`char`]: ../../std/primitive.char.html
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub struct ToLowercase(CaseMappingIter);
59
60 #[stable(feature = "rust1", since = "1.0.0")]
61 impl Iterator for ToLowercase {
62     type Item = char;
63     fn next(&mut self) -> Option<char> {
64         self.0.next()
65     }
66 }
67
68 #[unstable(feature = "fused", issue = "35602")]
69 impl FusedIterator for ToLowercase {}
70
71 /// Returns an iterator that yields the uppercase equivalent of a `char`.
72 ///
73 /// This `struct` is created by the [`to_uppercase`] method on [`char`]. See
74 /// its documentation for more.
75 ///
76 /// [`to_uppercase`]: ../../std/primitive.char.html#method.to_uppercase
77 /// [`char`]: ../../std/primitive.char.html
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub struct ToUppercase(CaseMappingIter);
80
81 #[stable(feature = "rust1", since = "1.0.0")]
82 impl Iterator for ToUppercase {
83     type Item = char;
84     fn next(&mut self) -> Option<char> {
85         self.0.next()
86     }
87 }
88
89 #[unstable(feature = "fused", issue = "35602")]
90 impl FusedIterator for ToUppercase {}
91
92 enum CaseMappingIter {
93     Three(char, char, char),
94     Two(char, char),
95     One(char),
96     Zero,
97 }
98
99 impl CaseMappingIter {
100     fn new(chars: [char; 3]) -> CaseMappingIter {
101         if chars[2] == '\0' {
102             if chars[1] == '\0' {
103                 CaseMappingIter::One(chars[0])  // Including if chars[0] == '\0'
104             } else {
105                 CaseMappingIter::Two(chars[0], chars[1])
106             }
107         } else {
108             CaseMappingIter::Three(chars[0], chars[1], chars[2])
109         }
110     }
111 }
112
113 impl Iterator for CaseMappingIter {
114     type Item = char;
115     fn next(&mut self) -> Option<char> {
116         match *self {
117             CaseMappingIter::Three(a, b, c) => {
118                 *self = CaseMappingIter::Two(b, c);
119                 Some(a)
120             }
121             CaseMappingIter::Two(b, c) => {
122                 *self = CaseMappingIter::One(c);
123                 Some(b)
124             }
125             CaseMappingIter::One(c) => {
126                 *self = CaseMappingIter::Zero;
127                 Some(c)
128             }
129             CaseMappingIter::Zero => None,
130         }
131     }
132 }
133
134 impl fmt::Display for CaseMappingIter {
135     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136         match *self {
137             CaseMappingIter::Three(a, b, c) => {
138                 f.write_char(a)?;
139                 f.write_char(b)?;
140                 f.write_char(c)
141             }
142             CaseMappingIter::Two(b, c) => {
143                 f.write_char(b)?;
144                 f.write_char(c)
145             }
146             CaseMappingIter::One(c) => {
147                 f.write_char(c)
148             }
149             CaseMappingIter::Zero => Ok(()),
150         }
151     }
152 }
153
154 #[stable(feature = "char_struct_display", since = "1.16.0")]
155 impl fmt::Display for ToLowercase {
156     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157         fmt::Display::fmt(&self.0, f)
158     }
159 }
160
161 #[stable(feature = "char_struct_display", since = "1.16.0")]
162 impl fmt::Display for ToUppercase {
163     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164         fmt::Display::fmt(&self.0, f)
165     }
166 }
167
168 #[lang = "char"]
169 impl char {
170     /// Checks if a `char` is a digit in the given radix.
171     ///
172     /// A 'radix' here is sometimes also called a 'base'. A radix of two
173     /// indicates a binary number, a radix of ten, decimal, and a radix of
174     /// sixteen, hexadecimal, to give some common values. Arbitrary
175     /// radices are supported.
176     ///
177     /// Compared to `is_numeric()`, this function only recognizes the characters
178     /// `0-9`, `a-z` and `A-Z`.
179     ///
180     /// 'Digit' is defined to be only the following characters:
181     ///
182     /// * `0-9`
183     /// * `a-z`
184     /// * `A-Z`
185     ///
186     /// For a more comprehensive understanding of 'digit', see [`is_numeric`][is_numeric].
187     ///
188     /// [is_numeric]: #method.is_numeric
189     ///
190     /// # Panics
191     ///
192     /// Panics if given a radix larger than 36.
193     ///
194     /// # Examples
195     ///
196     /// Basic usage:
197     ///
198     /// ```
199     /// assert!('1'.is_digit(10));
200     /// assert!('f'.is_digit(16));
201     /// assert!(!'f'.is_digit(10));
202     /// ```
203     ///
204     /// Passing a large radix, causing a panic:
205     ///
206     /// ```
207     /// use std::thread;
208     ///
209     /// let result = thread::spawn(|| {
210     ///     // this panics
211     ///     '1'.is_digit(37);
212     /// }).join();
213     ///
214     /// assert!(result.is_err());
215     /// ```
216     #[stable(feature = "rust1", since = "1.0.0")]
217     #[inline]
218     pub fn is_digit(self, radix: u32) -> bool {
219         C::is_digit(self, radix)
220     }
221
222     /// Converts a `char` to a digit in the given radix.
223     ///
224     /// A 'radix' here is sometimes also called a 'base'. A radix of two
225     /// indicates a binary number, a radix of ten, decimal, and a radix of
226     /// sixteen, hexadecimal, to give some common values. Arbitrary
227     /// radices are supported.
228     ///
229     /// 'Digit' is defined to be only the following characters:
230     ///
231     /// * `0-9`
232     /// * `a-z`
233     /// * `A-Z`
234     ///
235     /// # Errors
236     ///
237     /// Returns `None` if the `char` does not refer to a digit in the given radix.
238     ///
239     /// # Panics
240     ///
241     /// Panics if given a radix larger than 36.
242     ///
243     /// # Examples
244     ///
245     /// Basic usage:
246     ///
247     /// ```
248     /// assert_eq!('1'.to_digit(10), Some(1));
249     /// assert_eq!('f'.to_digit(16), Some(15));
250     /// ```
251     ///
252     /// Passing a non-digit results in failure:
253     ///
254     /// ```
255     /// assert_eq!('f'.to_digit(10), None);
256     /// assert_eq!('z'.to_digit(16), None);
257     /// ```
258     ///
259     /// Passing a large radix, causing a panic:
260     ///
261     /// ```
262     /// use std::thread;
263     ///
264     /// let result = thread::spawn(|| {
265     ///     '1'.to_digit(37);
266     /// }).join();
267     ///
268     /// assert!(result.is_err());
269     /// ```
270     #[stable(feature = "rust1", since = "1.0.0")]
271     #[inline]
272     pub fn to_digit(self, radix: u32) -> Option<u32> {
273         C::to_digit(self, radix)
274     }
275
276     /// Returns an iterator that yields the hexadecimal Unicode escape of a
277     /// character as `char`s.
278     ///
279     /// This will escape characters with the Rust syntax of the form
280     /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
281     ///
282     /// # Examples
283     ///
284     /// As an iterator:
285     ///
286     /// ```
287     /// for c in '❤'.escape_unicode() {
288     ///     print!("{}", c);
289     /// }
290     /// println!();
291     /// ```
292     ///
293     /// Using `println!` directly:
294     ///
295     /// ```
296     /// println!("{}", '❤'.escape_unicode());
297     /// ```
298     ///
299     /// Both are equivalent to:
300     ///
301     /// ```
302     /// println!("\\u{{2764}}");
303     /// ```
304     ///
305     /// Using `to_string`:
306     ///
307     /// ```
308     /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
309     /// ```
310     #[stable(feature = "rust1", since = "1.0.0")]
311     #[inline]
312     pub fn escape_unicode(self) -> EscapeUnicode {
313         C::escape_unicode(self)
314     }
315
316     /// Returns an iterator that yields the literal escape code of a character
317     /// as `char`s.
318     ///
319     /// This will escape the characters similar to the `Debug` implementations
320     /// of `str` or `char`.
321     ///
322     /// # Examples
323     ///
324     /// As an iterator:
325     ///
326     /// ```
327     /// # #![feature(char_escape_debug)]
328     /// for c in '\n'.escape_debug() {
329     ///     print!("{}", c);
330     /// }
331     /// println!();
332     /// ```
333     ///
334     /// Using `println!` directly:
335     ///
336     /// ```
337     /// # #![feature(char_escape_debug)]
338     /// println!("{}", '\n'.escape_debug());
339     /// ```
340     ///
341     /// Both are equivalent to:
342     ///
343     /// ```
344     /// println!("\\n");
345     /// ```
346     ///
347     /// Using `to_string`:
348     ///
349     /// ```
350     /// # #![feature(char_escape_debug)]
351     /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
352     /// ```
353     #[unstable(feature = "char_escape_debug", issue = "35068")]
354     #[inline]
355     pub fn escape_debug(self) -> EscapeDebug {
356         C::escape_debug(self)
357     }
358
359     /// Returns an iterator that yields the literal escape code of a character
360     /// as `char`s.
361     ///
362     /// The default is chosen with a bias toward producing literals that are
363     /// legal in a variety of languages, including C++11 and similar C-family
364     /// languages. The exact rules are:
365     ///
366     /// * Tab is escaped as `\t`.
367     /// * Carriage return is escaped as `\r`.
368     /// * Line feed is escaped as `\n`.
369     /// * Single quote is escaped as `\'`.
370     /// * Double quote is escaped as `\"`.
371     /// * Backslash is escaped as `\\`.
372     /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
373     ///   inclusive is not escaped.
374     /// * All other characters are given hexadecimal Unicode escapes; see
375     ///   [`escape_unicode`][escape_unicode].
376     ///
377     /// [escape_unicode]: #method.escape_unicode
378     ///
379     /// # Examples
380     ///
381     /// As an iterator:
382     ///
383     /// ```
384     /// for c in '"'.escape_default() {
385     ///     print!("{}", c);
386     /// }
387     /// println!();
388     /// ```
389     ///
390     /// Using `println!` directly:
391     ///
392     /// ```
393     /// println!("{}", '"'.escape_default());
394     /// ```
395     ///
396     ///
397     /// Both are equivalent to:
398     ///
399     /// ```
400     /// println!("\\\"");
401     /// ```
402     ///
403     /// Using `to_string`:
404     ///
405     /// ```
406     /// assert_eq!('"'.escape_default().to_string(), "\\\"");
407     /// ```
408     #[stable(feature = "rust1", since = "1.0.0")]
409     #[inline]
410     pub fn escape_default(self) -> EscapeDefault {
411         C::escape_default(self)
412     }
413
414     /// Returns the number of bytes this `char` would need if encoded in UTF-8.
415     ///
416     /// That number of bytes is always between 1 and 4, inclusive.
417     ///
418     /// # Examples
419     ///
420     /// Basic usage:
421     ///
422     /// ```
423     /// let len = 'A'.len_utf8();
424     /// assert_eq!(len, 1);
425     ///
426     /// let len = 'ß'.len_utf8();
427     /// assert_eq!(len, 2);
428     ///
429     /// let len = 'ℝ'.len_utf8();
430     /// assert_eq!(len, 3);
431     ///
432     /// let len = '💣'.len_utf8();
433     /// assert_eq!(len, 4);
434     /// ```
435     ///
436     /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
437     /// would take if each code point was represented as a `char` vs in the `&str` itself:
438     ///
439     /// ```
440     /// // as chars
441     /// let eastern = '東';
442     /// let capitol = '京';
443     ///
444     /// // both can be represented as three bytes
445     /// assert_eq!(3, eastern.len_utf8());
446     /// assert_eq!(3, capitol.len_utf8());
447     ///
448     /// // as a &str, these two are encoded in UTF-8
449     /// let tokyo = "東京";
450     ///
451     /// let len = eastern.len_utf8() + capitol.len_utf8();
452     ///
453     /// // we can see that they take six bytes total...
454     /// assert_eq!(6, tokyo.len());
455     ///
456     /// // ... just like the &str
457     /// assert_eq!(len, tokyo.len());
458     /// ```
459     #[stable(feature = "rust1", since = "1.0.0")]
460     #[inline]
461     pub fn len_utf8(self) -> usize {
462         C::len_utf8(self)
463     }
464
465     /// Returns the number of 16-bit code units this `char` would need if
466     /// encoded in UTF-16.
467     ///
468     /// See the documentation for [`len_utf8`] for more explanation of this
469     /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
470     ///
471     /// [`len_utf8`]: #method.len_utf8
472     ///
473     /// # Examples
474     ///
475     /// Basic usage:
476     ///
477     /// ```
478     /// let n = 'ß'.len_utf16();
479     /// assert_eq!(n, 1);
480     ///
481     /// let len = '💣'.len_utf16();
482     /// assert_eq!(len, 2);
483     /// ```
484     #[stable(feature = "rust1", since = "1.0.0")]
485     #[inline]
486     pub fn len_utf16(self) -> usize {
487         C::len_utf16(self)
488     }
489
490     /// Encodes this character as UTF-8 into the provided byte buffer,
491     /// and then returns the subslice of the buffer that contains the encoded character.
492     ///
493     /// # Panics
494     ///
495     /// Panics if the buffer is not large enough.
496     /// A buffer of length four is large enough to encode any `char`.
497     ///
498     /// # Examples
499     ///
500     /// In both of these examples, 'ß' takes two bytes to encode.
501     ///
502     /// ```
503     /// let mut b = [0; 2];
504     ///
505     /// let result = 'ß'.encode_utf8(&mut b);
506     ///
507     /// assert_eq!(result, "ß");
508     ///
509     /// assert_eq!(result.len(), 2);
510     /// ```
511     ///
512     /// A buffer that's too small:
513     ///
514     /// ```
515     /// use std::thread;
516     ///
517     /// let result = thread::spawn(|| {
518     ///     let mut b = [0; 1];
519     ///
520     ///     // this panics
521     ///    'ß'.encode_utf8(&mut b);
522     /// }).join();
523     ///
524     /// assert!(result.is_err());
525     /// ```
526     #[stable(feature = "unicode_encode_char", since = "1.15.0")]
527     #[inline]
528     pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
529         C::encode_utf8(self, dst)
530     }
531
532     /// Encodes this character as UTF-16 into the provided `u16` buffer,
533     /// and then returns the subslice of the buffer that contains the encoded character.
534     ///
535     /// # Panics
536     ///
537     /// Panics if the buffer is not large enough.
538     /// A buffer of length 2 is large enough to encode any `char`.
539     ///
540     /// # Examples
541     ///
542     /// In both of these examples, '𝕊' takes two `u16`s to encode.
543     ///
544     /// ```
545     /// let mut b = [0; 2];
546     ///
547     /// let result = '𝕊'.encode_utf16(&mut b);
548     ///
549     /// assert_eq!(result.len(), 2);
550     /// ```
551     ///
552     /// A buffer that's too small:
553     ///
554     /// ```
555     /// use std::thread;
556     ///
557     /// let result = thread::spawn(|| {
558     ///     let mut b = [0; 1];
559     ///
560     ///     // this panics
561     ///     '𝕊'.encode_utf16(&mut b);
562     /// }).join();
563     ///
564     /// assert!(result.is_err());
565     /// ```
566     #[stable(feature = "unicode_encode_char", since = "1.15.0")]
567     #[inline]
568     pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
569         C::encode_utf16(self, dst)
570     }
571
572     /// Returns true if this `char` is an alphabetic code point, and false if not.
573     ///
574     /// # Examples
575     ///
576     /// Basic usage:
577     ///
578     /// ```
579     /// assert!('a'.is_alphabetic());
580     /// assert!('京'.is_alphabetic());
581     ///
582     /// let c = '💝';
583     /// // love is many things, but it is not alphabetic
584     /// assert!(!c.is_alphabetic());
585     /// ```
586     #[stable(feature = "rust1", since = "1.0.0")]
587     #[inline]
588     pub fn is_alphabetic(self) -> bool {
589         match self {
590             'a'...'z' | 'A'...'Z' => true,
591             c if c > '\x7f' => derived_property::Alphabetic(c),
592             _ => false,
593         }
594     }
595
596     /// Returns true if this `char` satisfies the 'XID_Start' Unicode property, and false
597     /// otherwise.
598     ///
599     /// 'XID_Start' is a Unicode Derived Property specified in
600     /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
601     /// mostly similar to `ID_Start` but modified for closure under `NFKx`.
602     #[unstable(feature = "unicode",
603                reason = "mainly needed for compiler internals",
604                issue = "0")]
605     #[inline]
606     pub fn is_xid_start(self) -> bool {
607         derived_property::XID_Start(self)
608     }
609
610     /// Returns true if this `char` satisfies the 'XID_Continue' Unicode property, and false
611     /// otherwise.
612     ///
613     /// 'XID_Continue' is a Unicode Derived Property specified in
614     /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
615     /// mostly similar to 'ID_Continue' but modified for closure under NFKx.
616     #[unstable(feature = "unicode",
617                reason = "mainly needed for compiler internals",
618                issue = "0")]
619     #[inline]
620     pub fn is_xid_continue(self) -> bool {
621         derived_property::XID_Continue(self)
622     }
623
624     /// Returns true if this `char` is lowercase, and false otherwise.
625     ///
626     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core
627     /// Property `Lowercase`.
628     ///
629     /// # Examples
630     ///
631     /// Basic usage:
632     ///
633     /// ```
634     /// assert!('a'.is_lowercase());
635     /// assert!('δ'.is_lowercase());
636     /// assert!(!'A'.is_lowercase());
637     /// assert!(!'Δ'.is_lowercase());
638     ///
639     /// // The various Chinese scripts do not have case, and so:
640     /// assert!(!'中'.is_lowercase());
641     /// ```
642     #[stable(feature = "rust1", since = "1.0.0")]
643     #[inline]
644     pub fn is_lowercase(self) -> bool {
645         match self {
646             'a'...'z' => true,
647             c if c > '\x7f' => derived_property::Lowercase(c),
648             _ => false,
649         }
650     }
651
652     /// Returns true if this `char` is uppercase, and false otherwise.
653     ///
654     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core
655     /// Property `Uppercase`.
656     ///
657     /// # Examples
658     ///
659     /// Basic usage:
660     ///
661     /// ```
662     /// assert!(!'a'.is_uppercase());
663     /// assert!(!'δ'.is_uppercase());
664     /// assert!('A'.is_uppercase());
665     /// assert!('Δ'.is_uppercase());
666     ///
667     /// // The various Chinese scripts do not have case, and so:
668     /// assert!(!'中'.is_uppercase());
669     /// ```
670     #[stable(feature = "rust1", since = "1.0.0")]
671     #[inline]
672     pub fn is_uppercase(self) -> bool {
673         match self {
674             'A'...'Z' => true,
675             c if c > '\x7f' => derived_property::Uppercase(c),
676             _ => false,
677         }
678     }
679
680     /// Returns true if this `char` is whitespace, and false otherwise.
681     ///
682     /// 'Whitespace' is defined according to the terms of the Unicode Derived Core
683     /// Property `White_Space`.
684     ///
685     /// # Examples
686     ///
687     /// Basic usage:
688     ///
689     /// ```
690     /// assert!(' '.is_whitespace());
691     ///
692     /// // a non-breaking space
693     /// assert!('\u{A0}'.is_whitespace());
694     ///
695     /// assert!(!'越'.is_whitespace());
696     /// ```
697     #[stable(feature = "rust1", since = "1.0.0")]
698     #[inline]
699     pub fn is_whitespace(self) -> bool {
700         match self {
701             ' ' | '\x09'...'\x0d' => true,
702             c if c > '\x7f' => property::White_Space(c),
703             _ => false,
704         }
705     }
706
707     /// Returns true if this `char` is alphanumeric, and false otherwise.
708     ///
709     /// 'Alphanumeric'-ness is defined in terms of the Unicode General Categories
710     /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
711     ///
712     /// # Examples
713     ///
714     /// Basic usage:
715     ///
716     /// ```
717     /// assert!('٣'.is_alphanumeric());
718     /// assert!('7'.is_alphanumeric());
719     /// assert!('৬'.is_alphanumeric());
720     /// assert!('K'.is_alphanumeric());
721     /// assert!('و'.is_alphanumeric());
722     /// assert!('藏'.is_alphanumeric());
723     /// assert!(!'¾'.is_alphanumeric());
724     /// assert!(!'①'.is_alphanumeric());
725     /// ```
726     #[stable(feature = "rust1", since = "1.0.0")]
727     #[inline]
728     pub fn is_alphanumeric(self) -> bool {
729         self.is_alphabetic() || self.is_numeric()
730     }
731
732     /// Returns true if this `char` is a control code point, and false otherwise.
733     ///
734     /// 'Control code point' is defined in terms of the Unicode General
735     /// Category `Cc`.
736     ///
737     /// # Examples
738     ///
739     /// Basic usage:
740     ///
741     /// ```
742     /// // U+009C, STRING TERMINATOR
743     /// assert!('\9c'.is_control());
744     /// assert!(!'q'.is_control());
745     /// ```
746     #[stable(feature = "rust1", since = "1.0.0")]
747     #[inline]
748     pub fn is_control(self) -> bool {
749         general_category::Cc(self)
750     }
751
752     /// Returns true if this `char` is numeric, and false otherwise.
753     ///
754     /// 'Numeric'-ness is defined in terms of the Unicode General Categories
755     /// 'Nd', 'Nl', 'No'.
756     ///
757     /// # Examples
758     ///
759     /// Basic usage:
760     ///
761     /// ```
762     /// assert!('٣'.is_numeric());
763     /// assert!('7'.is_numeric());
764     /// assert!('৬'.is_numeric());
765     /// assert!(!'K'.is_numeric());
766     /// assert!(!'و'.is_numeric());
767     /// assert!(!'藏'.is_numeric());
768     /// assert!(!'¾'.is_numeric());
769     /// assert!(!'①'.is_numeric());
770     /// ```
771     #[stable(feature = "rust1", since = "1.0.0")]
772     #[inline]
773     pub fn is_numeric(self) -> bool {
774         match self {
775             '0'...'9' => true,
776             c if c > '\x7f' => general_category::N(c),
777             _ => false,
778         }
779     }
780
781     /// Returns an iterator that yields the lowercase equivalent of a `char`
782     /// as one or more `char`s.
783     ///
784     /// If a character does not have a lowercase equivalent, the same character
785     /// will be returned back by the iterator.
786     ///
787     /// This performs complex unconditional mappings with no tailoring: it maps
788     /// one Unicode character to its lowercase equivalent according to the
789     /// [Unicode database] and the additional complex mappings
790     /// [`SpecialCasing.txt`]. Conditional mappings (based on context or
791     /// language) are not considered here.
792     ///
793     /// For a full reference, see [here][reference].
794     ///
795     /// [Unicode database]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
796     ///
797     /// [`SpecialCasing.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt
798     ///
799     /// [reference]: http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
800     ///
801     /// # Examples
802     ///
803     /// As an iterator:
804     ///
805     /// ```
806     /// for c in 'İ'.to_lowercase() {
807     ///     print!("{}", c);
808     /// }
809     /// println!();
810     /// ```
811     ///
812     /// Using `println!` directly:
813     ///
814     /// ```
815     /// println!("{}", 'İ'.to_lowercase());
816     /// ```
817     ///
818     /// Both are equivalent to:
819     ///
820     /// ```
821     /// println!("i\u{307}");
822     /// ```
823     ///
824     /// Using `to_string`:
825     ///
826     /// ```
827     /// assert_eq!('C'.to_lowercase().to_string(), "c");
828     ///
829     /// // Sometimes the result is more than one character:
830     /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
831     ///
832     /// // Characters that do not have both uppercase and lowercase
833     /// // convert into themselves.
834     /// assert_eq!('山'.to_lowercase().to_string(), "山");
835     /// ```
836     #[stable(feature = "rust1", since = "1.0.0")]
837     #[inline]
838     pub fn to_lowercase(self) -> ToLowercase {
839         ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
840     }
841
842     /// Returns an iterator that yields the uppercase equivalent of a `char`
843     /// as one or more `char`s.
844     ///
845     /// If a character does not have a uppercase equivalent, the same character
846     /// will be returned back by the iterator.
847     ///
848     /// This performs complex unconditional mappings with no tailoring: it maps
849     /// one Unicode character to its lowercase equivalent according to the
850     /// [Unicode database] and the additional complex mappings
851     /// [`SpecialCasing.txt`]. Conditional mappings (based on context or
852     /// language) are not considered here.
853     ///
854     /// For a full reference, see [here][reference].
855     ///
856     /// [Unicode database]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
857     ///
858     /// [`SpecialCasing.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt
859     ///
860     /// [reference]: http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
861     ///
862     /// # Examples
863     ///
864     /// As an iterator:
865     ///
866     /// ```
867     /// for c in 'ß'.to_uppercase() {
868     ///     print!("{}", c);
869     /// }
870     /// println!();
871     /// ```
872     ///
873     /// Using `println!` directly:
874     ///
875     /// ```
876     /// println!("{}", 'ß'.to_uppercase());
877     /// ```
878     ///
879     /// Both are equivalent to:
880     ///
881     /// ```
882     /// println!("SS");
883     /// ```
884     ///
885     /// Using `to_string`:
886     ///
887     /// ```
888     /// assert_eq!('c'.to_uppercase().to_string(), "C");
889     ///
890     /// // Sometimes the result is more than one character:
891     /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
892     ///
893     /// // Characters that do not have both uppercase and lowercase
894     /// // convert into themselves.
895     /// assert_eq!('山'.to_uppercase().to_string(), "山");
896     /// ```
897     ///
898     /// # Note on locale
899     ///
900     /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
901     ///
902     /// * 'Dotless': I / ı, sometimes written ï
903     /// * 'Dotted': İ / i
904     ///
905     /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
906     ///
907     /// ```
908     /// let upper_i = 'i'.to_uppercase().to_string();
909     /// ```
910     ///
911     /// The value of `upper_i` here relies on the language of the text: if we're
912     /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
913     /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
914     ///
915     /// ```
916     /// let upper_i = 'i'.to_uppercase().to_string();
917     ///
918     /// assert_eq!(upper_i, "I");
919     /// ```
920     ///
921     /// holds across languages.
922     #[stable(feature = "rust1", since = "1.0.0")]
923     #[inline]
924     pub fn to_uppercase(self) -> ToUppercase {
925         ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
926     }
927 }
928
929 /// An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s.
930 #[stable(feature = "decode_utf16", since = "1.9.0")]
931 #[derive(Clone)]
932 pub struct DecodeUtf16<I>
933     where I: Iterator<Item = u16>
934 {
935     iter: I,
936     buf: Option<u16>,
937 }
938
939 /// An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s.
940 #[stable(feature = "decode_utf16", since = "1.9.0")]
941 #[derive(Debug, Clone, Eq, PartialEq)]
942 pub struct DecodeUtf16Error {
943     code: u16,
944 }
945
946 /// Create an iterator over the UTF-16 encoded code points in `iter`,
947 /// returning unpaired surrogates as `Err`s.
948 ///
949 /// # Examples
950 ///
951 /// Basic usage:
952 ///
953 /// ```
954 /// use std::char::decode_utf16;
955 ///
956 /// fn main() {
957 ///     // 𝄞mus<invalid>ic<invalid>
958 ///     let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
959 ///              0x0073, 0xDD1E, 0x0069, 0x0063,
960 ///              0xD834];
961 ///
962 ///     assert_eq!(decode_utf16(v.iter().cloned())
963 ///                            .map(|r| r.map_err(|e| e.unpaired_surrogate()))
964 ///                            .collect::<Vec<_>>(),
965 ///                vec![Ok('𝄞'),
966 ///                     Ok('m'), Ok('u'), Ok('s'),
967 ///                     Err(0xDD1E),
968 ///                     Ok('i'), Ok('c'),
969 ///                     Err(0xD834)]);
970 /// }
971 /// ```
972 ///
973 /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
974 ///
975 /// ```
976 /// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
977 ///
978 /// fn main() {
979 ///     // 𝄞mus<invalid>ic<invalid>
980 ///     let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
981 ///              0x0073, 0xDD1E, 0x0069, 0x0063,
982 ///              0xD834];
983 ///
984 ///     assert_eq!(decode_utf16(v.iter().cloned())
985 ///                    .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
986 ///                    .collect::<String>(),
987 ///                "𝄞mus�ic�");
988 /// }
989 /// ```
990 #[stable(feature = "decode_utf16", since = "1.9.0")]
991 #[inline]
992 pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
993     DecodeUtf16 {
994         iter: iter.into_iter(),
995         buf: None,
996     }
997 }
998
999 #[stable(feature = "decode_utf16", since = "1.9.0")]
1000 impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
1001     type Item = Result<char, DecodeUtf16Error>;
1002
1003     fn next(&mut self) -> Option<Result<char, DecodeUtf16Error>> {
1004         let u = match self.buf.take() {
1005             Some(buf) => buf,
1006             None => {
1007                 match self.iter.next() {
1008                     Some(u) => u,
1009                     None => return None,
1010                 }
1011             }
1012         };
1013
1014         if u < 0xD800 || 0xDFFF < u {
1015             // not a surrogate
1016             Some(Ok(unsafe { from_u32_unchecked(u as u32) }))
1017         } else if u >= 0xDC00 {
1018             // a trailing surrogate
1019             Some(Err(DecodeUtf16Error { code: u }))
1020         } else {
1021             let u2 = match self.iter.next() {
1022                 Some(u2) => u2,
1023                 // eof
1024                 None => return Some(Err(DecodeUtf16Error { code: u })),
1025             };
1026             if u2 < 0xDC00 || u2 > 0xDFFF {
1027                 // not a trailing surrogate so we're not a valid
1028                 // surrogate pair, so rewind to redecode u2 next time.
1029                 self.buf = Some(u2);
1030                 return Some(Err(DecodeUtf16Error { code: u }));
1031             }
1032
1033             // all ok, so lets decode it.
1034             let c = (((u - 0xD800) as u32) << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
1035             Some(Ok(unsafe { from_u32_unchecked(c) }))
1036         }
1037     }
1038
1039     #[inline]
1040     fn size_hint(&self) -> (usize, Option<usize>) {
1041         let (low, high) = self.iter.size_hint();
1042         // we could be entirely valid surrogates (2 elements per
1043         // char), or entirely non-surrogates (1 element per char)
1044         (low / 2, high)
1045     }
1046 }
1047
1048 impl DecodeUtf16Error {
1049     /// Returns the unpaired surrogate which caused this error.
1050     #[stable(feature = "decode_utf16", since = "1.9.0")]
1051     pub fn unpaired_surrogate(&self) -> u16 {
1052         self.code
1053     }
1054 }
1055
1056 #[stable(feature = "decode_utf16", since = "1.9.0")]
1057 impl fmt::Display for DecodeUtf16Error {
1058     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1059         write!(f, "unpaired surrogate found: {:x}", self.code)
1060     }
1061 }
1062
1063 /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
1064 /// decoding error.
1065 ///
1066 /// It can occur, for example, when giving ill-formed UTF-8 bytes to
1067 /// [`String::from_utf8_lossy`](../../std/string/struct.String.html#method.from_utf8_lossy).
1068 #[stable(feature = "decode_utf16", since = "1.9.0")]
1069 pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';