4 use crate::str::from_utf8_unchecked_mut;
5 use crate::unicode::printable::is_printable;
6 use crate::unicode::{self, conversions};
11 /// The highest valid code point a `char` can have, `'\u{10FFFF}'`.
16 /// # fn something_which_returns_char() -> char { 'a' }
17 /// let c: char = something_which_returns_char();
18 /// assert!(c <= char::MAX);
20 /// let value_at_max = char::MAX as u32;
21 /// assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
22 /// assert_eq!(char::from_u32(value_at_max + 1), None);
24 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
25 pub const MAX: char = '\u{10ffff}';
27 /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
30 /// It can occur, for example, when giving ill-formed UTF-8 bytes to
31 /// [`String::from_utf8_lossy`](../std/string/struct.String.html#method.from_utf8_lossy).
32 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
33 pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
35 /// The version of [Unicode](https://www.unicode.org/) that the Unicode parts of
36 /// `char` and `str` methods are based on.
38 /// New versions of Unicode are released regularly and subsequently all methods
39 /// in the standard library depending on Unicode are updated. Therefore the
40 /// behavior of some `char` and `str` methods and the value of this constant
41 /// changes over time. This is *not* considered to be a breaking change.
43 /// The version numbering scheme is explained in
44 /// [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).
45 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
46 pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION;
48 /// Creates an iterator over the UTF-16 encoded code points in `iter`,
49 /// returning unpaired surrogates as `Err`s.
56 /// use std::char::decode_utf16;
58 /// // 𝄞mus<invalid>ic<invalid>
60 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
65 /// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
66 /// .collect::<Vec<_>>(),
69 /// Ok('m'), Ok('u'), Ok('s'),
77 /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
80 /// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
82 /// // 𝄞mus<invalid>ic<invalid>
84 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
89 /// .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
90 /// .collect::<String>(),
94 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
96 pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
97 super::decode::decode_utf16(iter)
100 /// Converts a `u32` to a `char`.
102 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
103 /// [`as`](../std/keyword.as.html):
107 /// let i = c as u32;
109 /// assert_eq!(128175, i);
112 /// However, the reverse is not true: not all valid [`u32`]s are valid
113 /// `char`s. `from_u32()` will return `None` if the input is not a valid value
116 /// For an unsafe version of this function which ignores these checks, see
117 /// [`from_u32_unchecked`].
119 /// [`from_u32_unchecked`]: #method.from_u32_unchecked
128 /// let c = char::from_u32(0x2764);
130 /// assert_eq!(Some('❤'), c);
133 /// Returning `None` when the input is not a valid `char`:
138 /// let c = char::from_u32(0x110000);
140 /// assert_eq!(None, c);
142 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
143 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
146 pub const fn from_u32(i: u32) -> Option<char> {
147 super::convert::from_u32(i)
150 /// Converts a `u32` to a `char`, ignoring validity.
152 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
157 /// let i = c as u32;
159 /// assert_eq!(128175, i);
162 /// However, the reverse is not true: not all valid [`u32`]s are valid
163 /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to
164 /// `char`, possibly creating an invalid one.
168 /// This function is unsafe, as it may construct invalid `char` values.
170 /// For a safe version of this function, see the [`from_u32`] function.
172 /// [`from_u32`]: #method.from_u32
181 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
183 /// assert_eq!('❤', c);
185 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
186 #[rustc_const_unstable(feature = "const_char_from_u32_unchecked", issue = "89259")]
189 pub const unsafe fn from_u32_unchecked(i: u32) -> char {
190 // SAFETY: the safety contract must be upheld by the caller.
191 unsafe { super::convert::from_u32_unchecked(i) }
194 /// Converts a digit in the given radix to a `char`.
196 /// A 'radix' here is sometimes also called a 'base'. A radix of two
197 /// indicates a binary number, a radix of ten, decimal, and a radix of
198 /// sixteen, hexadecimal, to give some common values. Arbitrary
199 /// radices are supported.
201 /// `from_digit()` will return `None` if the input is not a digit in
206 /// Panics if given a radix larger than 36.
215 /// let c = char::from_digit(4, 10);
217 /// assert_eq!(Some('4'), c);
219 /// // Decimal 11 is a single digit in base 16
220 /// let c = char::from_digit(11, 16);
222 /// assert_eq!(Some('b'), c);
225 /// Returning `None` when the input is not a digit:
230 /// let c = char::from_digit(20, 10);
232 /// assert_eq!(None, c);
235 /// Passing a large radix, causing a panic:
241 /// let _c = char::from_digit(1, 37);
243 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
244 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
247 pub const fn from_digit(num: u32, radix: u32) -> Option<char> {
248 super::convert::from_digit(num, radix)
251 /// Checks if a `char` is a digit in the given radix.
253 /// A 'radix' here is sometimes also called a 'base'. A radix of two
254 /// indicates a binary number, a radix of ten, decimal, and a radix of
255 /// sixteen, hexadecimal, to give some common values. Arbitrary
256 /// radices are supported.
258 /// Compared to [`is_numeric()`], this function only recognizes the characters
259 /// `0-9`, `a-z` and `A-Z`.
261 /// 'Digit' is defined to be only the following characters:
267 /// For a more comprehensive understanding of 'digit', see [`is_numeric()`].
269 /// [`is_numeric()`]: #method.is_numeric
273 /// Panics if given a radix larger than 36.
280 /// assert!('1'.is_digit(10));
281 /// assert!('f'.is_digit(16));
282 /// assert!(!'f'.is_digit(10));
285 /// Passing a large radix, causing a panic:
289 /// '1'.is_digit(37);
291 #[stable(feature = "rust1", since = "1.0.0")]
293 pub fn is_digit(self, radix: u32) -> bool {
294 self.to_digit(radix).is_some()
297 /// Converts a `char` to a digit in the given radix.
299 /// A 'radix' here is sometimes also called a 'base'. A radix of two
300 /// indicates a binary number, a radix of ten, decimal, and a radix of
301 /// sixteen, hexadecimal, to give some common values. Arbitrary
302 /// radices are supported.
304 /// 'Digit' is defined to be only the following characters:
312 /// Returns `None` if the `char` does not refer to a digit in the given radix.
316 /// Panics if given a radix larger than 36.
323 /// assert_eq!('1'.to_digit(10), Some(1));
324 /// assert_eq!('f'.to_digit(16), Some(15));
327 /// Passing a non-digit results in failure:
330 /// assert_eq!('f'.to_digit(10), None);
331 /// assert_eq!('z'.to_digit(16), None);
334 /// Passing a large radix, causing a panic:
338 /// let _ = '1'.to_digit(37);
340 #[stable(feature = "rust1", since = "1.0.0")]
341 #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
342 #[must_use = "this returns the result of the operation, \
343 without modifying the original"]
345 pub const fn to_digit(self, radix: u32) -> Option<u32> {
346 // If not a digit, a number greater than radix will be created.
347 let mut digit = (self as u32).wrapping_sub('0' as u32);
349 assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
353 // Force the 6th bit to be set to ensure ascii is lower case.
354 digit = (self as u32 | 0b10_0000).wrapping_sub('a' as u32).saturating_add(10);
356 // FIXME: once then_some is const fn, use it here
357 if digit < radix { Some(digit) } else { None }
360 /// Returns an iterator that yields the hexadecimal Unicode escape of a
361 /// character as `char`s.
363 /// This will escape characters with the Rust syntax of the form
364 /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
371 /// for c in '❤'.escape_unicode() {
377 /// Using `println!` directly:
380 /// println!("{}", '❤'.escape_unicode());
383 /// Both are equivalent to:
386 /// println!("\\u{{2764}}");
389 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
392 /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
394 #[must_use = "this returns the escaped char as an iterator, \
395 without modifying the original"]
396 #[stable(feature = "rust1", since = "1.0.0")]
398 pub fn escape_unicode(self) -> EscapeUnicode {
401 // or-ing 1 ensures that for c==0 the code computes that one
402 // digit should be printed and (which is the same) avoids the
403 // (31 - 32) underflow
404 let msb = 31 - (c | 1).leading_zeros();
406 // the index of the most significant hex digit
407 let ms_hex_digit = msb / 4;
410 state: EscapeUnicodeState::Backslash,
411 hex_digit_idx: ms_hex_digit as usize,
415 /// An extended version of `escape_debug` that optionally permits escaping
416 /// Extended Grapheme codepoints, single quotes, and double quotes. This
417 /// allows us to format characters like nonspacing marks better when they're
418 /// at the start of a string, and allows escaping single quotes in
419 /// characters, and double quotes in strings.
421 pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
422 let init_state = match self {
423 '\0' => EscapeDefaultState::Backslash('0'),
424 '\t' => EscapeDefaultState::Backslash('t'),
425 '\r' => EscapeDefaultState::Backslash('r'),
426 '\n' => EscapeDefaultState::Backslash('n'),
427 '\\' => EscapeDefaultState::Backslash(self),
428 '"' if args.escape_double_quote => EscapeDefaultState::Backslash(self),
429 '\'' if args.escape_single_quote => EscapeDefaultState::Backslash(self),
430 _ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
431 EscapeDefaultState::Unicode(self.escape_unicode())
433 _ if is_printable(self) => EscapeDefaultState::Char(self),
434 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
436 EscapeDebug(EscapeDefault { state: init_state })
439 /// Returns an iterator that yields the literal escape code of a character
442 /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
443 /// of `str` or `char`.
450 /// for c in '\n'.escape_debug() {
456 /// Using `println!` directly:
459 /// println!("{}", '\n'.escape_debug());
462 /// Both are equivalent to:
468 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
471 /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
473 #[must_use = "this returns the escaped char as an iterator, \
474 without modifying the original"]
475 #[stable(feature = "char_escape_debug", since = "1.20.0")]
477 pub fn escape_debug(self) -> EscapeDebug {
478 self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
481 /// Returns an iterator that yields the literal escape code of a character
484 /// The default is chosen with a bias toward producing literals that are
485 /// legal in a variety of languages, including C++11 and similar C-family
486 /// languages. The exact rules are:
488 /// * Tab is escaped as `\t`.
489 /// * Carriage return is escaped as `\r`.
490 /// * Line feed is escaped as `\n`.
491 /// * Single quote is escaped as `\'`.
492 /// * Double quote is escaped as `\"`.
493 /// * Backslash is escaped as `\\`.
494 /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
495 /// inclusive is not escaped.
496 /// * All other characters are given hexadecimal Unicode escapes; see
497 /// [`escape_unicode`].
499 /// [`escape_unicode`]: #method.escape_unicode
506 /// for c in '"'.escape_default() {
512 /// Using `println!` directly:
515 /// println!("{}", '"'.escape_default());
518 /// Both are equivalent to:
521 /// println!("\\\"");
524 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
527 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
529 #[must_use = "this returns the escaped char as an iterator, \
530 without modifying the original"]
531 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn escape_default(self) -> EscapeDefault {
534 let init_state = match self {
535 '\t' => EscapeDefaultState::Backslash('t'),
536 '\r' => EscapeDefaultState::Backslash('r'),
537 '\n' => EscapeDefaultState::Backslash('n'),
538 '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
539 '\x20'..='\x7e' => EscapeDefaultState::Char(self),
540 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
542 EscapeDefault { state: init_state }
545 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
547 /// That number of bytes is always between 1 and 4, inclusive.
554 /// let len = 'A'.len_utf8();
555 /// assert_eq!(len, 1);
557 /// let len = 'ß'.len_utf8();
558 /// assert_eq!(len, 2);
560 /// let len = 'ℝ'.len_utf8();
561 /// assert_eq!(len, 3);
563 /// let len = '💣'.len_utf8();
564 /// assert_eq!(len, 4);
567 /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
568 /// would take if each code point was represented as a `char` vs in the `&str` itself:
572 /// let eastern = '東';
573 /// let capital = '京';
575 /// // both can be represented as three bytes
576 /// assert_eq!(3, eastern.len_utf8());
577 /// assert_eq!(3, capital.len_utf8());
579 /// // as a &str, these two are encoded in UTF-8
580 /// let tokyo = "東京";
582 /// let len = eastern.len_utf8() + capital.len_utf8();
584 /// // we can see that they take six bytes total...
585 /// assert_eq!(6, tokyo.len());
587 /// // ... just like the &str
588 /// assert_eq!(len, tokyo.len());
590 #[stable(feature = "rust1", since = "1.0.0")]
591 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
593 pub const fn len_utf8(self) -> usize {
594 len_utf8(self as u32)
597 /// Returns the number of 16-bit code units this `char` would need if
598 /// encoded in UTF-16.
600 /// See the documentation for [`len_utf8()`] for more explanation of this
601 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
603 /// [`len_utf8()`]: #method.len_utf8
610 /// let n = 'ß'.len_utf16();
611 /// assert_eq!(n, 1);
613 /// let len = '💣'.len_utf16();
614 /// assert_eq!(len, 2);
616 #[stable(feature = "rust1", since = "1.0.0")]
617 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
619 pub const fn len_utf16(self) -> usize {
620 let ch = self as u32;
621 if (ch & 0xFFFF) == ch { 1 } else { 2 }
624 /// Encodes this character as UTF-8 into the provided byte buffer,
625 /// and then returns the subslice of the buffer that contains the encoded character.
629 /// Panics if the buffer is not large enough.
630 /// A buffer of length four is large enough to encode any `char`.
634 /// In both of these examples, 'ß' takes two bytes to encode.
637 /// let mut b = [0; 2];
639 /// let result = 'ß'.encode_utf8(&mut b);
641 /// assert_eq!(result, "ß");
643 /// assert_eq!(result.len(), 2);
646 /// A buffer that's too small:
649 /// let mut b = [0; 1];
652 /// 'ß'.encode_utf8(&mut b);
654 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
656 pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
657 // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
658 unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
661 /// Encodes this character as UTF-16 into the provided `u16` buffer,
662 /// and then returns the subslice of the buffer that contains the encoded character.
666 /// Panics if the buffer is not large enough.
667 /// A buffer of length 2 is large enough to encode any `char`.
671 /// In both of these examples, '𝕊' takes two `u16`s to encode.
674 /// let mut b = [0; 2];
676 /// let result = '𝕊'.encode_utf16(&mut b);
678 /// assert_eq!(result.len(), 2);
681 /// A buffer that's too small:
684 /// let mut b = [0; 1];
687 /// '𝕊'.encode_utf16(&mut b);
689 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
691 pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
692 encode_utf16_raw(self as u32, dst)
695 /// Returns `true` if this `char` has the `Alphabetic` property.
697 /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
698 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
700 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
701 /// [ucd]: https://www.unicode.org/reports/tr44/
702 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
709 /// assert!('a'.is_alphabetic());
710 /// assert!('京'.is_alphabetic());
713 /// // love is many things, but it is not alphabetic
714 /// assert!(!c.is_alphabetic());
717 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn is_alphabetic(self) -> bool {
721 'a'..='z' | 'A'..='Z' => true,
722 c => c > '\x7f' && unicode::Alphabetic(c),
726 /// Returns `true` if this `char` has the `Lowercase` property.
728 /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
729 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
731 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
732 /// [ucd]: https://www.unicode.org/reports/tr44/
733 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
740 /// assert!('a'.is_lowercase());
741 /// assert!('δ'.is_lowercase());
742 /// assert!(!'A'.is_lowercase());
743 /// assert!(!'Δ'.is_lowercase());
745 /// // The various Chinese scripts and punctuation do not have case, and so:
746 /// assert!(!'中'.is_lowercase());
747 /// assert!(!' '.is_lowercase());
750 /// In a const context:
753 /// #![feature(const_unicode_case_lookup)]
754 /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
755 /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
758 #[stable(feature = "rust1", since = "1.0.0")]
759 #[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
761 pub const fn is_lowercase(self) -> bool {
764 c => c > '\x7f' && unicode::Lowercase(c),
768 /// Returns `true` if this `char` has the `Uppercase` property.
770 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
771 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
773 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
774 /// [ucd]: https://www.unicode.org/reports/tr44/
775 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
782 /// assert!(!'a'.is_uppercase());
783 /// assert!(!'δ'.is_uppercase());
784 /// assert!('A'.is_uppercase());
785 /// assert!('Δ'.is_uppercase());
787 /// // The various Chinese scripts and punctuation do not have case, and so:
788 /// assert!(!'中'.is_uppercase());
789 /// assert!(!' '.is_uppercase());
792 /// In a const context:
795 /// #![feature(const_unicode_case_lookup)]
796 /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
797 /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
800 #[stable(feature = "rust1", since = "1.0.0")]
801 #[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
803 pub const fn is_uppercase(self) -> bool {
806 c => c > '\x7f' && unicode::Uppercase(c),
810 /// Returns `true` if this `char` has the `White_Space` property.
812 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
814 /// [ucd]: https://www.unicode.org/reports/tr44/
815 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
822 /// assert!(' '.is_whitespace());
825 /// assert!('\n'.is_whitespace());
827 /// // a non-breaking space
828 /// assert!('\u{A0}'.is_whitespace());
830 /// assert!(!'越'.is_whitespace());
833 #[stable(feature = "rust1", since = "1.0.0")]
835 pub fn is_whitespace(self) -> bool {
837 ' ' | '\x09'..='\x0d' => true,
838 c => c > '\x7f' && unicode::White_Space(c),
842 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
844 /// [`is_alphabetic()`]: #method.is_alphabetic
845 /// [`is_numeric()`]: #method.is_numeric
852 /// assert!('٣'.is_alphanumeric());
853 /// assert!('7'.is_alphanumeric());
854 /// assert!('৬'.is_alphanumeric());
855 /// assert!('¾'.is_alphanumeric());
856 /// assert!('①'.is_alphanumeric());
857 /// assert!('K'.is_alphanumeric());
858 /// assert!('و'.is_alphanumeric());
859 /// assert!('藏'.is_alphanumeric());
862 #[stable(feature = "rust1", since = "1.0.0")]
864 pub fn is_alphanumeric(self) -> bool {
865 self.is_alphabetic() || self.is_numeric()
868 /// Returns `true` if this `char` has the general category for control codes.
870 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
871 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
872 /// Database][ucd] [`UnicodeData.txt`].
874 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
875 /// [ucd]: https://www.unicode.org/reports/tr44/
876 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
883 /// // U+009C, STRING TERMINATOR
884 /// assert!('
\9c'.is_control());
885 /// assert!(!'q'.is_control());
888 #[stable(feature = "rust1", since = "1.0.0")]
890 pub fn is_control(self) -> bool {
894 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
896 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
897 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
898 /// [`DerivedCoreProperties.txt`].
900 /// [uax29]: https://www.unicode.org/reports/tr29/
901 /// [ucd]: https://www.unicode.org/reports/tr44/
902 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
905 pub(crate) fn is_grapheme_extended(self) -> bool {
906 unicode::Grapheme_Extend(self)
909 /// Returns `true` if this `char` has one of the general categories for numbers.
911 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
912 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
913 /// Database][ucd] [`UnicodeData.txt`].
915 /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
916 /// If you want everything including characters with overlapping purposes then you might want to use
917 /// a unicode or language-processing library that exposes the appropriate character properties instead
918 /// of looking at the unicode categories.
920 /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
921 /// `is_ascii_digit` or `is_digit` instead.
923 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
924 /// [ucd]: https://www.unicode.org/reports/tr44/
925 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
932 /// assert!('٣'.is_numeric());
933 /// assert!('7'.is_numeric());
934 /// assert!('৬'.is_numeric());
935 /// assert!('¾'.is_numeric());
936 /// assert!('①'.is_numeric());
937 /// assert!(!'K'.is_numeric());
938 /// assert!(!'و'.is_numeric());
939 /// assert!(!'藏'.is_numeric());
940 /// assert!(!'三'.is_numeric());
943 #[stable(feature = "rust1", since = "1.0.0")]
945 pub fn is_numeric(self) -> bool {
948 c => c > '\x7f' && unicode::N(c),
952 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
955 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
957 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
958 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
960 /// [ucd]: https://www.unicode.org/reports/tr44/
961 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
963 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
964 /// the `char`(s) given by [`SpecialCasing.txt`].
966 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
968 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
969 /// is independent of context and language.
971 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
972 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
974 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
981 /// for c in 'İ'.to_lowercase() {
987 /// Using `println!` directly:
990 /// println!("{}", 'İ'.to_lowercase());
993 /// Both are equivalent to:
996 /// println!("i\u{307}");
999 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1002 /// assert_eq!('C'.to_lowercase().to_string(), "c");
1004 /// // Sometimes the result is more than one character:
1005 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1007 /// // Characters that do not have both uppercase and lowercase
1008 /// // convert into themselves.
1009 /// assert_eq!('山'.to_lowercase().to_string(), "山");
1011 #[must_use = "this returns the lowercase character as a new iterator, \
1012 without modifying the original"]
1013 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub fn to_lowercase(self) -> ToLowercase {
1016 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1019 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1022 /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1024 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1025 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1027 /// [ucd]: https://www.unicode.org/reports/tr44/
1028 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1030 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1031 /// the `char`(s) given by [`SpecialCasing.txt`].
1033 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1035 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1036 /// is independent of context and language.
1038 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1039 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1041 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1048 /// for c in 'ß'.to_uppercase() {
1054 /// Using `println!` directly:
1057 /// println!("{}", 'ß'.to_uppercase());
1060 /// Both are equivalent to:
1066 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1069 /// assert_eq!('c'.to_uppercase().to_string(), "C");
1071 /// // Sometimes the result is more than one character:
1072 /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
1074 /// // Characters that do not have both uppercase and lowercase
1075 /// // convert into themselves.
1076 /// assert_eq!('山'.to_uppercase().to_string(), "山");
1079 /// # Note on locale
1081 /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1083 /// * 'Dotless': I / ı, sometimes written ï
1084 /// * 'Dotted': İ / i
1086 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1089 /// let upper_i = 'i'.to_uppercase().to_string();
1092 /// The value of `upper_i` here relies on the language of the text: if we're
1093 /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
1094 /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1097 /// let upper_i = 'i'.to_uppercase().to_string();
1099 /// assert_eq!(upper_i, "I");
1102 /// holds across languages.
1103 #[must_use = "this returns the uppercase character as a new iterator, \
1104 without modifying the original"]
1105 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub fn to_uppercase(self) -> ToUppercase {
1108 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1111 /// Checks if the value is within the ASCII range.
1116 /// let ascii = 'a';
1117 /// let non_ascii = '❤';
1119 /// assert!(ascii.is_ascii());
1120 /// assert!(!non_ascii.is_ascii());
1123 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1124 #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1126 pub const fn is_ascii(&self) -> bool {
1127 *self as u32 <= 0x7F
1130 /// Makes a copy of the value in its ASCII upper case equivalent.
1132 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1133 /// but non-ASCII letters are unchanged.
1135 /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1137 /// To uppercase ASCII characters in addition to non-ASCII characters, use
1138 /// [`to_uppercase()`].
1143 /// let ascii = 'a';
1144 /// let non_ascii = '❤';
1146 /// assert_eq!('A', ascii.to_ascii_uppercase());
1147 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1150 /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1151 /// [`to_uppercase()`]: #method.to_uppercase
1152 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1153 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1154 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1156 pub const fn to_ascii_uppercase(&self) -> char {
1157 if self.is_ascii_lowercase() {
1158 (*self as u8).ascii_change_case_unchecked() as char
1164 /// Makes a copy of the value in its ASCII lower case equivalent.
1166 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1167 /// but non-ASCII letters are unchanged.
1169 /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1171 /// To lowercase ASCII characters in addition to non-ASCII characters, use
1172 /// [`to_lowercase()`].
1177 /// let ascii = 'A';
1178 /// let non_ascii = '❤';
1180 /// assert_eq!('a', ascii.to_ascii_lowercase());
1181 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1184 /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1185 /// [`to_lowercase()`]: #method.to_lowercase
1186 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1187 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1188 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1190 pub const fn to_ascii_lowercase(&self) -> char {
1191 if self.is_ascii_uppercase() {
1192 (*self as u8).ascii_change_case_unchecked() as char
1198 /// Checks that two values are an ASCII case-insensitive match.
1200 /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1205 /// let upper_a = 'A';
1206 /// let lower_a = 'a';
1207 /// let lower_z = 'z';
1209 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1210 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1211 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1214 /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1215 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1216 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1218 pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1219 self.to_ascii_lowercase() == other.to_ascii_lowercase()
1222 /// Converts this type to its ASCII upper case equivalent in-place.
1224 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1225 /// but non-ASCII letters are unchanged.
1227 /// To return a new uppercased value without modifying the existing one, use
1228 /// [`to_ascii_uppercase()`].
1233 /// let mut ascii = 'a';
1235 /// ascii.make_ascii_uppercase();
1237 /// assert_eq!('A', ascii);
1240 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1241 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1243 pub fn make_ascii_uppercase(&mut self) {
1244 *self = self.to_ascii_uppercase();
1247 /// Converts this type to its ASCII lower case equivalent in-place.
1249 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1250 /// but non-ASCII letters are unchanged.
1252 /// To return a new lowercased value without modifying the existing one, use
1253 /// [`to_ascii_lowercase()`].
1258 /// let mut ascii = 'A';
1260 /// ascii.make_ascii_lowercase();
1262 /// assert_eq!('a', ascii);
1265 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1266 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1268 pub fn make_ascii_lowercase(&mut self) {
1269 *self = self.to_ascii_lowercase();
1272 /// Checks if the value is an ASCII alphabetic character:
1274 /// - U+0041 'A' ..= U+005A 'Z', or
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 = '\x1b';
1290 /// assert!(uppercase_a.is_ascii_alphabetic());
1291 /// assert!(uppercase_g.is_ascii_alphabetic());
1292 /// assert!(a.is_ascii_alphabetic());
1293 /// assert!(g.is_ascii_alphabetic());
1294 /// assert!(!zero.is_ascii_alphabetic());
1295 /// assert!(!percent.is_ascii_alphabetic());
1296 /// assert!(!space.is_ascii_alphabetic());
1297 /// assert!(!lf.is_ascii_alphabetic());
1298 /// assert!(!esc.is_ascii_alphabetic());
1301 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1302 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1304 pub const fn is_ascii_alphabetic(&self) -> bool {
1305 matches!(*self, 'A'..='Z' | 'a'..='z')
1308 /// Checks if the value is an ASCII uppercase character:
1309 /// U+0041 'A' ..= U+005A 'Z'.
1314 /// let uppercase_a = 'A';
1315 /// let uppercase_g = 'G';
1319 /// let percent = '%';
1320 /// let space = ' ';
1322 /// let esc = '\x1b';
1324 /// assert!(uppercase_a.is_ascii_uppercase());
1325 /// assert!(uppercase_g.is_ascii_uppercase());
1326 /// assert!(!a.is_ascii_uppercase());
1327 /// assert!(!g.is_ascii_uppercase());
1328 /// assert!(!zero.is_ascii_uppercase());
1329 /// assert!(!percent.is_ascii_uppercase());
1330 /// assert!(!space.is_ascii_uppercase());
1331 /// assert!(!lf.is_ascii_uppercase());
1332 /// assert!(!esc.is_ascii_uppercase());
1335 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1336 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1338 pub const fn is_ascii_uppercase(&self) -> bool {
1339 matches!(*self, 'A'..='Z')
1342 /// Checks if the value is an ASCII lowercase character:
1343 /// U+0061 'a' ..= U+007A 'z'.
1348 /// let uppercase_a = 'A';
1349 /// let uppercase_g = 'G';
1353 /// let percent = '%';
1354 /// let space = ' ';
1356 /// let esc = '\x1b';
1358 /// assert!(!uppercase_a.is_ascii_lowercase());
1359 /// assert!(!uppercase_g.is_ascii_lowercase());
1360 /// assert!(a.is_ascii_lowercase());
1361 /// assert!(g.is_ascii_lowercase());
1362 /// assert!(!zero.is_ascii_lowercase());
1363 /// assert!(!percent.is_ascii_lowercase());
1364 /// assert!(!space.is_ascii_lowercase());
1365 /// assert!(!lf.is_ascii_lowercase());
1366 /// assert!(!esc.is_ascii_lowercase());
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_lowercase(&self) -> bool {
1373 matches!(*self, 'a'..='z')
1376 /// Checks if the value is an ASCII alphanumeric character:
1378 /// - U+0041 'A' ..= U+005A 'Z', or
1379 /// - U+0061 'a' ..= U+007A 'z', or
1380 /// - U+0030 '0' ..= U+0039 '9'.
1385 /// let uppercase_a = 'A';
1386 /// let uppercase_g = 'G';
1390 /// let percent = '%';
1391 /// let space = ' ';
1393 /// let esc = '\x1b';
1395 /// assert!(uppercase_a.is_ascii_alphanumeric());
1396 /// assert!(uppercase_g.is_ascii_alphanumeric());
1397 /// assert!(a.is_ascii_alphanumeric());
1398 /// assert!(g.is_ascii_alphanumeric());
1399 /// assert!(zero.is_ascii_alphanumeric());
1400 /// assert!(!percent.is_ascii_alphanumeric());
1401 /// assert!(!space.is_ascii_alphanumeric());
1402 /// assert!(!lf.is_ascii_alphanumeric());
1403 /// assert!(!esc.is_ascii_alphanumeric());
1406 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1407 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1409 pub const fn is_ascii_alphanumeric(&self) -> bool {
1410 matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1413 /// Checks if the value is an ASCII decimal digit:
1414 /// U+0030 '0' ..= U+0039 '9'.
1419 /// let uppercase_a = 'A';
1420 /// let uppercase_g = 'G';
1424 /// let percent = '%';
1425 /// let space = ' ';
1427 /// let esc = '\x1b';
1429 /// assert!(!uppercase_a.is_ascii_digit());
1430 /// assert!(!uppercase_g.is_ascii_digit());
1431 /// assert!(!a.is_ascii_digit());
1432 /// assert!(!g.is_ascii_digit());
1433 /// assert!(zero.is_ascii_digit());
1434 /// assert!(!percent.is_ascii_digit());
1435 /// assert!(!space.is_ascii_digit());
1436 /// assert!(!lf.is_ascii_digit());
1437 /// assert!(!esc.is_ascii_digit());
1440 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1441 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1443 pub const fn is_ascii_digit(&self) -> bool {
1444 matches!(*self, '0'..='9')
1447 /// Checks if the value is an ASCII hexadecimal digit:
1449 /// - U+0030 '0' ..= U+0039 '9', or
1450 /// - U+0041 'A' ..= U+0046 'F', or
1451 /// - U+0061 'a' ..= U+0066 'f'.
1456 /// let uppercase_a = 'A';
1457 /// let uppercase_g = 'G';
1461 /// let percent = '%';
1462 /// let space = ' ';
1464 /// let esc = '\x1b';
1466 /// assert!(uppercase_a.is_ascii_hexdigit());
1467 /// assert!(!uppercase_g.is_ascii_hexdigit());
1468 /// assert!(a.is_ascii_hexdigit());
1469 /// assert!(!g.is_ascii_hexdigit());
1470 /// assert!(zero.is_ascii_hexdigit());
1471 /// assert!(!percent.is_ascii_hexdigit());
1472 /// assert!(!space.is_ascii_hexdigit());
1473 /// assert!(!lf.is_ascii_hexdigit());
1474 /// assert!(!esc.is_ascii_hexdigit());
1477 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1478 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1480 pub const fn is_ascii_hexdigit(&self) -> bool {
1481 matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1484 /// Checks if the value is an ASCII punctuation character:
1486 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1487 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1488 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1489 /// - U+007B ..= U+007E `{ | } ~`
1494 /// let uppercase_a = 'A';
1495 /// let uppercase_g = 'G';
1499 /// let percent = '%';
1500 /// let space = ' ';
1502 /// let esc = '\x1b';
1504 /// assert!(!uppercase_a.is_ascii_punctuation());
1505 /// assert!(!uppercase_g.is_ascii_punctuation());
1506 /// assert!(!a.is_ascii_punctuation());
1507 /// assert!(!g.is_ascii_punctuation());
1508 /// assert!(!zero.is_ascii_punctuation());
1509 /// assert!(percent.is_ascii_punctuation());
1510 /// assert!(!space.is_ascii_punctuation());
1511 /// assert!(!lf.is_ascii_punctuation());
1512 /// assert!(!esc.is_ascii_punctuation());
1515 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1516 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1518 pub const fn is_ascii_punctuation(&self) -> bool {
1519 matches!(*self, '!'..='/' | ':'..='@' | '['..='`' | '{'..='~')
1522 /// Checks if the value is an ASCII graphic character:
1523 /// U+0021 '!' ..= U+007E '~'.
1528 /// let uppercase_a = 'A';
1529 /// let uppercase_g = 'G';
1533 /// let percent = '%';
1534 /// let space = ' ';
1536 /// let esc = '\x1b';
1538 /// assert!(uppercase_a.is_ascii_graphic());
1539 /// assert!(uppercase_g.is_ascii_graphic());
1540 /// assert!(a.is_ascii_graphic());
1541 /// assert!(g.is_ascii_graphic());
1542 /// assert!(zero.is_ascii_graphic());
1543 /// assert!(percent.is_ascii_graphic());
1544 /// assert!(!space.is_ascii_graphic());
1545 /// assert!(!lf.is_ascii_graphic());
1546 /// assert!(!esc.is_ascii_graphic());
1549 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1550 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1552 pub const fn is_ascii_graphic(&self) -> bool {
1553 matches!(*self, '!'..='~')
1556 /// Checks if the value is an ASCII whitespace character:
1557 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1558 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1560 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1561 /// whitespace][infra-aw]. There are several other definitions in
1562 /// wide use. For instance, [the POSIX locale][pct] includes
1563 /// U+000B VERTICAL TAB as well as all the above characters,
1564 /// but—from the very same specification—[the default rule for
1565 /// "field splitting" in the Bourne shell][bfs] considers *only*
1566 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1568 /// If you are writing a program that will process an existing
1569 /// file format, check what that format's definition of whitespace is
1570 /// before using this function.
1572 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1573 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1574 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1579 /// let uppercase_a = 'A';
1580 /// let uppercase_g = 'G';
1584 /// let percent = '%';
1585 /// let space = ' ';
1587 /// let esc = '\x1b';
1589 /// assert!(!uppercase_a.is_ascii_whitespace());
1590 /// assert!(!uppercase_g.is_ascii_whitespace());
1591 /// assert!(!a.is_ascii_whitespace());
1592 /// assert!(!g.is_ascii_whitespace());
1593 /// assert!(!zero.is_ascii_whitespace());
1594 /// assert!(!percent.is_ascii_whitespace());
1595 /// assert!(space.is_ascii_whitespace());
1596 /// assert!(lf.is_ascii_whitespace());
1597 /// assert!(!esc.is_ascii_whitespace());
1600 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1601 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1603 pub const fn is_ascii_whitespace(&self) -> bool {
1604 matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1607 /// Checks if the value is an ASCII control character:
1608 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1609 /// Note that most ASCII whitespace characters are control
1610 /// characters, but SPACE is not.
1615 /// let uppercase_a = 'A';
1616 /// let uppercase_g = 'G';
1620 /// let percent = '%';
1621 /// let space = ' ';
1623 /// let esc = '\x1b';
1625 /// assert!(!uppercase_a.is_ascii_control());
1626 /// assert!(!uppercase_g.is_ascii_control());
1627 /// assert!(!a.is_ascii_control());
1628 /// assert!(!g.is_ascii_control());
1629 /// assert!(!zero.is_ascii_control());
1630 /// assert!(!percent.is_ascii_control());
1631 /// assert!(!space.is_ascii_control());
1632 /// assert!(lf.is_ascii_control());
1633 /// assert!(esc.is_ascii_control());
1636 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1637 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1639 pub const fn is_ascii_control(&self) -> bool {
1640 matches!(*self, '\0'..='\x1F' | '\x7F')
1644 pub(crate) struct EscapeDebugExtArgs {
1645 /// Escape Extended Grapheme codepoints?
1646 pub(crate) escape_grapheme_extended: bool,
1648 /// Escape single quotes?
1649 pub(crate) escape_single_quote: bool,
1651 /// Escape double quotes?
1652 pub(crate) escape_double_quote: bool,
1655 impl EscapeDebugExtArgs {
1656 pub(crate) const ESCAPE_ALL: Self = Self {
1657 escape_grapheme_extended: true,
1658 escape_single_quote: true,
1659 escape_double_quote: true,
1664 const fn len_utf8(code: u32) -> usize {
1665 if code < MAX_ONE_B {
1667 } else if code < MAX_TWO_B {
1669 } else if code < MAX_THREE_B {
1676 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1677 /// and then returns the subslice of the buffer that contains the encoded character.
1679 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1680 /// (Creating a `char` in the surrogate range is UB.)
1681 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1683 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1687 /// Panics if the buffer is not large enough.
1688 /// A buffer of length four is large enough to encode any `char`.
1689 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1692 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1693 let len = len_utf8(code);
1694 match (len, &mut dst[..]) {
1698 (2, [a, b, ..]) => {
1699 *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
1700 *b = (code & 0x3F) as u8 | TAG_CONT;
1702 (3, [a, b, c, ..]) => {
1703 *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
1704 *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1705 *c = (code & 0x3F) as u8 | TAG_CONT;
1707 (4, [a, b, c, d, ..]) => {
1708 *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
1709 *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1710 *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1711 *d = (code & 0x3F) as u8 | TAG_CONT;
1714 "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1723 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1724 /// and then returns the subslice of the buffer that contains the encoded character.
1726 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1727 /// (Creating a `char` in the surrogate range is UB.)
1731 /// Panics if the buffer is not large enough.
1732 /// A buffer of length 2 is large enough to encode any `char`.
1733 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1736 pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1737 // SAFETY: each arm checks whether there are enough bits to write into
1739 if (code & 0xFFFF) == code && !dst.is_empty() {
1740 // The BMP falls through
1741 *dst.get_unchecked_mut(0) = code as u16;
1742 slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
1743 } else if dst.len() >= 2 {
1744 // Supplementary planes break into surrogates.
1746 *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
1747 *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
1748 slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
1751 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1752 from_u32_unchecked(code).len_utf16(),