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_convert", 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 #[stable(feature = "rust1
", since = "1.0.0")]
752 pub fn is_lowercase(self) -> bool {
755 c => c > '\x7f' && unicode::Lowercase(c),
759 /// Returns `true` if this `char` has the `Uppercase` property.
761 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
762 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
764 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
765 /// [ucd]: https://www.unicode.org/reports/tr44/
766 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
773 /// assert!(!'a'.is_uppercase());
774 /// assert!(!'δ'.is_uppercase());
775 /// assert!('A'.is_uppercase());
776 /// assert!('Δ'.is_uppercase());
778 /// // The various Chinese scripts and punctuation do not have case, and so:
779 /// assert!(!'中'.is_uppercase());
780 /// assert!(!' '.is_uppercase());
783 #[stable(feature = "rust1
", since = "1.0.0")]
785 pub fn is_uppercase(self) -> bool {
788 c => c > '\x7f' && unicode::Uppercase(c),
792 /// Returns `true` if this `char` has the `White_Space` property.
794 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
796 /// [ucd]: https://www.unicode.org/reports/tr44/
797 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
804 /// assert!(' '.is_whitespace());
807 /// assert!('\n'.is_whitespace());
809 /// // a non-breaking space
810 /// assert!('\u{A0}'.is_whitespace());
812 /// assert!(!'越'.is_whitespace());
815 #[stable(feature = "rust1
", since = "1.0.0")]
817 pub fn is_whitespace(self) -> bool {
819 ' ' | '\x09'..='\x0d' => true,
820 c => c > '\x7f' && unicode::White_Space(c),
824 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
826 /// [`is_alphabetic()`]: #method.is_alphabetic
827 /// [`is_numeric()`]: #method.is_numeric
834 /// assert!('٣'.is_alphanumeric());
835 /// assert!('7'.is_alphanumeric());
836 /// assert!('৬'.is_alphanumeric());
837 /// assert!('¾'.is_alphanumeric());
838 /// assert!('①'.is_alphanumeric());
839 /// assert!('K'.is_alphanumeric());
840 /// assert!('و'.is_alphanumeric());
841 /// assert!('藏'.is_alphanumeric());
844 #[stable(feature = "rust1
", since = "1.0.0")]
846 pub fn is_alphanumeric(self) -> bool {
847 self.is_alphabetic() || self.is_numeric()
850 /// Returns `true` if this `char` has the general category for control codes.
852 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
853 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
854 /// Database][ucd] [`UnicodeData.txt`].
856 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
857 /// [ucd]: https://www.unicode.org/reports/tr44/
858 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
865 /// // U+009C, STRING TERMINATOR
866 /// assert!('\9c'.is_control());
867 /// assert!(!'q'.is_control());
870 #[stable(feature = "rust1
", since = "1.0.0")]
872 pub fn is_control(self) -> bool {
876 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
878 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
879 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
880 /// [`DerivedCoreProperties.txt`].
882 /// [uax29]: https://www.unicode.org/reports/tr29/
883 /// [ucd]: https://www.unicode.org/reports/tr44/
884 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
887 pub(crate) fn is_grapheme_extended(self) -> bool {
888 unicode::Grapheme_Extend(self)
891 /// Returns `true` if this `char` has one of the general categories for numbers.
893 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
894 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
895 /// Database][ucd] [`UnicodeData.txt`]. Note that this means ideographic numbers like '三'
896 /// are considered alphabetic, not numeric. Please consider to use `is_ascii_digit` or `is_digit`.
898 /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
899 /// If you want everything including characters with overlapping purposes then you might want to use
900 /// a unicode or language-processing library that exposes the appropriate character properties instead
901 /// of looking at the unicode categories.
903 /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
904 /// `is_ascii_digit` or `is_digit` instead.
906 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
907 /// [ucd]: https://www.unicode.org/reports/tr44/
908 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
915 /// assert!('٣'.is_numeric());
916 /// assert!('7'.is_numeric());
917 /// assert!('৬'.is_numeric());
918 /// assert!('¾'.is_numeric());
919 /// assert!('①'.is_numeric());
920 /// assert!(!'K'.is_numeric());
921 /// assert!(!'و'.is_numeric());
922 /// assert!(!'藏'.is_numeric());
923 /// assert!(!'三'.is_numeric());
926 #[stable(feature = "rust1
", since = "1.0.0")]
928 pub fn is_numeric(self) -> bool {
931 c => c > '\x7f' && unicode::N(c),
935 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
938 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
940 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
941 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
943 /// [ucd]: https://www.unicode.org/reports/tr44/
944 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
946 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
947 /// the `char`(s) given by [`SpecialCasing.txt`].
949 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
951 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
952 /// is independent of context and language.
954 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
955 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
957 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
964 /// for c in 'İ'.to_lowercase() {
970 /// Using `println!` directly:
973 /// println!("{}
", 'İ'.to_lowercase());
976 /// Both are equivalent to:
979 /// println!("i
\u{307}
");
982 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
985 /// assert_eq!('C'.to_lowercase().to_string(), "c
");
987 /// // Sometimes the result is more than one character:
988 /// assert_eq!('İ'.to_lowercase().to_string(), "i
\u{307}
");
990 /// // Characters that do not have both uppercase and lowercase
991 /// // convert into themselves.
992 /// assert_eq!('山'.to_lowercase().to_string(), "山
");
994 #[must_use = "this returns the lowercase character
as a new iterator
, \
995 without modifying the original
"]
996 #[stable(feature = "rust1
", since = "1.0.0")]
998 pub fn to_lowercase(self) -> ToLowercase {
999 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1002 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1005 /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1007 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1008 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1010 /// [ucd]: https://www.unicode.org/reports/tr44/
1011 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1013 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1014 /// the `char`(s) given by [`SpecialCasing.txt`].
1016 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1018 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1019 /// is independent of context and language.
1021 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1022 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1024 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1031 /// for c in 'ß'.to_uppercase() {
1037 /// Using `println!` directly:
1040 /// println!("{}
", 'ß'.to_uppercase());
1043 /// Both are equivalent to:
1049 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1052 /// assert_eq!('c'.to_uppercase().to_string(), "C
");
1054 /// // Sometimes the result is more than one character:
1055 /// assert_eq!('ß'.to_uppercase().to_string(), "SS
");
1057 /// // Characters that do not have both uppercase and lowercase
1058 /// // convert into themselves.
1059 /// assert_eq!('山'.to_uppercase().to_string(), "山
");
1062 /// # Note on locale
1064 /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1066 /// * 'Dotless': I / ı, sometimes written ï
1067 /// * 'Dotted': İ / i
1069 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1072 /// let upper_i = 'i'.to_uppercase().to_string();
1075 /// The value of `upper_i` here relies on the language of the text: if we're
1076 /// in `en-US`, it should be `"I
"`, but if we're in `tr_TR`, it should
1077 /// be `"İ
"`. `to_uppercase()` does not take this into account, and so:
1080 /// let upper_i = 'i'.to_uppercase().to_string();
1082 /// assert_eq!(upper_i, "I
");
1085 /// holds across languages.
1086 #[must_use = "this returns the uppercase character
as a new iterator
, \
1087 without modifying the original
"]
1088 #[stable(feature = "rust1
", since = "1.0.0")]
1090 pub fn to_uppercase(self) -> ToUppercase {
1091 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1094 /// Checks if the value is within the ASCII range.
1099 /// let ascii = 'a';
1100 /// let non_ascii = '❤';
1102 /// assert!(ascii.is_ascii());
1103 /// assert!(!non_ascii.is_ascii());
1106 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1107 #[rustc_const_stable(feature = "const_char_is_ascii
", since = "1.32.0")]
1109 pub const fn is_ascii(&self) -> bool {
1110 *self as u32 <= 0x7F
1113 /// Makes a copy of the value in its ASCII upper case equivalent.
1115 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1116 /// but non-ASCII letters are unchanged.
1118 /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1120 /// To uppercase ASCII characters in addition to non-ASCII characters, use
1121 /// [`to_uppercase()`].
1126 /// let ascii = 'a';
1127 /// let non_ascii = '❤';
1129 /// assert_eq!('A', ascii.to_ascii_uppercase());
1130 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1133 /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1134 /// [`to_uppercase()`]: #method.to_uppercase
1135 #[must_use = "to uppercase the value
in-place
, use `
make_ascii_uppercase()`
"]
1136 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1137 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics
", since = "1.52.0")]
1139 pub const fn to_ascii_uppercase(&self) -> char {
1140 if self.is_ascii_lowercase() {
1141 (*self as u8).ascii_change_case_unchecked() as char
1147 /// Makes a copy of the value in its ASCII lower case equivalent.
1149 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1150 /// but non-ASCII letters are unchanged.
1152 /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1154 /// To lowercase ASCII characters in addition to non-ASCII characters, use
1155 /// [`to_lowercase()`].
1160 /// let ascii = 'A';
1161 /// let non_ascii = '❤';
1163 /// assert_eq!('a', ascii.to_ascii_lowercase());
1164 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1167 /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1168 /// [`to_lowercase()`]: #method.to_lowercase
1169 #[must_use = "to lowercase the value
in-place
, use `
make_ascii_lowercase()`
"]
1170 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1171 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics
", since = "1.52.0")]
1173 pub const fn to_ascii_lowercase(&self) -> char {
1174 if self.is_ascii_uppercase() {
1175 (*self as u8).ascii_change_case_unchecked() as char
1181 /// Checks that two values are an ASCII case-insensitive match.
1183 /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1188 /// let upper_a = 'A';
1189 /// let lower_a = 'a';
1190 /// let lower_z = 'z';
1192 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1193 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1194 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1197 /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1198 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1199 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics
", since = "1.52.0")]
1201 pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1202 self.to_ascii_lowercase() == other.to_ascii_lowercase()
1205 /// Converts this type to its ASCII upper case equivalent in-place.
1207 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1208 /// but non-ASCII letters are unchanged.
1210 /// To return a new uppercased value without modifying the existing one, use
1211 /// [`to_ascii_uppercase()`].
1216 /// let mut ascii = 'a';
1218 /// ascii.make_ascii_uppercase();
1220 /// assert_eq!('A', ascii);
1223 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1224 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1226 pub fn make_ascii_uppercase(&mut self) {
1227 *self = self.to_ascii_uppercase();
1230 /// Converts this type to its ASCII lower case equivalent in-place.
1232 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1233 /// but non-ASCII letters are unchanged.
1235 /// To return a new lowercased value without modifying the existing one, use
1236 /// [`to_ascii_lowercase()`].
1241 /// let mut ascii = 'A';
1243 /// ascii.make_ascii_lowercase();
1245 /// assert_eq!('a', ascii);
1248 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1249 #[stable(feature = "ascii_methods_on_intrinsics
", since = "1.23.0")]
1251 pub fn make_ascii_lowercase(&mut self) {
1252 *self = self.to_ascii_lowercase();
1255 /// Checks if the value is an ASCII alphabetic character:
1257 /// - U+0041 'A' ..= U+005A 'Z', or
1258 /// - U+0061 'a' ..= U+007A 'z'.
1263 /// let uppercase_a = 'A';
1264 /// let uppercase_g = 'G';
1268 /// let percent = '%';
1269 /// let space = ' ';
1271 /// let esc = '\x1b';
1273 /// assert!(uppercase_a.is_ascii_alphabetic());
1274 /// assert!(uppercase_g.is_ascii_alphabetic());
1275 /// assert!(a.is_ascii_alphabetic());
1276 /// assert!(g.is_ascii_alphabetic());
1277 /// assert!(!zero.is_ascii_alphabetic());
1278 /// assert!(!percent.is_ascii_alphabetic());
1279 /// assert!(!space.is_ascii_alphabetic());
1280 /// assert!(!lf.is_ascii_alphabetic());
1281 /// assert!(!esc.is_ascii_alphabetic());
1284 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1285 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1287 pub const fn is_ascii_alphabetic(&self) -> bool {
1288 matches!(*self, 'A'..='Z' | 'a'..='z')
1291 /// Checks if the value is an ASCII uppercase character:
1292 /// U+0041 'A' ..= U+005A 'Z'.
1297 /// let uppercase_a = 'A';
1298 /// let uppercase_g = 'G';
1302 /// let percent = '%';
1303 /// let space = ' ';
1305 /// let esc = '\x1b';
1307 /// assert!(uppercase_a.is_ascii_uppercase());
1308 /// assert!(uppercase_g.is_ascii_uppercase());
1309 /// assert!(!a.is_ascii_uppercase());
1310 /// assert!(!g.is_ascii_uppercase());
1311 /// assert!(!zero.is_ascii_uppercase());
1312 /// assert!(!percent.is_ascii_uppercase());
1313 /// assert!(!space.is_ascii_uppercase());
1314 /// assert!(!lf.is_ascii_uppercase());
1315 /// assert!(!esc.is_ascii_uppercase());
1318 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1319 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1321 pub const fn is_ascii_uppercase(&self) -> bool {
1322 matches!(*self, 'A'..='Z')
1325 /// Checks if the value is an ASCII lowercase character:
1326 /// U+0061 'a' ..= U+007A 'z'.
1331 /// let uppercase_a = 'A';
1332 /// let uppercase_g = 'G';
1336 /// let percent = '%';
1337 /// let space = ' ';
1339 /// let esc = '\x1b';
1341 /// assert!(!uppercase_a.is_ascii_lowercase());
1342 /// assert!(!uppercase_g.is_ascii_lowercase());
1343 /// assert!(a.is_ascii_lowercase());
1344 /// assert!(g.is_ascii_lowercase());
1345 /// assert!(!zero.is_ascii_lowercase());
1346 /// assert!(!percent.is_ascii_lowercase());
1347 /// assert!(!space.is_ascii_lowercase());
1348 /// assert!(!lf.is_ascii_lowercase());
1349 /// assert!(!esc.is_ascii_lowercase());
1352 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1353 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1355 pub const fn is_ascii_lowercase(&self) -> bool {
1356 matches!(*self, 'a'..='z')
1359 /// Checks if the value is an ASCII alphanumeric character:
1361 /// - U+0041 'A' ..= U+005A 'Z', or
1362 /// - U+0061 'a' ..= U+007A 'z', or
1363 /// - U+0030 '0' ..= U+0039 '9'.
1368 /// let uppercase_a = 'A';
1369 /// let uppercase_g = 'G';
1373 /// let percent = '%';
1374 /// let space = ' ';
1376 /// let esc = '\x1b';
1378 /// assert!(uppercase_a.is_ascii_alphanumeric());
1379 /// assert!(uppercase_g.is_ascii_alphanumeric());
1380 /// assert!(a.is_ascii_alphanumeric());
1381 /// assert!(g.is_ascii_alphanumeric());
1382 /// assert!(zero.is_ascii_alphanumeric());
1383 /// assert!(!percent.is_ascii_alphanumeric());
1384 /// assert!(!space.is_ascii_alphanumeric());
1385 /// assert!(!lf.is_ascii_alphanumeric());
1386 /// assert!(!esc.is_ascii_alphanumeric());
1389 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1390 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1392 pub const fn is_ascii_alphanumeric(&self) -> bool {
1393 matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1396 /// Checks if the value is an ASCII decimal digit:
1397 /// U+0030 '0' ..= U+0039 '9'.
1402 /// let uppercase_a = 'A';
1403 /// let uppercase_g = 'G';
1407 /// let percent = '%';
1408 /// let space = ' ';
1410 /// let esc = '\x1b';
1412 /// assert!(!uppercase_a.is_ascii_digit());
1413 /// assert!(!uppercase_g.is_ascii_digit());
1414 /// assert!(!a.is_ascii_digit());
1415 /// assert!(!g.is_ascii_digit());
1416 /// assert!(zero.is_ascii_digit());
1417 /// assert!(!percent.is_ascii_digit());
1418 /// assert!(!space.is_ascii_digit());
1419 /// assert!(!lf.is_ascii_digit());
1420 /// assert!(!esc.is_ascii_digit());
1423 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1424 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1426 pub const fn is_ascii_digit(&self) -> bool {
1427 matches!(*self, '0'..='9')
1430 /// Checks if the value is an ASCII hexadecimal digit:
1432 /// - U+0030 '0' ..= U+0039 '9', or
1433 /// - U+0041 'A' ..= U+0046 'F', or
1434 /// - U+0061 'a' ..= U+0066 'f'.
1439 /// let uppercase_a = 'A';
1440 /// let uppercase_g = 'G';
1444 /// let percent = '%';
1445 /// let space = ' ';
1447 /// let esc = '\x1b';
1449 /// assert!(uppercase_a.is_ascii_hexdigit());
1450 /// assert!(!uppercase_g.is_ascii_hexdigit());
1451 /// assert!(a.is_ascii_hexdigit());
1452 /// assert!(!g.is_ascii_hexdigit());
1453 /// assert!(zero.is_ascii_hexdigit());
1454 /// assert!(!percent.is_ascii_hexdigit());
1455 /// assert!(!space.is_ascii_hexdigit());
1456 /// assert!(!lf.is_ascii_hexdigit());
1457 /// assert!(!esc.is_ascii_hexdigit());
1460 #[stable(feature = "ascii_ctype_on_intrinsics
", since = "1.24.0")]
1461 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics
", since = "1.47.0")]
1463 pub const fn is_ascii_hexdigit(&self) -> bool {
1464 matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1467 /// Checks if the value is an ASCII punctuation character:
1469 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1470 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1471 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1472 /// - U+007B ..= U+007E `{ | } ~`
1477 /// let uppercase_a = 'A';
1478 /// let uppercase_g = 'G';
1482 /// let percent = '%';
1483 /// let space = ' ';
1485 /// let esc = '\x1b';
1487 /// assert!(!uppercase_a.is_ascii_punctuation());
1488 /// assert!(!uppercase_g.is_ascii_punctuation());
1489 /// assert!(!a.is_ascii_punctuation());
1490 /// assert!(!g.is_ascii_punctuation());
1491 /// assert!(!zero.is_ascii_punctuation());
1492 /// assert!(percent.is_ascii_punctuation());
1493 /// assert!(!space.is_ascii_punctuation());
1494 /// assert!(!lf.is_ascii_punctuation());
1495 /// assert!(!esc.is_ascii_punctuation());
1498 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1499 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1501 pub const fn is_ascii_punctuation(&self) -> bool
{
1502 matches
!(*self, '
!'
..='
/'
| '
:'
..='@'
| '
['
..='`'
| '
{'
..='
~'
)
1505 /// Checks if the value is an ASCII graphic character:
1506 /// U+0021 '!' ..= U+007E '~'.
1511 /// let uppercase_a = 'A';
1512 /// let uppercase_g = 'G';
1516 /// let percent = '%';
1517 /// let space = ' ';
1519 /// let esc = '\x1b';
1521 /// assert!(uppercase_a.is_ascii_graphic());
1522 /// assert!(uppercase_g.is_ascii_graphic());
1523 /// assert!(a.is_ascii_graphic());
1524 /// assert!(g.is_ascii_graphic());
1525 /// assert!(zero.is_ascii_graphic());
1526 /// assert!(percent.is_ascii_graphic());
1527 /// assert!(!space.is_ascii_graphic());
1528 /// assert!(!lf.is_ascii_graphic());
1529 /// assert!(!esc.is_ascii_graphic());
1532 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1533 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1535 pub const fn is_ascii_graphic(&self) -> bool
{
1536 matches
!(*self, '
!'
..='
~'
)
1539 /// Checks if the value is an ASCII whitespace character:
1540 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1541 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1543 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1544 /// whitespace][infra-aw]. There are several other definitions in
1545 /// wide use. For instance, [the POSIX locale][pct] includes
1546 /// U+000B VERTICAL TAB as well as all the above characters,
1547 /// but—from the very same specification—[the default rule for
1548 /// "field splitting" in the Bourne shell][bfs] considers *only*
1549 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1551 /// If you are writing a program that will process an existing
1552 /// file format, check what that format's definition of whitespace is
1553 /// before using this function.
1555 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1556 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1557 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1562 /// let uppercase_a = 'A';
1563 /// let uppercase_g = 'G';
1567 /// let percent = '%';
1568 /// let space = ' ';
1570 /// let esc = '\x1b';
1572 /// assert!(!uppercase_a.is_ascii_whitespace());
1573 /// assert!(!uppercase_g.is_ascii_whitespace());
1574 /// assert!(!a.is_ascii_whitespace());
1575 /// assert!(!g.is_ascii_whitespace());
1576 /// assert!(!zero.is_ascii_whitespace());
1577 /// assert!(!percent.is_ascii_whitespace());
1578 /// assert!(space.is_ascii_whitespace());
1579 /// assert!(lf.is_ascii_whitespace());
1580 /// assert!(!esc.is_ascii_whitespace());
1583 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1584 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1586 pub const fn is_ascii_whitespace(&self) -> bool
{
1587 matches
!(*self, '
\t'
| '
\n'
| '
\x0C'
| '
\r'
| ' '
)
1590 /// Checks if the value is an ASCII control character:
1591 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1592 /// Note that most ASCII whitespace characters are control
1593 /// characters, but SPACE is not.
1598 /// let uppercase_a = 'A';
1599 /// let uppercase_g = 'G';
1603 /// let percent = '%';
1604 /// let space = ' ';
1606 /// let esc = '\x1b';
1608 /// assert!(!uppercase_a.is_ascii_control());
1609 /// assert!(!uppercase_g.is_ascii_control());
1610 /// assert!(!a.is_ascii_control());
1611 /// assert!(!g.is_ascii_control());
1612 /// assert!(!zero.is_ascii_control());
1613 /// assert!(!percent.is_ascii_control());
1614 /// assert!(!space.is_ascii_control());
1615 /// assert!(lf.is_ascii_control());
1616 /// assert!(esc.is_ascii_control());
1619 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1620 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1622 pub const fn is_ascii_control(&self) -> bool
{
1623 matches
!(*self, '
\0'
..='
\x1F'
| '
\x7F'
)
1627 pub(crate) struct EscapeDebugExtArgs
{
1628 /// Escape Extended Grapheme codepoints?
1629 pub(crate) escape_grapheme_extended
: bool
,
1631 /// Escape single quotes?
1632 pub(crate) escape_single_quote
: bool
,
1634 /// Escape double quotes?
1635 pub(crate) escape_double_quote
: bool
,
1638 impl EscapeDebugExtArgs
{
1639 pub(crate) const ESCAPE_ALL
: Self = Self {
1640 escape_grapheme_extended
: true,
1641 escape_single_quote
: true,
1642 escape_double_quote
: true,
1647 const fn len_utf8(code
: u32) -> usize {
1648 if code
< MAX_ONE_B
{
1650 } else if code
< MAX_TWO_B
{
1652 } else if code
< MAX_THREE_B
{
1659 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1660 /// and then returns the subslice of the buffer that contains the encoded character.
1662 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1663 /// (Creating a `char` in the surrogate range is UB.)
1664 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1666 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1670 /// Panics if the buffer is not large enough.
1671 /// A buffer of length four is large enough to encode any `char`.
1672 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1675 pub fn encode_utf8_raw(code
: u32, dst
: &mut [u8]) -> &mut [u8] {
1676 let len
= len_utf8(code
);
1677 match (len
, &mut dst
[..]) {
1681 (2, [a
, b
, ..]) => {
1682 *a
= (code
>> 6 & 0x1F) as u8 | TAG_TWO_B
;
1683 *b
= (code
& 0x3F) as u8 | TAG_CONT
;
1685 (3, [a
, b
, c
, ..]) => {
1686 *a
= (code
>> 12 & 0x0F) as u8 | TAG_THREE_B
;
1687 *b
= (code
>> 6 & 0x3F) as u8 | TAG_CONT
;
1688 *c
= (code
& 0x3F) as u8 | TAG_CONT
;
1690 (4, [a
, b
, c
, d
, ..]) => {
1691 *a
= (code
>> 18 & 0x07) as u8 | TAG_FOUR_B
;
1692 *b
= (code
>> 12 & 0x3F) as u8 | TAG_CONT
;
1693 *c
= (code
>> 6 & 0x3F) as u8 | TAG_CONT
;
1694 *d
= (code
& 0x3F) as u8 | TAG_CONT
;
1697 "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1706 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1707 /// and then returns the subslice of the buffer that contains the encoded character.
1709 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1710 /// (Creating a `char` in the surrogate range is UB.)
1714 /// Panics if the buffer is not large enough.
1715 /// A buffer of length 2 is large enough to encode any `char`.
1716 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1719 pub fn encode_utf16_raw(mut code
: u32, dst
: &mut [u16]) -> &mut [u16] {
1720 // SAFETY: each arm checks whether there are enough bits to write into
1722 if (code
& 0xFFFF) == code
&& !dst
.is_empty() {
1723 // The BMP falls through
1724 *dst
.get_unchecked_mut(0) = code
as u16;
1725 slice
::from_raw_parts_mut(dst
.as_mut_ptr(), 1)
1726 } else if dst
.len() >= 2 {
1727 // Supplementary planes break into surrogates.
1729 *dst
.get_unchecked_mut(0) = 0xD800 | ((code
>> 10) as u16);
1730 *dst
.get_unchecked_mut(1) = 0xDC00 | ((code
as u16) & 0x3FF);
1731 slice
::from_raw_parts_mut(dst
.as_mut_ptr(), 2)
1734 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1735 from_u32_unchecked(code
).len_utf16(),