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]: https://www.unicode.org/glossary/#unicode_scalar_value
19 /// [Code Point]: https://www.unicode.org/glossary/#code_point
20 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
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`](../std/string/struct.String.html#method.from_utf8_lossy).
28 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
29 pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
31 /// The version of [Unicode](https://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 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
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,
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,
85 /// .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
86 /// .collect::<String>(),
90 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
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
99 /// [`as`](../std/keyword.as.html):
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 /// For an unsafe version of this function which ignores these checks, see
113 /// [`from_u32_unchecked`].
115 /// [`from_u32_unchecked`]: #method.from_u32_unchecked
124 /// let c = char::from_u32(0x2764);
126 /// assert_eq!(Some('❤'), c);
129 /// Returning `None` when the input is not a valid `char`:
134 /// let c = char::from_u32(0x110000);
136 /// assert_eq!(None, c);
138 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
139 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
142 pub const 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.
164 /// This function is unsafe, as it may construct invalid `char` values.
166 /// For a safe version of this function, see the [`from_u32`] function.
168 /// [`from_u32`]: #method.from_u32
177 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
179 /// assert_eq!('❤', c);
181 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
182 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
185 pub const 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 /// let _c = char::from_digit(1, 37);
239 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
240 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
243 pub const fn from_digit(num: u32, radix: u32) -> Option<char> {
244 super::convert::from_digit(num, radix)
247 /// Checks if a `char` is a digit in the given radix.
249 /// A 'radix' here is sometimes also called a 'base'. A radix of two
250 /// indicates a binary number, a radix of ten, decimal, and a radix of
251 /// sixteen, hexadecimal, to give some common values. Arbitrary
252 /// radices are supported.
254 /// Compared to [`is_numeric()`], this function only recognizes the characters
255 /// `0-9`, `a-z` and `A-Z`.
257 /// 'Digit' is defined to be only the following characters:
263 /// For a more comprehensive understanding of 'digit', see [`is_numeric()`].
265 /// [`is_numeric()`]: #method.is_numeric
269 /// Panics if given a radix larger than 36.
276 /// assert!('1'.is_digit(10));
277 /// assert!('f'.is_digit(16));
278 /// assert!(!'f'.is_digit(10));
281 /// Passing a large radix, causing a panic:
285 /// '1'.is_digit(37);
287 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn is_digit(self, radix: u32) -> bool {
290 self.to_digit(radix).is_some()
293 /// Converts a `char` to a digit in the given radix.
295 /// A 'radix' here is sometimes also called a 'base'. A radix of two
296 /// indicates a binary number, a radix of ten, decimal, and a radix of
297 /// sixteen, hexadecimal, to give some common values. Arbitrary
298 /// radices are supported.
300 /// 'Digit' is defined to be only the following characters:
308 /// Returns `None` if the `char` does not refer to a digit in the given radix.
312 /// Panics if given a radix larger than 36.
319 /// assert_eq!('1'.to_digit(10), Some(1));
320 /// assert_eq!('f'.to_digit(16), Some(15));
323 /// Passing a non-digit results in failure:
326 /// assert_eq!('f'.to_digit(10), None);
327 /// assert_eq!('z'.to_digit(16), None);
330 /// Passing a large radix, causing a panic:
334 /// let _ = '1'.to_digit(37);
336 #[stable(feature = "rust1", since = "1.0.0")]
337 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
338 #[must_use = "this returns the result of the operation, \
339 without modifying the original"]
341 pub const fn to_digit(self, radix: u32) -> Option<u32> {
342 assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
343 // If not a digit, a number greater than radix will be created.
344 let mut digit = (self as u32).wrapping_sub('0' as u32);
349 // Force the 6th bit to be set to ensure ascii is lower case.
350 digit = (self as u32 | 0b10_0000).wrapping_sub('a' as u32).saturating_add(10);
352 // FIXME: once then_some is const fn, use it here
353 if digit < radix { Some(digit) } else { None }
356 /// Returns an iterator that yields the hexadecimal Unicode escape of a
357 /// character as `char`s.
359 /// This will escape characters with the Rust syntax of the form
360 /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
367 /// for c in '❤'.escape_unicode() {
373 /// Using `println!` directly:
376 /// println!("{}", '❤'.escape_unicode());
379 /// Both are equivalent to:
382 /// println!("\\u{{2764}}");
385 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
388 /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
390 #[must_use = "this returns the escaped char as an iterator, \
391 without modifying the original"]
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, single quotes, and double quotes. This
413 /// allows us to format characters like nonspacing marks better when they're
414 /// at the start of a string, and allows escaping single quotes in
415 /// characters, and double quotes in strings.
417 pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
418 let init_state = match self {
419 '\t' => EscapeDefaultState::Backslash('t'),
420 '\r' => EscapeDefaultState::Backslash('r'),
421 '\n' => EscapeDefaultState::Backslash('n'),
422 '\\' => EscapeDefaultState::Backslash(self),
423 '"' if args.escape_double_quote => EscapeDefaultState::Backslash(self),
424 '\'' if args.escape_single_quote => EscapeDefaultState::Backslash(self),
425 _ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
426 EscapeDefaultState::Unicode(self.escape_unicode())
428 _ if is_printable(self) => EscapeDefaultState::Char(self),
429 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
431 EscapeDebug(EscapeDefault { state: init_state })
434 /// Returns an iterator that yields the literal escape code of a character
437 /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
438 /// of `str` or `char`.
445 /// for c in '\n'.escape_debug() {
451 /// Using `println!` directly:
454 /// println!("{}", '\n'.escape_debug());
457 /// Both are equivalent to:
463 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
466 /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
468 #[must_use = "this returns the escaped char as an iterator, \
469 without modifying the original"]
470 #[stable(feature = "char_escape_debug", since = "1.20.0")]
472 pub fn escape_debug(self) -> EscapeDebug {
473 self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
476 /// Returns an iterator that yields the literal escape code of a character
479 /// The default is chosen with a bias toward producing literals that are
480 /// legal in a variety of languages, including C++11 and similar C-family
481 /// languages. The exact rules are:
483 /// * Tab is escaped as `\t`.
484 /// * Carriage return is escaped as `\r`.
485 /// * Line feed is escaped as `\n`.
486 /// * Single quote is escaped as `\'`.
487 /// * Double quote is escaped as `\"`.
488 /// * Backslash is escaped as `\\`.
489 /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
490 /// inclusive is not escaped.
491 /// * All other characters are given hexadecimal Unicode escapes; see
492 /// [`escape_unicode`].
494 /// [`escape_unicode`]: #method.escape_unicode
501 /// for c in '"'.escape_default() {
507 /// Using `println!` directly:
510 /// println!("{}", '"'.escape_default());
513 /// Both are equivalent to:
516 /// println!("\\\"");
519 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
522 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
524 #[must_use = "this returns the escaped char as an iterator, \
525 without modifying the original"]
526 #[stable(feature = "rust1", since = "1.0.0")]
528 pub fn escape_default(self) -> EscapeDefault {
529 let init_state = match self {
530 '\t' => EscapeDefaultState::Backslash('t'),
531 '\r' => EscapeDefaultState::Backslash('r'),
532 '\n' => EscapeDefaultState::Backslash('n'),
533 '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
534 '\x20'..='\x7e' => EscapeDefaultState::Char(self),
535 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
537 EscapeDefault { state: init_state }
540 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
542 /// That number of bytes is always between 1 and 4, inclusive.
549 /// let len = 'A'.len_utf8();
550 /// assert_eq!(len, 1);
552 /// let len = 'ß'.len_utf8();
553 /// assert_eq!(len, 2);
555 /// let len = 'ℝ'.len_utf8();
556 /// assert_eq!(len, 3);
558 /// let len = '💣'.len_utf8();
559 /// assert_eq!(len, 4);
562 /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
563 /// would take if each code point was represented as a `char` vs in the `&str` itself:
567 /// let eastern = '東';
568 /// let capital = '京';
570 /// // both can be represented as three bytes
571 /// assert_eq!(3, eastern.len_utf8());
572 /// assert_eq!(3, capital.len_utf8());
574 /// // as a &str, these two are encoded in UTF-8
575 /// let tokyo = "東京";
577 /// let len = eastern.len_utf8() + capital.len_utf8();
579 /// // we can see that they take six bytes total...
580 /// assert_eq!(6, tokyo.len());
582 /// // ... just like the &str
583 /// assert_eq!(len, tokyo.len());
585 #[stable(feature = "rust1", since = "1.0.0")]
586 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
588 pub const fn len_utf8(self) -> usize {
589 len_utf8(self as u32)
592 /// Returns the number of 16-bit code units this `char` would need if
593 /// encoded in UTF-16.
595 /// See the documentation for [`len_utf8()`] for more explanation of this
596 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
598 /// [`len_utf8()`]: #method.len_utf8
605 /// let n = 'ß'.len_utf16();
606 /// assert_eq!(n, 1);
608 /// let len = '💣'.len_utf16();
609 /// assert_eq!(len, 2);
611 #[stable(feature = "rust1", since = "1.0.0")]
612 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
614 pub const fn len_utf16(self) -> usize {
615 let ch = self as u32;
616 if (ch & 0xFFFF) == ch { 1 } else { 2 }
619 /// Encodes this character as UTF-8 into the provided byte buffer,
620 /// and then returns the subslice of the buffer that contains the encoded character.
624 /// Panics if the buffer is not large enough.
625 /// A buffer of length four is large enough to encode any `char`.
629 /// In both of these examples, 'ß' takes two bytes to encode.
632 /// let mut b = [0; 2];
634 /// let result = 'ß'.encode_utf8(&mut b);
636 /// assert_eq!(result, "ß");
638 /// assert_eq!(result.len(), 2);
641 /// A buffer that's too small:
644 /// let mut b = [0; 1];
647 /// 'ß'.encode_utf8(&mut b);
649 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
651 pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
652 // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
653 unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
656 /// Encodes this character as UTF-16 into the provided `u16` buffer,
657 /// and then returns the subslice of the buffer that contains the encoded character.
661 /// Panics if the buffer is not large enough.
662 /// A buffer of length 2 is large enough to encode any `char`.
666 /// In both of these examples, '𝕊' takes two `u16`s to encode.
669 /// let mut b = [0; 2];
671 /// let result = '𝕊'.encode_utf16(&mut b);
673 /// assert_eq!(result.len(), 2);
676 /// A buffer that's too small:
679 /// let mut b = [0; 1];
682 /// '𝕊'.encode_utf16(&mut b);
684 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
686 pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
687 encode_utf16_raw(self as u32, dst)
690 /// Returns `true` if this `char` has the `Alphabetic` property.
692 /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
693 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
695 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
696 /// [ucd]: https://www.unicode.org/reports/tr44/
697 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
704 /// assert!('a'.is_alphabetic());
705 /// assert!('京'.is_alphabetic());
708 /// // love is many things, but it is not alphabetic
709 /// assert!(!c.is_alphabetic());
712 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn is_alphabetic(self) -> bool {
716 'a'..='z' | 'A'..='Z' => true,
717 c => c > '\x7f' && unicode::Alphabetic(c),
721 /// Returns `true` if this `char` has the `Lowercase` property.
723 /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
724 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
726 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
727 /// [ucd]: https://www.unicode.org/reports/tr44/
728 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
735 /// assert!('a'.is_lowercase());
736 /// assert!('δ'.is_lowercase());
737 /// assert!(!'A'.is_lowercase());
738 /// assert!(!'Δ'.is_lowercase());
740 /// // The various Chinese scripts and punctuation do not have case, and so:
741 /// assert!(!'中'.is_lowercase());
742 /// assert!(!' '.is_lowercase());
745 #[stable(feature = "rust1", since = "1.0.0")]
747 pub fn is_lowercase(self) -> bool {
750 c => c > '\x7f' && unicode::Lowercase(c),
754 /// Returns `true` if this `char` has the `Uppercase` property.
756 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
757 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
759 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
760 /// [ucd]: https://www.unicode.org/reports/tr44/
761 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
768 /// assert!(!'a'.is_uppercase());
769 /// assert!(!'δ'.is_uppercase());
770 /// assert!('A'.is_uppercase());
771 /// assert!('Δ'.is_uppercase());
773 /// // The various Chinese scripts and punctuation do not have case, and so:
774 /// assert!(!'中'.is_uppercase());
775 /// assert!(!' '.is_uppercase());
778 #[stable(feature = "rust1", since = "1.0.0")]
780 pub fn is_uppercase(self) -> bool {
783 c => c > '\x7f' && unicode::Uppercase(c),
787 /// Returns `true` if this `char` has the `White_Space` property.
789 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
791 /// [ucd]: https://www.unicode.org/reports/tr44/
792 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
799 /// assert!(' '.is_whitespace());
801 /// // a non-breaking space
802 /// assert!('\u{A0}'.is_whitespace());
804 /// assert!(!'越'.is_whitespace());
807 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn is_whitespace(self) -> bool {
811 ' ' | '\x09'..='\x0d' => true,
812 c => c > '\x7f' && unicode::White_Space(c),
816 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
818 /// [`is_alphabetic()`]: #method.is_alphabetic
819 /// [`is_numeric()`]: #method.is_numeric
826 /// assert!('٣'.is_alphanumeric());
827 /// assert!('7'.is_alphanumeric());
828 /// assert!('৬'.is_alphanumeric());
829 /// assert!('¾'.is_alphanumeric());
830 /// assert!('①'.is_alphanumeric());
831 /// assert!('K'.is_alphanumeric());
832 /// assert!('و'.is_alphanumeric());
833 /// assert!('藏'.is_alphanumeric());
836 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn is_alphanumeric(self) -> bool {
839 self.is_alphabetic() || self.is_numeric()
842 /// Returns `true` if this `char` has the general category for control codes.
844 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
845 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
846 /// Database][ucd] [`UnicodeData.txt`].
848 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
849 /// [ucd]: https://www.unicode.org/reports/tr44/
850 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
857 /// // U+009C, STRING TERMINATOR
858 /// assert!('
\9c'.is_control());
859 /// assert!(!'q'.is_control());
862 #[stable(feature = "rust1", since = "1.0.0")]
864 pub fn is_control(self) -> bool {
868 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
870 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
871 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
872 /// [`DerivedCoreProperties.txt`].
874 /// [uax29]: https://www.unicode.org/reports/tr29/
875 /// [ucd]: https://www.unicode.org/reports/tr44/
876 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
879 pub(crate) fn is_grapheme_extended(self) -> bool {
880 unicode::Grapheme_Extend(self)
883 /// Returns `true` if this `char` has one of the general categories for numbers.
885 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
886 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
887 /// Database][ucd] [`UnicodeData.txt`].
889 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
890 /// [ucd]: https://www.unicode.org/reports/tr44/
891 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
898 /// assert!('٣'.is_numeric());
899 /// assert!('7'.is_numeric());
900 /// assert!('৬'.is_numeric());
901 /// assert!('¾'.is_numeric());
902 /// assert!('①'.is_numeric());
903 /// assert!(!'K'.is_numeric());
904 /// assert!(!'و'.is_numeric());
905 /// assert!(!'藏'.is_numeric());
908 #[stable(feature = "rust1", since = "1.0.0")]
910 pub fn is_numeric(self) -> bool {
913 c => c > '\x7f' && unicode::N(c),
917 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
920 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
922 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
923 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
925 /// [ucd]: https://www.unicode.org/reports/tr44/
926 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
928 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
929 /// the `char`(s) given by [`SpecialCasing.txt`].
931 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
933 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
934 /// is independent of context and language.
936 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
937 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
939 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
946 /// for c in 'İ'.to_lowercase() {
952 /// Using `println!` directly:
955 /// println!("{}", 'İ'.to_lowercase());
958 /// Both are equivalent to:
961 /// println!("i\u{307}");
964 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
967 /// assert_eq!('C'.to_lowercase().to_string(), "c");
969 /// // Sometimes the result is more than one character:
970 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
972 /// // Characters that do not have both uppercase and lowercase
973 /// // convert into themselves.
974 /// assert_eq!('山'.to_lowercase().to_string(), "山");
976 #[must_use = "this returns the lowercase character as a new iterator, \
977 without modifying the original"]
978 #[stable(feature = "rust1", since = "1.0.0")]
980 pub fn to_lowercase(self) -> ToLowercase {
981 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
984 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
987 /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
989 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
990 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
992 /// [ucd]: https://www.unicode.org/reports/tr44/
993 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
995 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
996 /// the `char`(s) given by [`SpecialCasing.txt`].
998 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1000 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1001 /// is independent of context and language.
1003 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1004 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1006 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1013 /// for c in 'ß'.to_uppercase() {
1014 /// print!("{}", c);
1019 /// Using `println!` directly:
1022 /// println!("{}", 'ß'.to_uppercase());
1025 /// Both are equivalent to:
1031 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1034 /// assert_eq!('c'.to_uppercase().to_string(), "C");
1036 /// // Sometimes the result is more than one character:
1037 /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
1039 /// // Characters that do not have both uppercase and lowercase
1040 /// // convert into themselves.
1041 /// assert_eq!('山'.to_uppercase().to_string(), "山");
1044 /// # Note on locale
1046 /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1048 /// * 'Dotless': I / ı, sometimes written ï
1049 /// * 'Dotted': İ / i
1051 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1054 /// let upper_i = 'i'.to_uppercase().to_string();
1057 /// The value of `upper_i` here relies on the language of the text: if we're
1058 /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
1059 /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1062 /// let upper_i = 'i'.to_uppercase().to_string();
1064 /// assert_eq!(upper_i, "I");
1067 /// holds across languages.
1068 #[must_use = "this returns the uppercase character as a new iterator, \
1069 without modifying the original"]
1070 #[stable(feature = "rust1", since = "1.0.0")]
1072 pub fn to_uppercase(self) -> ToUppercase {
1073 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1076 /// Checks if the value is within the ASCII range.
1081 /// let ascii = 'a';
1082 /// let non_ascii = '❤';
1084 /// assert!(ascii.is_ascii());
1085 /// assert!(!non_ascii.is_ascii());
1088 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1089 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.32.0")]
1091 pub const fn is_ascii(&self) -> bool {
1092 *self as u32 <= 0x7F
1095 /// Makes a copy of the value in its ASCII upper case equivalent.
1097 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1098 /// but non-ASCII letters are unchanged.
1100 /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1102 /// To uppercase ASCII characters in addition to non-ASCII characters, use
1103 /// [`to_uppercase()`].
1108 /// let ascii = 'a';
1109 /// let non_ascii = '❤';
1111 /// assert_eq!('A', ascii.to_ascii_uppercase());
1112 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1115 /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1116 /// [`to_uppercase()`]: #method.to_uppercase
1117 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1118 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1119 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1121 pub const fn to_ascii_uppercase(&self) -> char {
1122 if self.is_ascii_lowercase() {
1123 (*self as u8).ascii_change_case_unchecked() as char
1129 /// Makes a copy of the value in its ASCII lower case equivalent.
1131 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1132 /// but non-ASCII letters are unchanged.
1134 /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1136 /// To lowercase ASCII characters in addition to non-ASCII characters, use
1137 /// [`to_lowercase()`].
1142 /// let ascii = 'A';
1143 /// let non_ascii = '❤';
1145 /// assert_eq!('a', ascii.to_ascii_lowercase());
1146 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1149 /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1150 /// [`to_lowercase()`]: #method.to_lowercase
1151 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1152 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1153 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1155 pub const fn to_ascii_lowercase(&self) -> char {
1156 if self.is_ascii_uppercase() {
1157 (*self as u8).ascii_change_case_unchecked() as char
1163 /// Checks that two values are an ASCII case-insensitive match.
1165 /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1170 /// let upper_a = 'A';
1171 /// let lower_a = 'a';
1172 /// let lower_z = 'z';
1174 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1175 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1176 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1179 /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1180 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1181 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1183 pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1184 self.to_ascii_lowercase() == other.to_ascii_lowercase()
1187 /// Converts this type to its ASCII upper case equivalent in-place.
1189 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1190 /// but non-ASCII letters are unchanged.
1192 /// To return a new uppercased value without modifying the existing one, use
1193 /// [`to_ascii_uppercase()`].
1198 /// let mut ascii = 'a';
1200 /// ascii.make_ascii_uppercase();
1202 /// assert_eq!('A', ascii);
1205 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1206 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1208 pub fn make_ascii_uppercase(&mut self) {
1209 *self = self.to_ascii_uppercase();
1212 /// Converts this type to its ASCII lower case equivalent in-place.
1214 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1215 /// but non-ASCII letters are unchanged.
1217 /// To return a new lowercased value without modifying the existing one, use
1218 /// [`to_ascii_lowercase()`].
1223 /// let mut ascii = 'A';
1225 /// ascii.make_ascii_lowercase();
1227 /// assert_eq!('a', ascii);
1230 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1231 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1233 pub fn make_ascii_lowercase(&mut self) {
1234 *self = self.to_ascii_lowercase();
1237 /// Checks if the value is an ASCII alphabetic character:
1239 /// - U+0041 'A' ..= U+005A 'Z', or
1240 /// - U+0061 'a' ..= U+007A 'z'.
1245 /// let uppercase_a = 'A';
1246 /// let uppercase_g = 'G';
1250 /// let percent = '%';
1251 /// let space = ' ';
1253 /// let esc = '\x1b';
1255 /// assert!(uppercase_a.is_ascii_alphabetic());
1256 /// assert!(uppercase_g.is_ascii_alphabetic());
1257 /// assert!(a.is_ascii_alphabetic());
1258 /// assert!(g.is_ascii_alphabetic());
1259 /// assert!(!zero.is_ascii_alphabetic());
1260 /// assert!(!percent.is_ascii_alphabetic());
1261 /// assert!(!space.is_ascii_alphabetic());
1262 /// assert!(!lf.is_ascii_alphabetic());
1263 /// assert!(!esc.is_ascii_alphabetic());
1266 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1267 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1269 pub const fn is_ascii_alphabetic(&self) -> bool {
1270 matches!(*self, 'A'..='Z' | 'a'..='z')
1273 /// Checks if the value is an ASCII uppercase character:
1274 /// U+0041 'A' ..= U+005A 'Z'.
1279 /// let uppercase_a = 'A';
1280 /// let uppercase_g = 'G';
1284 /// let percent = '%';
1285 /// let space = ' ';
1287 /// let esc = '\x1b';
1289 /// assert!(uppercase_a.is_ascii_uppercase());
1290 /// assert!(uppercase_g.is_ascii_uppercase());
1291 /// assert!(!a.is_ascii_uppercase());
1292 /// assert!(!g.is_ascii_uppercase());
1293 /// assert!(!zero.is_ascii_uppercase());
1294 /// assert!(!percent.is_ascii_uppercase());
1295 /// assert!(!space.is_ascii_uppercase());
1296 /// assert!(!lf.is_ascii_uppercase());
1297 /// assert!(!esc.is_ascii_uppercase());
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_uppercase(&self) -> bool {
1304 matches!(*self, 'A'..='Z')
1307 /// Checks if the value is an ASCII lowercase character:
1308 /// U+0061 'a' ..= U+007A 'z'.
1313 /// let uppercase_a = 'A';
1314 /// let uppercase_g = 'G';
1318 /// let percent = '%';
1319 /// let space = ' ';
1321 /// let esc = '\x1b';
1323 /// assert!(!uppercase_a.is_ascii_lowercase());
1324 /// assert!(!uppercase_g.is_ascii_lowercase());
1325 /// assert!(a.is_ascii_lowercase());
1326 /// assert!(g.is_ascii_lowercase());
1327 /// assert!(!zero.is_ascii_lowercase());
1328 /// assert!(!percent.is_ascii_lowercase());
1329 /// assert!(!space.is_ascii_lowercase());
1330 /// assert!(!lf.is_ascii_lowercase());
1331 /// assert!(!esc.is_ascii_lowercase());
1334 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1335 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1337 pub const fn is_ascii_lowercase(&self) -> bool {
1338 matches!(*self, 'a'..='z')
1341 /// Checks if the value is an ASCII alphanumeric character:
1343 /// - U+0041 'A' ..= U+005A 'Z', or
1344 /// - U+0061 'a' ..= U+007A 'z', or
1345 /// - U+0030 '0' ..= U+0039 '9'.
1350 /// let uppercase_a = 'A';
1351 /// let uppercase_g = 'G';
1355 /// let percent = '%';
1356 /// let space = ' ';
1358 /// let esc = '\x1b';
1360 /// assert!(uppercase_a.is_ascii_alphanumeric());
1361 /// assert!(uppercase_g.is_ascii_alphanumeric());
1362 /// assert!(a.is_ascii_alphanumeric());
1363 /// assert!(g.is_ascii_alphanumeric());
1364 /// assert!(zero.is_ascii_alphanumeric());
1365 /// assert!(!percent.is_ascii_alphanumeric());
1366 /// assert!(!space.is_ascii_alphanumeric());
1367 /// assert!(!lf.is_ascii_alphanumeric());
1368 /// assert!(!esc.is_ascii_alphanumeric());
1371 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1372 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1374 pub const fn is_ascii_alphanumeric(&self) -> bool {
1375 matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1378 /// Checks if the value is an ASCII decimal digit:
1379 /// U+0030 '0' ..= U+0039 '9'.
1384 /// let uppercase_a = 'A';
1385 /// let uppercase_g = 'G';
1389 /// let percent = '%';
1390 /// let space = ' ';
1392 /// let esc = '\x1b';
1394 /// assert!(!uppercase_a.is_ascii_digit());
1395 /// assert!(!uppercase_g.is_ascii_digit());
1396 /// assert!(!a.is_ascii_digit());
1397 /// assert!(!g.is_ascii_digit());
1398 /// assert!(zero.is_ascii_digit());
1399 /// assert!(!percent.is_ascii_digit());
1400 /// assert!(!space.is_ascii_digit());
1401 /// assert!(!lf.is_ascii_digit());
1402 /// assert!(!esc.is_ascii_digit());
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_digit(&self) -> bool {
1409 matches!(*self, '0'..='9')
1412 /// Checks if the value is an ASCII hexadecimal digit:
1414 /// - U+0030 '0' ..= U+0039 '9', or
1415 /// - U+0041 'A' ..= U+0046 'F', or
1416 /// - U+0061 'a' ..= U+0066 'f'.
1421 /// let uppercase_a = 'A';
1422 /// let uppercase_g = 'G';
1426 /// let percent = '%';
1427 /// let space = ' ';
1429 /// let esc = '\x1b';
1431 /// assert!(uppercase_a.is_ascii_hexdigit());
1432 /// assert!(!uppercase_g.is_ascii_hexdigit());
1433 /// assert!(a.is_ascii_hexdigit());
1434 /// assert!(!g.is_ascii_hexdigit());
1435 /// assert!(zero.is_ascii_hexdigit());
1436 /// assert!(!percent.is_ascii_hexdigit());
1437 /// assert!(!space.is_ascii_hexdigit());
1438 /// assert!(!lf.is_ascii_hexdigit());
1439 /// assert!(!esc.is_ascii_hexdigit());
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_hexdigit(&self) -> bool {
1446 matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1449 /// Checks if the value is an ASCII punctuation character:
1451 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1452 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1453 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1454 /// - U+007B ..= U+007E `{ | } ~`
1459 /// let uppercase_a = 'A';
1460 /// let uppercase_g = 'G';
1464 /// let percent = '%';
1465 /// let space = ' ';
1467 /// let esc = '\x1b';
1469 /// assert!(!uppercase_a.is_ascii_punctuation());
1470 /// assert!(!uppercase_g.is_ascii_punctuation());
1471 /// assert!(!a.is_ascii_punctuation());
1472 /// assert!(!g.is_ascii_punctuation());
1473 /// assert!(!zero.is_ascii_punctuation());
1474 /// assert!(percent.is_ascii_punctuation());
1475 /// assert!(!space.is_ascii_punctuation());
1476 /// assert!(!lf.is_ascii_punctuation());
1477 /// assert!(!esc.is_ascii_punctuation());
1480 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1481 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1483 pub const fn is_ascii_punctuation(&self) -> bool {
1484 matches!(*self, '!'..='/' | ':'..='@' | '['..='`' | '{'..='~')
1487 /// Checks if the value is an ASCII graphic character:
1488 /// U+0021 '!' ..= U+007E '~'.
1493 /// let uppercase_a = 'A';
1494 /// let uppercase_g = 'G';
1498 /// let percent = '%';
1499 /// let space = ' ';
1501 /// let esc = '\x1b';
1503 /// assert!(uppercase_a.is_ascii_graphic());
1504 /// assert!(uppercase_g.is_ascii_graphic());
1505 /// assert!(a.is_ascii_graphic());
1506 /// assert!(g.is_ascii_graphic());
1507 /// assert!(zero.is_ascii_graphic());
1508 /// assert!(percent.is_ascii_graphic());
1509 /// assert!(!space.is_ascii_graphic());
1510 /// assert!(!lf.is_ascii_graphic());
1511 /// assert!(!esc.is_ascii_graphic());
1514 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1515 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1517 pub const fn is_ascii_graphic(&self) -> bool {
1518 matches!(*self, '!'..='~')
1521 /// Checks if the value is an ASCII whitespace character:
1522 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1523 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1525 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1526 /// whitespace][infra-aw]. There are several other definitions in
1527 /// wide use. For instance, [the POSIX locale][pct] includes
1528 /// U+000B VERTICAL TAB as well as all the above characters,
1529 /// but—from the very same specification—[the default rule for
1530 /// "field splitting" in the Bourne shell][bfs] considers *only*
1531 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1533 /// If you are writing a program that will process an existing
1534 /// file format, check what that format's definition of whitespace is
1535 /// before using this function.
1537 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1538 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1539 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1544 /// let uppercase_a = 'A';
1545 /// let uppercase_g = 'G';
1549 /// let percent = '%';
1550 /// let space = ' ';
1552 /// let esc = '\x1b';
1554 /// assert!(!uppercase_a.is_ascii_whitespace());
1555 /// assert!(!uppercase_g.is_ascii_whitespace());
1556 /// assert!(!a.is_ascii_whitespace());
1557 /// assert!(!g.is_ascii_whitespace());
1558 /// assert!(!zero.is_ascii_whitespace());
1559 /// assert!(!percent.is_ascii_whitespace());
1560 /// assert!(space.is_ascii_whitespace());
1561 /// assert!(lf.is_ascii_whitespace());
1562 /// assert!(!esc.is_ascii_whitespace());
1565 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1566 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1568 pub const fn is_ascii_whitespace(&self) -> bool {
1569 matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1572 /// Checks if the value is an ASCII control character:
1573 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1574 /// Note that most ASCII whitespace characters are control
1575 /// characters, but SPACE is not.
1580 /// let uppercase_a = 'A';
1581 /// let uppercase_g = 'G';
1585 /// let percent = '%';
1586 /// let space = ' ';
1588 /// let esc = '\x1b';
1590 /// assert!(!uppercase_a.is_ascii_control());
1591 /// assert!(!uppercase_g.is_ascii_control());
1592 /// assert!(!a.is_ascii_control());
1593 /// assert!(!g.is_ascii_control());
1594 /// assert!(!zero.is_ascii_control());
1595 /// assert!(!percent.is_ascii_control());
1596 /// assert!(!space.is_ascii_control());
1597 /// assert!(lf.is_ascii_control());
1598 /// assert!(esc.is_ascii_control());
1601 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1602 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1604 pub const fn is_ascii_control(&self) -> bool {
1605 matches!(*self, '\0'..='\x1F' | '\x7F')
1609 pub(crate) struct EscapeDebugExtArgs {
1610 /// Escape Extended Grapheme codepoints?
1611 pub(crate) escape_grapheme_extended: bool,
1613 /// Escape single quotes?
1614 pub(crate) escape_single_quote: bool,
1616 /// Escape double quotes?
1617 pub(crate) escape_double_quote: bool,
1620 impl EscapeDebugExtArgs {
1621 pub(crate) const ESCAPE_ALL: Self = Self {
1622 escape_grapheme_extended: true,
1623 escape_single_quote: true,
1624 escape_double_quote: true,
1629 const fn len_utf8(code: u32) -> usize {
1630 if code < MAX_ONE_B {
1632 } else if code < MAX_TWO_B {
1634 } else if code < MAX_THREE_B {
1641 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1642 /// and then returns the subslice of the buffer that contains the encoded character.
1644 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1645 /// (Creating a `char` in the surrogate range is UB.)
1646 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1648 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1652 /// Panics if the buffer is not large enough.
1653 /// A buffer of length four is large enough to encode any `char`.
1654 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1657 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1658 let len = len_utf8(code);
1659 match (len, &mut dst[..]) {
1663 (2, [a, b, ..]) => {
1664 *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
1665 *b = (code & 0x3F) as u8 | TAG_CONT;
1667 (3, [a, b, c, ..]) => {
1668 *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
1669 *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1670 *c = (code & 0x3F) as u8 | TAG_CONT;
1672 (4, [a, b, c, d, ..]) => {
1673 *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
1674 *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1675 *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1676 *d = (code & 0x3F) as u8 | TAG_CONT;
1679 "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1688 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1689 /// and then returns the subslice of the buffer that contains the encoded character.
1691 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1692 /// (Creating a `char` in the surrogate range is UB.)
1696 /// Panics if the buffer is not large enough.
1697 /// A buffer of length 2 is large enough to encode any `char`.
1698 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1701 pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1702 // SAFETY: each arm checks whether there are enough bits to write into
1704 if (code & 0xFFFF) == code && !dst.is_empty() {
1705 // The BMP falls through
1706 *dst.get_unchecked_mut(0) = code as u16;
1707 slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
1708 } else if dst.len() >= 2 {
1709 // Supplementary planes break into surrogates.
1711 *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
1712 *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
1713 slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
1716 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1717 from_u32_unchecked(code).len_utf16(),