| //! impl char {} | |
| #![expect(clippy::manual_is_ascii_check, reason = "this module implements various is_ascii checks")] | |
| use super::*; | |
| use crate::panic::const_panic; | |
| use crate::slice; | |
| use crate::str::from_utf8_unchecked_mut; | |
| use crate::ub_checks::assert_unsafe_precondition; | |
| use crate::unicode::{self, conversions}; | |
| impl char { | |
| /// The lowest valid code point a `char` can have, `'\0'`. | |
| /// | |
| /// Unlike integer types, `char` actually has a gap in the middle, | |
| /// meaning that the range of possible `char`s is smaller than you | |
| /// might expect. Ranges of `char` will automatically hop this gap | |
| /// for you: | |
| /// | |
| /// ``` | |
| /// let dist = u32::from(char::MAX) - u32::from(char::MIN); | |
| /// let size = (char::MIN..=char::MAX).count() as u32; | |
| /// assert!(size < dist); | |
| /// ``` | |
| /// | |
| /// Despite this gap, the `MIN` and [`MAX`] values can be used as bounds for | |
| /// all `char` values. | |
| /// | |
| /// [`MAX`]: char::MAX | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// # fn something_which_returns_char() -> char { 'a' } | |
| /// let c: char = something_which_returns_char(); | |
| /// assert!(char::MIN <= c); | |
| /// | |
| /// let value_at_min = u32::from(char::MIN); | |
| /// assert_eq!(char::from_u32(value_at_min), Some('\0')); | |
| /// ``` | |
| #[stable(feature = "char_min", since = "1.83.0")] | |
| pub const MIN: char = '\0'; | |
| /// The highest valid code point a `char` can have, `'\u{10FFFF}'`. | |
| /// | |
| /// Unlike integer types, `char` actually has a gap in the middle, | |
| /// meaning that the range of possible `char`s is smaller than you | |
| /// might expect. Ranges of `char` will automatically hop this gap | |
| /// for you: | |
| /// | |
| /// ``` | |
| /// let dist = u32::from(char::MAX) - u32::from(char::MIN); | |
| /// let size = (char::MIN..=char::MAX).count() as u32; | |
| /// assert!(size < dist); | |
| /// ``` | |
| /// | |
| /// Despite this gap, the [`MIN`] and `MAX` values can be used as bounds for | |
| /// all `char` values. | |
| /// | |
| /// [`MIN`]: char::MIN | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// # fn something_which_returns_char() -> char { 'a' } | |
| /// let c: char = something_which_returns_char(); | |
| /// assert!(c <= char::MAX); | |
| /// | |
| /// let value_at_max = u32::from(char::MAX); | |
| /// assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}')); | |
| /// assert_eq!(char::from_u32(value_at_max + 1), None); | |
| /// ``` | |
| #[stable(feature = "assoc_char_consts", since = "1.52.0")] | |
| pub const MAX: char = '\u{10FFFF}'; | |
| /// The maximum number of bytes required to [encode](char::encode_utf8) a `char` to | |
| /// UTF-8 encoding. | |
| #[stable(feature = "char_max_len_assoc", since = "1.93.0")] | |
| pub const MAX_LEN_UTF8: usize = 4; | |
| /// The maximum number of two-byte units required to [encode](char::encode_utf16) a `char` | |
| /// to UTF-16 encoding. | |
| #[stable(feature = "char_max_len_assoc", since = "1.93.0")] | |
| pub const MAX_LEN_UTF16: usize = 2; | |
| /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a | |
| /// decoding error. | |
| /// | |
| /// It can occur, for example, when giving ill-formed UTF-8 bytes to | |
| /// [`String::from_utf8_lossy`](../std/string/struct.String.html#method.from_utf8_lossy). | |
| #[stable(feature = "assoc_char_consts", since = "1.52.0")] | |
| pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}'; | |
| /// The version of [Unicode](https://www.unicode.org/) that the Unicode parts of | |
| /// `char` and `str` methods are based on. | |
| /// | |
| /// New versions of Unicode are released regularly, and subsequently all methods | |
| /// in the standard library depending on Unicode are updated. Therefore, the | |
| /// behavior of some `char` and `str` methods, and the value of this constant, | |
| /// change over time (within the boundaries of Unicode's [stability policies]). | |
| /// This is *not* considered to be a breaking change. | |
| /// | |
| /// [stability policies]: https://www.unicode.org/policies/stability_policy.html | |
| /// | |
| /// The version numbering scheme is explained in | |
| /// [Section 3.1 (Version Numbering)] of the Unicode Standard. | |
| /// | |
| /// [Section 3.1 (Version Numbering)]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G49512 | |
| #[stable(feature = "assoc_char_consts", since = "1.52.0")] | |
| pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION; | |
| /// Creates an iterator over the native endian UTF-16 encoded code points in `iter`, | |
| /// returning unpaired surrogates as `Err`s. | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// // 𝄞mus<invalid>ic<invalid> | |
| /// let v = [ | |
| /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834, | |
| /// ]; | |
| /// | |
| /// assert_eq!( | |
| /// char::decode_utf16(v) | |
| /// .map(|r| r.map_err(|e| e.unpaired_surrogate())) | |
| /// .collect::<Vec<_>>(), | |
| /// vec![ | |
| /// Ok('𝄞'), | |
| /// Ok('m'), Ok('u'), Ok('s'), | |
| /// Err(0xDD1E), | |
| /// Ok('i'), Ok('c'), | |
| /// Err(0xD834) | |
| /// ] | |
| /// ); | |
| /// ``` | |
| /// | |
| /// A lossy decoder can be obtained by replacing `Err` results with the replacement character: | |
| /// | |
| /// ``` | |
| /// // 𝄞mus<invalid>ic<invalid> | |
| /// let v = [ | |
| /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834, | |
| /// ]; | |
| /// | |
| /// assert_eq!( | |
| /// char::decode_utf16(v) | |
| /// .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)) | |
| /// .collect::<String>(), | |
| /// "𝄞mus�ic�" | |
| /// ); | |
| /// ``` | |
| #[stable(feature = "assoc_char_funcs", since = "1.52.0")] | |
| #[inline] | |
| pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> { | |
| super::decode::decode_utf16(iter) | |
| } | |
| /// Converts a `u32` to a `char`. | |
| /// | |
| /// Note that all `char`s are valid [`u32`]s, and can be cast to one with | |
| /// [`as`](../std/keyword.as.html): | |
| /// | |
| /// ``` | |
| /// let c = '💯'; | |
| /// let i = c as u32; | |
| /// | |
| /// assert_eq!(128175, i); | |
| /// ``` | |
| /// | |
| /// However, the reverse is not true: not all valid [`u32`]s are valid | |
| /// `char`s. `from_u32()` will return `None` if the input is not a valid value | |
| /// for a `char`. | |
| /// | |
| /// For an unsafe version of this function which ignores these checks, see | |
| /// [`from_u32_unchecked`]. | |
| /// | |
| /// [`from_u32_unchecked`]: #method.from_u32_unchecked | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// let c = char::from_u32(0x2764); | |
| /// | |
| /// assert_eq!(Some('❤'), c); | |
| /// ``` | |
| /// | |
| /// Returning `None` when the input is not a valid `char`: | |
| /// | |
| /// ``` | |
| /// let c = char::from_u32(0x110000); | |
| /// | |
| /// assert_eq!(None, c); | |
| /// ``` | |
| #[stable(feature = "assoc_char_funcs", since = "1.52.0")] | |
| #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")] | |
| #[must_use] | |
| #[inline] | |
| pub const fn from_u32(i: u32) -> Option<char> { | |
| super::convert::from_u32(i) | |
| } | |
| /// Converts a `u32` to a `char`, ignoring validity. | |
| /// | |
| /// Note that all `char`s are valid [`u32`]s, and can be cast to one with | |
| /// `as`: | |
| /// | |
| /// ``` | |
| /// let c = '💯'; | |
| /// let i = c as u32; | |
| /// | |
| /// assert_eq!(128175, i); | |
| /// ``` | |
| /// | |
| /// However, the reverse is not true: not all valid [`u32`]s are valid | |
| /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to | |
| /// `char`, possibly creating an invalid one. | |
| /// | |
| /// # Safety | |
| /// | |
| /// This function is unsafe, as it may construct invalid `char` values. | |
| /// | |
| /// For a safe version of this function, see the [`from_u32`] function. | |
| /// | |
| /// [`from_u32`]: #method.from_u32 | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// let c = unsafe { char::from_u32_unchecked(0x2764) }; | |
| /// | |
| /// assert_eq!('❤', c); | |
| /// ``` | |
| #[stable(feature = "assoc_char_funcs", since = "1.52.0")] | |
| #[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")] | |
| #[must_use] | |
| #[inline] | |
| pub const unsafe fn from_u32_unchecked(i: u32) -> char { | |
| // SAFETY: the safety contract must be upheld by the caller. | |
| unsafe { super::convert::from_u32_unchecked(i) } | |
| } | |
| /// Converts a digit in the given radix to a `char`. | |
| /// | |
| /// A 'radix' here is sometimes also called a 'base'. A radix of two | |
| /// indicates a binary number, a radix of ten, decimal, and a radix of | |
| /// sixteen, hexadecimal, to give some common values. Arbitrary | |
| /// radices are supported. | |
| /// | |
| /// `from_digit()` will return `None` if the input is not a digit in | |
| /// the given radix. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if given a radix larger than 36. | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// let c = char::from_digit(4, 10); | |
| /// | |
| /// assert_eq!(Some('4'), c); | |
| /// | |
| /// // Decimal 11 is a single digit in base 16 | |
| /// let c = char::from_digit(11, 16); | |
| /// | |
| /// assert_eq!(Some('b'), c); | |
| /// ``` | |
| /// | |
| /// Returning `None` when the input is not a digit: | |
| /// | |
| /// ``` | |
| /// let c = char::from_digit(20, 10); | |
| /// | |
| /// assert_eq!(None, c); | |
| /// ``` | |
| /// | |
| /// Passing a large radix, causing a panic: | |
| /// | |
| /// ```should_panic | |
| /// // this panics | |
| /// let _c = char::from_digit(1, 37); | |
| /// ``` | |
| #[stable(feature = "assoc_char_funcs", since = "1.52.0")] | |
| #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")] | |
| #[must_use] | |
| #[inline] | |
| pub const fn from_digit(num: u32, radix: u32) -> Option<char> { | |
| super::convert::from_digit(num, radix) | |
| } | |
| /// Checks if a `char` is a digit in the given radix. | |
| /// | |
| /// A 'radix' here is sometimes also called a 'base'. A radix of two | |
| /// indicates a binary number, a radix of ten, decimal, and a radix of | |
| /// sixteen, hexadecimal, to give some common values. Arbitrary | |
| /// radices are supported. | |
| /// | |
| /// Compared to [`is_numeric()`], this function only recognizes the characters | |
| /// `0-9`, `a-z` and `A-Z`. | |
| /// | |
| /// 'Digit' is defined to be only the following characters: | |
| /// | |
| /// * `0-9` | |
| /// * `a-z` | |
| /// * `A-Z` | |
| /// | |
| /// For a more comprehensive understanding of 'digit', see [`is_numeric()`]. | |
| /// | |
| /// [`is_numeric()`]: #method.is_numeric | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if given a radix smaller than 2 or larger than 36. | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert!('1'.is_digit(10)); | |
| /// assert!('f'.is_digit(16)); | |
| /// assert!(!'f'.is_digit(10)); | |
| /// ``` | |
| /// | |
| /// Passing a large radix, causing a panic: | |
| /// | |
| /// ```should_panic | |
| /// // this panics | |
| /// '1'.is_digit(37); | |
| /// ``` | |
| /// | |
| /// Passing a small radix, causing a panic: | |
| /// | |
| /// ```should_panic | |
| /// // this panics | |
| /// '1'.is_digit(1); | |
| /// ``` | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")] | |
| #[expect(clippy::to_digit_is_some, reason = "implements is_digit")] | |
| #[inline] | |
| pub const fn is_digit(self, radix: u32) -> bool { | |
| self.to_digit(radix).is_some() | |
| } | |
| /// Converts a `char` to a digit in the given radix. | |
| /// | |
| /// A 'radix' here is sometimes also called a 'base'. A radix of two | |
| /// indicates a binary number, a radix of ten, decimal, and a radix of | |
| /// sixteen, hexadecimal, to give some common values. Arbitrary | |
| /// radices are supported. | |
| /// | |
| /// 'Digit' is defined to be only the following characters: | |
| /// | |
| /// * `0-9` | |
| /// * `a-z` | |
| /// * `A-Z` | |
| /// | |
| /// # Errors | |
| /// | |
| /// Returns `None` if the `char` does not refer to a digit in the given radix. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if given a radix smaller than 2 or larger than 36. | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert_eq!('1'.to_digit(10), Some(1)); | |
| /// assert_eq!('f'.to_digit(16), Some(15)); | |
| /// ``` | |
| /// | |
| /// Passing a non-digit results in failure: | |
| /// | |
| /// ``` | |
| /// assert_eq!('f'.to_digit(10), None); | |
| /// assert_eq!('z'.to_digit(16), None); | |
| /// ``` | |
| /// | |
| /// Passing a large radix, causing a panic: | |
| /// | |
| /// ```should_panic | |
| /// // this panics | |
| /// let _ = '1'.to_digit(37); | |
| /// ``` | |
| /// Passing a small radix, causing a panic: | |
| /// | |
| /// ```should_panic | |
| /// // this panics | |
| /// let _ = '1'.to_digit(1); | |
| /// ``` | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")] | |
| #[rustc_diagnostic_item = "char_to_digit"] | |
| #[must_use = "this returns the result of the operation, \ | |
| without modifying the original"] | |
| #[inline] | |
| pub const fn to_digit(self, radix: u32) -> Option<u32> { | |
| assert!( | |
| radix >= 2 && radix <= 36, | |
| "to_digit: invalid radix -- radix must be in the range 2 to 36 inclusive" | |
| ); | |
| // check radix to remove letter handling code when radix is a known constant | |
| let value = if self > '9' && radix > 10 { | |
| // mask to convert ASCII letters to uppercase | |
| const TO_UPPERCASE_MASK: u32 = !0b0010_0000; | |
| // Converts an ASCII letter to its corresponding integer value: | |
| // A-Z => 10-35, a-z => 10-35. Other characters produce values >= 36. | |
| // | |
| // Add Overflow Safety: | |
| // By applying the mask after the subtraction, the first addendum is | |
| // constrained such that it never exceeds u32::MAX - 0x20. | |
| ((self as u32).wrapping_sub('A' as u32) & TO_UPPERCASE_MASK) + 10 | |
| } else { | |
| // convert digit to value, non-digits wrap to values > 36 | |
| (self as u32).wrapping_sub('0' as u32) | |
| }; | |
| // FIXME(const-hack): once then_some is const fn, use it here | |
| if value < radix { Some(value) } else { None } | |
| } | |
| /// Returns an iterator that yields the hexadecimal Unicode escape of a | |
| /// character as `char`s. | |
| /// | |
| /// This will escape characters with the Rust syntax of the form | |
| /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation. | |
| /// | |
| /// # Examples | |
| /// | |
| /// As an iterator: | |
| /// | |
| /// ``` | |
| /// for c in '❤'.escape_unicode() { | |
| /// print!("{c}"); | |
| /// } | |
| /// println!(); | |
| /// ``` | |
| /// | |
| /// Using `println!` directly: | |
| /// | |
| /// ``` | |
| /// println!("{}", '❤'.escape_unicode()); | |
| /// ``` | |
| /// | |
| /// Both are equivalent to: | |
| /// | |
| /// ``` | |
| /// println!("\\u{{2764}}"); | |
| /// ``` | |
| /// | |
| /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string): | |
| /// | |
| /// ``` | |
| /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}"); | |
| /// ``` | |
| #[must_use = "this returns the escaped char as an iterator, \ | |
| without modifying the original"] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[inline] | |
| pub fn escape_unicode(self) -> EscapeUnicode { | |
| EscapeUnicode::new(self) | |
| } | |
| /// An extended version of `escape_debug` that optionally permits escaping | |
| /// single quotes and double quotes. This allows escaping single quotes in | |
| /// characters, and double quotes in strings. | |
| #[inline] | |
| pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug { | |
| match self { | |
| // Special escapes | |
| '\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark), | |
| '\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe), | |
| '\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus), | |
| '\n' => EscapeDebug::backslash(ascii::Char::SmallN), | |
| '\t' => EscapeDebug::backslash(ascii::Char::SmallT), | |
| '\r' => EscapeDebug::backslash(ascii::Char::SmallR), | |
| '\0' => EscapeDebug::backslash(ascii::Char::Digit0), | |
| // ASCII fast path, | |
| // plus U+FF9E HALFWIDTH KATAKANA VOICED SOUND MARK | |
| // and U+FF9F HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK | |
| // which should not be escaped despite being grapheme extenders. | |
| '\x20'..='\x7E' | '\u{FF9E}' | '\u{FF9F}' => EscapeDebug::printable(self), | |
| _ if self.is_control() | |
| || self.is_private_use() | |
| || self.is_whitespace() | |
| || self.is_grapheme_extender() | |
| || self.is_default_ignorable() | |
| || self.is_format_control() | |
| || !self.is_assigned() => | |
| { | |
| EscapeDebug::unicode(self) | |
| } | |
| _ => EscapeDebug::printable(self), | |
| } | |
| } | |
| /// Returns an iterator that yields the literal escape code of a character | |
| /// as `char`s. | |
| /// | |
| /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations | |
| /// of `str` or `char`. | |
| /// | |
| /// # Examples | |
| /// | |
| /// As an iterator: | |
| /// | |
| /// ``` | |
| /// for c in '\n'.escape_debug() { | |
| /// print!("{c}"); | |
| /// } | |
| /// println!(); | |
| /// ``` | |
| /// | |
| /// Using `println!` directly: | |
| /// | |
| /// ``` | |
| /// println!("{}", '\n'.escape_debug()); | |
| /// ``` | |
| /// | |
| /// Both are equivalent to: | |
| /// | |
| /// ``` | |
| /// println!("\\n"); | |
| /// ``` | |
| /// | |
| /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string): | |
| /// | |
| /// ``` | |
| /// assert_eq!('\n'.escape_debug().to_string(), "\\n"); | |
| /// ``` | |
| #[must_use = "this returns the escaped char as an iterator, \ | |
| without modifying the original"] | |
| #[stable(feature = "char_escape_debug", since = "1.20.0")] | |
| #[inline] | |
| pub fn escape_debug(self) -> EscapeDebug { | |
| self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL) | |
| } | |
| /// Returns an iterator that yields the literal escape code of a character | |
| /// as `char`s. | |
| /// | |
| /// The default is chosen with a bias toward producing literals that are | |
| /// legal in a variety of languages, including C++11 and similar C-family | |
| /// languages. The exact rules are: | |
| /// | |
| /// * Tab is escaped as `\t`. | |
| /// * Carriage return is escaped as `\r`. | |
| /// * Line feed is escaped as `\n`. | |
| /// * Single quote is escaped as `\'`. | |
| /// * Double quote is escaped as `\"`. | |
| /// * Backslash is escaped as `\\`. | |
| /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e` | |
| /// inclusive is not escaped. | |
| /// * All other characters are given hexadecimal Unicode escapes; see | |
| /// [`escape_unicode`]. | |
| /// | |
| /// [`escape_unicode`]: #method.escape_unicode | |
| /// | |
| /// # Examples | |
| /// | |
| /// As an iterator: | |
| /// | |
| /// ``` | |
| /// for c in '"'.escape_default() { | |
| /// print!("{c}"); | |
| /// } | |
| /// println!(); | |
| /// ``` | |
| /// | |
| /// Using `println!` directly: | |
| /// | |
| /// ``` | |
| /// println!("{}", '"'.escape_default()); | |
| /// ``` | |
| /// | |
| /// Both are equivalent to: | |
| /// | |
| /// ``` | |
| /// println!("\\\""); | |
| /// ``` | |
| /// | |
| /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string): | |
| /// | |
| /// ``` | |
| /// assert_eq!('"'.escape_default().to_string(), "\\\""); | |
| /// ``` | |
| #[must_use = "this returns the escaped char as an iterator, \ | |
| without modifying the original"] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[inline] | |
| pub fn escape_default(self) -> EscapeDefault { | |
| match self { | |
| '\t' => EscapeDefault::backslash(ascii::Char::SmallT), | |
| '\r' => EscapeDefault::backslash(ascii::Char::SmallR), | |
| '\n' => EscapeDefault::backslash(ascii::Char::SmallN), | |
| '\\' | '\'' | '\"' => EscapeDefault::backslash(self.as_ascii().unwrap()), | |
| '\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()), | |
| _ => EscapeDefault::unicode(self), | |
| } | |
| } | |
| /// Returns the number of bytes this `char` would need if encoded in UTF-8. | |
| /// | |
| /// That number of bytes is always between 1 and 4, inclusive. | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// let len = 'A'.len_utf8(); | |
| /// assert_eq!(len, 1); | |
| /// | |
| /// let len = 'ß'.len_utf8(); | |
| /// assert_eq!(len, 2); | |
| /// | |
| /// let len = 'ℝ'.len_utf8(); | |
| /// assert_eq!(len, 3); | |
| /// | |
| /// let len = '💣'.len_utf8(); | |
| /// assert_eq!(len, 4); | |
| /// ``` | |
| /// | |
| /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it | |
| /// would take if each code point was represented as a `char` vs in the `&str` itself: | |
| /// | |
| /// ``` | |
| /// // as chars | |
| /// let eastern = '東'; | |
| /// let capital = '京'; | |
| /// | |
| /// // both can be represented as three bytes | |
| /// assert_eq!(3, eastern.len_utf8()); | |
| /// assert_eq!(3, capital.len_utf8()); | |
| /// | |
| /// // as a &str, these two are encoded in UTF-8 | |
| /// let tokyo = "東京"; | |
| /// | |
| /// let len = eastern.len_utf8() + capital.len_utf8(); | |
| /// | |
| /// // we can see that they take six bytes total... | |
| /// assert_eq!(6, tokyo.len()); | |
| /// | |
| /// // ... just like the &str | |
| /// assert_eq!(len, tokyo.len()); | |
| /// ``` | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")] | |
| #[inline] | |
| #[must_use] | |
| pub const fn len_utf8(self) -> usize { | |
| len_utf8(self as u32) | |
| } | |
| /// Returns the number of 16-bit code units this `char` would need if | |
| /// encoded in UTF-16. | |
| /// | |
| /// That number of code units is always either 1 or 2, for unicode scalar values in | |
| /// the [basic multilingual plane] or [supplementary planes] respectively. | |
| /// | |
| /// See the documentation for [`len_utf8()`] for more explanation of this | |
| /// concept. This function is a mirror, but for UTF-16 instead of UTF-8. | |
| /// | |
| /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane | |
| /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes | |
| /// [`len_utf8()`]: #method.len_utf8 | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// let n = 'ß'.len_utf16(); | |
| /// assert_eq!(n, 1); | |
| /// | |
| /// let len = '💣'.len_utf16(); | |
| /// assert_eq!(len, 2); | |
| /// ``` | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")] | |
| #[inline] | |
| #[must_use] | |
| pub const fn len_utf16(self) -> usize { | |
| len_utf16(self as u32) | |
| } | |
| /// Encodes this character as UTF-8 into the provided byte buffer, | |
| /// and then returns the subslice of the buffer that contains the encoded character. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the buffer is not large enough. | |
| /// A buffer of length four is large enough to encode any `char`. | |
| /// | |
| /// # Examples | |
| /// | |
| /// In both of these examples, 'ß' takes two bytes to encode. | |
| /// | |
| /// ``` | |
| /// let mut b = [0; 2]; | |
| /// | |
| /// let result = 'ß'.encode_utf8(&mut b); | |
| /// | |
| /// assert_eq!(result, "ß"); | |
| /// | |
| /// assert_eq!(result.len(), 2); | |
| /// ``` | |
| /// | |
| /// A buffer that's too small: | |
| /// | |
| /// ```should_panic | |
| /// let mut b = [0; 1]; | |
| /// | |
| /// // this panics | |
| /// 'ß'.encode_utf8(&mut b); | |
| /// ``` | |
| #[stable(feature = "unicode_encode_char", since = "1.15.0")] | |
| #[rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0")] | |
| #[inline] | |
| pub const fn encode_utf8(self, dst: &mut [u8]) -> &mut str { | |
| // SAFETY: `char` is not a surrogate, so this is valid UTF-8. | |
| unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) } | |
| } | |
| /// Encodes this character as native endian UTF-16 into the provided `u16` buffer, | |
| /// and then returns the subslice of the buffer that contains the encoded character. | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the buffer is not large enough. | |
| /// A buffer of length 2 is large enough to encode any `char`. | |
| /// | |
| /// # Examples | |
| /// | |
| /// In both of these examples, '𝕊' takes two `u16`s to encode. | |
| /// | |
| /// ``` | |
| /// let mut b = [0; 2]; | |
| /// | |
| /// let result = '𝕊'.encode_utf16(&mut b); | |
| /// | |
| /// assert_eq!(result.len(), 2); | |
| /// ``` | |
| /// | |
| /// A buffer that's too small: | |
| /// | |
| /// ```should_panic | |
| /// let mut b = [0; 1]; | |
| /// | |
| /// // this panics | |
| /// '𝕊'.encode_utf16(&mut b); | |
| /// ``` | |
| #[stable(feature = "unicode_encode_char", since = "1.15.0")] | |
| #[rustc_const_stable(feature = "const_char_encode_utf16", since = "1.84.0")] | |
| #[inline] | |
| pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] { | |
| encode_utf16_raw(self as u32, dst) | |
| } | |
| /// Returns `true` if this `char` has the `Alphabetic` property. | |
| /// | |
| /// `Alphabetic` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and | |
| /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`]. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G32524 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#Alphabetic | |
| /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert!('a'.is_alphabetic()); | |
| /// assert!('京'.is_alphabetic()); | |
| /// | |
| /// let c = '💝'; | |
| /// // love is many things, but it is not alphabetic | |
| /// assert!(!c.is_alphabetic()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[inline] | |
| pub fn is_alphabetic(self) -> bool { | |
| match self { | |
| 'a'..='z' | 'A'..='Z' => true, | |
| '\0'..='\u{A9}' => false, | |
| _ => unicode::Alphabetic(self), | |
| } | |
| } | |
| /// Returns `true` if this `char` has the `Cased` property. | |
| /// A character is cased if and only if it is uppercase, lowercase, or titlecase. | |
| /// | |
| /// `Cased` is [described] in Chapter 3 (Character Properties) of the Unicode Standard and | |
| /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`]. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G44595 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#Cased | |
| /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// assert!('A'.is_cased()); | |
| /// assert!('a'.is_cased()); | |
| /// assert!(!'京'.is_cased()); | |
| /// ``` | |
| #[must_use] | |
| #[unstable(feature = "titlecase", issue = "153892")] | |
| #[inline] | |
| pub fn is_cased(self) -> bool { | |
| match self { | |
| 'a'..='z' | 'A'..='Z' => true, | |
| '\0'..='\u{A9}' => false, | |
| _ => unicode::Lowercase(self) || unicode::Uppercase(self) || unicode::Lt(self), | |
| } | |
| } | |
| /// Returns the case of this character: | |
| /// [`Some(CharCase::Upper)`][`CharCase::Upper`] if [`self.is_uppercase()`][`char::is_uppercase`], | |
| /// [`Some(CharCase::Lower)`][`CharCase::Lower`] if [`self.is_lowercase()`][`char::is_lowercase`], | |
| /// [`Some(CharCase::Title)`][`CharCase::Title`] if [`self.is_titlecase()`][`char::is_titlecase`], and | |
| /// `None` if [`!self.is_cased()`][`char::is_cased`]. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// use core::char::CharCase; | |
| /// assert_eq!('a'.case(), Some(CharCase::Lower)); | |
| /// assert_eq!('δ'.case(), Some(CharCase::Lower)); | |
| /// assert_eq!('A'.case(), Some(CharCase::Upper)); | |
| /// assert_eq!('Δ'.case(), Some(CharCase::Upper)); | |
| /// assert_eq!('Dž'.case(), Some(CharCase::Title)); | |
| /// assert_eq!('中'.case(), None); | |
| /// ``` | |
| #[must_use] | |
| #[unstable(feature = "titlecase", issue = "153892")] | |
| #[inline] | |
| pub fn case(self) -> Option<CharCase> { | |
| match self { | |
| 'a'..='z' => Some(CharCase::Lower), | |
| 'A'..='Z' => Some(CharCase::Upper), | |
| '\0'..='\u{A9}' => None, | |
| _ if unicode::Lowercase(self) => Some(CharCase::Lower), | |
| _ if unicode::Uppercase(self) => Some(CharCase::Upper), | |
| _ if unicode::Lt(self) => Some(CharCase::Title), | |
| _ => None, | |
| } | |
| } | |
| /// Returns `true` if this `char` has the `Lowercase` property. | |
| /// | |
| /// `Lowercase` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and | |
| /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`]. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G136255 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#Lowercase | |
| /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert!('a'.is_lowercase()); | |
| /// assert!('δ'.is_lowercase()); | |
| /// assert!(!'A'.is_lowercase()); | |
| /// assert!(!'Δ'.is_lowercase()); | |
| /// | |
| /// // The various Chinese scripts and punctuation do not have case, and so: | |
| /// assert!(!'中'.is_lowercase()); | |
| /// assert!(!' '.is_lowercase()); | |
| /// ``` | |
| /// | |
| /// In a const context: | |
| /// | |
| /// ``` | |
| /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase(); | |
| /// assert!(!CAPITAL_DELTA_IS_LOWERCASE); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")] | |
| #[inline] | |
| pub const fn is_lowercase(self) -> bool { | |
| match self { | |
| 'a'..='z' => true, | |
| '\0'..='\u{A9}' => false, | |
| _ => unicode::Lowercase(self), | |
| } | |
| } | |
| /// Returns `true` if this `char` is in the general category for titlecase letters. | |
| /// Conceptually, these characters consist of an uppercase portion followed by a lowercase portion. | |
| /// | |
| /// Titlecase letters (code points with the general category of `Lt`) are [described] in Chapter 4 | |
| /// (Character Properties) of the Unicode Standard, and [specified] in the Unicode Character | |
| /// Database [`UnicodeData.txt`]. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G124722 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// assert!('Dž'.is_titlecase()); | |
| /// assert!('ῼ'.is_titlecase()); | |
| /// assert!(!'D'.is_titlecase()); | |
| /// assert!(!'z'.is_titlecase()); | |
| /// assert!(!'中'.is_titlecase()); | |
| /// assert!(!' '.is_titlecase()); | |
| /// ``` | |
| #[must_use] | |
| #[unstable(feature = "titlecase", issue = "153892")] | |
| #[inline] | |
| pub fn is_titlecase(self) -> bool { | |
| match self { | |
| '\0'..='\u{01C4}' => false, | |
| _ => unicode::Lt(self), | |
| } | |
| } | |
| /// Returns `true` if this `char` has the `Uppercase` property. | |
| /// | |
| /// `Uppercase` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and | |
| /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`]. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G136255 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#Uppercase | |
| /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert!(!'a'.is_uppercase()); | |
| /// assert!(!'δ'.is_uppercase()); | |
| /// assert!('A'.is_uppercase()); | |
| /// assert!('Δ'.is_uppercase()); | |
| /// | |
| /// // The various Chinese scripts and punctuation do not have case, and so: | |
| /// assert!(!'中'.is_uppercase()); | |
| /// assert!(!' '.is_uppercase()); | |
| /// ``` | |
| /// | |
| /// In a const context: | |
| /// | |
| /// ``` | |
| /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase(); | |
| /// assert!(CAPITAL_DELTA_IS_UPPERCASE); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")] | |
| #[inline] | |
| pub const fn is_uppercase(self) -> bool { | |
| match self { | |
| 'A'..='Z' => true, | |
| '\0'..='\u{BF}' => false, | |
| _ => unicode::Uppercase(self), | |
| } | |
| } | |
| /// Returns `true` if this `char` has one of the general categories for numbers. | |
| /// | |
| /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric | |
| /// characters, and `No` for other numeric characters) are [specified] in the Unicode Character | |
| /// Database [`UnicodeData.txt`]. | |
| /// | |
| /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'. | |
| /// If you want everything including characters with overlapping purposes, then you might want to use | |
| /// a Unicode or language-processing library that exposes the appropriate character properties | |
| /// (e.g. [`Numeric_Type`]) instead of looking at the Unicode categories. | |
| /// | |
| /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use | |
| /// `is_ascii_digit` or `is_digit` instead. | |
| /// | |
| /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// [`Numeric_Type`]: https://www.unicode.org/reports/tr44/#Numeric_Type | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert!('٣'.is_numeric()); | |
| /// assert!('7'.is_numeric()); | |
| /// assert!('৬'.is_numeric()); | |
| /// assert!('¾'.is_numeric()); | |
| /// assert!('①'.is_numeric()); | |
| /// assert!(!'K'.is_numeric()); | |
| /// assert!(!'و'.is_numeric()); | |
| /// assert!(!'藏'.is_numeric()); | |
| /// assert!(!'三'.is_numeric()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[inline] | |
| pub fn is_numeric(self) -> bool { | |
| match self { | |
| '0'..='9' => true, | |
| '\0'..='\u{B1}' => false, | |
| _ => unicode::N(self), | |
| } | |
| } | |
| /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`]. | |
| /// | |
| /// [`is_alphabetic()`]: Self::is_alphabetic | |
| /// [`is_numeric()`]: Self::is_numeric | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert!('٣'.is_alphanumeric()); | |
| /// assert!('7'.is_alphanumeric()); | |
| /// assert!('৬'.is_alphanumeric()); | |
| /// assert!('¾'.is_alphanumeric()); | |
| /// assert!('①'.is_alphanumeric()); | |
| /// assert!('K'.is_alphanumeric()); | |
| /// assert!('و'.is_alphanumeric()); | |
| /// assert!('藏'.is_alphanumeric()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[inline] | |
| pub fn is_alphanumeric(self) -> bool { | |
| match self { | |
| 'a'..='z' | 'A'..='Z' | '0'..='9' => true, | |
| '\0'..='\u{A9}' => false, | |
| _ => unicode::Alphabetic(self) || unicode::N(self), | |
| } | |
| } | |
| /// Returns `true` if this `char` has the `White_Space` property. | |
| /// | |
| /// `White_Space` is [specified] in the Unicode Character Database [`PropList.txt`]. | |
| /// | |
| /// [specified]: https://www.unicode.org/reports/tr44/#White_Space | |
| /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert!(' '.is_whitespace()); | |
| /// | |
| /// // line break | |
| /// assert!('\n'.is_whitespace()); | |
| /// | |
| /// // a non-breaking space | |
| /// assert!('\u{A0}'.is_whitespace()); | |
| /// | |
| /// assert!(!'越'.is_whitespace()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")] | |
| #[inline] | |
| pub const fn is_whitespace(self) -> bool { | |
| match self { | |
| ' ' | '\x09'..='\x0d' => true, | |
| '\0'..='\u{84}' => false, | |
| _ => unicode::White_Space(self), | |
| } | |
| } | |
| /// Returns `true` if this `char` has the general category for control codes. | |
| /// | |
| /// Control codes (code points with the general category of `Cc`) are [described] in Chapter 23 | |
| /// (Special Areas and Format Characters) of the Unicode Standard, and [specified] in the Unicode Character | |
| /// Database [`UnicodeData.txt`]. The full set of Unicode control codes is | |
| /// `'\0'..='\x1f' | '\x7f'..='\u{9f}'`, and will never change. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-23/#G20365 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// assert!('\t'.is_control()); | |
| /// assert!('\n'.is_control()); | |
| /// assert!('\u{9C}'.is_control()); // STRING TERMINATOR | |
| /// assert!(!'q'.is_control()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[rustc_const_stable(feature = "const_is_control", since = "1.97.0")] | |
| #[inline] | |
| pub const fn is_control(self) -> bool { | |
| // According to | |
| // https://www.unicode.org/policies/stability_policy.html#Property_Value, | |
| // the set of codepoints in `Cc` will never change. | |
| // So we can just hard-code the patterns to match against instead of using a table. | |
| matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}') | |
| } | |
| /// Returns `true` if this `char` has the general category for [private-use characters]. | |
| /// These characters do not have an interpretation specified by Unicode; individual programs | |
| /// and users are free to assign them whatever meaning they like. | |
| /// | |
| /// [private-use characters]: https://www.unicode.org/faq/private_use#private_use | |
| /// | |
| /// Private-use characters (code points with the general category of `Co`) are [described] in Chapter 23 | |
| /// (Special Areas and Format Characters) of the Unicode Standard, and [specified] in the | |
| /// Unicode Character Database [`UnicodeData.txt`]. The full set of private-use characters is | |
| /// `'\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}'`, | |
| /// and will never change. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-23/#G19184 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// | |
| #[must_use] | |
| #[unstable(feature = "char_unassigned_private_use", issue = "158322")] | |
| #[inline] | |
| pub const fn is_private_use(self) -> bool { | |
| // According to | |
| // https://www.unicode.org/policies/stability_policy.html#Property_Value, | |
| // the set of codepoints in `Co` will never change. | |
| // So we can just hard-code the patterns to match against instead of using a table. | |
| matches!(self, '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}') | |
| } | |
| /// Returns `true` if this `char` has the general category for format control characters. | |
| /// | |
| /// Format controls (code points with the general category of `Cf`) are [described] in Chapter 4 | |
| /// (Character Properties) of the Unicode Standard, and [specified] in the Unicode Character | |
| /// Database [`UnicodeData.txt`]. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G134153 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ```ignore(private) | |
| /// assert!('\u{AD}'.is_format_control()); // SOFT HYPHEN | |
| /// assert!('\u{200B}'.is_format_control()); // ZERO WIDTH SPACE | |
| /// assert!('\u{E0041}'.is_format_control()); // TAG LATIN CAPITAL LETTER A | |
| /// assert!(''.is_format_control()); // ARABIC END OF AYAH | |
| /// assert!(''.is_format_control()); // EGYPTIAN HIEROGLYPH INSERT AT TOP START | |
| /// assert!(!'q'.is_format_control()); | |
| /// ``` | |
| #[must_use] | |
| #[inline] | |
| fn is_format_control(self) -> bool { | |
| self > '\u{AC}' && unicode::Cf(self) | |
| } | |
| /// Returns `true` if this `char` has been assigned a meaning by Unicode, as of | |
| /// [`UNICODE_VERSION`]. | |
| /// | |
| /// [`UNICODE_VERSION`]: Self::UNICODE_VERSION | |
| /// | |
| /// Many of Unicode's [stability policies] apply only to assigned characters. | |
| /// | |
| /// [stability policies]: https://www.unicode.org/policies/stability_policy.html | |
| /// | |
| /// Currently unassigned characters (characters for which this method returns `false`) | |
| /// may have a meaning assigned in a future version of Unicode, | |
| /// except for the 66 [noncharacters] which will never be assigned a meaning. | |
| /// | |
| /// [noncharacters]: https://www.unicode.org/faq/private_use.html#noncharacters | |
| /// | |
| /// A character is considered assigned if it is present in [`UnicodeData.txt`]. | |
| /// Unassigned characters have general category `Cn`, as [described] in Chapter 4 | |
| /// (Character Properties) of the Unicode Standard. | |
| /// | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G134153 | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// #![feature(char_unassigned_private_use)] | |
| /// assert!('γ'.is_assigned()); // once a character is assigned, it stays assigned forever | |
| /// assert!(!'\u{FFFE}'.is_assigned()); // noncharacter, will never be assigned | |
| /// | |
| /// // Not currently assigned, but may be in the future, | |
| /// // so we shouldn't rely on the current status | |
| /// /* assert!(!'\u{7AAAA}'.is_assigned()); */ | |
| /// ``` | |
| #[must_use] | |
| #[unstable(feature = "char_unassigned_private_use", issue = "158322")] | |
| #[inline] | |
| pub fn is_assigned(self) -> bool { | |
| match self { | |
| '\0'..='\u{377}' => true, | |
| '\u{378}'..='\u{3FFFD}' => !unicode::Cn_planes_0_3(self), | |
| // Assigned character ranges in planes 4 and above. | |
| // `src/tools/unicode-table-generator/src/main.rs` asserts that this is correct | |
| '\u{E0001}' | |
| | '\u{E0020}'..='\u{E007F}' | |
| | '\u{E0100}'..='\u{E01EF}' | |
| | '\u{F0000}'..='\u{FFFFD}' | |
| | '\u{100000}'..='\u{10FFFD}' => true, | |
| _ => false, | |
| } | |
| } | |
| /// Returns `true` if this `char` has the `Default_Ignorable_Code_Point` property. | |
| /// These characters [should be displayed as invisible in fallback rendering](https://www.unicode.org/faq/unsup_char#3). | |
| /// | |
| /// `Default_Ignorable_Code_Point` is [described] in Chapter 5 (Implementation Guidelines) of the Unicode Standard, | |
| /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`]. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-5/#G40120 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#Default_Ignorable_Code_Point | |
| /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt | |
| /// | |
| /// # Examples | |
| /// | |
| /// Basic usage: | |
| /// | |
| /// ``` | |
| /// #![feature(default_ignorable)] | |
| /// assert!('\u{AD}'.is_default_ignorable()); // SOFT HYPHEN | |
| /// assert!('\u{115F}'.is_default_ignorable()); // HANGUL CHOSEONG FILLER | |
| /// assert!('\u{200B}'.is_default_ignorable()); // ZERO WIDTH SPACE | |
| /// assert!('\u{E0041}'.is_default_ignorable()); // TAG LATIN CAPITAL LETTER A | |
| /// assert!(!''.is_default_ignorable()); // ARABIC END OF AYAH | |
| /// assert!(!''.is_default_ignorable()); // EGYPTIAN HIEROGLYPH INSERT AT TOP START | |
| /// assert!(!' '.is_default_ignorable()); | |
| /// assert!(!'\n'.is_default_ignorable()); | |
| /// assert!(!'\0'.is_default_ignorable()); | |
| /// assert!(!'q'.is_default_ignorable()); | |
| /// ``` | |
| #[must_use] | |
| #[unstable(feature = "default_ignorable", issue = "160583")] | |
| #[inline] | |
| pub fn is_default_ignorable(self) -> bool { | |
| self > '\u{AC}' && unicode::Default_Ignorable_Code_Point(self) | |
| } | |
| /// Returns `true` if this `char` has the `Grapheme_Extend` property. | |
| /// | |
| /// `Grapheme_Extend` is [described] in Chapter 3 (Conformance) of the Unicode Standard, | |
| /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`]. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G41165 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#Grapheme_Extend | |
| /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt | |
| #[must_use] | |
| #[inline] | |
| fn is_grapheme_extender(self) -> bool { | |
| self > '\u{02FF}' && unicode::Grapheme_Extend(self) | |
| } | |
| /// Returns `true` if this `char` has the `Case_Ignorable` property. This narrow-use property | |
| /// is used to implement context-dependent casing for the Greek letter sigma (uppercase 'Σ'), | |
| /// which has two lowercase forms. | |
| /// | |
| /// `Case_Ignorable` is [described] in Chapter 3 (Conformance) of the Unicode Core Specification, | |
| /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`]. | |
| /// See those resources, as well as [`to_lowercase()`]'s documentation, for more information. | |
| /// | |
| /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G63116 | |
| /// [specified]: https://www.unicode.org/reports/tr44/#Case_Ignorable | |
| /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt | |
| /// [`to_lowercase()`]: Self::to_lowercase() | |
| #[must_use] | |
| #[inline] | |
| #[unstable(feature = "case_ignorable", issue = "154848")] | |
| pub fn is_case_ignorable(self) -> bool { | |
| if self.is_ascii() { | |
| matches!(self, '\'' | '.' | ':' | '^' | '`') | |
| } else { | |
| unicode::Case_Ignorable(self) | |
| } | |
| } | |
| /// Returns an iterator that yields the lowercase mapping of this `char` as one or more | |
| /// `char`s. | |
| /// | |
| /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`. | |
| /// | |
| /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character | |
| /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`. | |
| /// | |
| /// [ucd]: https://www.unicode.org/reports/tr44/ | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// | |
| /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by | |
| /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3. | |
| /// | |
| /// This operation performs an unconditional mapping without tailoring. That is, the conversion | |
| /// is independent of context and language. See [below](#notes-on-context-and-locale) | |
| /// for more information. | |
| /// | |
| /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in | |
| /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion. | |
| /// | |
| /// [Unicode Standard]: https://www.unicode.org/versions/latest/ | |
| /// | |
| /// # Examples | |
| /// | |
| /// As an iterator: | |
| /// | |
| /// ``` | |
| /// for c in 'İ'.to_lowercase() { | |
| /// print!("{c}"); | |
| /// } | |
| /// println!(); | |
| /// ``` | |
| /// | |
| /// Using `println!` directly: | |
| /// | |
| /// ``` | |
| /// println!("{}", 'İ'.to_lowercase()); | |
| /// ``` | |
| /// | |
| /// Both are equivalent to: | |
| /// | |
| /// ``` | |
| /// println!("i\u{307}"); | |
| /// ``` | |
| /// | |
| /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string): | |
| /// | |
| /// ``` | |
| /// assert_eq!('C'.to_lowercase().to_string(), "c"); | |
| /// | |
| /// // Sometimes the result is more than one character: | |
| /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}"); | |
| /// | |
| /// // Characters that do not have both uppercase and lowercase | |
| /// // convert into themselves. | |
| /// assert_eq!('山'.to_lowercase().to_string(), "山"); | |
| /// ``` | |
| /// # Notes on context and locale | |
| /// | |
| /// As stated earlier, this method does not take into account language or context. | |
| /// Below is a non-exhaustive list of situations where this can be relevant. | |
| /// If you need to handle locale-depedendent casing in your code, consider using | |
| /// an external crate, like [`icu_casemap`](https://crates.io/crates/icu_casemap) | |
| /// which is developed by Unicode. | |
| /// | |
| /// ## Greek sigma | |
| /// | |
| /// In Greek, the letter simga (uppercase 'Σ') has two lowercase forms: | |
| /// 'σ' which is used in most situations, and 'ς' which appears only | |
| /// at the end of a word. [`char::to_lowercase()`] always uses the first form: | |
| /// | |
| /// ``` | |
| /// assert_eq!('Σ'.to_lowercase().to_string(), "σ"); | |
| /// ``` | |
| /// | |
| /// `str::to_lowercase()` (only available with the `alloc` crate) | |
| /// *does* properly handle this contextual mapping, | |
| /// so prefer using that method if you can. Alternatively, you can use | |
| /// [`is_cased()`] and [`is_case_ignorable()`] to implement it yourself. | |
| /// See `Final_Sigma` in [Table 3.17] of the Unicode Standard, | |
| /// along with [`SpecialCasing.txt`], for more details. | |
| /// | |
| /// [`is_cased()`]: Self::is_cased() | |
| /// [`is_case_ignorable()`]: Self::is_case_ignorable() | |
| /// [Table 3.17]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G54277 | |
| /// | |
| /// ## Turkish and Azeri I/ı/İ/i | |
| /// | |
| /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two: | |
| /// | |
| /// * 'Dotless': I / ı, sometimes written ï | |
| /// * 'Dotted': İ / i | |
| /// | |
| /// Note that the uppercase undotted 'I' is the same codepoint as the Latin. Therefore: | |
| /// | |
| /// ``` | |
| /// let lower_i = 'I'.to_lowercase().to_string(); | |
| /// ``` | |
| /// | |
| /// `'I'`'s correct lowercase relies on the language of the text: if we're | |
| /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should | |
| /// be `"ı"`. `to_lowercase()` does not take this into account, and so: | |
| /// | |
| /// ``` | |
| /// let lower_i = 'I'.to_lowercase().to_string(); | |
| /// | |
| /// assert_eq!(lower_i, "i"); | |
| /// ``` | |
| /// | |
| /// holds across languages. | |
| /// | |
| /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt | |
| #[must_use = "this returns the lowercased character as a new iterator, \ | |
| without modifying the original"] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[inline] | |
| pub fn to_lowercase(self) -> ToLowercase { | |
| ToLowercase(CaseMappingIter::new(conversions::to_lower(self))) | |
| } | |
| /// Returns an iterator that yields the titlecase mapping of this `char` as one or more | |
| /// `char`s. | |
| /// | |
| /// This is usually, but not always, equivalent to the uppercase mapping | |
| /// returned by [`to_uppercase()`]. Prefer this method when seeking to capitalize | |
| /// Only The First Letter of a word, but use [`to_uppercase()`] for ALL CAPS. | |
| /// See [below](#difference-from-uppercase) for a thorough explanation | |
| /// of the difference between the two methods. | |
| /// | |
| /// If this `char` does not have a titlecase mapping, the iterator yields the same `char`. | |
| /// | |
| /// If this `char` has a one-to-one titlecase mapping given by the [Unicode Character | |
| /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`. | |
| /// | |
| /// [ucd]: https://www.unicode.org/reports/tr44/ | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// | |
| /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by | |
| /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3. | |
| /// | |
| /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt | |
| /// | |
| /// This operation performs an unconditional mapping without tailoring. That is, the conversion | |
| /// is independent of context and language. See [below](#note-on-locale) | |
| /// for more information. | |
| /// | |
| /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in | |
| /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion. | |
| /// | |
| /// [Unicode Standard]: https://www.unicode.org/versions/latest/ | |
| /// | |
| /// # Examples | |
| /// | |
| /// As an iterator: | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// for c in 'ß'.to_titlecase() { | |
| /// print!("{c}"); | |
| /// } | |
| /// println!(); | |
| /// ``` | |
| /// | |
| /// Using `println!` directly: | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// println!("{}", 'ß'.to_titlecase()); | |
| /// ``` | |
| /// | |
| /// Both are equivalent to: | |
| /// | |
| /// ``` | |
| /// println!("Ss"); | |
| /// ``` | |
| /// | |
| /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string): | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// assert_eq!('c'.to_titlecase().to_string(), "C"); | |
| /// assert_eq!('ა'.to_titlecase().to_string(), "ა"); | |
| /// assert_eq!('dž'.to_titlecase().to_string(), "Dž"); | |
| /// assert_eq!('ᾨ'.to_titlecase().to_string(), "ᾨ"); | |
| /// | |
| /// // Sometimes the result is more than one character: | |
| /// assert_eq!('ß'.to_titlecase().to_string(), "Ss"); | |
| /// | |
| /// // Characters that do not have separate cased forms | |
| /// // convert into themselves. | |
| /// assert_eq!('山'.to_titlecase().to_string(), "山"); | |
| /// ``` | |
| /// | |
| /// # Difference from uppercase | |
| /// | |
| /// Currently, there are three classes of characters where [`to_uppercase()`] | |
| /// and `to_titlecase()` give different results: | |
| /// | |
| /// ## Georgian script | |
| /// | |
| /// Each letter in the modern Georgian alphabet can be written in one of two forms: | |
| /// the typical lowercase-like "mkhedruli" form, and a variant uppercase-like "mtavruli" | |
| /// form. However, unlike uppercase in most cased scripts, mtavruli is not typically used | |
| /// to start sentences, denote proper nouns, or for any other purpose | |
| /// in running text. It is instead confined to titles and headings, which are written entirely | |
| /// in mtavruli. For this reason, [`to_uppercase()`] applied to a Georgian letter | |
| /// will return the mtavruli form, but `to_titlecase()` will return the mkhedruli form. | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// let ani = 'ა'; // First letter of the Georgian alphabet, in mkhedruli form | |
| /// | |
| /// // Titlecasing mkhedruli maps it to itself... | |
| /// assert_eq!(ani.to_titlecase().to_string(), ani.to_string()); | |
| /// | |
| /// // but uppercasing it maps it to mtavruli | |
| /// assert_eq!(ani.to_uppercase().to_string(), "Ა"); | |
| /// ``` | |
| /// | |
| /// ## Compatibility digraphs for Latin-alphabet Serbo-Croatian | |
| /// | |
| /// The standard Latin alphabet for the Serbo-Croatian language | |
| /// (Bosnian, Croatian, Montenegrin, and Serbian) contains | |
| /// three digraphs: Dž, Lj, and Nj. These are usually represented as | |
| /// two characters. However, for compatibility with older character sets, | |
| /// Unicode includes single-character versions of these digraphs. | |
| /// Each has a uppercase, titlecase, and lowercase version: | |
| /// | |
| /// - `'DŽ'`, `'Dž'`, `'dž'` | |
| /// - `'LJ'`, `'Lj'`, `'lj'` | |
| /// - `'NJ'`, `'Nj'`, `'nj'` | |
| /// | |
| /// Unicode additionally encodes a casing triad for the Dz digraph | |
| /// without the caron: `'DZ'`, `'Dz'`, `'dz'`. | |
| /// | |
| /// ## Iota-subscritped Greek vowels | |
| /// | |
| /// In ancient Greek, the long vowels alpha (α), eta (η), and omega (ω) | |
| /// were sometimes followed by an iota (ι), forming a diphthong. Over time, | |
| /// the diphthong pronunciation was slowly lost, with the iota becoming mute. | |
| /// Eventually, the ι disappeared from the spelling as well. | |
| /// However, there remains a need to represent ancient texts faithfully. | |
| /// | |
| /// Modern editions of ancient Greek texts commonly use a reduced-sized | |
| /// ι symbol to denote mute iotas, while distinguishing them from ιs | |
| /// which continued to affect pronunciation. The exact standard differs | |
| /// between different publications. Some render the mute ι below its associated | |
| /// vowel (subscript), while others place it to the right of said vowel (adscript). | |
| /// The interaction of mute ι symbols with casing also varies. | |
| /// | |
| /// The Unicode Standard, for its default casing rules, chose to make lowercase | |
| /// Greek vowels with iota subscipt (e.g. `'ᾠ'`) titlecase to the uppercase vowel | |
| /// with iota subscript (`'ᾨ'`) but uppercase to the uppercase vowel followed by | |
| /// full-size uppercase iota (`"ὨΙ"`). This is just one convention among many | |
| /// in common use, but it is the one Unicode settled on, | |
| /// so it is what this method does also. | |
| /// | |
| /// # Note on locale | |
| /// | |
| /// As stated above, this method is locale-insensitive. | |
| /// If you need locale support, consider using an external crate, | |
| /// like [`icu_casemap`](https://crates.io/crates/icu_casemap) | |
| /// which is developed by Unicode. A description of one common | |
| /// locale-dependent casing issue follows (there are others): | |
| /// | |
| /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two: | |
| /// | |
| /// * 'Dotless': I / ı, sometimes written ï | |
| /// * 'Dotted': İ / i | |
| /// | |
| /// Note that the lowercase dotted 'i' is the same codepoint as the Latin. Therefore: | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// let upper_i = 'i'.to_titlecase().to_string(); | |
| /// ``` | |
| /// | |
| /// `'i'`'s correct titlecase relies on the language of the text: if we're | |
| /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should | |
| /// be `"İ"`. `to_titlecase()` does not take this into account, and so: | |
| /// | |
| /// ``` | |
| /// #![feature(titlecase)] | |
| /// let upper_i = 'i'.to_titlecase().to_string(); | |
| /// | |
| /// assert_eq!(upper_i, "I"); | |
| /// ``` | |
| /// | |
| /// holds across languages. | |
| /// | |
| /// [`to_uppercase()`]: Self::to_uppercase() | |
| #[must_use = "this returns the titlecased character as a new iterator, \ | |
| without modifying the original"] | |
| #[unstable(feature = "titlecase", issue = "153892")] | |
| #[inline] | |
| pub fn to_titlecase(self) -> ToTitlecase { | |
| ToTitlecase(CaseMappingIter::new(conversions::to_title(self))) | |
| } | |
| /// Returns an iterator that yields the uppercase mapping of this `char` as one or more | |
| /// `char`s. | |
| /// | |
| /// Prefer this method when converting a word into ALL CAPS, but consider [`to_titlecase()`] | |
| /// instead if you seek to capitalize Only The First Letter. See that method's documentation | |
| /// for more information on the difference between the two. | |
| /// | |
| /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`. | |
| /// | |
| /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character | |
| /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`. | |
| /// | |
| /// [ucd]: https://www.unicode.org/reports/tr44/ | |
| /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt | |
| /// | |
| /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by | |
| /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3. | |
| /// | |
| /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt | |
| /// | |
| /// This operation performs an unconditional mapping without tailoring. That is, the conversion | |
| /// is independent of context and language. See [below](#note-on-locale) | |
| /// for more information. | |
| /// | |
| /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in | |
| /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion. | |
| /// | |
| /// [Unicode Standard]: https://www.unicode.org/versions/latest/ | |
| /// | |
| /// # Examples | |
| /// | |
| /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase. | |
| /// | |
| /// As an iterator: | |
| /// | |
| /// ``` | |
| /// for c in 'ſt'.to_uppercase() { | |
| /// print!("{c}"); | |
| /// } | |
| /// println!(); | |
| /// ``` | |
| /// | |
| /// Using `println!` directly: | |
| /// | |
| /// ``` | |
| /// println!("{}", 'ſt'.to_uppercase()); | |
| /// ``` | |
| /// | |
| /// Both are equivalent to: | |
| /// | |
| /// ``` | |
| /// println!("ST"); | |
| /// ``` | |
| /// | |
| /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string): | |
| /// | |
| /// ``` | |
| /// assert_eq!('c'.to_uppercase().to_string(), "C"); | |
| /// assert_eq!('ა'.to_uppercase().to_string(), "Ა"); | |
| /// assert_eq!('dž'.to_uppercase().to_string(), "DŽ"); | |
| /// | |
| /// // Sometimes the result is more than one character: | |
| /// assert_eq!('ſt'.to_uppercase().to_string(), "ST"); | |
| /// assert_eq!('ᾨ'.to_uppercase().to_string(), "ὨΙ"); | |
| /// | |
| /// // Characters that do not have both uppercase and lowercase | |
| /// // convert into themselves. | |
| /// assert_eq!('山'.to_uppercase().to_string(), "山"); | |
| /// ``` | |
| /// | |
| /// # Note on locale | |
| /// | |
| /// As stated above, this method is locale-insensitive. | |
| /// If you need locale support, consider using an external crate, | |
| /// like [`icu_casemap`](https://crates.io/crates/icu_casemap) | |
| /// which is developed by Unicode. A description of one common | |
| /// locale-dependent casing issue follows (there are others): | |
| /// | |
| /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two: | |
| /// | |
| /// * 'Dotless': I / ı, sometimes written ï | |
| /// * 'Dotted': İ / i | |
| /// | |
| /// Note that the lowercase dotted 'i' is the same codepoint as the Latin. Therefore: | |
| /// | |
| /// ``` | |
| /// let upper_i = 'i'.to_uppercase().to_string(); | |
| /// ``` | |
| /// | |
| /// `'i'`'s correct uppercase relies on the language of the text: if we're | |
| /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should | |
| /// be `"İ"`. `to_uppercase()` does not take this into account, and so: | |
| /// | |
| /// ``` | |
| /// let upper_i = 'i'.to_uppercase().to_string(); | |
| /// | |
| /// assert_eq!(upper_i, "I"); | |
| /// ``` | |
| /// | |
| /// holds across languages. | |
| /// | |
| /// [`to_titlecase()`]: Self::to_titlecase() | |
| #[must_use = "this returns the uppercased character as a new iterator, \ | |
| without modifying the original"] | |
| #[stable(feature = "rust1", since = "1.0.0")] | |
| #[inline] | |
| pub fn to_uppercase(self) -> ToUppercase { | |
| ToUppercase(CaseMappingIter::new(conversions::to_upper(self))) | |
| } | |
| /// Returns an iterator that yields the case folding of this `char` as one or more | |
| /// `char`s. | |
| /// | |
| /// Case folding is meant to be used when performing case-insensitive string comparisons. | |
| /// Case-folded strings should not usually be exposed directly to users. For most, | |
| /// but not all, characters, the casefold mapping is identical to the lowercase one. | |
| /// | |
| /// This iterator yields the `char`(s) in the common or full case folding for this `char`, | |
| /// as given by the [Unicode Character Database][ucd] [`CaseFolding.txt`]. | |
| /// The maximum number of `char`s in a case folding is 3. | |
| /// | |
| /// [ucd]: https://www.unicode.org/reports/tr44/ | |
| /// [`CaseFolding.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt | |
| /// | |
| /// | |
| /// No [normalization] (e.g. NFC) is performed, so visually and semantically identical characters | |
| /// might still casefold differently. For example, `'ά'` (U+03AC GREEK SMALL LETTER ALPHA WITH TONOS) | |
| /// is considered distinct from `'ά'` (U+1F71 GREEK SMALL LETTER ALPHA WITH OXIA), | |
| /// even though Unicode considers them canonically equivalent. | |
| /// | |
| /// In addition, this method is independent of language/locale, | |
| /// so the special behavior of I/ı/İ/i in Turkish and Azeri is not handled. | |
| /// | |
| /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case folding in | |
| /// general and Chapter 3 (Conformance) discusses the default algorithm for case folding. | |
| /// | |
| /// [Unicode Standard]: https://www.unicode.org/versions/latest/ | |
| /// | |
| /// # Examples | |
| /// | |
| /// The German sharp S `'ß'` (U+DF) is a single Unicode code point | |
| /// that casefolds to `"ss"`. Its uppercase variant '`ẞ`' (U+1E9E) | |
| /// has the same case-folding. | |
| /// | |
| /// As an iterator: | |
| /// | |
| /// ``` | |
| /// #![feature(casefold)] | |
| /// assert!('ß'.to_casefold_unnormalized().eq(['s', 's'])); | |
| /// assert!('ẞ'.to_casefold_unnormalized().eq(['s', 's'])); | |
| /// ``` | |
| /// | |
| /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string): | |
| /// | |
| /// ``` | |
| /// #![feature(casefold)] | |
| /// assert_eq!('ß'.to_casefold_unnormalized().to_string(), "ss"); | |
| /// assert_eq!('ẞ'.to_casefold_unnormalized().to_string(), "ss"); | |
| /// ``` | |
| /// | |
| /// No [normalization] is performed: | |
| /// | |
| /// ```rust | |
| /// #![feature(casefold)] | |
| /// // These two characters are visually and semantically identical; | |
| /// // Unicode considers them to be canonically equivalent. | |
| /// let alpha_tonos = 'ά'; | |
| /// let alpha_oxia = 'ά'; | |
| /// | |
| /// // However, they are different codepoints: | |
| /// assert_eq!(alpha_tonos, '\u{03AC}'); | |
| /// assert_eq!(alpha_oxia, '\u{1F71}'); | |
| /// | |
| /// // Their case-foldings are likewise unequal: | |
| /// assert!(alpha_tonos.to_casefold_unnormalized().eq(['\u{03AC}'])); | |
| /// assert!(alpha_oxia.to_casefold_unnormalized().eq(['\u{1F71}'])); | |
| /// ``` | |
| /// | |
| /// # Note on locale | |
| /// | |
| /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two: | |
| /// | |
| /// * 'Dotless': I / ı, sometimes written ï | |
| /// * 'Dotted': İ / i | |
| /// | |
| /// Note that the uppercase undotted 'I' is the same codepoint as the Latin. Therefore: | |
| /// | |
| /// ``` | |
| /// #![feature(casefold)] | |
| /// let casefold_i = 'I'.to_casefold_unnormalized().to_string(); | |
| /// ``` | |
| /// | |
| /// `'I'`'s correct case folding relies on the language of the text: if we're | |
| /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should | |
| /// be `"ı"`. `to_casefold_unnormalized()` does not take this into account, and so: | |
| /// | |
| /// ``` | |
| /// #![feature(casefold)] | |
| /// let casefold_i = 'I'.to_casefold_unnormalized().to_string(); | |
| /// | |
| /// assert_eq!(casefold_i, "i"); | |
| /// ``` | |
| /// | |
| /// holds across languages. | |
| /// | |
| /// [normalization]: https://www.unicode.org/faq/normalization.html | |
| #[must_use = "this returns the case-folded character as a new iterator, \ | |
| without modifying the original"] | |
| #[unstable(feature = "casefold", issue = "157000")] | |
| #[inline] | |
| pub fn to_casefold_unnormalized(self) -> ToCasefold { | |
| ToCasefold(CaseMappingIter::new(conversions::to_casefold(self))) | |
| } | |
| /// Returns the code point value as a `u32`. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// #![feature(char_to_u32)] | |
| /// | |
| /// let ascii = 'a'; | |
| /// let heart = '❤'; | |
| /// | |
| /// assert_eq!(ascii.to_u32(), 97_u32); | |
| /// assert_eq!(heart.to_u32(), 0x2764_u32); | |
| /// ``` | |
| #[must_use = "this returns the result of the operation, \ | |
| without modifying the original"] | |
| #[unstable(feature = "char_to_u32", issue = "158938")] | |
| #[rustc_const_unstable(feature = "char_to_u32", issue = "158938")] | |
| #[inline(always)] | |
| pub const fn to_u32(self) -> u32 { | |
| self as u32 | |
| } | |
| /// Checks if the value is within the ASCII range. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let ascii = 'a'; | |
| /// let non_ascii = '❤'; | |
| /// | |
| /// assert!(ascii.is_ascii()); | |
| /// assert!(!non_ascii.is_ascii()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] | |
| #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")] | |
| #[rustc_diagnostic_item = "char_is_ascii"] | |
| #[inline] | |
| pub const fn is_ascii(&self) -> bool { | |
| *self as u32 <= 0x7F | |
| } | |
| /// Returns `Some` if the value is within the ASCII range, | |
| /// or `None` if it's not. | |
| /// | |
| /// This is preferred to [`Self::is_ascii`] when you're passing the value | |
| /// along to something else that can take [`ascii::Char`] rather than | |
| /// needing to check again for itself whether the value is in ASCII. | |
| #[must_use] | |
| #[unstable(feature = "ascii_char", issue = "110998")] | |
| #[inline] | |
| pub const fn as_ascii(&self) -> Option<ascii::Char> { | |
| if self.is_ascii() { | |
| // SAFETY: Just checked that this is ASCII. | |
| Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) }) | |
| } else { | |
| None | |
| } | |
| } | |
| /// Converts this char into an [ASCII character](`ascii::Char`), without | |
| /// checking whether it is valid. | |
| /// | |
| /// # Safety | |
| /// | |
| /// This char must be within the ASCII range, or else this is UB. | |
| #[must_use] | |
| #[unstable(feature = "ascii_char", issue = "110998")] | |
| #[inline] | |
| pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char { | |
| assert_unsafe_precondition!( | |
| check_library_ub, | |
| "as_ascii_unchecked requires that the char is valid ASCII", | |
| (it: &char = self) => it.is_ascii() | |
| ); | |
| // SAFETY: the caller promised that this char is ASCII. | |
| unsafe { ascii::Char::from_u8_unchecked(*self as u8) } | |
| } | |
| /// Makes a copy of the value in its ASCII upper case equivalent. | |
| /// | |
| /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', | |
| /// but non-ASCII letters are unchanged. | |
| /// | |
| /// To uppercase the value in-place, use [`make_ascii_uppercase()`]. | |
| /// | |
| /// To uppercase ASCII characters in addition to non-ASCII characters, use | |
| /// [`to_uppercase()`]. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let ascii = 'a'; | |
| /// let non_ascii = '❤'; | |
| /// | |
| /// assert_eq!('A', ascii.to_ascii_uppercase()); | |
| /// assert_eq!('❤', non_ascii.to_ascii_uppercase()); | |
| /// ``` | |
| /// | |
| /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase | |
| /// [`to_uppercase()`]: #method.to_uppercase | |
| #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"] | |
| #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] | |
| #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")] | |
| #[inline] | |
| pub const fn to_ascii_uppercase(&self) -> char { | |
| if self.is_ascii_lowercase() { | |
| (*self as u8).ascii_change_case_unchecked() as char | |
| } else { | |
| *self | |
| } | |
| } | |
| /// Makes a copy of the value in its ASCII lower case equivalent. | |
| /// | |
| /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', | |
| /// but non-ASCII letters are unchanged. | |
| /// | |
| /// To lowercase the value in-place, use [`make_ascii_lowercase()`]. | |
| /// | |
| /// To lowercase ASCII characters in addition to non-ASCII characters, use | |
| /// [`to_lowercase()`]. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let ascii = 'A'; | |
| /// let non_ascii = '❤'; | |
| /// | |
| /// assert_eq!('a', ascii.to_ascii_lowercase()); | |
| /// assert_eq!('❤', non_ascii.to_ascii_lowercase()); | |
| /// ``` | |
| /// | |
| /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase | |
| /// [`to_lowercase()`]: #method.to_lowercase | |
| #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"] | |
| #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] | |
| #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")] | |
| #[inline] | |
| pub const fn to_ascii_lowercase(&self) -> char { | |
| if self.is_ascii_uppercase() { | |
| (*self as u8).ascii_change_case_unchecked() as char | |
| } else { | |
| *self | |
| } | |
| } | |
| /// Checks that two values are an ASCII case-insensitive match. | |
| /// | |
| /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let upper_a = 'A'; | |
| /// let lower_a = 'a'; | |
| /// let lower_z = 'z'; | |
| /// | |
| /// assert!(upper_a.eq_ignore_ascii_case(&lower_a)); | |
| /// assert!(upper_a.eq_ignore_ascii_case(&upper_a)); | |
| /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z)); | |
| /// ``` | |
| /// | |
| /// [to_ascii_lowercase]: #method.to_ascii_lowercase | |
| #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] | |
| #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")] | |
| #[expect(clippy::manual_ignore_case_cmp, reason = "implements eq_ignore_ascii_case")] | |
| #[inline] | |
| pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool { | |
| self.to_ascii_lowercase() == other.to_ascii_lowercase() | |
| } | |
| /// Converts this type to its ASCII upper case equivalent in-place. | |
| /// | |
| /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', | |
| /// but non-ASCII letters are unchanged. | |
| /// | |
| /// To return a new uppercased value without modifying the existing one, use | |
| /// [`to_ascii_uppercase()`]. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let mut ascii = 'a'; | |
| /// | |
| /// ascii.make_ascii_uppercase(); | |
| /// | |
| /// assert_eq!('A', ascii); | |
| /// ``` | |
| /// | |
| /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase | |
| #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] | |
| #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")] | |
| #[inline] | |
| pub const fn make_ascii_uppercase(&mut self) { | |
| *self = self.to_ascii_uppercase(); | |
| } | |
| /// Converts this type to its ASCII lower case equivalent in-place. | |
| /// | |
| /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', | |
| /// but non-ASCII letters are unchanged. | |
| /// | |
| /// To return a new lowercased value without modifying the existing one, use | |
| /// [`to_ascii_lowercase()`]. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let mut ascii = 'A'; | |
| /// | |
| /// ascii.make_ascii_lowercase(); | |
| /// | |
| /// assert_eq!('a', ascii); | |
| /// ``` | |
| /// | |
| /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase | |
| #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] | |
| #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")] | |
| #[inline] | |
| pub const fn make_ascii_lowercase(&mut self) { | |
| *self = self.to_ascii_lowercase(); | |
| } | |
| /// Checks if the value is an ASCII alphabetic character: | |
| /// | |
| /// - U+0041 'A' ..= U+005A 'Z', or | |
| /// - U+0061 'a' ..= U+007A 'z'. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(uppercase_a.is_ascii_alphabetic()); | |
| /// assert!(uppercase_g.is_ascii_alphabetic()); | |
| /// assert!(a.is_ascii_alphabetic()); | |
| /// assert!(g.is_ascii_alphabetic()); | |
| /// assert!(!zero.is_ascii_alphabetic()); | |
| /// assert!(!percent.is_ascii_alphabetic()); | |
| /// assert!(!space.is_ascii_alphabetic()); | |
| /// assert!(!lf.is_ascii_alphabetic()); | |
| /// assert!(!esc.is_ascii_alphabetic()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_alphabetic(&self) -> bool { | |
| matches!(*self, 'a'..='z' | 'A'..='Z') | |
| } | |
| /// Checks if the value is an ASCII uppercase character: | |
| /// U+0041 'A' ..= U+005A 'Z'. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(uppercase_a.is_ascii_uppercase()); | |
| /// assert!(uppercase_g.is_ascii_uppercase()); | |
| /// assert!(!a.is_ascii_uppercase()); | |
| /// assert!(!g.is_ascii_uppercase()); | |
| /// assert!(!zero.is_ascii_uppercase()); | |
| /// assert!(!percent.is_ascii_uppercase()); | |
| /// assert!(!space.is_ascii_uppercase()); | |
| /// assert!(!lf.is_ascii_uppercase()); | |
| /// assert!(!esc.is_ascii_uppercase()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_uppercase(&self) -> bool { | |
| matches!(*self, 'A'..='Z') | |
| } | |
| /// Checks if the value is an ASCII lowercase character: | |
| /// U+0061 'a' ..= U+007A 'z'. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(!uppercase_a.is_ascii_lowercase()); | |
| /// assert!(!uppercase_g.is_ascii_lowercase()); | |
| /// assert!(a.is_ascii_lowercase()); | |
| /// assert!(g.is_ascii_lowercase()); | |
| /// assert!(!zero.is_ascii_lowercase()); | |
| /// assert!(!percent.is_ascii_lowercase()); | |
| /// assert!(!space.is_ascii_lowercase()); | |
| /// assert!(!lf.is_ascii_lowercase()); | |
| /// assert!(!esc.is_ascii_lowercase()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_lowercase(&self) -> bool { | |
| matches!(*self, 'a'..='z') | |
| } | |
| /// Checks if the value is an ASCII alphanumeric character: | |
| /// | |
| /// - U+0041 'A' ..= U+005A 'Z', or | |
| /// - U+0061 'a' ..= U+007A 'z', or | |
| /// - U+0030 '0' ..= U+0039 '9'. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(uppercase_a.is_ascii_alphanumeric()); | |
| /// assert!(uppercase_g.is_ascii_alphanumeric()); | |
| /// assert!(a.is_ascii_alphanumeric()); | |
| /// assert!(g.is_ascii_alphanumeric()); | |
| /// assert!(zero.is_ascii_alphanumeric()); | |
| /// assert!(!percent.is_ascii_alphanumeric()); | |
| /// assert!(!space.is_ascii_alphanumeric()); | |
| /// assert!(!lf.is_ascii_alphanumeric()); | |
| /// assert!(!esc.is_ascii_alphanumeric()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_alphanumeric(&self) -> bool { | |
| matches!(*self, '0'..='9') | matches!(*self, 'A'..='Z') | matches!(*self, 'a'..='z') | |
| } | |
| /// Checks if the value is an ASCII decimal digit: | |
| /// U+0030 '0' ..= U+0039 '9'. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(!uppercase_a.is_ascii_digit()); | |
| /// assert!(!uppercase_g.is_ascii_digit()); | |
| /// assert!(!a.is_ascii_digit()); | |
| /// assert!(!g.is_ascii_digit()); | |
| /// assert!(zero.is_ascii_digit()); | |
| /// assert!(!percent.is_ascii_digit()); | |
| /// assert!(!space.is_ascii_digit()); | |
| /// assert!(!lf.is_ascii_digit()); | |
| /// assert!(!esc.is_ascii_digit()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_digit(&self) -> bool { | |
| matches!(*self, '0'..='9') | |
| } | |
| /// Checks if the value is an ASCII octal digit: | |
| /// U+0030 '0' ..= U+0037 '7'. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// #![feature(is_ascii_octdigit)] | |
| /// | |
| /// let uppercase_a = 'A'; | |
| /// let a = 'a'; | |
| /// let zero = '0'; | |
| /// let seven = '7'; | |
| /// let nine = '9'; | |
| /// let percent = '%'; | |
| /// let lf = '\n'; | |
| /// | |
| /// assert!(!uppercase_a.is_ascii_octdigit()); | |
| /// assert!(!a.is_ascii_octdigit()); | |
| /// assert!(zero.is_ascii_octdigit()); | |
| /// assert!(seven.is_ascii_octdigit()); | |
| /// assert!(!nine.is_ascii_octdigit()); | |
| /// assert!(!percent.is_ascii_octdigit()); | |
| /// assert!(!lf.is_ascii_octdigit()); | |
| /// ``` | |
| #[must_use] | |
| #[unstable(feature = "is_ascii_octdigit", issue = "101288")] | |
| #[inline] | |
| pub const fn is_ascii_octdigit(&self) -> bool { | |
| matches!(*self, '0'..='7') | |
| } | |
| /// Checks if the value is an ASCII hexadecimal digit: | |
| /// | |
| /// - U+0030 '0' ..= U+0039 '9', or | |
| /// - U+0041 'A' ..= U+0046 'F', or | |
| /// - U+0061 'a' ..= U+0066 'f'. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(uppercase_a.is_ascii_hexdigit()); | |
| /// assert!(!uppercase_g.is_ascii_hexdigit()); | |
| /// assert!(a.is_ascii_hexdigit()); | |
| /// assert!(!g.is_ascii_hexdigit()); | |
| /// assert!(zero.is_ascii_hexdigit()); | |
| /// assert!(!percent.is_ascii_hexdigit()); | |
| /// assert!(!space.is_ascii_hexdigit()); | |
| /// assert!(!lf.is_ascii_hexdigit()); | |
| /// assert!(!esc.is_ascii_hexdigit()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_hexdigit(&self) -> bool { | |
| matches!(*self, '0'..='9') | matches!(*self, 'A'..='F') | matches!(*self, 'a'..='f') | |
| } | |
| /// Checks if the value is an ASCII punctuation or symbol character | |
| /// (i.e. not alphanumeric, whitespace, or control): | |
| /// | |
| /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or | |
| /// - U+003A ..= U+0040 `: ; < = > ? @`, or | |
| /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or | |
| /// - U+007B ..= U+007E `{ | } ~` | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(!uppercase_a.is_ascii_punctuation()); | |
| /// assert!(!uppercase_g.is_ascii_punctuation()); | |
| /// assert!(!a.is_ascii_punctuation()); | |
| /// assert!(!g.is_ascii_punctuation()); | |
| /// assert!(!zero.is_ascii_punctuation()); | |
| /// assert!(percent.is_ascii_punctuation()); | |
| /// assert!(!space.is_ascii_punctuation()); | |
| /// assert!(!lf.is_ascii_punctuation()); | |
| /// assert!(!esc.is_ascii_punctuation()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_punctuation(&self) -> bool { | |
| matches!(*self, '!'..='/') | |
| | matches!(*self, ':'..='@') | |
| | matches!(*self, '['..='`') | |
| | matches!(*self, '{'..='~') | |
| } | |
| /// Checks if the value is an ASCII graphic character | |
| /// (i.e. not whitespace or control): | |
| /// U+0021 '!' ..= U+007E '~'. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(uppercase_a.is_ascii_graphic()); | |
| /// assert!(uppercase_g.is_ascii_graphic()); | |
| /// assert!(a.is_ascii_graphic()); | |
| /// assert!(g.is_ascii_graphic()); | |
| /// assert!(zero.is_ascii_graphic()); | |
| /// assert!(percent.is_ascii_graphic()); | |
| /// assert!(!space.is_ascii_graphic()); | |
| /// assert!(!lf.is_ascii_graphic()); | |
| /// assert!(!esc.is_ascii_graphic()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_graphic(&self) -> bool { | |
| matches!(*self, '!'..='~') | |
| } | |
| /// Checks if the value is an ASCII whitespace character: | |
| /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED, | |
| /// U+000C FORM FEED, or U+000D CARRIAGE RETURN. | |
| /// | |
| /// **Warning:** Because the list above excludes U+000B VERTICAL TAB, | |
| /// `c.is_ascii_whitespace()` is **not** equivalent to `c.is_ascii() && c.is_whitespace()`. | |
| /// | |
| /// Rust uses the WhatWG Infra Standard's [definition of ASCII | |
| /// whitespace][infra-aw]. There are several other definitions in | |
| /// wide use. For instance, [the POSIX locale][pct] includes | |
| /// U+000B VERTICAL TAB as well as all the above characters, | |
| /// but—from the very same specification—[the default rule for | |
| /// "field splitting" in the Bourne shell][bfs] considers *only* | |
| /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace. | |
| /// | |
| /// If you are writing a program that will process an existing | |
| /// file format, check what that format's definition of whitespace is | |
| /// before using this function. | |
| /// | |
| /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace | |
| /// [pct]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap07.html#tag_07_03_01 | |
| /// [bfs]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_06_05 | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(!uppercase_a.is_ascii_whitespace()); | |
| /// assert!(!uppercase_g.is_ascii_whitespace()); | |
| /// assert!(!a.is_ascii_whitespace()); | |
| /// assert!(!g.is_ascii_whitespace()); | |
| /// assert!(!zero.is_ascii_whitespace()); | |
| /// assert!(!percent.is_ascii_whitespace()); | |
| /// assert!(space.is_ascii_whitespace()); | |
| /// assert!(lf.is_ascii_whitespace()); | |
| /// assert!(!esc.is_ascii_whitespace()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_whitespace(&self) -> bool { | |
| matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ') | |
| } | |
| /// Checks if the value is an ASCII control character: | |
| /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE. | |
| /// Note that most ASCII whitespace characters are control | |
| /// characters, but SPACE is not. | |
| /// | |
| /// # Examples | |
| /// | |
| /// ``` | |
| /// let uppercase_a = 'A'; | |
| /// let uppercase_g = 'G'; | |
| /// let a = 'a'; | |
| /// let g = 'g'; | |
| /// let zero = '0'; | |
| /// let percent = '%'; | |
| /// let space = ' '; | |
| /// let lf = '\n'; | |
| /// let esc = '\x1b'; | |
| /// | |
| /// assert!(!uppercase_a.is_ascii_control()); | |
| /// assert!(!uppercase_g.is_ascii_control()); | |
| /// assert!(!a.is_ascii_control()); | |
| /// assert!(!g.is_ascii_control()); | |
| /// assert!(!zero.is_ascii_control()); | |
| /// assert!(!percent.is_ascii_control()); | |
| /// assert!(!space.is_ascii_control()); | |
| /// assert!(lf.is_ascii_control()); | |
| /// assert!(esc.is_ascii_control()); | |
| /// ``` | |
| #[must_use] | |
| #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] | |
| #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] | |
| #[inline] | |
| pub const fn is_ascii_control(&self) -> bool { | |
| matches!(*self, '\0'..='\x1F' | '\x7F') | |
| } | |
| } | |
| pub(crate) struct EscapeDebugExtArgs { | |
| /// Escape single quotes? | |
| pub(crate) escape_single_quote: bool, | |
| /// Escape double quotes? | |
| pub(crate) escape_double_quote: bool, | |
| } | |
| impl EscapeDebugExtArgs { | |
| pub(crate) const ESCAPE_ALL: Self = | |
| Self { escape_single_quote: true, escape_double_quote: true }; | |
| } | |
| #[inline] | |
| #[must_use] | |
| const fn len_utf8(code: u32) -> usize { | |
| match code { | |
| ..MAX_ONE_B => 1, | |
| ..MAX_TWO_B => 2, | |
| ..MAX_THREE_B => 3, | |
| _ => 4, | |
| } | |
| } | |
| #[inline] | |
| #[must_use] | |
| const fn len_utf16(code: u32) -> usize { | |
| if (code & 0xFFFF) == code { 1 } else { 2 } | |
| } | |
| /// Encodes a raw `u32` value as UTF-8 into the provided byte buffer, | |
| /// and then returns the subslice of the buffer that contains the encoded character. | |
| /// | |
| /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range. | |
| /// (Creating a `char` in the surrogate range is UB.) | |
| /// The result is valid [generalized UTF-8] but not valid UTF-8. | |
| /// | |
| /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8 | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the buffer is not large enough. | |
| /// A buffer of length four is large enough to encode any `char`. | |
| #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] | |
| #[doc(hidden)] | |
| #[inline] | |
| pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] { | |
| let len = len_utf8(code); | |
| if dst.len() < len { | |
| const_panic!( | |
| "encode_utf8: buffer does not have enough bytes to encode code point", | |
| "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}", | |
| code: u32 = code, | |
| len: usize = len, | |
| dst_len: usize = dst.len(), | |
| ); | |
| } | |
| // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint. | |
| unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) }; | |
| // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds. | |
| unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) } | |
| } | |
| /// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`. | |
| /// | |
| /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range. | |
| /// (Creating a `char` in the surrogate range is UB.) | |
| /// The result is valid [generalized UTF-8] but not valid UTF-8. | |
| /// | |
| /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8 | |
| /// | |
| /// # Safety | |
| /// | |
| /// The behavior is undefined if the buffer pointed to by `dst` is not | |
| /// large enough to hold the encoded codepoint. A buffer of length four | |
| /// is large enough to encode any `char`. | |
| /// | |
| /// For a safe version of this function, see the [`encode_utf8_raw`] function. | |
| #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] | |
| #[doc(hidden)] | |
| #[inline] | |
| pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) { | |
| let len = len_utf8(code); | |
| // SAFETY: The caller must guarantee that the buffer pointed to by `dst` | |
| // is at least `len` bytes long. | |
| unsafe { | |
| if len == 1 { | |
| *dst = code as u8; | |
| return; | |
| } | |
| let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT; | |
| let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT; | |
| let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT; | |
| let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B; | |
| if len == 2 { | |
| *dst = last2 | TAG_TWO_B; | |
| *dst.add(1) = last1; | |
| return; | |
| } | |
| if len == 3 { | |
| *dst = last3 | TAG_THREE_B; | |
| *dst.add(1) = last2; | |
| *dst.add(2) = last1; | |
| return; | |
| } | |
| *dst = last4; | |
| *dst.add(1) = last3; | |
| *dst.add(2) = last2; | |
| *dst.add(3) = last1; | |
| } | |
| } | |
| /// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer, | |
| /// and then returns the subslice of the buffer that contains the encoded character. | |
| /// | |
| /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range. | |
| /// (Creating a `char` in the surrogate range is UB.) | |
| /// | |
| /// # Panics | |
| /// | |
| /// Panics if the buffer is not large enough. | |
| /// A buffer of length 2 is large enough to encode any `char`. | |
| #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] | |
| #[doc(hidden)] | |
| #[inline] | |
| pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] { | |
| let len = len_utf16(code); | |
| match (len, &mut *dst) { | |
| (1, [a, ..]) => { | |
| *a = code as u16; | |
| } | |
| (2, [a, b, ..]) => { | |
| code -= 0x1_0000; | |
| *a = (code >> 10) as u16 | 0xD800; | |
| *b = (code & 0x3FF) as u16 | 0xDC00; | |
| } | |
| _ => { | |
| const_panic!( | |
| "encode_utf16: buffer does not have enough bytes to encode code point", | |
| "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}", | |
| code: u32 = code, | |
| len: usize = len, | |
| dst_len: usize = dst.len(), | |
| ) | |
| } | |
| }; | |
| // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds. | |
| unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) } | |
| } |