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_stable(feature = "const_char_convert", since = "CURRENT_RUSTC_VERSION")]
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_stable(feature = "const_char_convert", since = "CURRENT_RUSTC_VERSION")]
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_stable(feature = "const_char_convert", since = "CURRENT_RUSTC_VERSION")]
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 /// That number of code units is always either 1 or 2, for unicode scalar values in
601 /// the [basic multilingual plane] or [supplementary planes] respectively.
603 /// See the documentation for [`len_utf8()`] for more explanation of this
604 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
606 /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
607 /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
608 /// [`len_utf8()`]: #method.len_utf8
615 /// let n = 'ß'.len_utf16();
616 /// assert_eq!(n, 1);
618 /// let len = '💣'.len_utf16();
619 /// assert_eq!(len, 2);
621 #[stable(feature = "rust1", since = "1.0.0")]
622 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
624 pub const fn len_utf16(self) -> usize {
625 let ch = self as u32;
626 if (ch & 0xFFFF) == ch { 1 } else { 2 }
629 /// Encodes this character as UTF-8 into the provided byte buffer,
630 /// and then returns the subslice of the buffer that contains the encoded character.
634 /// Panics if the buffer is not large enough.
635 /// A buffer of length four is large enough to encode any `char`.
639 /// In both of these examples, 'ß' takes two bytes to encode.
642 /// let mut b = [0; 2];
644 /// let result = 'ß'.encode_utf8(&mut b);
646 /// assert_eq!(result, "ß");
648 /// assert_eq!(result.len(), 2);
651 /// A buffer that's too small:
654 /// let mut b = [0; 1];
657 /// 'ß'.encode_utf8(&mut b);
659 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
661 pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
662 // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
663 unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
666 /// Encodes this character as UTF-16 into the provided `u16` buffer,
667 /// and then returns the subslice of the buffer that contains the encoded character.
671 /// Panics if the buffer is not large enough.
672 /// A buffer of length 2 is large enough to encode any `char`.
676 /// In both of these examples, '𝕊' takes two `u16`s to encode.
679 /// let mut b = [0; 2];
681 /// let result = '𝕊'.encode_utf16(&mut b);
683 /// assert_eq!(result.len(), 2);
686 /// A buffer that's too small:
689 /// let mut b = [0; 1];
692 /// '𝕊'.encode_utf16(&mut b);
694 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
696 pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
697 encode_utf16_raw(self as u32, dst)
700 /// Returns `true` if this `char` has the `Alphabetic` property.
702 /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
703 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
705 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
706 /// [ucd]: https://www.unicode.org/reports/tr44/
707 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
714 /// assert!('a'.is_alphabetic());
715 /// assert!('京'.is_alphabetic());
718 /// // love is many things, but it is not alphabetic
719 /// assert!(!c.is_alphabetic());
722 #[stable(feature = "rust1", since = "1.0.0")]
724 pub fn is_alphabetic(self) -> bool {
726 'a'..='z' | 'A'..='Z' => true,
727 c => c > '\x7f' && unicode::Alphabetic(c),
731 /// Returns `true` if this `char` has the `Lowercase` property.
733 /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
734 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
736 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
737 /// [ucd]: https://www.unicode.org/reports/tr44/
738 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
745 /// assert!('a'.is_lowercase());
746 /// assert!('δ'.is_lowercase());
747 /// assert!(!'A'.is_lowercase());
748 /// assert!(!'Δ'.is_lowercase());
750 /// // The various Chinese scripts and punctuation do not have case, and so:
751 /// assert!(!'中'.is_lowercase());
752 /// assert!(!' '.is_lowercase());
755 /// In a const context:
758 /// #![feature(const_unicode_case_lookup)]
759 /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
760 /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
763 #[stable(feature = "rust1", since = "1.0.0")]
764 #[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
766 pub const fn is_lowercase(self) -> bool {
769 c => c > '\x7f' && unicode::Lowercase(c),
773 /// Returns `true` if this `char` has the `Uppercase` property.
775 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
776 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
778 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
779 /// [ucd]: https://www.unicode.org/reports/tr44/
780 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
787 /// assert!(!'a'.is_uppercase());
788 /// assert!(!'δ'.is_uppercase());
789 /// assert!('A'.is_uppercase());
790 /// assert!('Δ'.is_uppercase());
792 /// // The various Chinese scripts and punctuation do not have case, and so:
793 /// assert!(!'中'.is_uppercase());
794 /// assert!(!' '.is_uppercase());
797 /// In a const context:
800 /// #![feature(const_unicode_case_lookup)]
801 /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
802 /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
805 #[stable(feature = "rust1", since = "1.0.0")]
806 #[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
808 pub const fn is_uppercase(self) -> bool {
811 c => c > '\x7f' && unicode::Uppercase(c),
815 /// Returns `true` if this `char` has the `White_Space` property.
817 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
819 /// [ucd]: https://www.unicode.org/reports/tr44/
820 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
827 /// assert!(' '.is_whitespace());
830 /// assert!('\n'.is_whitespace());
832 /// // a non-breaking space
833 /// assert!('\u{A0}'.is_whitespace());
835 /// assert!(!'越'.is_whitespace());
838 #[stable(feature = "rust1", since = "1.0.0")]
840 pub fn is_whitespace(self) -> bool {
842 ' ' | '\x09'..='\x0d' => true,
843 c => c > '\x7f' && unicode::White_Space(c),
847 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
849 /// [`is_alphabetic()`]: #method.is_alphabetic
850 /// [`is_numeric()`]: #method.is_numeric
857 /// assert!('٣'.is_alphanumeric());
858 /// assert!('7'.is_alphanumeric());
859 /// assert!('৬'.is_alphanumeric());
860 /// assert!('¾'.is_alphanumeric());
861 /// assert!('①'.is_alphanumeric());
862 /// assert!('K'.is_alphanumeric());
863 /// assert!('و'.is_alphanumeric());
864 /// assert!('藏'.is_alphanumeric());
867 #[stable(feature = "rust1", since = "1.0.0")]
869 pub fn is_alphanumeric(self) -> bool {
870 self.is_alphabetic() || self.is_numeric()
873 /// Returns `true` if this `char` has the general category for control codes.
875 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
876 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
877 /// Database][ucd] [`UnicodeData.txt`].
879 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
880 /// [ucd]: https://www.unicode.org/reports/tr44/
881 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
888 /// // U+009C, STRING TERMINATOR
889 /// assert!('
\9c'.is_control());
890 /// assert!(!'q'.is_control());
893 #[stable(feature = "rust1", since = "1.0.0")]
895 pub fn is_control(self) -> bool {
899 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
901 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
902 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
903 /// [`DerivedCoreProperties.txt`].
905 /// [uax29]: https://www.unicode.org/reports/tr29/
906 /// [ucd]: https://www.unicode.org/reports/tr44/
907 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
910 pub(crate) fn is_grapheme_extended(self) -> bool {
911 unicode::Grapheme_Extend(self)
914 /// Returns `true` if this `char` has one of the general categories for numbers.
916 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
917 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
918 /// Database][ucd] [`UnicodeData.txt`].
920 /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
921 /// If you want everything including characters with overlapping purposes then you might want to use
922 /// a unicode or language-processing library that exposes the appropriate character properties instead
923 /// of looking at the unicode categories.
925 /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
926 /// `is_ascii_digit` or `is_digit` instead.
928 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
929 /// [ucd]: https://www.unicode.org/reports/tr44/
930 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
937 /// assert!('٣'.is_numeric());
938 /// assert!('7'.is_numeric());
939 /// assert!('৬'.is_numeric());
940 /// assert!('¾'.is_numeric());
941 /// assert!('①'.is_numeric());
942 /// assert!(!'K'.is_numeric());
943 /// assert!(!'و'.is_numeric());
944 /// assert!(!'藏'.is_numeric());
945 /// assert!(!'三'.is_numeric());
948 #[stable(feature = "rust1", since = "1.0.0")]
950 pub fn is_numeric(self) -> bool {
953 c => c > '\x7f' && unicode::N(c),
957 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
960 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
962 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
963 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
965 /// [ucd]: https://www.unicode.org/reports/tr44/
966 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
968 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
969 /// the `char`(s) given by [`SpecialCasing.txt`].
971 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
973 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
974 /// is independent of context and language.
976 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
977 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
979 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
986 /// for c in 'İ'.to_lowercase() {
992 /// Using `println!` directly:
995 /// println!("{}", 'İ'.to_lowercase());
998 /// Both are equivalent to:
1001 /// println!("i\u{307}");
1004 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1007 /// assert_eq!('C'.to_lowercase().to_string(), "c");
1009 /// // Sometimes the result is more than one character:
1010 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1012 /// // Characters that do not have both uppercase and lowercase
1013 /// // convert into themselves.
1014 /// assert_eq!('山'.to_lowercase().to_string(), "山");
1016 #[must_use = "this returns the lowercase character as a new iterator, \
1017 without modifying the original"]
1018 #[stable(feature = "rust1", since = "1.0.0")]
1020 pub fn to_lowercase(self) -> ToLowercase {
1021 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1024 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1027 /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1029 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1030 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1032 /// [ucd]: https://www.unicode.org/reports/tr44/
1033 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1035 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1036 /// the `char`(s) given by [`SpecialCasing.txt`].
1038 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1040 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1041 /// is independent of context and language.
1043 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1044 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1046 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1053 /// for c in 'ß'.to_uppercase() {
1059 /// Using `println!` directly:
1062 /// println!("{}", 'ß'.to_uppercase());
1065 /// Both are equivalent to:
1071 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1074 /// assert_eq!('c'.to_uppercase().to_string(), "C");
1076 /// // Sometimes the result is more than one character:
1077 /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
1079 /// // Characters that do not have both uppercase and lowercase
1080 /// // convert into themselves.
1081 /// assert_eq!('山'.to_uppercase().to_string(), "山");
1084 /// # Note on locale
1086 /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1088 /// * 'Dotless': I / ı, sometimes written ï
1089 /// * 'Dotted': İ / i
1091 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1094 /// let upper_i = 'i'.to_uppercase().to_string();
1097 /// The value of `upper_i` here relies on the language of the text: if we're
1098 /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
1099 /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1102 /// let upper_i = 'i'.to_uppercase().to_string();
1104 /// assert_eq!(upper_i, "I");
1107 /// holds across languages.
1108 #[must_use = "this returns the uppercase character as a new iterator, \
1109 without modifying the original"]
1110 #[stable(feature = "rust1", since = "1.0.0")]
1112 pub fn to_uppercase(self) -> ToUppercase {
1113 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1116 /// Checks if the value is within the ASCII range.
1121 /// let ascii = 'a';
1122 /// let non_ascii = '❤';
1124 /// assert!(ascii.is_ascii());
1125 /// assert!(!non_ascii.is_ascii());
1128 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1129 #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1131 pub const fn is_ascii(&self) -> bool {
1132 *self as u32 <= 0x7F
1135 /// Makes a copy of the value in its ASCII upper case equivalent.
1137 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1138 /// but non-ASCII letters are unchanged.
1140 /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1142 /// To uppercase ASCII characters in addition to non-ASCII characters, use
1143 /// [`to_uppercase()`].
1148 /// let ascii = 'a';
1149 /// let non_ascii = '❤';
1151 /// assert_eq!('A', ascii.to_ascii_uppercase());
1152 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1155 /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1156 /// [`to_uppercase()`]: #method.to_uppercase
1157 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1158 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1159 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1161 pub const fn to_ascii_uppercase(&self) -> char {
1162 if self.is_ascii_lowercase() {
1163 (*self as u8).ascii_change_case_unchecked() as char
1169 /// Makes a copy of the value in its ASCII lower case equivalent.
1171 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1172 /// but non-ASCII letters are unchanged.
1174 /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1176 /// To lowercase ASCII characters in addition to non-ASCII characters, use
1177 /// [`to_lowercase()`].
1182 /// let ascii = 'A';
1183 /// let non_ascii = '❤';
1185 /// assert_eq!('a', ascii.to_ascii_lowercase());
1186 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1189 /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1190 /// [`to_lowercase()`]: #method.to_lowercase
1191 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1192 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1193 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1195 pub const fn to_ascii_lowercase(&self) -> char {
1196 if self.is_ascii_uppercase() {
1197 (*self as u8).ascii_change_case_unchecked() as char
1203 /// Checks that two values are an ASCII case-insensitive match.
1205 /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1210 /// let upper_a = 'A';
1211 /// let lower_a = 'a';
1212 /// let lower_z = 'z';
1214 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1215 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1216 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1219 /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1220 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1221 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1223 pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1224 self.to_ascii_lowercase() == other.to_ascii_lowercase()
1227 /// Converts this type to its ASCII upper case equivalent in-place.
1229 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1230 /// but non-ASCII letters are unchanged.
1232 /// To return a new uppercased value without modifying the existing one, use
1233 /// [`to_ascii_uppercase()`].
1238 /// let mut ascii = 'a';
1240 /// ascii.make_ascii_uppercase();
1242 /// assert_eq!('A', ascii);
1245 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1246 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1248 pub fn make_ascii_uppercase(&mut self) {
1249 *self = self.to_ascii_uppercase();
1252 /// Converts this type to its ASCII lower case equivalent in-place.
1254 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1255 /// but non-ASCII letters are unchanged.
1257 /// To return a new lowercased value without modifying the existing one, use
1258 /// [`to_ascii_lowercase()`].
1263 /// let mut ascii = 'A';
1265 /// ascii.make_ascii_lowercase();
1267 /// assert_eq!('a', ascii);
1270 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1271 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1273 pub fn make_ascii_lowercase(&mut self) {
1274 *self = self.to_ascii_lowercase();
1277 /// Checks if the value is an ASCII alphabetic character:
1279 /// - U+0041 'A' ..= U+005A 'Z', or
1280 /// - U+0061 'a' ..= U+007A 'z'.
1285 /// let uppercase_a = 'A';
1286 /// let uppercase_g = 'G';
1290 /// let percent = '%';
1291 /// let space = ' ';
1293 /// let esc = '\x1b';
1295 /// assert!(uppercase_a.is_ascii_alphabetic());
1296 /// assert!(uppercase_g.is_ascii_alphabetic());
1297 /// assert!(a.is_ascii_alphabetic());
1298 /// assert!(g.is_ascii_alphabetic());
1299 /// assert!(!zero.is_ascii_alphabetic());
1300 /// assert!(!percent.is_ascii_alphabetic());
1301 /// assert!(!space.is_ascii_alphabetic());
1302 /// assert!(!lf.is_ascii_alphabetic());
1303 /// assert!(!esc.is_ascii_alphabetic());
1306 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1307 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1309 pub const fn is_ascii_alphabetic(&self) -> bool {
1310 matches!(*self, 'A'..='Z' | 'a'..='z')
1313 /// Checks if the value is an ASCII uppercase character:
1314 /// U+0041 'A' ..= U+005A 'Z'.
1319 /// let uppercase_a = 'A';
1320 /// let uppercase_g = 'G';
1324 /// let percent = '%';
1325 /// let space = ' ';
1327 /// let esc = '\x1b';
1329 /// assert!(uppercase_a.is_ascii_uppercase());
1330 /// assert!(uppercase_g.is_ascii_uppercase());
1331 /// assert!(!a.is_ascii_uppercase());
1332 /// assert!(!g.is_ascii_uppercase());
1333 /// assert!(!zero.is_ascii_uppercase());
1334 /// assert!(!percent.is_ascii_uppercase());
1335 /// assert!(!space.is_ascii_uppercase());
1336 /// assert!(!lf.is_ascii_uppercase());
1337 /// assert!(!esc.is_ascii_uppercase());
1340 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1341 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1343 pub const fn is_ascii_uppercase(&self) -> bool {
1344 matches!(*self, 'A'..='Z')
1347 /// Checks if the value is an ASCII lowercase character:
1348 /// U+0061 'a' ..= U+007A 'z'.
1353 /// let uppercase_a = 'A';
1354 /// let uppercase_g = 'G';
1358 /// let percent = '%';
1359 /// let space = ' ';
1361 /// let esc = '\x1b';
1363 /// assert!(!uppercase_a.is_ascii_lowercase());
1364 /// assert!(!uppercase_g.is_ascii_lowercase());
1365 /// assert!(a.is_ascii_lowercase());
1366 /// assert!(g.is_ascii_lowercase());
1367 /// assert!(!zero.is_ascii_lowercase());
1368 /// assert!(!percent.is_ascii_lowercase());
1369 /// assert!(!space.is_ascii_lowercase());
1370 /// assert!(!lf.is_ascii_lowercase());
1371 /// assert!(!esc.is_ascii_lowercase());
1374 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1375 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1377 pub const fn is_ascii_lowercase(&self) -> bool {
1378 matches!(*self, 'a'..='z')
1381 /// Checks if the value is an ASCII alphanumeric character:
1383 /// - U+0041 'A' ..= U+005A 'Z', or
1384 /// - U+0061 'a' ..= U+007A 'z', or
1385 /// - U+0030 '0' ..= U+0039 '9'.
1390 /// let uppercase_a = 'A';
1391 /// let uppercase_g = 'G';
1395 /// let percent = '%';
1396 /// let space = ' ';
1398 /// let esc = '\x1b';
1400 /// assert!(uppercase_a.is_ascii_alphanumeric());
1401 /// assert!(uppercase_g.is_ascii_alphanumeric());
1402 /// assert!(a.is_ascii_alphanumeric());
1403 /// assert!(g.is_ascii_alphanumeric());
1404 /// assert!(zero.is_ascii_alphanumeric());
1405 /// assert!(!percent.is_ascii_alphanumeric());
1406 /// assert!(!space.is_ascii_alphanumeric());
1407 /// assert!(!lf.is_ascii_alphanumeric());
1408 /// assert!(!esc.is_ascii_alphanumeric());
1411 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1412 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1414 pub const fn is_ascii_alphanumeric(&self) -> bool {
1415 matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1418 /// Checks if the value is an ASCII decimal digit:
1419 /// U+0030 '0' ..= U+0039 '9'.
1424 /// let uppercase_a = 'A';
1425 /// let uppercase_g = 'G';
1429 /// let percent = '%';
1430 /// let space = ' ';
1432 /// let esc = '\x1b';
1434 /// assert!(!uppercase_a.is_ascii_digit());
1435 /// assert!(!uppercase_g.is_ascii_digit());
1436 /// assert!(!a.is_ascii_digit());
1437 /// assert!(!g.is_ascii_digit());
1438 /// assert!(zero.is_ascii_digit());
1439 /// assert!(!percent.is_ascii_digit());
1440 /// assert!(!space.is_ascii_digit());
1441 /// assert!(!lf.is_ascii_digit());
1442 /// assert!(!esc.is_ascii_digit());
1445 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1446 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1448 pub const fn is_ascii_digit(&self) -> bool {
1449 matches!(*self, '0'..='9')
1452 /// Checks if the value is an ASCII octal digit:
1453 /// U+0030 '0' ..= U+0037 '7'.
1458 /// #![feature(is_ascii_octdigit)]
1460 /// let uppercase_a = 'A';
1463 /// let seven = '7';
1465 /// let percent = '%';
1468 /// assert!(!uppercase_a.is_ascii_octdigit());
1469 /// assert!(!a.is_ascii_octdigit());
1470 /// assert!(zero.is_ascii_octdigit());
1471 /// assert!(seven.is_ascii_octdigit());
1472 /// assert!(!nine.is_ascii_octdigit());
1473 /// assert!(!percent.is_ascii_octdigit());
1474 /// assert!(!lf.is_ascii_octdigit());
1477 #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
1478 #[rustc_const_unstable(feature = "is_ascii_octdigit", issue = "101288")]
1480 pub const fn is_ascii_octdigit(&self) -> bool {
1481 matches!(*self, '0'..='7')
1484 /// Checks if the value is an ASCII hexadecimal digit:
1486 /// - U+0030 '0' ..= U+0039 '9', or
1487 /// - U+0041 'A' ..= U+0046 'F', or
1488 /// - U+0061 'a' ..= U+0066 'f'.
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_hexdigit());
1504 /// assert!(!uppercase_g.is_ascii_hexdigit());
1505 /// assert!(a.is_ascii_hexdigit());
1506 /// assert!(!g.is_ascii_hexdigit());
1507 /// assert!(zero.is_ascii_hexdigit());
1508 /// assert!(!percent.is_ascii_hexdigit());
1509 /// assert!(!space.is_ascii_hexdigit());
1510 /// assert!(!lf.is_ascii_hexdigit());
1511 /// assert!(!esc.is_ascii_hexdigit());
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_hexdigit(&self) -> bool {
1518 matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1521 /// Checks if the value is an ASCII punctuation character:
1523 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1524 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1525 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1526 /// - U+007B ..= U+007E `{ | } ~`
1531 /// let uppercase_a = 'A';
1532 /// let uppercase_g = 'G';
1536 /// let percent = '%';
1537 /// let space = ' ';
1539 /// let esc = '\x1b';
1541 /// assert!(!uppercase_a.is_ascii_punctuation());
1542 /// assert!(!uppercase_g.is_ascii_punctuation());
1543 /// assert!(!a.is_ascii_punctuation());
1544 /// assert!(!g.is_ascii_punctuation());
1545 /// assert!(!zero.is_ascii_punctuation());
1546 /// assert!(percent.is_ascii_punctuation());
1547 /// assert!(!space.is_ascii_punctuation());
1548 /// assert!(!lf.is_ascii_punctuation());
1549 /// assert!(!esc.is_ascii_punctuation());
1552 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1553 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1555 pub const fn is_ascii_punctuation(&self) -> bool {
1556 matches!(*self, '!'..='/' | ':'..='@' | '['..='`' | '{'..='~')
1559 /// Checks if the value is an ASCII graphic character:
1560 /// U+0021 '!' ..= U+007E '~'.
1565 /// let uppercase_a = 'A';
1566 /// let uppercase_g = 'G';
1570 /// let percent = '%';
1571 /// let space = ' ';
1573 /// let esc = '\x1b';
1575 /// assert!(uppercase_a.is_ascii_graphic());
1576 /// assert!(uppercase_g.is_ascii_graphic());
1577 /// assert!(a.is_ascii_graphic());
1578 /// assert!(g.is_ascii_graphic());
1579 /// assert!(zero.is_ascii_graphic());
1580 /// assert!(percent.is_ascii_graphic());
1581 /// assert!(!space.is_ascii_graphic());
1582 /// assert!(!lf.is_ascii_graphic());
1583 /// assert!(!esc.is_ascii_graphic());
1586 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1587 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1589 pub const fn is_ascii_graphic(&self) -> bool {
1590 matches!(*self, '!'..='~')
1593 /// Checks if the value is an ASCII whitespace character:
1594 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1595 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1597 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1598 /// whitespace][infra-aw]. There are several other definitions in
1599 /// wide use. For instance, [the POSIX locale][pct] includes
1600 /// U+000B VERTICAL TAB as well as all the above characters,
1601 /// but—from the very same specification—[the default rule for
1602 /// "field splitting" in the Bourne shell][bfs] considers *only*
1603 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1605 /// If you are writing a program that will process an existing
1606 /// file format, check what that format's definition of whitespace is
1607 /// before using this function.
1609 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1610 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1611 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1616 /// let uppercase_a = 'A';
1617 /// let uppercase_g = 'G';
1621 /// let percent = '%';
1622 /// let space = ' ';
1624 /// let esc = '\x1b';
1626 /// assert!(!uppercase_a.is_ascii_whitespace());
1627 /// assert!(!uppercase_g.is_ascii_whitespace());
1628 /// assert!(!a.is_ascii_whitespace());
1629 /// assert!(!g.is_ascii_whitespace());
1630 /// assert!(!zero.is_ascii_whitespace());
1631 /// assert!(!percent.is_ascii_whitespace());
1632 /// assert!(space.is_ascii_whitespace());
1633 /// assert!(lf.is_ascii_whitespace());
1634 /// assert!(!esc.is_ascii_whitespace());
1637 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1638 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1640 pub const fn is_ascii_whitespace(&self) -> bool {
1641 matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1644 /// Checks if the value is an ASCII control character:
1645 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1646 /// Note that most ASCII whitespace characters are control
1647 /// characters, but SPACE is not.
1652 /// let uppercase_a = 'A';
1653 /// let uppercase_g = 'G';
1657 /// let percent = '%';
1658 /// let space = ' ';
1660 /// let esc = '\x1b';
1662 /// assert!(!uppercase_a.is_ascii_control());
1663 /// assert!(!uppercase_g.is_ascii_control());
1664 /// assert!(!a.is_ascii_control());
1665 /// assert!(!g.is_ascii_control());
1666 /// assert!(!zero.is_ascii_control());
1667 /// assert!(!percent.is_ascii_control());
1668 /// assert!(!space.is_ascii_control());
1669 /// assert!(lf.is_ascii_control());
1670 /// assert!(esc.is_ascii_control());
1673 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1674 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1676 pub const fn is_ascii_control(&self) -> bool {
1677 matches!(*self, '\0'..='\x1F' | '\x7F')
1681 pub(crate) struct EscapeDebugExtArgs {
1682 /// Escape Extended Grapheme codepoints?
1683 pub(crate) escape_grapheme_extended: bool,
1685 /// Escape single quotes?
1686 pub(crate) escape_single_quote: bool,
1688 /// Escape double quotes?
1689 pub(crate) escape_double_quote: bool,
1692 impl EscapeDebugExtArgs {
1693 pub(crate) const ESCAPE_ALL: Self = Self {
1694 escape_grapheme_extended: true,
1695 escape_single_quote: true,
1696 escape_double_quote: true,
1701 const fn len_utf8(code: u32) -> usize {
1702 if code < MAX_ONE_B {
1704 } else if code < MAX_TWO_B {
1706 } else if code < MAX_THREE_B {
1713 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1714 /// and then returns the subslice of the buffer that contains the encoded character.
1716 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1717 /// (Creating a `char` in the surrogate range is UB.)
1718 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1720 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1724 /// Panics if the buffer is not large enough.
1725 /// A buffer of length four is large enough to encode any `char`.
1726 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1729 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1730 let len = len_utf8(code);
1731 match (len, &mut dst[..]) {
1735 (2, [a, b, ..]) => {
1736 *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
1737 *b = (code & 0x3F) as u8 | TAG_CONT;
1739 (3, [a, b, c, ..]) => {
1740 *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
1741 *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1742 *c = (code & 0x3F) as u8 | TAG_CONT;
1744 (4, [a, b, c, d, ..]) => {
1745 *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
1746 *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1747 *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1748 *d = (code & 0x3F) as u8 | TAG_CONT;
1751 "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1760 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1761 /// and then returns the subslice of the buffer that contains the encoded character.
1763 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1764 /// (Creating a `char` in the surrogate range is UB.)
1768 /// Panics if the buffer is not large enough.
1769 /// A buffer of length 2 is large enough to encode any `char`.
1770 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1773 pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1774 // SAFETY: each arm checks whether there are enough bits to write into
1776 if (code & 0xFFFF) == code && !dst.is_empty() {
1777 // The BMP falls through
1778 *dst.get_unchecked_mut(0) = code as u16;
1779 slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
1780 } else if dst.len() >= 2 {
1781 // Supplementary planes break into surrogates.
1783 *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
1784 *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
1785 slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
1788 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1789 from_u32_unchecked(code).len_utf16(),