3 use crate::intrinsics::likely;
5 use crate::str::from_utf8_unchecked_mut;
6 use crate::unicode::printable::is_printable;
7 use crate::unicode::{self, conversions};
13 /// The highest valid code point a `char` can have.
15 /// A `char` is a [Unicode Scalar Value], which means that it is a [Code
16 /// Point], but only ones within a certain range. `MAX` is the highest valid
17 /// code point that's a valid [Unicode Scalar Value].
19 /// [Unicode Scalar Value]: http://www.unicode.org/glossary/#unicode_scalar_value
20 /// [Code Point]: http://www.unicode.org/glossary/#code_point
21 #[unstable(feature = "assoc_char_consts", reason = "recently added", issue = "71763")]
22 pub const MAX: char = '\u{10ffff}';
24 /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
27 /// It can occur, for example, when giving ill-formed UTF-8 bytes to
28 /// [`String::from_utf8_lossy`](string/struct.String.html#method.from_utf8_lossy).
29 #[unstable(feature = "assoc_char_consts", reason = "recently added", issue = "71763")]
30 pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
32 /// The version of [Unicode](http://www.unicode.org/) that the Unicode parts of
33 /// `char` and `str` methods are based on.
35 /// New versions of Unicode are released regularly and subsequently all methods
36 /// in the standard library depending on Unicode are updated. Therefore the
37 /// behavior of some `char` and `str` methods and the value of this constant
38 /// changes over time. This is *not* considered to be a breaking change.
40 /// The version numbering scheme is explained in
41 /// [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).
42 #[unstable(feature = "assoc_char_consts", reason = "recently added", issue = "71763")]
43 pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION;
45 /// Creates an iterator over the UTF-16 encoded code points in `iter`,
46 /// returning unpaired surrogates as `Err`s.
53 /// use std::char::decode_utf16;
55 /// // 𝄞mus<invalid>ic<invalid>
57 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
61 /// decode_utf16(v.iter().cloned())
62 /// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
63 /// .collect::<Vec<_>>(),
66 /// Ok('m'), Ok('u'), Ok('s'),
74 /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
77 /// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
79 /// // 𝄞mus<invalid>ic<invalid>
81 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
85 /// decode_utf16(v.iter().cloned())
86 /// .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
87 /// .collect::<String>(),
91 #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")]
93 pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
94 super::decode::decode_utf16(iter)
97 /// Converts a `u32` to a `char`.
99 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
104 /// let i = c as u32;
106 /// assert_eq!(128175, i);
109 /// However, the reverse is not true: not all valid [`u32`]s are valid
110 /// `char`s. `from_u32()` will return `None` if the input is not a valid value
113 /// For an unsafe version of this function which ignores these checks, see
114 /// [`from_u32_unchecked`].
116 /// [`from_u32_unchecked`]: #method.from_u32_unchecked
125 /// let c = char::from_u32(0x2764);
127 /// assert_eq!(Some('❤'), c);
130 /// Returning `None` when the input is not a valid `char`:
135 /// let c = char::from_u32(0x110000);
137 /// assert_eq!(None, c);
139 #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")]
141 pub fn from_u32(i: u32) -> Option<char> {
142 super::convert::from_u32(i)
145 /// Converts a `u32` to a `char`, ignoring validity.
147 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
152 /// let i = c as u32;
154 /// assert_eq!(128175, i);
157 /// However, the reverse is not true: not all valid [`u32`]s are valid
158 /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to
159 /// `char`, possibly creating an invalid one.
163 /// This function is unsafe, as it may construct invalid `char` values.
165 /// For a safe version of this function, see the [`from_u32`] function.
167 /// [`from_u32`]: #method.from_u32
176 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
178 /// assert_eq!('❤', c);
180 #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")]
182 pub unsafe fn from_u32_unchecked(i: u32) -> char {
183 // SAFETY: the safety contract must be upheld by the caller.
184 unsafe { super::convert::from_u32_unchecked(i) }
187 /// Converts a digit in the given radix to a `char`.
189 /// A 'radix' here is sometimes also called a 'base'. A radix of two
190 /// indicates a binary number, a radix of ten, decimal, and a radix of
191 /// sixteen, hexadecimal, to give some common values. Arbitrary
192 /// radices are supported.
194 /// `from_digit()` will return `None` if the input is not a digit in
199 /// Panics if given a radix larger than 36.
208 /// let c = char::from_digit(4, 10);
210 /// assert_eq!(Some('4'), c);
212 /// // Decimal 11 is a single digit in base 16
213 /// let c = char::from_digit(11, 16);
215 /// assert_eq!(Some('b'), c);
218 /// Returning `None` when the input is not a digit:
223 /// let c = char::from_digit(20, 10);
225 /// assert_eq!(None, c);
228 /// Passing a large radix, causing a panic:
234 /// char::from_digit(1, 37);
236 #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")]
238 pub fn from_digit(num: u32, radix: u32) -> Option<char> {
239 super::convert::from_digit(num, radix)
242 /// Checks if a `char` is a digit in the given radix.
244 /// A 'radix' here is sometimes also called a 'base'. A radix of two
245 /// indicates a binary number, a radix of ten, decimal, and a radix of
246 /// sixteen, hexadecimal, to give some common values. Arbitrary
247 /// radices are supported.
249 /// Compared to [`is_numeric()`], this function only recognizes the characters
250 /// `0-9`, `a-z` and `A-Z`.
252 /// 'Digit' is defined to be only the following characters:
258 /// For a more comprehensive understanding of 'digit', see [`is_numeric()`].
260 /// [`is_numeric()`]: #method.is_numeric
264 /// Panics if given a radix larger than 36.
271 /// assert!('1'.is_digit(10));
272 /// assert!('f'.is_digit(16));
273 /// assert!(!'f'.is_digit(10));
276 /// Passing a large radix, causing a panic:
280 /// '1'.is_digit(37);
282 #[stable(feature = "rust1", since = "1.0.0")]
284 pub fn is_digit(self, radix: u32) -> bool {
285 self.to_digit(radix).is_some()
288 /// Converts a `char` to a digit in the given radix.
290 /// A 'radix' here is sometimes also called a 'base'. A radix of two
291 /// indicates a binary number, a radix of ten, decimal, and a radix of
292 /// sixteen, hexadecimal, to give some common values. Arbitrary
293 /// radices are supported.
295 /// 'Digit' is defined to be only the following characters:
303 /// Returns `None` if the `char` does not refer to a digit in the given radix.
307 /// Panics if given a radix larger than 36.
314 /// assert_eq!('1'.to_digit(10), Some(1));
315 /// assert_eq!('f'.to_digit(16), Some(15));
318 /// Passing a non-digit results in failure:
321 /// assert_eq!('f'.to_digit(10), None);
322 /// assert_eq!('z'.to_digit(16), None);
325 /// Passing a large radix, causing a panic:
329 /// '1'.to_digit(37);
331 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn to_digit(self, radix: u32) -> Option<u32> {
334 assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
335 // the code is split up here to improve execution speed for cases where
336 // the `radix` is constant and 10 or smaller
337 let val = if likely(radix <= 10) {
338 // If not a digit, a number greater than radix will be created.
339 (self as u32).wrapping_sub('0' as u32)
342 '0'..='9' => self as u32 - '0' as u32,
343 'a'..='z' => self as u32 - 'a' as u32 + 10,
344 'A'..='Z' => self as u32 - 'A' as u32 + 10,
349 if val < radix { Some(val) } else { None }
352 /// Returns an iterator that yields the hexadecimal Unicode escape of a
353 /// character as `char`s.
355 /// This will escape characters with the Rust syntax of the form
356 /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
363 /// for c in '❤'.escape_unicode() {
369 /// Using `println!` directly:
372 /// println!("{}", '❤'.escape_unicode());
375 /// Both are equivalent to:
378 /// println!("\\u{{2764}}");
381 /// Using `to_string`:
384 /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
386 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn escape_unicode(self) -> EscapeUnicode {
391 // or-ing 1 ensures that for c==0 the code computes that one
392 // digit should be printed and (which is the same) avoids the
393 // (31 - 32) underflow
394 let msb = 31 - (c | 1).leading_zeros();
396 // the index of the most significant hex digit
397 let ms_hex_digit = msb / 4;
400 state: EscapeUnicodeState::Backslash,
401 hex_digit_idx: ms_hex_digit as usize,
405 /// An extended version of `escape_debug` that optionally permits escaping
406 /// Extended Grapheme codepoints. This allows us to format characters like
407 /// nonspacing marks better when they're at the start of a string.
409 pub(crate) fn escape_debug_ext(self, escape_grapheme_extended: bool) -> EscapeDebug {
410 let init_state = match self {
411 '\t' => EscapeDefaultState::Backslash('t'),
412 '\r' => EscapeDefaultState::Backslash('r'),
413 '\n' => EscapeDefaultState::Backslash('n'),
414 '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
415 _ if escape_grapheme_extended && self.is_grapheme_extended() => {
416 EscapeDefaultState::Unicode(self.escape_unicode())
418 _ if is_printable(self) => EscapeDefaultState::Char(self),
419 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
421 EscapeDebug(EscapeDefault { state: init_state })
424 /// Returns an iterator that yields the literal escape code of a character
427 /// This will escape the characters similar to the `Debug` implementations
428 /// of `str` or `char`.
435 /// for c in '\n'.escape_debug() {
441 /// Using `println!` directly:
444 /// println!("{}", '\n'.escape_debug());
447 /// Both are equivalent to:
453 /// Using `to_string`:
456 /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
458 #[stable(feature = "char_escape_debug", since = "1.20.0")]
460 pub fn escape_debug(self) -> EscapeDebug {
461 self.escape_debug_ext(true)
464 /// Returns an iterator that yields the literal escape code of a character
467 /// The default is chosen with a bias toward producing literals that are
468 /// legal in a variety of languages, including C++11 and similar C-family
469 /// languages. The exact rules are:
471 /// * Tab is escaped as `\t`.
472 /// * Carriage return is escaped as `\r`.
473 /// * Line feed is escaped as `\n`.
474 /// * Single quote is escaped as `\'`.
475 /// * Double quote is escaped as `\"`.
476 /// * Backslash is escaped as `\\`.
477 /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
478 /// inclusive is not escaped.
479 /// * All other characters are given hexadecimal Unicode escapes; see
480 /// [`escape_unicode`].
482 /// [`escape_unicode`]: #method.escape_unicode
489 /// for c in '"'.escape_default() {
495 /// Using `println!` directly:
498 /// println!("{}", '"'.escape_default());
501 /// Both are equivalent to:
504 /// println!("\\\"");
507 /// Using `to_string`:
510 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
512 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn escape_default(self) -> EscapeDefault {
515 let init_state = match self {
516 '\t' => EscapeDefaultState::Backslash('t'),
517 '\r' => EscapeDefaultState::Backslash('r'),
518 '\n' => EscapeDefaultState::Backslash('n'),
519 '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
520 '\x20'..='\x7e' => EscapeDefaultState::Char(self),
521 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
523 EscapeDefault { state: init_state }
526 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
528 /// That number of bytes is always between 1 and 4, inclusive.
535 /// let len = 'A'.len_utf8();
536 /// assert_eq!(len, 1);
538 /// let len = 'ß'.len_utf8();
539 /// assert_eq!(len, 2);
541 /// let len = 'ℝ'.len_utf8();
542 /// assert_eq!(len, 3);
544 /// let len = '💣'.len_utf8();
545 /// assert_eq!(len, 4);
548 /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
549 /// would take if each code point was represented as a `char` vs in the `&str` itself:
553 /// let eastern = '東';
554 /// let capital = '京';
556 /// // both can be represented as three bytes
557 /// assert_eq!(3, eastern.len_utf8());
558 /// assert_eq!(3, capital.len_utf8());
560 /// // as a &str, these two are encoded in UTF-8
561 /// let tokyo = "東京";
563 /// let len = eastern.len_utf8() + capital.len_utf8();
565 /// // we can see that they take six bytes total...
566 /// assert_eq!(6, tokyo.len());
568 /// // ... just like the &str
569 /// assert_eq!(len, tokyo.len());
571 #[stable(feature = "rust1", since = "1.0.0")]
572 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
574 pub const fn len_utf8(self) -> usize {
575 len_utf8(self as u32)
578 /// Returns the number of 16-bit code units this `char` would need if
579 /// encoded in UTF-16.
581 /// See the documentation for [`len_utf8()`] for more explanation of this
582 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
584 /// [`len_utf8()`]: #method.len_utf8
591 /// let n = 'ß'.len_utf16();
592 /// assert_eq!(n, 1);
594 /// let len = '💣'.len_utf16();
595 /// assert_eq!(len, 2);
597 #[stable(feature = "rust1", since = "1.0.0")]
598 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
600 pub const fn len_utf16(self) -> usize {
601 let ch = self as u32;
602 if (ch & 0xFFFF) == ch { 1 } else { 2 }
605 /// Encodes this character as UTF-8 into the provided byte buffer,
606 /// and then returns the subslice of the buffer that contains the encoded character.
610 /// Panics if the buffer is not large enough.
611 /// A buffer of length four is large enough to encode any `char`.
615 /// In both of these examples, 'ß' takes two bytes to encode.
618 /// let mut b = [0; 2];
620 /// let result = 'ß'.encode_utf8(&mut b);
622 /// assert_eq!(result, "ß");
624 /// assert_eq!(result.len(), 2);
627 /// A buffer that's too small:
630 /// let mut b = [0; 1];
633 /// 'ß'.encode_utf8(&mut b);
635 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
637 pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
638 // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
639 unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
642 /// Encodes this character as UTF-16 into the provided `u16` buffer,
643 /// and then returns the subslice of the buffer that contains the encoded character.
647 /// Panics if the buffer is not large enough.
648 /// A buffer of length 2 is large enough to encode any `char`.
652 /// In both of these examples, '𝕊' takes two `u16`s to encode.
655 /// let mut b = [0; 2];
657 /// let result = '𝕊'.encode_utf16(&mut b);
659 /// assert_eq!(result.len(), 2);
662 /// A buffer that's too small:
665 /// let mut b = [0; 1];
668 /// '𝕊'.encode_utf16(&mut b);
670 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
672 pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
673 encode_utf16_raw(self as u32, dst)
676 /// Returns `true` if this `char` has the `Alphabetic` property.
678 /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
679 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
681 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
682 /// [ucd]: https://www.unicode.org/reports/tr44/
683 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
690 /// assert!('a'.is_alphabetic());
691 /// assert!('京'.is_alphabetic());
694 /// // love is many things, but it is not alphabetic
695 /// assert!(!c.is_alphabetic());
697 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn is_alphabetic(self) -> bool {
701 'a'..='z' | 'A'..='Z' => true,
702 c => c > '\x7f' && unicode::Alphabetic(c),
706 /// Returns `true` if this `char` has the `Lowercase` property.
708 /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
709 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
711 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
712 /// [ucd]: https://www.unicode.org/reports/tr44/
713 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
720 /// assert!('a'.is_lowercase());
721 /// assert!('δ'.is_lowercase());
722 /// assert!(!'A'.is_lowercase());
723 /// assert!(!'Δ'.is_lowercase());
725 /// // The various Chinese scripts and punctuation do not have case, and so:
726 /// assert!(!'中'.is_lowercase());
727 /// assert!(!' '.is_lowercase());
729 #[stable(feature = "rust1", since = "1.0.0")]
731 pub fn is_lowercase(self) -> bool {
734 c => c > '\x7f' && unicode::Lowercase(c),
738 /// Returns `true` if this `char` has the `Uppercase` property.
740 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
741 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
743 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
744 /// [ucd]: https://www.unicode.org/reports/tr44/
745 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
752 /// assert!(!'a'.is_uppercase());
753 /// assert!(!'δ'.is_uppercase());
754 /// assert!('A'.is_uppercase());
755 /// assert!('Δ'.is_uppercase());
757 /// // The various Chinese scripts and punctuation do not have case, and so:
758 /// assert!(!'中'.is_uppercase());
759 /// assert!(!' '.is_uppercase());
761 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn is_uppercase(self) -> bool {
766 c => c > '\x7f' && unicode::Uppercase(c),
770 /// Returns `true` if this `char` has the `White_Space` property.
772 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
774 /// [ucd]: https://www.unicode.org/reports/tr44/
775 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
782 /// assert!(' '.is_whitespace());
784 /// // a non-breaking space
785 /// assert!('\u{A0}'.is_whitespace());
787 /// assert!(!'越'.is_whitespace());
789 #[stable(feature = "rust1", since = "1.0.0")]
791 pub fn is_whitespace(self) -> bool {
793 ' ' | '\x09'..='\x0d' => true,
794 c => c > '\x7f' && unicode::White_Space(c),
798 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
800 /// [`is_alphabetic()`]: #method.is_alphabetic
801 /// [`is_numeric()`]: #method.is_numeric
808 /// assert!('٣'.is_alphanumeric());
809 /// assert!('7'.is_alphanumeric());
810 /// assert!('৬'.is_alphanumeric());
811 /// assert!('¾'.is_alphanumeric());
812 /// assert!('①'.is_alphanumeric());
813 /// assert!('K'.is_alphanumeric());
814 /// assert!('و'.is_alphanumeric());
815 /// assert!('藏'.is_alphanumeric());
817 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn is_alphanumeric(self) -> bool {
820 self.is_alphabetic() || self.is_numeric()
823 /// Returns `true` if this `char` has the general category for control codes.
825 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
826 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
827 /// Database][ucd] [`UnicodeData.txt`].
829 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
830 /// [ucd]: https://www.unicode.org/reports/tr44/
831 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
838 /// // U+009C, STRING TERMINATOR
839 /// assert!('
\9c'.is_control());
840 /// assert!(!'q'.is_control());
842 #[stable(feature = "rust1", since = "1.0.0")]
844 pub fn is_control(self) -> bool {
848 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
850 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
851 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
852 /// [`DerivedCoreProperties.txt`].
854 /// [uax29]: https://www.unicode.org/reports/tr29/
855 /// [ucd]: https://www.unicode.org/reports/tr44/
856 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
858 pub(crate) fn is_grapheme_extended(self) -> bool {
859 unicode::Grapheme_Extend(self)
862 /// Returns `true` if this `char` has one of the general categories for numbers.
864 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
865 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
866 /// Database][ucd] [`UnicodeData.txt`].
868 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
869 /// [ucd]: https://www.unicode.org/reports/tr44/
870 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
877 /// assert!('٣'.is_numeric());
878 /// assert!('7'.is_numeric());
879 /// assert!('৬'.is_numeric());
880 /// assert!('¾'.is_numeric());
881 /// assert!('①'.is_numeric());
882 /// assert!(!'K'.is_numeric());
883 /// assert!(!'و'.is_numeric());
884 /// assert!(!'藏'.is_numeric());
886 #[stable(feature = "rust1", since = "1.0.0")]
888 pub fn is_numeric(self) -> bool {
891 c => c > '\x7f' && unicode::N(c),
895 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
898 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
900 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
901 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
903 /// [ucd]: https://www.unicode.org/reports/tr44/
904 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
906 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
907 /// the `char`(s) given by [`SpecialCasing.txt`].
909 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
911 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
912 /// is independent of context and language.
914 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
915 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
917 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
924 /// for c in 'İ'.to_lowercase() {
930 /// Using `println!` directly:
933 /// println!("{}", 'İ'.to_lowercase());
936 /// Both are equivalent to:
939 /// println!("i\u{307}");
942 /// Using `to_string`:
945 /// assert_eq!('C'.to_lowercase().to_string(), "c");
947 /// // Sometimes the result is more than one character:
948 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
950 /// // Characters that do not have both uppercase and lowercase
951 /// // convert into themselves.
952 /// assert_eq!('山'.to_lowercase().to_string(), "山");
954 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn to_lowercase(self) -> ToLowercase {
957 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
960 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
963 /// If this `char` does not have a uppercase mapping, the iterator yields the same `char`.
965 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
966 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
968 /// [ucd]: https://www.unicode.org/reports/tr44/
969 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
971 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
972 /// the `char`(s) given by [`SpecialCasing.txt`].
974 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
976 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
977 /// is independent of context and language.
979 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
980 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
982 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
989 /// for c in 'ß'.to_uppercase() {
995 /// Using `println!` directly:
998 /// println!("{}", 'ß'.to_uppercase());
1001 /// Both are equivalent to:
1007 /// Using `to_string`:
1010 /// assert_eq!('c'.to_uppercase().to_string(), "C");
1012 /// // Sometimes the result is more than one character:
1013 /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
1015 /// // Characters that do not have both uppercase and lowercase
1016 /// // convert into themselves.
1017 /// assert_eq!('山'.to_uppercase().to_string(), "山");
1020 /// # Note on locale
1022 /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1024 /// * 'Dotless': I / ı, sometimes written ï
1025 /// * 'Dotted': İ / i
1027 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1030 /// let upper_i = 'i'.to_uppercase().to_string();
1033 /// The value of `upper_i` here relies on the language of the text: if we're
1034 /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
1035 /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1038 /// let upper_i = 'i'.to_uppercase().to_string();
1040 /// assert_eq!(upper_i, "I");
1043 /// holds across languages.
1044 #[stable(feature = "rust1", since = "1.0.0")]
1046 pub fn to_uppercase(self) -> ToUppercase {
1047 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1050 /// Checks if the value is within the ASCII range.
1055 /// let ascii = 'a';
1056 /// let non_ascii = '❤';
1058 /// assert!(ascii.is_ascii());
1059 /// assert!(!non_ascii.is_ascii());
1061 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1062 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.32.0")]
1064 pub const fn is_ascii(&self) -> bool {
1065 *self as u32 <= 0x7F
1068 /// Makes a copy of the value in its ASCII upper case equivalent.
1070 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1071 /// but non-ASCII letters are unchanged.
1073 /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1075 /// To uppercase ASCII characters in addition to non-ASCII characters, use
1076 /// [`to_uppercase()`].
1081 /// let ascii = 'a';
1082 /// let non_ascii = '❤';
1084 /// assert_eq!('A', ascii.to_ascii_uppercase());
1085 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1088 /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1089 /// [`to_uppercase()`]: #method.to_uppercase
1090 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1091 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1093 pub const fn to_ascii_uppercase(&self) -> char {
1094 if self.is_ascii_lowercase() {
1095 (*self as u8).ascii_change_case_unchecked() as char
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")]
1124 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1126 pub const fn to_ascii_lowercase(&self) -> char {
1127 if self.is_ascii_uppercase() {
1128 (*self as u8).ascii_change_case_unchecked() as char
1134 /// Checks that two values are an ASCII case-insensitive match.
1136 /// Equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
1141 /// let upper_a = 'A';
1142 /// let lower_a = 'a';
1143 /// let lower_z = 'z';
1145 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1146 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1147 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1149 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1150 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1152 pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1153 self.to_ascii_lowercase() == other.to_ascii_lowercase()
1156 /// Converts this type to its ASCII upper case equivalent in-place.
1158 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1159 /// but non-ASCII letters are unchanged.
1161 /// To return a new uppercased value without modifying the existing one, use
1162 /// [`to_ascii_uppercase()`].
1167 /// let mut ascii = 'a';
1169 /// ascii.make_ascii_uppercase();
1171 /// assert_eq!('A', ascii);
1174 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1175 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1177 pub fn make_ascii_uppercase(&mut self) {
1178 *self = self.to_ascii_uppercase();
1181 /// Converts this type to its ASCII lower case equivalent in-place.
1183 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1184 /// but non-ASCII letters are unchanged.
1186 /// To return a new lowercased value without modifying the existing one, use
1187 /// [`to_ascii_lowercase()`].
1192 /// let mut ascii = 'A';
1194 /// ascii.make_ascii_lowercase();
1196 /// assert_eq!('a', ascii);
1199 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1200 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1202 pub fn make_ascii_lowercase(&mut self) {
1203 *self = self.to_ascii_lowercase();
1206 /// Checks if the value is an ASCII alphabetic character:
1208 /// - U+0041 'A' ..= U+005A 'Z', or
1209 /// - U+0061 'a' ..= U+007A 'z'.
1214 /// let uppercase_a = 'A';
1215 /// let uppercase_g = 'G';
1219 /// let percent = '%';
1220 /// let space = ' ';
1222 /// let esc: char = 0x1b_u8.into();
1224 /// assert!(uppercase_a.is_ascii_alphabetic());
1225 /// assert!(uppercase_g.is_ascii_alphabetic());
1226 /// assert!(a.is_ascii_alphabetic());
1227 /// assert!(g.is_ascii_alphabetic());
1228 /// assert!(!zero.is_ascii_alphabetic());
1229 /// assert!(!percent.is_ascii_alphabetic());
1230 /// assert!(!space.is_ascii_alphabetic());
1231 /// assert!(!lf.is_ascii_alphabetic());
1232 /// assert!(!esc.is_ascii_alphabetic());
1234 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1235 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1237 pub const fn is_ascii_alphabetic(&self) -> bool {
1238 matches!(*self, 'A'..='Z' | 'a'..='z')
1241 /// Checks if the value is an ASCII uppercase character:
1242 /// U+0041 'A' ..= U+005A 'Z'.
1247 /// let uppercase_a = 'A';
1248 /// let uppercase_g = 'G';
1252 /// let percent = '%';
1253 /// let space = ' ';
1255 /// let esc: char = 0x1b_u8.into();
1257 /// assert!(uppercase_a.is_ascii_uppercase());
1258 /// assert!(uppercase_g.is_ascii_uppercase());
1259 /// assert!(!a.is_ascii_uppercase());
1260 /// assert!(!g.is_ascii_uppercase());
1261 /// assert!(!zero.is_ascii_uppercase());
1262 /// assert!(!percent.is_ascii_uppercase());
1263 /// assert!(!space.is_ascii_uppercase());
1264 /// assert!(!lf.is_ascii_uppercase());
1265 /// assert!(!esc.is_ascii_uppercase());
1267 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1268 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1270 pub const fn is_ascii_uppercase(&self) -> bool {
1271 matches!(*self, 'A'..='Z')
1274 /// Checks if the value is an ASCII lowercase character:
1275 /// U+0061 'a' ..= U+007A 'z'.
1280 /// let uppercase_a = 'A';
1281 /// let uppercase_g = 'G';
1285 /// let percent = '%';
1286 /// let space = ' ';
1288 /// let esc: char = 0x1b_u8.into();
1290 /// assert!(!uppercase_a.is_ascii_lowercase());
1291 /// assert!(!uppercase_g.is_ascii_lowercase());
1292 /// assert!(a.is_ascii_lowercase());
1293 /// assert!(g.is_ascii_lowercase());
1294 /// assert!(!zero.is_ascii_lowercase());
1295 /// assert!(!percent.is_ascii_lowercase());
1296 /// assert!(!space.is_ascii_lowercase());
1297 /// assert!(!lf.is_ascii_lowercase());
1298 /// assert!(!esc.is_ascii_lowercase());
1300 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1301 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1303 pub const fn is_ascii_lowercase(&self) -> bool {
1304 matches!(*self, 'a'..='z')
1307 /// Checks if the value is an ASCII alphanumeric character:
1309 /// - U+0041 'A' ..= U+005A 'Z', or
1310 /// - U+0061 'a' ..= U+007A 'z', or
1311 /// - U+0030 '0' ..= U+0039 '9'.
1316 /// let uppercase_a = 'A';
1317 /// let uppercase_g = 'G';
1321 /// let percent = '%';
1322 /// let space = ' ';
1324 /// let esc: char = 0x1b_u8.into();
1326 /// assert!(uppercase_a.is_ascii_alphanumeric());
1327 /// assert!(uppercase_g.is_ascii_alphanumeric());
1328 /// assert!(a.is_ascii_alphanumeric());
1329 /// assert!(g.is_ascii_alphanumeric());
1330 /// assert!(zero.is_ascii_alphanumeric());
1331 /// assert!(!percent.is_ascii_alphanumeric());
1332 /// assert!(!space.is_ascii_alphanumeric());
1333 /// assert!(!lf.is_ascii_alphanumeric());
1334 /// assert!(!esc.is_ascii_alphanumeric());
1336 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1337 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1339 pub const fn is_ascii_alphanumeric(&self) -> bool {
1340 matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1343 /// Checks if the value is an ASCII decimal digit:
1344 /// U+0030 '0' ..= U+0039 '9'.
1349 /// let uppercase_a = 'A';
1350 /// let uppercase_g = 'G';
1354 /// let percent = '%';
1355 /// let space = ' ';
1357 /// let esc: char = 0x1b_u8.into();
1359 /// assert!(!uppercase_a.is_ascii_digit());
1360 /// assert!(!uppercase_g.is_ascii_digit());
1361 /// assert!(!a.is_ascii_digit());
1362 /// assert!(!g.is_ascii_digit());
1363 /// assert!(zero.is_ascii_digit());
1364 /// assert!(!percent.is_ascii_digit());
1365 /// assert!(!space.is_ascii_digit());
1366 /// assert!(!lf.is_ascii_digit());
1367 /// assert!(!esc.is_ascii_digit());
1369 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1370 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1372 pub const fn is_ascii_digit(&self) -> bool {
1373 matches!(*self, '0'..='9')
1376 /// Checks if the value is an ASCII hexadecimal digit:
1378 /// - U+0030 '0' ..= U+0039 '9', or
1379 /// - U+0041 'A' ..= U+0046 'F', or
1380 /// - U+0061 'a' ..= U+0066 'f'.
1385 /// let uppercase_a = 'A';
1386 /// let uppercase_g = 'G';
1390 /// let percent = '%';
1391 /// let space = ' ';
1393 /// let esc: char = 0x1b_u8.into();
1395 /// assert!(uppercase_a.is_ascii_hexdigit());
1396 /// assert!(!uppercase_g.is_ascii_hexdigit());
1397 /// assert!(a.is_ascii_hexdigit());
1398 /// assert!(!g.is_ascii_hexdigit());
1399 /// assert!(zero.is_ascii_hexdigit());
1400 /// assert!(!percent.is_ascii_hexdigit());
1401 /// assert!(!space.is_ascii_hexdigit());
1402 /// assert!(!lf.is_ascii_hexdigit());
1403 /// assert!(!esc.is_ascii_hexdigit());
1405 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1406 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1408 pub const fn is_ascii_hexdigit(&self) -> bool {
1409 matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1412 /// Checks if the value is an ASCII punctuation character:
1414 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1415 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1416 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1417 /// - U+007B ..= U+007E `{ | } ~`
1422 /// let uppercase_a = 'A';
1423 /// let uppercase_g = 'G';
1427 /// let percent = '%';
1428 /// let space = ' ';
1430 /// let esc: char = 0x1b_u8.into();
1432 /// assert!(!uppercase_a.is_ascii_punctuation());
1433 /// assert!(!uppercase_g.is_ascii_punctuation());
1434 /// assert!(!a.is_ascii_punctuation());
1435 /// assert!(!g.is_ascii_punctuation());
1436 /// assert!(!zero.is_ascii_punctuation());
1437 /// assert!(percent.is_ascii_punctuation());
1438 /// assert!(!space.is_ascii_punctuation());
1439 /// assert!(!lf.is_ascii_punctuation());
1440 /// assert!(!esc.is_ascii_punctuation());
1442 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1443 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1445 pub const fn is_ascii_punctuation(&self) -> bool {
1446 matches!(*self, '!'..='/' | ':'..='@' | '['..='`' | '{'..='~')
1449 /// Checks if the value is an ASCII graphic character:
1450 /// U+0021 '!' ..= U+007E '~'.
1455 /// let uppercase_a = 'A';
1456 /// let uppercase_g = 'G';
1460 /// let percent = '%';
1461 /// let space = ' ';
1463 /// let esc: char = 0x1b_u8.into();
1465 /// assert!(uppercase_a.is_ascii_graphic());
1466 /// assert!(uppercase_g.is_ascii_graphic());
1467 /// assert!(a.is_ascii_graphic());
1468 /// assert!(g.is_ascii_graphic());
1469 /// assert!(zero.is_ascii_graphic());
1470 /// assert!(percent.is_ascii_graphic());
1471 /// assert!(!space.is_ascii_graphic());
1472 /// assert!(!lf.is_ascii_graphic());
1473 /// assert!(!esc.is_ascii_graphic());
1475 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1476 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1478 pub const fn is_ascii_graphic(&self) -> bool {
1479 matches!(*self, '!'..='~')
1482 /// Checks if the value is an ASCII whitespace character:
1483 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1484 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1486 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1487 /// whitespace][infra-aw]. There are several other definitions in
1488 /// wide use. For instance, [the POSIX locale][pct] includes
1489 /// U+000B VERTICAL TAB as well as all the above characters,
1490 /// but—from the very same specification—[the default rule for
1491 /// "field splitting" in the Bourne shell][bfs] considers *only*
1492 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1494 /// If you are writing a program that will process an existing
1495 /// file format, check what that format's definition of whitespace is
1496 /// before using this function.
1498 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1499 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1500 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1505 /// let uppercase_a = 'A';
1506 /// let uppercase_g = 'G';
1510 /// let percent = '%';
1511 /// let space = ' ';
1513 /// let esc: char = 0x1b_u8.into();
1515 /// assert!(!uppercase_a.is_ascii_whitespace());
1516 /// assert!(!uppercase_g.is_ascii_whitespace());
1517 /// assert!(!a.is_ascii_whitespace());
1518 /// assert!(!g.is_ascii_whitespace());
1519 /// assert!(!zero.is_ascii_whitespace());
1520 /// assert!(!percent.is_ascii_whitespace());
1521 /// assert!(space.is_ascii_whitespace());
1522 /// assert!(lf.is_ascii_whitespace());
1523 /// assert!(!esc.is_ascii_whitespace());
1525 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1526 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1528 pub const fn is_ascii_whitespace(&self) -> bool {
1529 matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1532 /// Checks if the value is an ASCII control character:
1533 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1534 /// Note that most ASCII whitespace characters are control
1535 /// characters, but SPACE is not.
1540 /// let uppercase_a = 'A';
1541 /// let uppercase_g = 'G';
1545 /// let percent = '%';
1546 /// let space = ' ';
1548 /// let esc: char = 0x1b_u8.into();
1550 /// assert!(!uppercase_a.is_ascii_control());
1551 /// assert!(!uppercase_g.is_ascii_control());
1552 /// assert!(!a.is_ascii_control());
1553 /// assert!(!g.is_ascii_control());
1554 /// assert!(!zero.is_ascii_control());
1555 /// assert!(!percent.is_ascii_control());
1556 /// assert!(!space.is_ascii_control());
1557 /// assert!(lf.is_ascii_control());
1558 /// assert!(esc.is_ascii_control());
1560 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1561 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1563 pub const fn is_ascii_control(&self) -> bool {
1564 matches!(*self, '\0'..='\x1F' | '\x7F')
1569 const fn len_utf8(code: u32) -> usize {
1570 if code < MAX_ONE_B {
1572 } else if code < MAX_TWO_B {
1574 } else if code < MAX_THREE_B {
1581 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1582 /// and then returns the subslice of the buffer that contains the encoded character.
1584 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1585 /// (Creating a `char` in the surrogate range is UB.)
1586 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1588 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1592 /// Panics if the buffer is not large enough.
1593 /// A buffer of length four is large enough to encode any `char`.
1594 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1597 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1598 let len = len_utf8(code);
1599 match (len, &mut dst[..]) {
1603 (2, [a, b, ..]) => {
1604 *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
1605 *b = (code & 0x3F) as u8 | TAG_CONT;
1607 (3, [a, b, c, ..]) => {
1608 *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
1609 *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1610 *c = (code & 0x3F) as u8 | TAG_CONT;
1612 (4, [a, b, c, d, ..]) => {
1613 *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
1614 *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1615 *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1616 *d = (code & 0x3F) as u8 | TAG_CONT;
1619 "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1628 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1629 /// and then returns the subslice of the buffer that contains the encoded character.
1631 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1632 /// (Creating a `char` in the surrogate range is UB.)
1636 /// Panics if the buffer is not large enough.
1637 /// A buffer of length 2 is large enough to encode any `char`.
1638 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1641 pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1642 // SAFETY: each arm checks whether there are enough bits to write into
1644 if (code & 0xFFFF) == code && !dst.is_empty() {
1645 // The BMP falls through
1646 *dst.get_unchecked_mut(0) = code as u16;
1647 slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
1648 } else if dst.len() >= 2 {
1649 // Supplementary planes break into surrogates.
1651 *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
1652 *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
1653 slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
1656 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1657 from_u32_unchecked(code).len_utf16(),