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.
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
18 //! [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
19 //! [Unicode code point]: http://www.unicode.org/glossary/#code_point
21 //! This module exists for technical reasons, the primary documentation for
22 //! `char` is directly on [the `char` primitive type](../../std/primitive.char.html)
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`.
29 #![stable(feature = "rust1", since = "1.0.0")]
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};
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};
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;
50 /// Returns an iterator that yields the lowercase equivalent of a `char`.
52 /// This `struct` is created by the [`to_lowercase`] method on [`char`]. See
53 /// its documentation for more.
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);
60 #[stable(feature = "rust1", since = "1.0.0")]
61 impl Iterator for ToLowercase {
63 fn next(&mut self) -> Option<char> {
68 #[unstable(feature = "fused", issue = "35602")]
69 impl FusedIterator for ToLowercase {}
71 /// Returns an iterator that yields the uppercase equivalent of a `char`.
73 /// This `struct` is created by the [`to_uppercase`] method on [`char`]. See
74 /// its documentation for more.
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);
81 #[stable(feature = "rust1", since = "1.0.0")]
82 impl Iterator for ToUppercase {
84 fn next(&mut self) -> Option<char> {
89 #[unstable(feature = "fused", issue = "35602")]
90 impl FusedIterator for ToUppercase {}
92 enum CaseMappingIter {
93 Three(char, char, char),
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'
105 CaseMappingIter::Two(chars[0], chars[1])
108 CaseMappingIter::Three(chars[0], chars[1], chars[2])
113 impl Iterator for CaseMappingIter {
115 fn next(&mut self) -> Option<char> {
117 CaseMappingIter::Three(a, b, c) => {
118 *self = CaseMappingIter::Two(b, c);
121 CaseMappingIter::Two(b, c) => {
122 *self = CaseMappingIter::One(c);
125 CaseMappingIter::One(c) => {
126 *self = CaseMappingIter::Zero;
129 CaseMappingIter::Zero => None,
134 impl fmt::Display for CaseMappingIter {
135 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137 CaseMappingIter::Three(a, b, c) => {
142 CaseMappingIter::Two(b, c) => {
146 CaseMappingIter::One(c) => {
149 CaseMappingIter::Zero => Ok(()),
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)
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)
170 /// Checks if a `char` is a digit in the given radix.
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.
177 /// Compared to `is_numeric()`, this function only recognizes the characters
178 /// `0-9`, `a-z` and `A-Z`.
180 /// 'Digit' is defined to be only the following characters:
186 /// For a more comprehensive understanding of 'digit', see [`is_numeric`][is_numeric].
188 /// [is_numeric]: #method.is_numeric
192 /// Panics if given a radix larger than 36.
199 /// assert!('1'.is_digit(10));
200 /// assert!('f'.is_digit(16));
201 /// assert!(!'f'.is_digit(10));
204 /// Passing a large radix, causing a panic:
209 /// let result = thread::spawn(|| {
211 /// '1'.is_digit(37);
214 /// assert!(result.is_err());
216 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn is_digit(self, radix: u32) -> bool {
219 C::is_digit(self, radix)
222 /// Converts a `char` to a digit in the given radix.
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.
229 /// 'Digit' is defined to be only the following characters:
237 /// Returns `None` if the `char` does not refer to a digit in the given radix.
241 /// Panics if given a radix larger than 36.
248 /// assert_eq!('1'.to_digit(10), Some(1));
249 /// assert_eq!('f'.to_digit(16), Some(15));
252 /// Passing a non-digit results in failure:
255 /// assert_eq!('f'.to_digit(10), None);
256 /// assert_eq!('z'.to_digit(16), None);
259 /// Passing a large radix, causing a panic:
264 /// let result = thread::spawn(|| {
265 /// '1'.to_digit(37);
268 /// assert!(result.is_err());
270 #[stable(feature = "rust1", since = "1.0.0")]
272 pub fn to_digit(self, radix: u32) -> Option<u32> {
273 C::to_digit(self, radix)
276 /// Returns an iterator that yields the hexadecimal Unicode escape of a
277 /// character as `char`s.
279 /// This will escape characters with the Rust syntax of the form
280 /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
287 /// for c in '❤'.escape_unicode() {
293 /// Using `println!` directly:
296 /// println!("{}", '❤'.escape_unicode());
299 /// Both are equivalent to:
302 /// println!("\\u{{2764}}");
305 /// Using `to_string`:
308 /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
310 #[stable(feature = "rust1", since = "1.0.0")]
312 pub fn escape_unicode(self) -> EscapeUnicode {
313 C::escape_unicode(self)
316 /// Returns an iterator that yields the literal escape code of a character
319 /// This will escape the characters similar to the `Debug` implementations
320 /// of `str` or `char`.
327 /// # #![feature(char_escape_debug)]
328 /// for c in '\n'.escape_debug() {
334 /// Using `println!` directly:
337 /// # #![feature(char_escape_debug)]
338 /// println!("{}", '\n'.escape_debug());
341 /// Both are equivalent to:
347 /// Using `to_string`:
350 /// # #![feature(char_escape_debug)]
351 /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
353 #[unstable(feature = "char_escape_debug", issue = "35068")]
355 pub fn escape_debug(self) -> EscapeDebug {
356 C::escape_debug(self)
359 /// Returns an iterator that yields the literal escape code of a character
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:
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].
377 /// [escape_unicode]: #method.escape_unicode
384 /// for c in '"'.escape_default() {
390 /// Using `println!` directly:
393 /// println!("{}", '"'.escape_default());
397 /// Both are equivalent to:
400 /// println!("\\\"");
403 /// Using `to_string`:
406 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
408 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn escape_default(self) -> EscapeDefault {
411 C::escape_default(self)
414 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
416 /// That number of bytes is always between 1 and 4, inclusive.
423 /// let len = 'A'.len_utf8();
424 /// assert_eq!(len, 1);
426 /// let len = 'ß'.len_utf8();
427 /// assert_eq!(len, 2);
429 /// let len = 'ℝ'.len_utf8();
430 /// assert_eq!(len, 3);
432 /// let len = '💣'.len_utf8();
433 /// assert_eq!(len, 4);
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:
441 /// let eastern = '東';
442 /// let capitol = '京';
444 /// // both can be represented as three bytes
445 /// assert_eq!(3, eastern.len_utf8());
446 /// assert_eq!(3, capitol.len_utf8());
448 /// // as a &str, these two are encoded in UTF-8
449 /// let tokyo = "東京";
451 /// let len = eastern.len_utf8() + capitol.len_utf8();
453 /// // we can see that they take six bytes total...
454 /// assert_eq!(6, tokyo.len());
456 /// // ... just like the &str
457 /// assert_eq!(len, tokyo.len());
459 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn len_utf8(self) -> usize {
465 /// Returns the number of 16-bit code units this `char` would need if
466 /// encoded in UTF-16.
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.
471 /// [`len_utf8`]: #method.len_utf8
478 /// let n = 'ß'.len_utf16();
479 /// assert_eq!(n, 1);
481 /// let len = '💣'.len_utf16();
482 /// assert_eq!(len, 2);
484 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn len_utf16(self) -> usize {
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.
495 /// Panics if the buffer is not large enough.
496 /// A buffer of length four is large enough to encode any `char`.
500 /// In both of these examples, 'ß' takes two bytes to encode.
503 /// let mut b = [0; 2];
505 /// let result = 'ß'.encode_utf8(&mut b);
507 /// assert_eq!(result, "ß");
509 /// assert_eq!(result.len(), 2);
512 /// A buffer that's too small:
517 /// let result = thread::spawn(|| {
518 /// let mut b = [0; 1];
521 /// 'ß'.encode_utf8(&mut b);
524 /// assert!(result.is_err());
526 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
528 pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
529 C::encode_utf8(self, dst)
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.
537 /// Panics if the buffer is not large enough.
538 /// A buffer of length 2 is large enough to encode any `char`.
542 /// In both of these examples, '𝕊' takes two `u16`s to encode.
545 /// let mut b = [0; 2];
547 /// let result = '𝕊'.encode_utf16(&mut b);
549 /// assert_eq!(result.len(), 2);
552 /// A buffer that's too small:
557 /// let result = thread::spawn(|| {
558 /// let mut b = [0; 1];
561 /// '𝕊'.encode_utf16(&mut b);
564 /// assert!(result.is_err());
566 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
568 pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
569 C::encode_utf16(self, dst)
572 /// Returns true if this `char` is an alphabetic code point, and false if not.
579 /// assert!('a'.is_alphabetic());
580 /// assert!('京'.is_alphabetic());
583 /// // love is many things, but it is not alphabetic
584 /// assert!(!c.is_alphabetic());
586 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn is_alphabetic(self) -> bool {
590 'a'...'z' | 'A'...'Z' => true,
591 c if c > '\x7f' => derived_property::Alphabetic(c),
596 /// Returns true if this `char` satisfies the 'XID_Start' Unicode property, and false
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",
606 pub fn is_xid_start(self) -> bool {
607 derived_property::XID_Start(self)
610 /// Returns true if this `char` satisfies the 'XID_Continue' Unicode property, and false
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",
620 pub fn is_xid_continue(self) -> bool {
621 derived_property::XID_Continue(self)
624 /// Returns true if this `char` is lowercase, and false otherwise.
626 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core
627 /// Property `Lowercase`.
634 /// assert!('a'.is_lowercase());
635 /// assert!('δ'.is_lowercase());
636 /// assert!(!'A'.is_lowercase());
637 /// assert!(!'Δ'.is_lowercase());
639 /// // The various Chinese scripts do not have case, and so:
640 /// assert!(!'中'.is_lowercase());
642 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn is_lowercase(self) -> bool {
647 c if c > '\x7f' => derived_property::Lowercase(c),
652 /// Returns true if this `char` is uppercase, and false otherwise.
654 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core
655 /// Property `Uppercase`.
662 /// assert!(!'a'.is_uppercase());
663 /// assert!(!'δ'.is_uppercase());
664 /// assert!('A'.is_uppercase());
665 /// assert!('Δ'.is_uppercase());
667 /// // The various Chinese scripts do not have case, and so:
668 /// assert!(!'中'.is_uppercase());
670 #[stable(feature = "rust1", since = "1.0.0")]
672 pub fn is_uppercase(self) -> bool {
675 c if c > '\x7f' => derived_property::Uppercase(c),
680 /// Returns true if this `char` is whitespace, and false otherwise.
682 /// 'Whitespace' is defined according to the terms of the Unicode Derived Core
683 /// Property `White_Space`.
690 /// assert!(' '.is_whitespace());
692 /// // a non-breaking space
693 /// assert!('\u{A0}'.is_whitespace());
695 /// assert!(!'越'.is_whitespace());
697 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn is_whitespace(self) -> bool {
701 ' ' | '\x09'...'\x0d' => true,
702 c if c > '\x7f' => property::White_Space(c),
707 /// Returns true if this `char` is alphanumeric, and false otherwise.
709 /// 'Alphanumeric'-ness is defined in terms of the Unicode General Categories
710 /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
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());
726 #[stable(feature = "rust1", since = "1.0.0")]
728 pub fn is_alphanumeric(self) -> bool {
729 self.is_alphabetic() || self.is_numeric()
732 /// Returns true if this `char` is a control code point, and false otherwise.
734 /// 'Control code point' is defined in terms of the Unicode General
742 /// // U+009C, STRING TERMINATOR
743 /// assert!('
\9c'.is_control());
744 /// assert!(!'q'.is_control());
746 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn is_control(self) -> bool {
749 general_category::Cc(self)
752 /// Returns true if this `char` is numeric, and false otherwise.
754 /// 'Numeric'-ness is defined in terms of the Unicode General Categories
755 /// 'Nd', 'Nl', 'No'.
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());
771 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn is_numeric(self) -> bool {
776 c if c > '\x7f' => general_category::N(c),
781 /// Returns an iterator that yields the lowercase equivalent of a `char`
782 /// as one or more `char`s.
784 /// If a character does not have a lowercase equivalent, the same character
785 /// will be returned back by the iterator.
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.
793 /// For a full reference, see [here][reference].
795 /// [Unicode database]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
797 /// [`SpecialCasing.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt
799 /// [reference]: http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
806 /// for c in 'İ'.to_lowercase() {
812 /// Using `println!` directly:
815 /// println!("{}", 'İ'.to_lowercase());
818 /// Both are equivalent to:
821 /// println!("i\u{307}");
824 /// Using `to_string`:
827 /// assert_eq!('C'.to_lowercase().to_string(), "c");
829 /// // Sometimes the result is more than one character:
830 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
832 /// // Characters that do not have both uppercase and lowercase
833 /// // convert into themselves.
834 /// assert_eq!('山'.to_lowercase().to_string(), "山");
836 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn to_lowercase(self) -> ToLowercase {
839 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
842 /// Returns an iterator that yields the uppercase equivalent of a `char`
843 /// as one or more `char`s.
845 /// If a character does not have a uppercase equivalent, the same character
846 /// will be returned back by the iterator.
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.
854 /// For a full reference, see [here][reference].
856 /// [Unicode database]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
858 /// [`SpecialCasing.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt
860 /// [reference]: http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
867 /// for c in 'ß'.to_uppercase() {
873 /// Using `println!` directly:
876 /// println!("{}", 'ß'.to_uppercase());
879 /// Both are equivalent to:
885 /// Using `to_string`:
888 /// assert_eq!('c'.to_uppercase().to_string(), "C");
890 /// // Sometimes the result is more than one character:
891 /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
893 /// // Characters that do not have both uppercase and lowercase
894 /// // convert into themselves.
895 /// assert_eq!('山'.to_uppercase().to_string(), "山");
900 /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
902 /// * 'Dotless': I / ı, sometimes written ï
903 /// * 'Dotted': İ / i
905 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
908 /// let upper_i = 'i'.to_uppercase().to_string();
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:
916 /// let upper_i = 'i'.to_uppercase().to_string();
918 /// assert_eq!(upper_i, "I");
921 /// holds across languages.
922 #[stable(feature = "rust1", since = "1.0.0")]
924 pub fn to_uppercase(self) -> ToUppercase {
925 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
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")]
932 pub struct DecodeUtf16<I>
933 where I: Iterator<Item = u16>
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 {
946 /// Create an iterator over the UTF-16 encoded code points in `iter`,
947 /// returning unpaired surrogates as `Err`s.
954 /// use std::char::decode_utf16;
957 /// // 𝄞mus<invalid>ic<invalid>
958 /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
959 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
962 /// assert_eq!(decode_utf16(v.iter().cloned())
963 /// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
964 /// .collect::<Vec<_>>(),
966 /// Ok('m'), Ok('u'), Ok('s'),
968 /// Ok('i'), Ok('c'),
973 /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
976 /// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
979 /// // 𝄞mus<invalid>ic<invalid>
980 /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
981 /// 0x0073, 0xDD1E, 0x0069, 0x0063,
984 /// assert_eq!(decode_utf16(v.iter().cloned())
985 /// .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
986 /// .collect::<String>(),
990 #[stable(feature = "decode_utf16", since = "1.9.0")]
992 pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
994 iter: iter.into_iter(),
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>;
1003 fn next(&mut self) -> Option<Result<char, DecodeUtf16Error>> {
1004 let u = match self.buf.take() {
1007 match self.iter.next() {
1009 None => return None,
1014 if u < 0xD800 || 0xDFFF < u {
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 }))
1021 let u2 = match self.iter.next() {
1024 None => return Some(Err(DecodeUtf16Error { code: u })),
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 }));
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) }))
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)
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 {
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)
1063 /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
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}';