4 use crate::str::from_utf8_unchecked_mut;
5 use crate::unicode::printable::is_printable;
6 use crate::unicode::{self, conversions};
12 /// Checks if a `char` is a digit in the given radix.
14 /// A 'radix' here is sometimes also called a 'base'. A radix of two
15 /// indicates a binary number, a radix of ten, decimal, and a radix of
16 /// sixteen, hexadecimal, to give some common values. Arbitrary
17 /// radices are supported.
19 /// Compared to `is_numeric()`, this function only recognizes the characters
20 /// `0-9`, `a-z` and `A-Z`.
22 /// 'Digit' is defined to be only the following characters:
28 /// For a more comprehensive understanding of 'digit', see [`is_numeric`][is_numeric].
30 /// [is_numeric]: #method.is_numeric
34 /// Panics if given a radix larger than 36.
41 /// assert!('1'.is_digit(10));
42 /// assert!('f'.is_digit(16));
43 /// assert!(!'f'.is_digit(10));
46 /// Passing a large radix, causing a panic:
51 /// let result = thread::spawn(|| {
56 /// assert!(result.is_err());
58 #[stable(feature = "rust1", since = "1.0.0")]
60 pub fn is_digit(self, radix: u32) -> bool {
61 self.to_digit(radix).is_some()
64 /// Converts a `char` to a digit in the given radix.
66 /// A 'radix' here is sometimes also called a 'base'. A radix of two
67 /// indicates a binary number, a radix of ten, decimal, and a radix of
68 /// sixteen, hexadecimal, to give some common values. Arbitrary
69 /// radices are supported.
71 /// 'Digit' is defined to be only the following characters:
79 /// Returns `None` if the `char` does not refer to a digit in the given radix.
83 /// Panics if given a radix larger than 36.
90 /// assert_eq!('1'.to_digit(10), Some(1));
91 /// assert_eq!('f'.to_digit(16), Some(15));
94 /// Passing a non-digit results in failure:
97 /// assert_eq!('f'.to_digit(10), None);
98 /// assert_eq!('z'.to_digit(16), None);
101 /// Passing a large radix, causing a panic:
106 /// let result = thread::spawn(|| {
107 /// '1'.to_digit(37);
110 /// assert!(result.is_err());
112 #[stable(feature = "rust1", since = "1.0.0")]
114 pub fn to_digit(self, radix: u32) -> Option<u32> {
115 assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
117 // the code is split up here to improve execution speed for cases where
118 // the `radix` is constant and 10 or smaller
119 let val = if radix <= 10 {
121 '0'..='9' => self as u32 - '0' as u32,
126 '0'..='9' => self as u32 - '0' as u32,
127 'a'..='z' => self as u32 - 'a' as u32 + 10,
128 'A'..='Z' => self as u32 - 'A' as u32 + 10,
133 if val < radix { Some(val) } else { None }
136 /// Returns an iterator that yields the hexadecimal Unicode escape of a
137 /// character as `char`s.
139 /// This will escape characters with the Rust syntax of the form
140 /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
147 /// for c in '❤'.escape_unicode() {
153 /// Using `println!` directly:
156 /// println!("{}", '❤'.escape_unicode());
159 /// Both are equivalent to:
162 /// println!("\\u{{2764}}");
165 /// Using `to_string`:
168 /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
170 #[stable(feature = "rust1", since = "1.0.0")]
172 pub fn escape_unicode(self) -> EscapeUnicode {
175 // or-ing 1 ensures that for c==0 the code computes that one
176 // digit should be printed and (which is the same) avoids the
177 // (31 - 32) underflow
178 let msb = 31 - (c | 1).leading_zeros();
180 // the index of the most significant hex digit
181 let ms_hex_digit = msb / 4;
184 state: EscapeUnicodeState::Backslash,
185 hex_digit_idx: ms_hex_digit as usize,
189 /// An extended version of `escape_debug` that optionally permits escaping
190 /// Extended Grapheme codepoints. This allows us to format characters like
191 /// nonspacing marks better when they're at the start of a string.
193 pub(crate) fn escape_debug_ext(self, escape_grapheme_extended: bool) -> EscapeDebug {
194 let init_state = match self {
195 '\t' => EscapeDefaultState::Backslash('t'),
196 '\r' => EscapeDefaultState::Backslash('r'),
197 '\n' => EscapeDefaultState::Backslash('n'),
198 '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
199 _ if escape_grapheme_extended && self.is_grapheme_extended() => {
200 EscapeDefaultState::Unicode(self.escape_unicode())
202 _ if is_printable(self) => EscapeDefaultState::Char(self),
203 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
205 EscapeDebug(EscapeDefault { state: init_state })
208 /// Returns an iterator that yields the literal escape code of a character
211 /// This will escape the characters similar to the `Debug` implementations
212 /// of `str` or `char`.
219 /// for c in '\n'.escape_debug() {
225 /// Using `println!` directly:
228 /// println!("{}", '\n'.escape_debug());
231 /// Both are equivalent to:
237 /// Using `to_string`:
240 /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
242 #[stable(feature = "char_escape_debug", since = "1.20.0")]
244 pub fn escape_debug(self) -> EscapeDebug {
245 self.escape_debug_ext(true)
248 /// Returns an iterator that yields the literal escape code of a character
251 /// The default is chosen with a bias toward producing literals that are
252 /// legal in a variety of languages, including C++11 and similar C-family
253 /// languages. The exact rules are:
255 /// * Tab is escaped as `\t`.
256 /// * Carriage return is escaped as `\r`.
257 /// * Line feed is escaped as `\n`.
258 /// * Single quote is escaped as `\'`.
259 /// * Double quote is escaped as `\"`.
260 /// * Backslash is escaped as `\\`.
261 /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
262 /// inclusive is not escaped.
263 /// * All other characters are given hexadecimal Unicode escapes; see
264 /// [`escape_unicode`][escape_unicode].
266 /// [escape_unicode]: #method.escape_unicode
273 /// for c in '"'.escape_default() {
279 /// Using `println!` directly:
282 /// println!("{}", '"'.escape_default());
286 /// Both are equivalent to:
289 /// println!("\\\"");
292 /// Using `to_string`:
295 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
297 #[stable(feature = "rust1", since = "1.0.0")]
299 pub fn escape_default(self) -> EscapeDefault {
300 let init_state = match self {
301 '\t' => EscapeDefaultState::Backslash('t'),
302 '\r' => EscapeDefaultState::Backslash('r'),
303 '\n' => EscapeDefaultState::Backslash('n'),
304 '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
305 '\x20'..='\x7e' => EscapeDefaultState::Char(self),
306 _ => EscapeDefaultState::Unicode(self.escape_unicode()),
308 EscapeDefault { state: init_state }
311 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
313 /// That number of bytes is always between 1 and 4, inclusive.
320 /// let len = 'A'.len_utf8();
321 /// assert_eq!(len, 1);
323 /// let len = 'ß'.len_utf8();
324 /// assert_eq!(len, 2);
326 /// let len = 'ℝ'.len_utf8();
327 /// assert_eq!(len, 3);
329 /// let len = '💣'.len_utf8();
330 /// assert_eq!(len, 4);
333 /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
334 /// would take if each code point was represented as a `char` vs in the `&str` itself:
338 /// let eastern = '東';
339 /// let capital = '京';
341 /// // both can be represented as three bytes
342 /// assert_eq!(3, eastern.len_utf8());
343 /// assert_eq!(3, capital.len_utf8());
345 /// // as a &str, these two are encoded in UTF-8
346 /// let tokyo = "東京";
348 /// let len = eastern.len_utf8() + capital.len_utf8();
350 /// // we can see that they take six bytes total...
351 /// assert_eq!(6, tokyo.len());
353 /// // ... just like the &str
354 /// assert_eq!(len, tokyo.len());
356 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn len_utf8(self) -> usize {
359 let code = self as u32;
360 if code < MAX_ONE_B {
362 } else if code < MAX_TWO_B {
364 } else if code < MAX_THREE_B {
371 /// Returns the number of 16-bit code units this `char` would need if
372 /// encoded in UTF-16.
374 /// See the documentation for [`len_utf8`] for more explanation of this
375 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
377 /// [`len_utf8`]: #method.len_utf8
384 /// let n = 'ß'.len_utf16();
385 /// assert_eq!(n, 1);
387 /// let len = '💣'.len_utf16();
388 /// assert_eq!(len, 2);
390 #[stable(feature = "rust1", since = "1.0.0")]
392 pub fn len_utf16(self) -> usize {
393 let ch = self as u32;
394 if (ch & 0xFFFF) == ch { 1 } else { 2 }
397 /// Encodes this character as UTF-8 into the provided byte buffer,
398 /// and then returns the subslice of the buffer that contains the encoded character.
402 /// Panics if the buffer is not large enough.
403 /// A buffer of length four is large enough to encode any `char`.
407 /// In both of these examples, 'ß' takes two bytes to encode.
410 /// let mut b = [0; 2];
412 /// let result = 'ß'.encode_utf8(&mut b);
414 /// assert_eq!(result, "ß");
416 /// assert_eq!(result.len(), 2);
419 /// A buffer that's too small:
424 /// let result = thread::spawn(|| {
425 /// let mut b = [0; 1];
428 /// 'ß'.encode_utf8(&mut b);
431 /// assert!(result.is_err());
433 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
435 pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
436 let code = self as u32;
437 let len = self.len_utf8();
438 match (len, &mut dst[..]) {
443 *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
444 *b = (code & 0x3F) as u8 | TAG_CONT;
446 (3, [a, b, c, ..]) => {
447 *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
448 *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
449 *c = (code & 0x3F) as u8 | TAG_CONT;
451 (4, [a, b, c, d, ..]) => {
452 *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
453 *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
454 *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
455 *d = (code & 0x3F) as u8 | TAG_CONT;
458 "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
464 // SAFETY: We just wrote UTF-8 content in, so converting to str is fine.
465 unsafe { from_utf8_unchecked_mut(&mut dst[..len]) }
468 /// Encodes this character as UTF-16 into the provided `u16` buffer,
469 /// and then returns the subslice of the buffer that contains the encoded character.
473 /// Panics if the buffer is not large enough.
474 /// A buffer of length 2 is large enough to encode any `char`.
478 /// In both of these examples, '𝕊' takes two `u16`s to encode.
481 /// let mut b = [0; 2];
483 /// let result = '𝕊'.encode_utf16(&mut b);
485 /// assert_eq!(result.len(), 2);
488 /// A buffer that's too small:
493 /// let result = thread::spawn(|| {
494 /// let mut b = [0; 1];
497 /// '𝕊'.encode_utf16(&mut b);
500 /// assert!(result.is_err());
502 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
504 pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
505 let mut code = self as u32;
506 // SAFETY: each arm checks whether there are enough bits to write into
508 if (code & 0xFFFF) == code && !dst.is_empty() {
509 // The BMP falls through (assuming non-surrogate, as it should)
510 *dst.get_unchecked_mut(0) = code as u16;
511 slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
512 } else if dst.len() >= 2 {
513 // Supplementary planes break into surrogates.
515 *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
516 *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
517 slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
520 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
521 from_u32_unchecked(code).len_utf16(),
529 /// Returns `true` if this `char` has the `Alphabetic` property.
531 /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
532 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
534 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
535 /// [ucd]: https://www.unicode.org/reports/tr44/
536 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
543 /// assert!('a'.is_alphabetic());
544 /// assert!('京'.is_alphabetic());
547 /// // love is many things, but it is not alphabetic
548 /// assert!(!c.is_alphabetic());
550 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn is_alphabetic(self) -> bool {
554 'a'..='z' | 'A'..='Z' => true,
555 c => c > '\x7f' && unicode::Alphabetic(c),
559 /// Returns `true` if this `char` has the `Lowercase` property.
561 /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
562 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
564 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
565 /// [ucd]: https://www.unicode.org/reports/tr44/
566 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
573 /// assert!('a'.is_lowercase());
574 /// assert!('δ'.is_lowercase());
575 /// assert!(!'A'.is_lowercase());
576 /// assert!(!'Δ'.is_lowercase());
578 /// // The various Chinese scripts and punctuation do not have case, and so:
579 /// assert!(!'中'.is_lowercase());
580 /// assert!(!' '.is_lowercase());
582 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn is_lowercase(self) -> bool {
587 c => c > '\x7f' && unicode::Lowercase(c),
591 /// Returns `true` if this `char` has the `Uppercase` property.
593 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
594 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
596 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
597 /// [ucd]: https://www.unicode.org/reports/tr44/
598 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
605 /// assert!(!'a'.is_uppercase());
606 /// assert!(!'δ'.is_uppercase());
607 /// assert!('A'.is_uppercase());
608 /// assert!('Δ'.is_uppercase());
610 /// // The various Chinese scripts and punctuation do not have case, and so:
611 /// assert!(!'中'.is_uppercase());
612 /// assert!(!' '.is_uppercase());
614 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn is_uppercase(self) -> bool {
619 c => c > '\x7f' && unicode::Uppercase(c),
623 /// Returns `true` if this `char` has the `White_Space` property.
625 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
627 /// [ucd]: https://www.unicode.org/reports/tr44/
628 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
635 /// assert!(' '.is_whitespace());
637 /// // a non-breaking space
638 /// assert!('\u{A0}'.is_whitespace());
640 /// assert!(!'越'.is_whitespace());
642 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn is_whitespace(self) -> bool {
646 ' ' | '\x09'..='\x0d' => true,
647 c => c > '\x7f' && unicode::White_Space(c),
651 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
653 /// [`is_alphabetic()`]: #method.is_alphabetic
654 /// [`is_numeric()`]: #method.is_numeric
661 /// assert!('٣'.is_alphanumeric());
662 /// assert!('7'.is_alphanumeric());
663 /// assert!('৬'.is_alphanumeric());
664 /// assert!('¾'.is_alphanumeric());
665 /// assert!('①'.is_alphanumeric());
666 /// assert!('K'.is_alphanumeric());
667 /// assert!('و'.is_alphanumeric());
668 /// assert!('藏'.is_alphanumeric());
670 #[stable(feature = "rust1", since = "1.0.0")]
672 pub fn is_alphanumeric(self) -> bool {
673 self.is_alphabetic() || self.is_numeric()
676 /// Returns `true` if this `char` has the general category for control codes.
678 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
679 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
680 /// Database][ucd] [`UnicodeData.txt`].
682 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
683 /// [ucd]: https://www.unicode.org/reports/tr44/
684 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
691 /// // U+009C, STRING TERMINATOR
692 /// assert!('
\9c'.is_control());
693 /// assert!(!'q'.is_control());
695 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn is_control(self) -> bool {
701 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
703 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
704 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
705 /// [`DerivedCoreProperties.txt`].
707 /// [uax29]: https://www.unicode.org/reports/tr29/
708 /// [ucd]: https://www.unicode.org/reports/tr44/
709 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
711 pub(crate) fn is_grapheme_extended(self) -> bool {
712 unicode::Grapheme_Extend(self)
715 /// Returns `true` if this `char` has one of the general categories for numbers.
717 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
718 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
719 /// Database][ucd] [`UnicodeData.txt`].
721 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
722 /// [ucd]: https://www.unicode.org/reports/tr44/
723 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
730 /// assert!('٣'.is_numeric());
731 /// assert!('7'.is_numeric());
732 /// assert!('৬'.is_numeric());
733 /// assert!('¾'.is_numeric());
734 /// assert!('①'.is_numeric());
735 /// assert!(!'K'.is_numeric());
736 /// assert!(!'و'.is_numeric());
737 /// assert!(!'藏'.is_numeric());
739 #[stable(feature = "rust1", since = "1.0.0")]
741 pub fn is_numeric(self) -> bool {
744 c => c > '\x7f' && unicode::N(c),
748 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
751 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
753 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
754 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
756 /// [ucd]: https://www.unicode.org/reports/tr44/
757 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
759 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
760 /// the `char`(s) given by [`SpecialCasing.txt`].
762 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
764 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
765 /// is independent of context and language.
767 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
768 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
770 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
777 /// for c in 'İ'.to_lowercase() {
783 /// Using `println!` directly:
786 /// println!("{}", 'İ'.to_lowercase());
789 /// Both are equivalent to:
792 /// println!("i\u{307}");
795 /// Using `to_string`:
798 /// assert_eq!('C'.to_lowercase().to_string(), "c");
800 /// // Sometimes the result is more than one character:
801 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
803 /// // Characters that do not have both uppercase and lowercase
804 /// // convert into themselves.
805 /// assert_eq!('山'.to_lowercase().to_string(), "山");
807 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn to_lowercase(self) -> ToLowercase {
810 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
813 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
816 /// If this `char` does not have a uppercase mapping, the iterator yields the same `char`.
818 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
819 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
821 /// [ucd]: https://www.unicode.org/reports/tr44/
822 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
824 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
825 /// the `char`(s) given by [`SpecialCasing.txt`].
827 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
829 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
830 /// is independent of context and language.
832 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
833 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
835 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
842 /// for c in 'ß'.to_uppercase() {
848 /// Using `println!` directly:
851 /// println!("{}", 'ß'.to_uppercase());
854 /// Both are equivalent to:
860 /// Using `to_string`:
863 /// assert_eq!('c'.to_uppercase().to_string(), "C");
865 /// // Sometimes the result is more than one character:
866 /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
868 /// // Characters that do not have both uppercase and lowercase
869 /// // convert into themselves.
870 /// assert_eq!('山'.to_uppercase().to_string(), "山");
875 /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
877 /// * 'Dotless': I / ı, sometimes written ï
878 /// * 'Dotted': İ / i
880 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
883 /// let upper_i = 'i'.to_uppercase().to_string();
886 /// The value of `upper_i` here relies on the language of the text: if we're
887 /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
888 /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
891 /// let upper_i = 'i'.to_uppercase().to_string();
893 /// assert_eq!(upper_i, "I");
896 /// holds across languages.
897 #[stable(feature = "rust1", since = "1.0.0")]
899 pub fn to_uppercase(self) -> ToUppercase {
900 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
903 /// Checks if the value is within the ASCII range.
909 /// let non_ascii = '❤';
911 /// assert!(ascii.is_ascii());
912 /// assert!(!non_ascii.is_ascii());
914 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
915 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.32.0")]
917 pub const fn is_ascii(&self) -> bool {
921 /// Makes a copy of the value in its ASCII upper case equivalent.
923 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
924 /// but non-ASCII letters are unchanged.
926 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
928 /// To uppercase ASCII characters in addition to non-ASCII characters, use
929 /// [`to_uppercase`].
935 /// let non_ascii = '❤';
937 /// assert_eq!('A', ascii.to_ascii_uppercase());
938 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
941 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
942 /// [`to_uppercase`]: #method.to_uppercase
943 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
945 pub fn to_ascii_uppercase(&self) -> char {
946 if self.is_ascii() { (*self as u8).to_ascii_uppercase() as char } else { *self }
949 /// Makes a copy of the value in its ASCII lower case equivalent.
951 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
952 /// but non-ASCII letters are unchanged.
954 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
956 /// To lowercase ASCII characters in addition to non-ASCII characters, use
957 /// [`to_lowercase`].
963 /// let non_ascii = '❤';
965 /// assert_eq!('a', ascii.to_ascii_lowercase());
966 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
969 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
970 /// [`to_lowercase`]: #method.to_lowercase
971 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
973 pub fn to_ascii_lowercase(&self) -> char {
974 if self.is_ascii() { (*self as u8).to_ascii_lowercase() as char } else { *self }
977 /// Checks that two values are an ASCII case-insensitive match.
979 /// Equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
984 /// let upper_a = 'A';
985 /// let lower_a = 'a';
986 /// let lower_z = 'z';
988 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
989 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
990 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
992 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
994 pub fn eq_ignore_ascii_case(&self, other: &char) -> bool {
995 self.to_ascii_lowercase() == other.to_ascii_lowercase()
998 /// Converts this type to its ASCII upper case equivalent in-place.
1000 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1001 /// but non-ASCII letters are unchanged.
1003 /// To return a new uppercased value without modifying the existing one, use
1004 /// [`to_ascii_uppercase`].
1009 /// let mut ascii = 'a';
1011 /// ascii.make_ascii_uppercase();
1013 /// assert_eq!('A', ascii);
1016 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
1017 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1019 pub fn make_ascii_uppercase(&mut self) {
1020 *self = self.to_ascii_uppercase();
1023 /// Converts this type to its ASCII lower case equivalent in-place.
1025 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1026 /// but non-ASCII letters are unchanged.
1028 /// To return a new lowercased value without modifying the existing one, use
1029 /// [`to_ascii_lowercase`].
1034 /// let mut ascii = 'A';
1036 /// ascii.make_ascii_lowercase();
1038 /// assert_eq!('a', ascii);
1041 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
1042 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1044 pub fn make_ascii_lowercase(&mut self) {
1045 *self = self.to_ascii_lowercase();
1048 /// Checks if the value is an ASCII alphabetic character:
1050 /// - U+0041 'A' ..= U+005A 'Z', or
1051 /// - U+0061 'a' ..= U+007A 'z'.
1056 /// let uppercase_a = 'A';
1057 /// let uppercase_g = 'G';
1061 /// let percent = '%';
1062 /// let space = ' ';
1064 /// let esc: char = 0x1b_u8.into();
1066 /// assert!(uppercase_a.is_ascii_alphabetic());
1067 /// assert!(uppercase_g.is_ascii_alphabetic());
1068 /// assert!(a.is_ascii_alphabetic());
1069 /// assert!(g.is_ascii_alphabetic());
1070 /// assert!(!zero.is_ascii_alphabetic());
1071 /// assert!(!percent.is_ascii_alphabetic());
1072 /// assert!(!space.is_ascii_alphabetic());
1073 /// assert!(!lf.is_ascii_alphabetic());
1074 /// assert!(!esc.is_ascii_alphabetic());
1076 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1077 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1079 pub const fn is_ascii_alphabetic(&self) -> bool {
1081 'A'..='Z' | 'a'..='z' => true,
1086 /// Checks if the value is an ASCII uppercase character:
1087 /// U+0041 'A' ..= U+005A 'Z'.
1092 /// let uppercase_a = 'A';
1093 /// let uppercase_g = 'G';
1097 /// let percent = '%';
1098 /// let space = ' ';
1100 /// let esc: char = 0x1b_u8.into();
1102 /// assert!(uppercase_a.is_ascii_uppercase());
1103 /// assert!(uppercase_g.is_ascii_uppercase());
1104 /// assert!(!a.is_ascii_uppercase());
1105 /// assert!(!g.is_ascii_uppercase());
1106 /// assert!(!zero.is_ascii_uppercase());
1107 /// assert!(!percent.is_ascii_uppercase());
1108 /// assert!(!space.is_ascii_uppercase());
1109 /// assert!(!lf.is_ascii_uppercase());
1110 /// assert!(!esc.is_ascii_uppercase());
1112 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1113 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1115 pub const fn is_ascii_uppercase(&self) -> bool {
1122 /// Checks if the value is an ASCII lowercase character:
1123 /// U+0061 'a' ..= U+007A 'z'.
1128 /// let uppercase_a = 'A';
1129 /// let uppercase_g = 'G';
1133 /// let percent = '%';
1134 /// let space = ' ';
1136 /// let esc: char = 0x1b_u8.into();
1138 /// assert!(!uppercase_a.is_ascii_lowercase());
1139 /// assert!(!uppercase_g.is_ascii_lowercase());
1140 /// assert!(a.is_ascii_lowercase());
1141 /// assert!(g.is_ascii_lowercase());
1142 /// assert!(!zero.is_ascii_lowercase());
1143 /// assert!(!percent.is_ascii_lowercase());
1144 /// assert!(!space.is_ascii_lowercase());
1145 /// assert!(!lf.is_ascii_lowercase());
1146 /// assert!(!esc.is_ascii_lowercase());
1148 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1149 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1151 pub const fn is_ascii_lowercase(&self) -> bool {
1158 /// Checks if the value is an ASCII alphanumeric character:
1160 /// - U+0041 'A' ..= U+005A 'Z', or
1161 /// - U+0061 'a' ..= U+007A 'z', or
1162 /// - U+0030 '0' ..= U+0039 '9'.
1167 /// let uppercase_a = 'A';
1168 /// let uppercase_g = 'G';
1172 /// let percent = '%';
1173 /// let space = ' ';
1175 /// let esc: char = 0x1b_u8.into();
1177 /// assert!(uppercase_a.is_ascii_alphanumeric());
1178 /// assert!(uppercase_g.is_ascii_alphanumeric());
1179 /// assert!(a.is_ascii_alphanumeric());
1180 /// assert!(g.is_ascii_alphanumeric());
1181 /// assert!(zero.is_ascii_alphanumeric());
1182 /// assert!(!percent.is_ascii_alphanumeric());
1183 /// assert!(!space.is_ascii_alphanumeric());
1184 /// assert!(!lf.is_ascii_alphanumeric());
1185 /// assert!(!esc.is_ascii_alphanumeric());
1187 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1188 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1190 pub const fn is_ascii_alphanumeric(&self) -> bool {
1192 '0'..='9' | 'A'..='Z' | 'a'..='z' => true,
1197 /// Checks if the value is an ASCII decimal digit:
1198 /// U+0030 '0' ..= U+0039 '9'.
1203 /// let uppercase_a = 'A';
1204 /// let uppercase_g = 'G';
1208 /// let percent = '%';
1209 /// let space = ' ';
1211 /// let esc: char = 0x1b_u8.into();
1213 /// assert!(!uppercase_a.is_ascii_digit());
1214 /// assert!(!uppercase_g.is_ascii_digit());
1215 /// assert!(!a.is_ascii_digit());
1216 /// assert!(!g.is_ascii_digit());
1217 /// assert!(zero.is_ascii_digit());
1218 /// assert!(!percent.is_ascii_digit());
1219 /// assert!(!space.is_ascii_digit());
1220 /// assert!(!lf.is_ascii_digit());
1221 /// assert!(!esc.is_ascii_digit());
1223 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1224 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1226 pub const fn is_ascii_digit(&self) -> bool {
1233 /// Checks if the value is an ASCII hexadecimal digit:
1235 /// - U+0030 '0' ..= U+0039 '9', or
1236 /// - U+0041 'A' ..= U+0046 'F', or
1237 /// - U+0061 'a' ..= U+0066 'f'.
1242 /// let uppercase_a = 'A';
1243 /// let uppercase_g = 'G';
1247 /// let percent = '%';
1248 /// let space = ' ';
1250 /// let esc: char = 0x1b_u8.into();
1252 /// assert!(uppercase_a.is_ascii_hexdigit());
1253 /// assert!(!uppercase_g.is_ascii_hexdigit());
1254 /// assert!(a.is_ascii_hexdigit());
1255 /// assert!(!g.is_ascii_hexdigit());
1256 /// assert!(zero.is_ascii_hexdigit());
1257 /// assert!(!percent.is_ascii_hexdigit());
1258 /// assert!(!space.is_ascii_hexdigit());
1259 /// assert!(!lf.is_ascii_hexdigit());
1260 /// assert!(!esc.is_ascii_hexdigit());
1262 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1263 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1265 pub const fn is_ascii_hexdigit(&self) -> bool {
1267 '0'..='9' | 'A'..='F' | 'a'..='f' => true,
1272 /// Checks if the value is an ASCII punctuation character:
1274 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1275 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1276 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1277 /// - U+007B ..= U+007E `{ | } ~`
1282 /// let uppercase_a = 'A';
1283 /// let uppercase_g = 'G';
1287 /// let percent = '%';
1288 /// let space = ' ';
1290 /// let esc: char = 0x1b_u8.into();
1292 /// assert!(!uppercase_a.is_ascii_punctuation());
1293 /// assert!(!uppercase_g.is_ascii_punctuation());
1294 /// assert!(!a.is_ascii_punctuation());
1295 /// assert!(!g.is_ascii_punctuation());
1296 /// assert!(!zero.is_ascii_punctuation());
1297 /// assert!(percent.is_ascii_punctuation());
1298 /// assert!(!space.is_ascii_punctuation());
1299 /// assert!(!lf.is_ascii_punctuation());
1300 /// assert!(!esc.is_ascii_punctuation());
1302 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1303 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1305 pub const fn is_ascii_punctuation(&self) -> bool {
1307 '!'..='/' | ':'..='@' | '['..='`' | '{'..='~' => true,
1312 /// Checks if the value is an ASCII graphic character:
1313 /// U+0021 '!' ..= U+007E '~'.
1318 /// let uppercase_a = 'A';
1319 /// let uppercase_g = 'G';
1323 /// let percent = '%';
1324 /// let space = ' ';
1326 /// let esc: char = 0x1b_u8.into();
1328 /// assert!(uppercase_a.is_ascii_graphic());
1329 /// assert!(uppercase_g.is_ascii_graphic());
1330 /// assert!(a.is_ascii_graphic());
1331 /// assert!(g.is_ascii_graphic());
1332 /// assert!(zero.is_ascii_graphic());
1333 /// assert!(percent.is_ascii_graphic());
1334 /// assert!(!space.is_ascii_graphic());
1335 /// assert!(!lf.is_ascii_graphic());
1336 /// assert!(!esc.is_ascii_graphic());
1338 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1339 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1341 pub const fn is_ascii_graphic(&self) -> bool {
1348 /// Checks if the value is an ASCII whitespace character:
1349 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1350 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1352 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1353 /// whitespace][infra-aw]. There are several other definitions in
1354 /// wide use. For instance, [the POSIX locale][pct] includes
1355 /// U+000B VERTICAL TAB as well as all the above characters,
1356 /// but—from the very same specification—[the default rule for
1357 /// "field splitting" in the Bourne shell][bfs] considers *only*
1358 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1360 /// If you are writing a program that will process an existing
1361 /// file format, check what that format's definition of whitespace is
1362 /// before using this function.
1364 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1365 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1366 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1371 /// let uppercase_a = 'A';
1372 /// let uppercase_g = 'G';
1376 /// let percent = '%';
1377 /// let space = ' ';
1379 /// let esc: char = 0x1b_u8.into();
1381 /// assert!(!uppercase_a.is_ascii_whitespace());
1382 /// assert!(!uppercase_g.is_ascii_whitespace());
1383 /// assert!(!a.is_ascii_whitespace());
1384 /// assert!(!g.is_ascii_whitespace());
1385 /// assert!(!zero.is_ascii_whitespace());
1386 /// assert!(!percent.is_ascii_whitespace());
1387 /// assert!(space.is_ascii_whitespace());
1388 /// assert!(lf.is_ascii_whitespace());
1389 /// assert!(!esc.is_ascii_whitespace());
1391 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1392 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1394 pub const fn is_ascii_whitespace(&self) -> bool {
1396 '\t' | '\n' | '\x0C' | '\r' | ' ' => true,
1401 /// Checks if the value is an ASCII control character:
1402 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1403 /// Note that most ASCII whitespace characters are control
1404 /// characters, but SPACE is not.
1409 /// let uppercase_a = 'A';
1410 /// let uppercase_g = 'G';
1414 /// let percent = '%';
1415 /// let space = ' ';
1417 /// let esc: char = 0x1b_u8.into();
1419 /// assert!(!uppercase_a.is_ascii_control());
1420 /// assert!(!uppercase_g.is_ascii_control());
1421 /// assert!(!a.is_ascii_control());
1422 /// assert!(!g.is_ascii_control());
1423 /// assert!(!zero.is_ascii_control());
1424 /// assert!(!percent.is_ascii_control());
1425 /// assert!(!space.is_ascii_control());
1426 /// assert!(lf.is_ascii_control());
1427 /// assert!(esc.is_ascii_control());
1429 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1430 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1432 pub const fn is_ascii_control(&self) -> bool {
1434 '\0'..='\x1F' | '\x7F' => true,