4 use crate::str::from_utf8_unchecked_mut
;
5 use crate::unicode
::printable
::is_printable
;
6 use crate::unicode
::{self, conversions}
;
12 /// The highest valid code point a `char` can have.
14 /// A `char` is a [Unicode Scalar Value], which means that it is a [Code
15 /// Point], but only ones within a certain range. `MAX` is the highest valid
16 /// code point that's a valid [Unicode Scalar Value].
18 /// [Unicode Scalar Value]: http://www.unicode.org/glossary/#unicode_scalar_value
19 /// [Code Point]: http://www.unicode.org/glossary/#code_point
20 #[unstable(feature = "assoc_char_consts", reason = "recently added", issue = "71763")]
21 pub const MAX
: char = '
\u{10ffff}'
;
23 /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
26 /// It can occur, for example, when giving ill-formed UTF-8 bytes to
27 /// [`String::from_utf8_lossy`](string/struct.String.html#method.from_utf8_lossy).
28 #[unstable(feature = "assoc_char_consts", reason = "recently added", issue = "71763")]
29 pub const REPLACEMENT_CHARACTER
: char = '
\u{FFFD}'
;
31 /// The version of [Unicode](http://www.unicode.org/) that the Unicode parts of
32 /// `char` and `str` methods are based on.
34 /// New versions of Unicode are released regularly and subsequently all methods
35 /// in the standard library depending on Unicode are updated. Therefore the
36 /// behavior of some `char` and `str` methods and the value of this constant
37 /// changes over time. This is *not* considered to be a breaking change.
39 /// The version numbering scheme is explained in
40 /// [Unicode 11.0 or later, Section 3.1 Versions of the Unicode Standard](https://www.unicode.org/versions/Unicode11.0.0/ch03.pdf#page=4).
41 #[unstable(feature = "assoc_char_consts", reason = "recently added", issue = "71763")]
42 pub const UNICODE_VERSION
: (u8, u8, u8) = crate::unicode
::UNICODE_VERSION
;
44 /// Creates an iterator over the UTF-16 encoded code points in `iter`,
45 /// returning unpaired surrogates as `Err`s.
52 /// use std::char::decode_utf16;
54 /// // 𝄞mus<invalid>ic<invalid>
56 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
60 /// decode_utf16(v.iter().cloned())
61 /// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
62 /// .collect::<Vec<_>>(),
65 /// Ok('m'), Ok('u'), Ok('s'),
73 /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
76 /// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
78 /// // 𝄞mus<invalid>ic<invalid>
80 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
84 /// decode_utf16(v.iter().cloned())
85 /// .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
86 /// .collect::<String>(),
90 #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")]
92 pub fn decode_utf16
<I
: IntoIterator
<Item
= u16>>(iter
: I
) -> DecodeUtf16
<I
::IntoIter
> {
93 super::decode
::decode_utf16(iter
)
96 /// Converts a `u32` to a `char`.
98 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
103 /// let i = c as u32;
105 /// assert_eq!(128175, i);
108 /// However, the reverse is not true: not all valid [`u32`]s are valid
109 /// `char`s. `from_u32()` will return `None` if the input is not a valid value
112 /// [`u32`]: primitive.u32.html
114 /// For an unsafe version of this function which ignores these checks, see
115 /// [`from_u32_unchecked`].
117 /// [`from_u32_unchecked`]: #method.from_u32_unchecked
126 /// let c = char::from_u32(0x2764);
128 /// assert_eq!(Some('❤'), c);
131 /// Returning `None` when the input is not a valid `char`:
136 /// let c = char::from_u32(0x110000);
138 /// assert_eq!(None, c);
140 #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")]
142 pub fn from_u32(i
: u32) -> Option
<char> {
143 super::convert
::from_u32(i
)
146 /// Converts a `u32` to a `char`, ignoring validity.
148 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
153 /// let i = c as u32;
155 /// assert_eq!(128175, i);
158 /// However, the reverse is not true: not all valid [`u32`]s are valid
159 /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to
160 /// `char`, possibly creating an invalid one.
162 /// [`u32`]: primitive.u32.html
166 /// This function is unsafe, as it may construct invalid `char` values.
168 /// For a safe version of this function, see the [`from_u32`] function.
170 /// [`from_u32`]: #method.from_u32
179 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
181 /// assert_eq!('❤', c);
183 #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")]
185 pub unsafe fn from_u32_unchecked(i
: u32) -> char {
186 // SAFETY: the safety contract must be upheld by the caller.
187 unsafe { super::convert::from_u32_unchecked(i) }
190 /// Converts a digit in the given radix to a `char`.
192 /// A 'radix' here is sometimes also called a 'base'. A radix of two
193 /// indicates a binary number, a radix of ten, decimal, and a radix of
194 /// sixteen, hexadecimal, to give some common values. Arbitrary
195 /// radices are supported.
197 /// `from_digit()` will return `None` if the input is not a digit in
202 /// Panics if given a radix larger than 36.
211 /// let c = char::from_digit(4, 10);
213 /// assert_eq!(Some('4'), c);
215 /// // Decimal 11 is a single digit in base 16
216 /// let c = char::from_digit(11, 16);
218 /// assert_eq!(Some('b'), c);
221 /// Returning `None` when the input is not a digit:
226 /// let c = char::from_digit(20, 10);
228 /// assert_eq!(None, c);
231 /// Passing a large radix, causing a panic:
237 /// char::from_digit(1, 37);
239 #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")]
241 pub fn from_digit(num
: u32, radix
: u32) -> Option
<char> {
242 super::convert
::from_digit(num
, radix
)
245 /// Checks if a `char` is a digit in the given radix.
247 /// A 'radix' here is sometimes also called a 'base'. A radix of two
248 /// indicates a binary number, a radix of ten, decimal, and a radix of
249 /// sixteen, hexadecimal, to give some common values. Arbitrary
250 /// radices are supported.
252 /// Compared to `is_numeric()`, this function only recognizes the characters
253 /// `0-9`, `a-z` and `A-Z`.
255 /// 'Digit' is defined to be only the following characters:
261 /// For a more comprehensive understanding of 'digit', see [`is_numeric`][is_numeric].
263 /// [is_numeric]: #method.is_numeric
267 /// Panics if given a radix larger than 36.
274 /// assert!('1'.is_digit(10));
275 /// assert!('f'.is_digit(16));
276 /// assert!(!'f'.is_digit(10));
279 /// Passing a large radix, causing a panic:
283 /// '1'.is_digit(37);
285 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn is_digit(self, radix
: u32) -> bool
{
288 self.to_digit(radix
).is_some()
291 /// Converts a `char` to a digit in the given radix.
293 /// A 'radix' here is sometimes also called a 'base'. A radix of two
294 /// indicates a binary number, a radix of ten, decimal, and a radix of
295 /// sixteen, hexadecimal, to give some common values. Arbitrary
296 /// radices are supported.
298 /// 'Digit' is defined to be only the following characters:
306 /// Returns `None` if the `char` does not refer to a digit in the given radix.
310 /// Panics if given a radix larger than 36.
317 /// assert_eq!('1'.to_digit(10), Some(1));
318 /// assert_eq!('f'.to_digit(16), Some(15));
321 /// Passing a non-digit results in failure:
324 /// assert_eq!('f'.to_digit(10), None);
325 /// assert_eq!('z'.to_digit(16), None);
328 /// Passing a large radix, causing a panic:
332 /// '1'.to_digit(37);
334 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn to_digit(self, radix
: u32) -> Option
<u32> {
337 assert
!(radix
<= 36, "to_digit: radix is too high (maximum 36)");
339 // the code is split up here to improve execution speed for cases where
340 // the `radix` is constant and 10 or smaller
341 let val
= if radix
<= 10 {
343 '
0'
..='
9'
=> self as u32 - '
0'
as u32,
348 '
0'
..='
9'
=> self as u32 - '
0'
as u32,
349 'a'
..='z'
=> self as u32 - 'a'
as u32 + 10,
350 'A'
..='Z'
=> self as u32 - 'A'
as u32 + 10,
355 if val
< radix { Some(val) }
else { None }
358 /// Returns an iterator that yields the hexadecimal Unicode escape of a
359 /// character as `char`s.
361 /// This will escape characters with the Rust syntax of the form
362 /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
369 /// for c in '❤'.escape_unicode() {
375 /// Using `println!` directly:
378 /// println!("{}", '❤'.escape_unicode());
381 /// Both are equivalent to:
384 /// println!("\\u{{2764}}");
387 /// Using `to_string`:
390 /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
392 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn escape_unicode(self) -> EscapeUnicode
{
397 // or-ing 1 ensures that for c==0 the code computes that one
398 // digit should be printed and (which is the same) avoids the
399 // (31 - 32) underflow
400 let msb
= 31 - (c
| 1).leading_zeros();
402 // the index of the most significant hex digit
403 let ms_hex_digit
= msb
/ 4;
406 state
: EscapeUnicodeState
::Backslash
,
407 hex_digit_idx
: ms_hex_digit
as usize,
411 /// An extended version of `escape_debug` that optionally permits escaping
412 /// Extended Grapheme codepoints. This allows us to format characters like
413 /// nonspacing marks better when they're at the start of a string.
415 pub(crate) fn escape_debug_ext(self, escape_grapheme_extended
: bool
) -> EscapeDebug
{
416 let init_state
= match self {
417 '
\t'
=> EscapeDefaultState
::Backslash('t'
),
418 '
\r'
=> EscapeDefaultState
::Backslash('r'
),
419 '
\n'
=> EscapeDefaultState
::Backslash('n'
),
420 '
\\'
| '
\''
| '
"' => EscapeDefaultState::Backslash(self),
421 _ if escape_grapheme_extended && self.is_grapheme_extended() => {
422 EscapeDefaultState::Unicode(self.escape_unicode())
424 _ if is_printable(self) => EscapeDefaultState::Char(self),
425 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
427 EscapeDebug(EscapeDefault { state: init_state })
430 /// Returns an iterator that yields the literal escape code of a character
433 /// This will escape the characters similar to the `Debug` implementations
434 /// of `str` or `char`.
441 /// for c in '\n'.escape_debug() {
447 /// Using `println!` directly:
450 /// println!("{}
", '\n'.escape_debug());
453 /// Both are equivalent to:
459 /// Using `to_string`:
462 /// assert_eq!('\n'.escape_debug().to_string(), "\\n
");
464 #[stable(feature = "char_escape_debug
", since = "1.20.0")]
466 pub fn escape_debug(self) -> EscapeDebug {
467 self.escape_debug_ext(true)
470 /// Returns an iterator that yields the literal escape code of a character
473 /// The default is chosen with a bias toward producing literals that are
474 /// legal in a variety of languages, including C++11 and similar C-family
475 /// languages. The exact rules are:
477 /// * Tab is escaped as `\t`.
478 /// * Carriage return is escaped as `\r`.
479 /// * Line feed is escaped as `\n`.
480 /// * Single quote is escaped as `\'`.
481 /// * Double quote is escaped as `\"`.
482 /// * Backslash is escaped as `\\`.
483 /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
484 /// inclusive is not escaped.
485 /// * All other characters are given hexadecimal Unicode escapes; see
486 /// [`escape_unicode`][escape_unicode].
488 /// [escape_unicode]: #method.escape_unicode
495 /// for c in '"'
.escape_default() {
501 /// Using `println!` directly:
504 /// println!("{}", '"'.escape_default());
508 /// Both are equivalent to:
511 /// println!("\\\"");
514 /// Using `to_string`:
517 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
519 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn escape_default(self) -> EscapeDefault
{
522 let init_state
= match self {
523 '
\t'
=> EscapeDefaultState
::Backslash('t'
),
524 '
\r'
=> EscapeDefaultState
::Backslash('r'
),
525 '
\n'
=> EscapeDefaultState
::Backslash('n'
),
526 '
\\'
| '
\''
| '
"' => EscapeDefaultState::Backslash(self),
527 '\x20'..='\x7e' => EscapeDefaultState::Char(self),
528 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
530 EscapeDefault { state: init_state }
533 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
535 /// That number of bytes is always between 1 and 4, inclusive.
542 /// let len = 'A'.len_utf8();
543 /// assert_eq!(len, 1);
545 /// let len = 'ß'.len_utf8();
546 /// assert_eq!(len, 2);
548 /// let len = 'ℝ'.len_utf8();
549 /// assert_eq!(len, 3);
551 /// let len = '💣'.len_utf8();
552 /// assert_eq!(len, 4);
555 /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
556 /// would take if each code point was represented as a `char` vs in the `&str` itself:
560 /// let eastern = '東';
561 /// let capital = '京';
563 /// // both can be represented as three bytes
564 /// assert_eq!(3, eastern.len_utf8());
565 /// assert_eq!(3, capital.len_utf8());
567 /// // as a &str, these two are encoded in UTF-8
568 /// let tokyo = "東京
";
570 /// let len = eastern.len_utf8() + capital.len_utf8();
572 /// // we can see that they take six bytes total...
573 /// assert_eq!(6, tokyo.len());
575 /// // ... just like the &str
576 /// assert_eq!(len, tokyo.len());
578 #[stable(feature = "rust1
", since = "1.0.0")]
580 pub fn len_utf8(self) -> usize {
581 len_utf8(self as u32)
584 /// Returns the number of 16-bit code units this `char` would need if
585 /// encoded in UTF-16.
587 /// See the documentation for [`len_utf8`] for more explanation of this
588 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
590 /// [`len_utf8`]: #method.len_utf8
597 /// let n = 'ß'.len_utf16();
598 /// assert_eq!(n, 1);
600 /// let len = '💣'.len_utf16();
601 /// assert_eq!(len, 2);
603 #[stable(feature = "rust1
", since = "1.0.0")]
605 pub fn len_utf16(self) -> usize {
606 let ch = self as u32;
607 if (ch & 0xFFFF) == ch { 1 } else { 2 }
610 /// Encodes this character as UTF-8 into the provided byte buffer,
611 /// and then returns the subslice of the buffer that contains the encoded character.
615 /// Panics if the buffer is not large enough.
616 /// A buffer of length four is large enough to encode any `char`.
620 /// In both of these examples, 'ß' takes two bytes to encode.
623 /// let mut b = [0; 2];
625 /// let result = 'ß'.encode_utf8(&mut b);
627 /// assert_eq!(result, "ß
");
629 /// assert_eq!(result.len(), 2);
632 /// A buffer that's too small:
635 /// let mut b = [0; 1];
638 /// 'ß'.encode_utf8(&mut b);
640 #[stable(feature = "unicode_encode_char
", since = "1.15.0")]
642 pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
643 // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
644 unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
647 /// Encodes this character as UTF-16 into the provided `u16` buffer,
648 /// and then returns the subslice of the buffer that contains the encoded character.
652 /// Panics if the buffer is not large enough.
653 /// A buffer of length 2 is large enough to encode any `char`.
657 /// In both of these examples, '𝕊' takes two `u16`s to encode.
660 /// let mut b = [0; 2];
662 /// let result = '𝕊'.encode_utf16(&mut b);
664 /// assert_eq!(result.len(), 2);
667 /// A buffer that's too small:
670 /// let mut b = [0; 1];
673 /// '𝕊'.encode_utf16(&mut b);
675 #[stable(feature = "unicode_encode_char
", since = "1.15.0")]
677 pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
678 encode_utf16_raw(self as u32, dst)
681 /// Returns `true` if this `char` has the `Alphabetic` property.
683 /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
684 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
686 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
687 /// [ucd]: https://www.unicode.org/reports/tr44/
688 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
695 /// assert!('a'.is_alphabetic());
696 /// assert!('京'.is_alphabetic());
699 /// // love is many things, but it is not alphabetic
700 /// assert!(!c.is_alphabetic());
702 #[stable(feature = "rust1
", since = "1.0.0")]
704 pub fn is_alphabetic(self) -> bool {
706 'a'..='z' | 'A'..='Z' => true,
707 c => c > '\x7f' && unicode::Alphabetic(c),
711 /// Returns `true` if this `char` has the `Lowercase` property.
713 /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
714 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
716 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
717 /// [ucd]: https://www.unicode.org/reports/tr44/
718 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
725 /// assert!('a'.is_lowercase());
726 /// assert!('δ'.is_lowercase());
727 /// assert!(!'A'.is_lowercase());
728 /// assert!(!'Δ'.is_lowercase());
730 /// // The various Chinese scripts and punctuation do not have case, and so:
731 /// assert!(!'中'.is_lowercase());
732 /// assert!(!' '.is_lowercase());
734 #[stable(feature = "rust1
", since = "1.0.0")]
736 pub fn is_lowercase(self) -> bool {
739 c => c > '\x7f' && unicode::Lowercase(c),
743 /// Returns `true` if this `char` has the `Uppercase` property.
745 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
746 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
748 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
749 /// [ucd]: https://www.unicode.org/reports/tr44/
750 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
757 /// assert!(!'a'.is_uppercase());
758 /// assert!(!'δ'.is_uppercase());
759 /// assert!('A'.is_uppercase());
760 /// assert!('Δ'.is_uppercase());
762 /// // The various Chinese scripts and punctuation do not have case, and so:
763 /// assert!(!'中'.is_uppercase());
764 /// assert!(!' '.is_uppercase());
766 #[stable(feature = "rust1
", since = "1.0.0")]
768 pub fn is_uppercase(self) -> bool {
771 c => c > '\x7f' && unicode::Uppercase(c),
775 /// Returns `true` if this `char` has the `White_Space` property.
777 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
779 /// [ucd]: https://www.unicode.org/reports/tr44/
780 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
787 /// assert!(' '.is_whitespace());
789 /// // a non-breaking space
790 /// assert!('\u{A0}'.is_whitespace());
792 /// assert!(!'越'.is_whitespace());
794 #[stable(feature = "rust1
", since = "1.0.0")]
796 pub fn is_whitespace(self) -> bool {
798 ' ' | '\x09'..='\x0d' => true,
799 c => c > '\x7f' && unicode::White_Space(c),
803 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
805 /// [`is_alphabetic()`]: #method.is_alphabetic
806 /// [`is_numeric()`]: #method.is_numeric
813 /// assert!('٣'.is_alphanumeric());
814 /// assert!('7'.is_alphanumeric());
815 /// assert!('৬'.is_alphanumeric());
816 /// assert!('¾'.is_alphanumeric());
817 /// assert!('①'.is_alphanumeric());
818 /// assert!('K'.is_alphanumeric());
819 /// assert!('و'.is_alphanumeric());
820 /// assert!('藏'.is_alphanumeric());
822 #[stable(feature = "rust1
", since = "1.0.0")]
824 pub fn is_alphanumeric(self) -> bool {
825 self.is_alphabetic() || self.is_numeric()
828 /// Returns `true` if this `char` has the general category for control codes.
830 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
831 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
832 /// Database][ucd] [`UnicodeData.txt`].
834 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
835 /// [ucd]: https://www.unicode.org/reports/tr44/
836 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
843 /// // U+009C, STRING TERMINATOR
844 /// assert!('\9c'.is_control());
845 /// assert!(!'q'.is_control());
847 #[stable(feature = "rust1
", since = "1.0.0")]
849 pub fn is_control(self) -> bool {
853 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
855 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
856 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
857 /// [`DerivedCoreProperties.txt`].
859 /// [uax29]: https://www.unicode.org/reports/tr29/
860 /// [ucd]: https://www.unicode.org/reports/tr44/
861 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
863 pub(crate) fn is_grapheme_extended(self) -> bool {
864 unicode::Grapheme_Extend(self)
867 /// Returns `true` if this `char` has one of the general categories for numbers.
869 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
870 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
871 /// Database][ucd] [`UnicodeData.txt`].
873 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
874 /// [ucd]: https://www.unicode.org/reports/tr44/
875 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
882 /// assert!('٣'.is_numeric());
883 /// assert!('7'.is_numeric());
884 /// assert!('৬'.is_numeric());
885 /// assert!('¾'.is_numeric());
886 /// assert!('①'.is_numeric());
887 /// assert!(!'K'.is_numeric());
888 /// assert!(!'و'.is_numeric());
889 /// assert!(!'藏'.is_numeric());
891 #[stable(feature = "rust1
", since = "1.0.0")]
893 pub fn is_numeric(self) -> bool {
896 c => c > '\x7f' && unicode::N(c),
900 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
903 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
905 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
906 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
908 /// [ucd]: https://www.unicode.org/reports/tr44/
909 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
911 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
912 /// the `char`(s) given by [`SpecialCasing.txt`].
914 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
916 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
917 /// is independent of context and language.
919 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
920 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
922 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
929 /// for c in 'İ'.to_lowercase() {
935 /// Using `println!` directly:
938 /// println!("{}
", 'İ'.to_lowercase());
941 /// Both are equivalent to:
944 /// println!("i
\u{307}
");
947 /// Using `to_string`:
950 /// assert_eq!('C'.to_lowercase().to_string(), "c
");
952 /// // Sometimes the result is more than one character:
953 /// assert_eq!('İ'.to_lowercase().to_string(), "i
\u{307}
");
955 /// // Characters that do not have both uppercase and lowercase
956 /// // convert into themselves.
957 /// assert_eq!('山'.to_lowercase().to_string(), "山
");
959 #[stable(feature = "rust1
", since = "1.0.0")]
961 pub fn to_lowercase(self) -> ToLowercase {
962 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
965 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
968 /// If this `char` does not have a uppercase mapping, the iterator yields the same `char`.
970 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
971 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
973 /// [ucd]: https://www.unicode.org/reports/tr44/
974 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
976 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
977 /// the `char`(s) given by [`SpecialCasing.txt`].
979 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
981 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
982 /// is independent of context and language.
984 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
985 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
987 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
994 /// for c in 'ß'.to_uppercase() {
1000 /// Using `println!` directly:
1003 /// println!("{}
", 'ß'.to_uppercase());
1006 /// Both are equivalent to:
1012 /// Using `to_string`:
1015 /// assert_eq!('c'.to_uppercase().to_string(), "C
");
1017 /// // Sometimes the result is more than one character:
1018 /// assert_eq!('ß'.to_uppercase().to_string(), "SS
");
1020 /// // Characters that do not have both uppercase and lowercase
1021 /// // convert into themselves.
1022 /// assert_eq!('山'.to_uppercase().to_string(), "山
");
1025 /// # Note on locale
1027 /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1029 /// * 'Dotless': I / ı, sometimes written ï
1030 /// * 'Dotted': İ / i
1032 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1035 /// let upper_i = 'i'.to_uppercase().to_string();
1038 /// The value of `upper_i` here relies on the language of the text: if we're
1039 /// in `en-US`, it should be `"I
"`, but if we're in `tr_TR`, it should
1040 /// be `"İ
"`. `to_uppercase()` does not take this into account, and so:
1043 /// let upper_i = 'i'.to_uppercase().to_string();
1045 /// assert_eq!(upper_i, "I
");
1048 /// holds across languages.
1049 #[stable(feature = "rust1
", since = "1.0.0")]
1051 pub fn to_uppercase(self) -> ToUppercase {
1052 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1055 /// Checks if the value is within the ASCII range.
1060 /// let ascii = 'a';
1061 /// let non_ascii = '❤';
1063 /// assert!(ascii.is_ascii());
1064 /// assert!(!non_ascii.is_ascii());
1066 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1067 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics
", since = "1.32.0")]
1069 pub const fn is_ascii(&self) -> bool {
1070 *self as u32 <= 0x7F
1073 /// Makes a copy of the value in its ASCII upper case equivalent.
1075 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1076 /// but non-ASCII letters are unchanged.
1078 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
1080 /// To uppercase ASCII characters in addition to non-ASCII characters, use
1081 /// [`to_uppercase`].
1086 /// let ascii = 'a';
1087 /// let non_ascii = '❤';
1089 /// assert_eq!('A', ascii.to_ascii_uppercase());
1090 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1093 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
1094 /// [`to_uppercase`]: #method.to_uppercase
1095 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1097 pub fn to_ascii_uppercase(&self) -> char {
1098 if self.is_ascii() { (*self as u8).to_ascii_uppercase() as char } else { *self }
1101 /// Makes a copy of the value in its ASCII lower case equivalent.
1103 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1104 /// but non-ASCII letters are unchanged.
1106 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
1108 /// To lowercase ASCII characters in addition to non-ASCII characters, use
1109 /// [`to_lowercase`].
1114 /// let ascii = 'A';
1115 /// let non_ascii = '❤';
1117 /// assert_eq!('a', ascii.to_ascii_lowercase());
1118 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1121 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
1122 /// [`to_lowercase`]: #method.to_lowercase
1123 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1125 pub fn to_ascii_lowercase(&self) -> char {
1126 if self.is_ascii() { (*self as u8).to_ascii_lowercase() as char } else { *self }
1129 /// Checks that two values are an ASCII case-insensitive match.
1131 /// Equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
1136 /// let upper_a = 'A';
1137 /// let lower_a = 'a';
1138 /// let lower_z = 'z';
1140 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1141 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1142 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1144 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1146 pub fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1147 self.to_ascii_lowercase() == other.to_ascii_lowercase()
1150 /// Converts this type to its ASCII upper case equivalent in-place.
1152 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1153 /// but non-ASCII letters are unchanged.
1155 /// To return a new uppercased value without modifying the existing one, use
1156 /// [`to_ascii_uppercase`].
1161 /// let mut ascii = 'a';
1163 /// ascii.make_ascii_uppercase();
1165 /// assert_eq!('A', ascii);
1168 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
1169 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1171 pub fn make_ascii_uppercase(&mut self) {
1172 *self = self.to_ascii_uppercase();
1175 /// Converts this type to its ASCII lower case equivalent in-place.
1177 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1178 /// but non-ASCII letters are unchanged.
1180 /// To return a new lowercased value without modifying the existing one, use
1181 /// [`to_ascii_lowercase`].
1186 /// let mut ascii = 'A';
1188 /// ascii.make_ascii_lowercase();
1190 /// assert_eq!('a', ascii);
1193 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
1194 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1196 pub fn make_ascii_lowercase(&mut self) {
1197 *self = self.to_ascii_lowercase();
1200 /// Checks if the value is an ASCII alphabetic character:
1202 /// - U+0041 'A' ..= U+005A 'Z', or
1203 /// - U+0061 'a' ..= U+007A 'z'.
1208 /// let uppercase_a = 'A';
1209 /// let uppercase_g = 'G';
1213 /// let percent = '%';
1214 /// let space = ' ';
1216 /// let esc: char = 0x1b_u8.into();
1218 /// assert!(uppercase_a.is_ascii_alphabetic());
1219 /// assert!(uppercase_g.is_ascii_alphabetic());
1220 /// assert!(a.is_ascii_alphabetic());
1221 /// assert!(g.is_ascii_alphabetic());
1222 /// assert!(!zero.is_ascii_alphabetic());
1223 /// assert!(!percent.is_ascii_alphabetic());
1224 /// assert!(!space.is_ascii_alphabetic());
1225 /// assert!(!lf.is_ascii_alphabetic());
1226 /// assert!(!esc.is_ascii_alphabetic());
1228 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1229 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1231 pub const fn is_ascii_alphabetic(&self) -> bool {
1232 matches!(*self, 'A'..='Z' | 'a'..='z')
1235 /// Checks if the value is an ASCII uppercase character:
1236 /// U+0041 'A' ..= U+005A 'Z'.
1241 /// let uppercase_a = 'A';
1242 /// let uppercase_g = 'G';
1246 /// let percent = '%';
1247 /// let space = ' ';
1249 /// let esc: char = 0x1b_u8.into();
1251 /// assert!(uppercase_a.is_ascii_uppercase());
1252 /// assert!(uppercase_g.is_ascii_uppercase());
1253 /// assert!(!a.is_ascii_uppercase());
1254 /// assert!(!g.is_ascii_uppercase());
1255 /// assert!(!zero.is_ascii_uppercase());
1256 /// assert!(!percent.is_ascii_uppercase());
1257 /// assert!(!space.is_ascii_uppercase());
1258 /// assert!(!lf.is_ascii_uppercase());
1259 /// assert!(!esc.is_ascii_uppercase());
1261 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1262 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1264 pub const fn is_ascii_uppercase(&self) -> bool {
1265 matches!(*self, 'A'..='Z')
1268 /// Checks if the value is an ASCII lowercase character:
1269 /// U+0061 'a' ..= U+007A 'z'.
1274 /// let uppercase_a = 'A';
1275 /// let uppercase_g = 'G';
1279 /// let percent = '%';
1280 /// let space = ' ';
1282 /// let esc: char = 0x1b_u8.into();
1284 /// assert!(!uppercase_a.is_ascii_lowercase());
1285 /// assert!(!uppercase_g.is_ascii_lowercase());
1286 /// assert!(a.is_ascii_lowercase());
1287 /// assert!(g.is_ascii_lowercase());
1288 /// assert!(!zero.is_ascii_lowercase());
1289 /// assert!(!percent.is_ascii_lowercase());
1290 /// assert!(!space.is_ascii_lowercase());
1291 /// assert!(!lf.is_ascii_lowercase());
1292 /// assert!(!esc.is_ascii_lowercase());
1294 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1295 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1297 pub const fn is_ascii_lowercase(&self) -> bool {
1298 matches!(*self, 'a'..='z')
1301 /// Checks if the value is an ASCII alphanumeric character:
1303 /// - U+0041 'A' ..= U+005A 'Z', or
1304 /// - U+0061 'a' ..= U+007A 'z', or
1305 /// - U+0030 '0' ..= U+0039 '9'.
1310 /// let uppercase_a = 'A';
1311 /// let uppercase_g = 'G';
1315 /// let percent = '%';
1316 /// let space = ' ';
1318 /// let esc: char = 0x1b_u8.into();
1320 /// assert!(uppercase_a.is_ascii_alphanumeric());
1321 /// assert!(uppercase_g.is_ascii_alphanumeric());
1322 /// assert!(a.is_ascii_alphanumeric());
1323 /// assert!(g.is_ascii_alphanumeric());
1324 /// assert!(zero.is_ascii_alphanumeric());
1325 /// assert!(!percent.is_ascii_alphanumeric());
1326 /// assert!(!space.is_ascii_alphanumeric());
1327 /// assert!(!lf.is_ascii_alphanumeric());
1328 /// assert!(!esc.is_ascii_alphanumeric());
1330 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1331 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1333 pub const fn is_ascii_alphanumeric(&self) -> bool {
1334 matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1337 /// Checks if the value is an ASCII decimal digit:
1338 /// U+0030 '0' ..= U+0039 '9'.
1343 /// let uppercase_a = 'A';
1344 /// let uppercase_g = 'G';
1348 /// let percent = '%';
1349 /// let space = ' ';
1351 /// let esc: char = 0x1b_u8.into();
1353 /// assert!(!uppercase_a.is_ascii_digit());
1354 /// assert!(!uppercase_g.is_ascii_digit());
1355 /// assert!(!a.is_ascii_digit());
1356 /// assert!(!g.is_ascii_digit());
1357 /// assert!(zero.is_ascii_digit());
1358 /// assert!(!percent.is_ascii_digit());
1359 /// assert!(!space.is_ascii_digit());
1360 /// assert!(!lf.is_ascii_digit());
1361 /// assert!(!esc.is_ascii_digit());
1363 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1364 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1366 pub const fn is_ascii_digit(&self) -> bool {
1367 matches!(*self, '0'..='9')
1370 /// Checks if the value is an ASCII hexadecimal digit:
1372 /// - U+0030 '0' ..= U+0039 '9', or
1373 /// - U+0041 'A' ..= U+0046 'F', or
1374 /// - U+0061 'a' ..= U+0066 'f'.
1379 /// let uppercase_a = 'A';
1380 /// let uppercase_g = 'G';
1384 /// let percent = '%';
1385 /// let space = ' ';
1387 /// let esc: char = 0x1b_u8.into();
1389 /// assert!(uppercase_a.is_ascii_hexdigit());
1390 /// assert!(!uppercase_g.is_ascii_hexdigit());
1391 /// assert!(a.is_ascii_hexdigit());
1392 /// assert!(!g.is_ascii_hexdigit());
1393 /// assert!(zero.is_ascii_hexdigit());
1394 /// assert!(!percent.is_ascii_hexdigit());
1395 /// assert!(!space.is_ascii_hexdigit());
1396 /// assert!(!lf.is_ascii_hexdigit());
1397 /// assert!(!esc.is_ascii_hexdigit());
1399 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1400 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1402 pub const fn is_ascii_hexdigit(&self) -> bool {
1403 matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1406 /// Checks if the value is an ASCII punctuation character:
1408 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1409 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1410 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1411 /// - U+007B ..= U+007E `{ | } ~`
1416 /// let uppercase_a = 'A';
1417 /// let uppercase_g = 'G';
1421 /// let percent = '%';
1422 /// let space = ' ';
1424 /// let esc: char = 0x1b_u8.into();
1426 /// assert!(!uppercase_a.is_ascii_punctuation());
1427 /// assert!(!uppercase_g.is_ascii_punctuation());
1428 /// assert!(!a.is_ascii_punctuation());
1429 /// assert!(!g.is_ascii_punctuation());
1430 /// assert!(!zero.is_ascii_punctuation());
1431 /// assert!(percent.is_ascii_punctuation());
1432 /// assert!(!space.is_ascii_punctuation());
1433 /// assert!(!lf.is_ascii_punctuation());
1434 /// assert!(!esc.is_ascii_punctuation());
1436 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1437 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1439 pub const fn is_ascii_punctuation(&self) -> bool
{
1440 matches
!(*self, '
!'
..='
/'
| '
:'
..='@'
| '
['
..='`'
| '
{'
..='
~'
)
1443 /// Checks if the value is an ASCII graphic character:
1444 /// U+0021 '!' ..= U+007E '~'.
1449 /// let uppercase_a = 'A';
1450 /// let uppercase_g = 'G';
1454 /// let percent = '%';
1455 /// let space = ' ';
1457 /// let esc: char = 0x1b_u8.into();
1459 /// assert!(uppercase_a.is_ascii_graphic());
1460 /// assert!(uppercase_g.is_ascii_graphic());
1461 /// assert!(a.is_ascii_graphic());
1462 /// assert!(g.is_ascii_graphic());
1463 /// assert!(zero.is_ascii_graphic());
1464 /// assert!(percent.is_ascii_graphic());
1465 /// assert!(!space.is_ascii_graphic());
1466 /// assert!(!lf.is_ascii_graphic());
1467 /// assert!(!esc.is_ascii_graphic());
1469 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1470 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1472 pub const fn is_ascii_graphic(&self) -> bool
{
1473 matches
!(*self, '
!'
..='
~'
)
1476 /// Checks if the value is an ASCII whitespace character:
1477 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1478 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1480 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1481 /// whitespace][infra-aw]. There are several other definitions in
1482 /// wide use. For instance, [the POSIX locale][pct] includes
1483 /// U+000B VERTICAL TAB as well as all the above characters,
1484 /// but—from the very same specification—[the default rule for
1485 /// "field splitting" in the Bourne shell][bfs] considers *only*
1486 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1488 /// If you are writing a program that will process an existing
1489 /// file format, check what that format's definition of whitespace is
1490 /// before using this function.
1492 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1493 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1494 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1499 /// let uppercase_a = 'A';
1500 /// let uppercase_g = 'G';
1504 /// let percent = '%';
1505 /// let space = ' ';
1507 /// let esc: char = 0x1b_u8.into();
1509 /// assert!(!uppercase_a.is_ascii_whitespace());
1510 /// assert!(!uppercase_g.is_ascii_whitespace());
1511 /// assert!(!a.is_ascii_whitespace());
1512 /// assert!(!g.is_ascii_whitespace());
1513 /// assert!(!zero.is_ascii_whitespace());
1514 /// assert!(!percent.is_ascii_whitespace());
1515 /// assert!(space.is_ascii_whitespace());
1516 /// assert!(lf.is_ascii_whitespace());
1517 /// assert!(!esc.is_ascii_whitespace());
1519 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1520 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1522 pub const fn is_ascii_whitespace(&self) -> bool
{
1523 matches
!(*self, '
\t'
| '
\n'
| '
\x0C'
| '
\r'
| ' '
)
1526 /// Checks if the value is an ASCII control character:
1527 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1528 /// Note that most ASCII whitespace characters are control
1529 /// characters, but SPACE is not.
1534 /// let uppercase_a = 'A';
1535 /// let uppercase_g = 'G';
1539 /// let percent = '%';
1540 /// let space = ' ';
1542 /// let esc: char = 0x1b_u8.into();
1544 /// assert!(!uppercase_a.is_ascii_control());
1545 /// assert!(!uppercase_g.is_ascii_control());
1546 /// assert!(!a.is_ascii_control());
1547 /// assert!(!g.is_ascii_control());
1548 /// assert!(!zero.is_ascii_control());
1549 /// assert!(!percent.is_ascii_control());
1550 /// assert!(!space.is_ascii_control());
1551 /// assert!(lf.is_ascii_control());
1552 /// assert!(esc.is_ascii_control());
1554 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1555 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1557 pub const fn is_ascii_control(&self) -> bool
{
1558 matches
!(*self, '
\0'
..='
\x1F'
| '
\x7F'
)
1563 fn len_utf8(code
: u32) -> usize {
1564 if code
< MAX_ONE_B
{
1566 } else if code
< MAX_TWO_B
{
1568 } else if code
< MAX_THREE_B
{
1575 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1576 /// and then returns the subslice of the buffer that contains the encoded character.
1578 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1579 /// (Creating a `char` in the surrogate range is UB.)
1580 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1582 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1586 /// Panics if the buffer is not large enough.
1587 /// A buffer of length four is large enough to encode any `char`.
1588 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1591 pub fn encode_utf8_raw(code
: u32, dst
: &mut [u8]) -> &mut [u8] {
1592 let len
= len_utf8(code
);
1593 match (len
, &mut dst
[..]) {
1597 (2, [a
, b
, ..]) => {
1598 *a
= (code
>> 6 & 0x1F) as u8 | TAG_TWO_B
;
1599 *b
= (code
& 0x3F) as u8 | TAG_CONT
;
1601 (3, [a
, b
, c
, ..]) => {
1602 *a
= (code
>> 12 & 0x0F) as u8 | TAG_THREE_B
;
1603 *b
= (code
>> 6 & 0x3F) as u8 | TAG_CONT
;
1604 *c
= (code
& 0x3F) as u8 | TAG_CONT
;
1606 (4, [a
, b
, c
, d
, ..]) => {
1607 *a
= (code
>> 18 & 0x07) as u8 | TAG_FOUR_B
;
1608 *b
= (code
>> 12 & 0x3F) as u8 | TAG_CONT
;
1609 *c
= (code
>> 6 & 0x3F) as u8 | TAG_CONT
;
1610 *d
= (code
& 0x3F) as u8 | TAG_CONT
;
1613 "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1622 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1623 /// and then returns the subslice of the buffer that contains the encoded character.
1625 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1626 /// (Creating a `char` in the surrogate range is UB.)
1630 /// Panics if the buffer is not large enough.
1631 /// A buffer of length 2 is large enough to encode any `char`.
1632 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1635 pub fn encode_utf16_raw(mut code
: u32, dst
: &mut [u16]) -> &mut [u16] {
1636 // SAFETY: each arm checks whether there are enough bits to write into
1638 if (code
& 0xFFFF) == code
&& !dst
.is_empty() {
1639 // The BMP falls through
1640 *dst
.get_unchecked_mut(0) = code
as u16;
1641 slice
::from_raw_parts_mut(dst
.as_mut_ptr(), 1)
1642 } else if dst
.len() >= 2 {
1643 // Supplementary planes break into surrogates.
1645 *dst
.get_unchecked_mut(0) = 0xD800 | ((code
>> 10) as u16);
1646 *dst
.get_unchecked_mut(1) = 0xDC00 | ((code
as u16) & 0x3FF);
1647 slice
::from_raw_parts_mut(dst
.as_mut_ptr(), 2)
1650 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1651 from_u32_unchecked(code
).len_utf16(),