Skip to main content

core/char/
methods.rs

1//! impl char {}
2
3#![expect(clippy::manual_is_ascii_check, reason = "this module implements various is_ascii checks")]
4
5use super::*;
6use crate::panic::const_panic;
7use crate::slice;
8use crate::str::from_utf8_unchecked_mut;
9use crate::ub_checks::assert_unsafe_precondition;
10use crate::unicode::{self, conversions};
11
12impl char {
13    /// The lowest valid code point a `char` can have, `'\0'`.
14    ///
15    /// Unlike integer types, `char` actually has a gap in the middle,
16    /// meaning that the range of possible `char`s is smaller than you
17    /// might expect. Ranges of `char` will automatically hop this gap
18    /// for you:
19    ///
20    /// ```
21    /// let dist = u32::from(char::MAX) - u32::from(char::MIN);
22    /// let size = (char::MIN..=char::MAX).count() as u32;
23    /// assert!(size < dist);
24    /// ```
25    ///
26    /// Despite this gap, the `MIN` and [`MAX`] values can be used as bounds for
27    /// all `char` values.
28    ///
29    /// [`MAX`]: char::MAX
30    ///
31    /// # Examples
32    ///
33    /// ```
34    /// # fn something_which_returns_char() -> char { 'a' }
35    /// let c: char = something_which_returns_char();
36    /// assert!(char::MIN <= c);
37    ///
38    /// let value_at_min = u32::from(char::MIN);
39    /// assert_eq!(char::from_u32(value_at_min), Some('\0'));
40    /// ```
41    #[stable(feature = "char_min", since = "1.83.0")]
42    pub const MIN: char = '\0';
43
44    /// The highest valid code point a `char` can have, `'\u{10FFFF}'`.
45    ///
46    /// Unlike integer types, `char` actually has a gap in the middle,
47    /// meaning that the range of possible `char`s is smaller than you
48    /// might expect. Ranges of `char` will automatically hop this gap
49    /// for you:
50    ///
51    /// ```
52    /// let dist = u32::from(char::MAX) - u32::from(char::MIN);
53    /// let size = (char::MIN..=char::MAX).count() as u32;
54    /// assert!(size < dist);
55    /// ```
56    ///
57    /// Despite this gap, the [`MIN`] and `MAX` values can be used as bounds for
58    /// all `char` values.
59    ///
60    /// [`MIN`]: char::MIN
61    ///
62    /// # Examples
63    ///
64    /// ```
65    /// # fn something_which_returns_char() -> char { 'a' }
66    /// let c: char = something_which_returns_char();
67    /// assert!(c <= char::MAX);
68    ///
69    /// let value_at_max = u32::from(char::MAX);
70    /// assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
71    /// assert_eq!(char::from_u32(value_at_max + 1), None);
72    /// ```
73    #[stable(feature = "assoc_char_consts", since = "1.52.0")]
74    pub const MAX: char = '\u{10FFFF}';
75
76    /// The maximum number of bytes required to [encode](char::encode_utf8) a `char` to
77    /// UTF-8 encoding.
78    #[stable(feature = "char_max_len_assoc", since = "1.93.0")]
79    pub const MAX_LEN_UTF8: usize = 4;
80
81    /// The maximum number of two-byte units required to [encode](char::encode_utf16) a `char`
82    /// to UTF-16 encoding.
83    #[stable(feature = "char_max_len_assoc", since = "1.93.0")]
84    pub const MAX_LEN_UTF16: usize = 2;
85
86    /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
87    /// decoding error.
88    ///
89    /// It can occur, for example, when giving ill-formed UTF-8 bytes to
90    /// [`String::from_utf8_lossy`](../std/string/struct.String.html#method.from_utf8_lossy).
91    #[stable(feature = "assoc_char_consts", since = "1.52.0")]
92    pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
93
94    /// The version of [Unicode](https://www.unicode.org/) that the Unicode parts of
95    /// `char` and `str` methods are based on.
96    ///
97    /// New versions of Unicode are released regularly, and subsequently all methods
98    /// in the standard library depending on Unicode are updated. Therefore, the
99    /// behavior of some `char` and `str` methods, and the value of this constant,
100    /// change over time (within the boundaries of Unicode's [stability policies]).
101    /// This is *not* considered to be a breaking change.
102    ///
103    /// [stability policies]: https://www.unicode.org/policies/stability_policy.html
104    ///
105    /// The version numbering scheme is explained in
106    /// [Section 3.1 (Version Numbering)] of the Unicode Standard.
107    ///
108    /// [Section 3.1 (Version Numbering)]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G49512
109    #[stable(feature = "assoc_char_consts", since = "1.52.0")]
110    pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION;
111
112    /// Creates an iterator over the native endian UTF-16 encoded code points in `iter`,
113    /// returning unpaired surrogates as `Err`s.
114    ///
115    /// # Examples
116    ///
117    /// Basic usage:
118    ///
119    /// ```
120    /// // 𝄞mus<invalid>ic<invalid>
121    /// let v = [
122    ///     0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
123    /// ];
124    ///
125    /// assert_eq!(
126    ///     char::decode_utf16(v)
127    ///         .map(|r| r.map_err(|e| e.unpaired_surrogate()))
128    ///         .collect::<Vec<_>>(),
129    ///     vec![
130    ///         Ok('𝄞'),
131    ///         Ok('m'), Ok('u'), Ok('s'),
132    ///         Err(0xDD1E),
133    ///         Ok('i'), Ok('c'),
134    ///         Err(0xD834)
135    ///     ]
136    /// );
137    /// ```
138    ///
139    /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
140    ///
141    /// ```
142    /// // 𝄞mus<invalid>ic<invalid>
143    /// let v = [
144    ///     0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
145    /// ];
146    ///
147    /// assert_eq!(
148    ///     char::decode_utf16(v)
149    ///        .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
150    ///        .collect::<String>(),
151    ///     "𝄞mus�ic�"
152    /// );
153    /// ```
154    #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
155    #[inline]
156    pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
157        super::decode::decode_utf16(iter)
158    }
159
160    /// Converts a `u32` to a `char`.
161    ///
162    /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
163    /// [`as`](../std/keyword.as.html):
164    ///
165    /// ```
166    /// let c = '💯';
167    /// let i = c as u32;
168    ///
169    /// assert_eq!(128175, i);
170    /// ```
171    ///
172    /// However, the reverse is not true: not all valid [`u32`]s are valid
173    /// `char`s. `from_u32()` will return `None` if the input is not a valid value
174    /// for a `char`.
175    ///
176    /// For an unsafe version of this function which ignores these checks, see
177    /// [`from_u32_unchecked`].
178    ///
179    /// [`from_u32_unchecked`]: #method.from_u32_unchecked
180    ///
181    /// # Examples
182    ///
183    /// Basic usage:
184    ///
185    /// ```
186    /// let c = char::from_u32(0x2764);
187    ///
188    /// assert_eq!(Some('❤'), c);
189    /// ```
190    ///
191    /// Returning `None` when the input is not a valid `char`:
192    ///
193    /// ```
194    /// let c = char::from_u32(0x110000);
195    ///
196    /// assert_eq!(None, c);
197    /// ```
198    #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
199    #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
200    #[must_use]
201    #[inline]
202    pub const fn from_u32(i: u32) -> Option<char> {
203        super::convert::from_u32(i)
204    }
205
206    /// Converts a `u32` to a `char`, ignoring validity.
207    ///
208    /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
209    /// `as`:
210    ///
211    /// ```
212    /// let c = '💯';
213    /// let i = c as u32;
214    ///
215    /// assert_eq!(128175, i);
216    /// ```
217    ///
218    /// However, the reverse is not true: not all valid [`u32`]s are valid
219    /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to
220    /// `char`, possibly creating an invalid one.
221    ///
222    /// # Safety
223    ///
224    /// This function is unsafe, as it may construct invalid `char` values.
225    ///
226    /// For a safe version of this function, see the [`from_u32`] function.
227    ///
228    /// [`from_u32`]: #method.from_u32
229    ///
230    /// # Examples
231    ///
232    /// Basic usage:
233    ///
234    /// ```
235    /// let c = unsafe { char::from_u32_unchecked(0x2764) };
236    ///
237    /// assert_eq!('❤', c);
238    /// ```
239    #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
240    #[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")]
241    #[must_use]
242    #[inline]
243    pub const unsafe fn from_u32_unchecked(i: u32) -> char {
244        // SAFETY: the safety contract must be upheld by the caller.
245        unsafe { super::convert::from_u32_unchecked(i) }
246    }
247
248    /// Converts a digit in the given radix to a `char`.
249    ///
250    /// A 'radix' here is sometimes also called a 'base'. A radix of two
251    /// indicates a binary number, a radix of ten, decimal, and a radix of
252    /// sixteen, hexadecimal, to give some common values. Arbitrary
253    /// radices are supported.
254    ///
255    /// `from_digit()` will return `None` if the input is not a digit in
256    /// the given radix.
257    ///
258    /// # Panics
259    ///
260    /// Panics if given a radix larger than 36.
261    ///
262    /// # Examples
263    ///
264    /// Basic usage:
265    ///
266    /// ```
267    /// let c = char::from_digit(4, 10);
268    ///
269    /// assert_eq!(Some('4'), c);
270    ///
271    /// // Decimal 11 is a single digit in base 16
272    /// let c = char::from_digit(11, 16);
273    ///
274    /// assert_eq!(Some('b'), c);
275    /// ```
276    ///
277    /// Returning `None` when the input is not a digit:
278    ///
279    /// ```
280    /// let c = char::from_digit(20, 10);
281    ///
282    /// assert_eq!(None, c);
283    /// ```
284    ///
285    /// Passing a large radix, causing a panic:
286    ///
287    /// ```should_panic
288    /// // this panics
289    /// let _c = char::from_digit(1, 37);
290    /// ```
291    #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
292    #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
293    #[must_use]
294    #[inline]
295    pub const fn from_digit(num: u32, radix: u32) -> Option<char> {
296        super::convert::from_digit(num, radix)
297    }
298
299    /// Checks if a `char` is a digit in the given radix.
300    ///
301    /// A 'radix' here is sometimes also called a 'base'. A radix of two
302    /// indicates a binary number, a radix of ten, decimal, and a radix of
303    /// sixteen, hexadecimal, to give some common values. Arbitrary
304    /// radices are supported.
305    ///
306    /// Compared to [`is_numeric()`], this function only recognizes the characters
307    /// `0-9`, `a-z` and `A-Z`.
308    ///
309    /// 'Digit' is defined to be only the following characters:
310    ///
311    /// * `0-9`
312    /// * `a-z`
313    /// * `A-Z`
314    ///
315    /// For a more comprehensive understanding of 'digit', see [`is_numeric()`].
316    ///
317    /// [`is_numeric()`]: #method.is_numeric
318    ///
319    /// # Panics
320    ///
321    /// Panics if given a radix smaller than 2 or larger than 36.
322    ///
323    /// # Examples
324    ///
325    /// Basic usage:
326    ///
327    /// ```
328    /// assert!('1'.is_digit(10));
329    /// assert!('f'.is_digit(16));
330    /// assert!(!'f'.is_digit(10));
331    /// ```
332    ///
333    /// Passing a large radix, causing a panic:
334    ///
335    /// ```should_panic
336    /// // this panics
337    /// '1'.is_digit(37);
338    /// ```
339    ///
340    /// Passing a small radix, causing a panic:
341    ///
342    /// ```should_panic
343    /// // this panics
344    /// '1'.is_digit(1);
345    /// ```
346    #[stable(feature = "rust1", since = "1.0.0")]
347    #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
348    #[expect(clippy::to_digit_is_some, reason = "implements is_digit")]
349    #[inline]
350    pub const fn is_digit(self, radix: u32) -> bool {
351        self.to_digit(radix).is_some()
352    }
353
354    /// Converts a `char` to a digit in the given radix.
355    ///
356    /// A 'radix' here is sometimes also called a 'base'. A radix of two
357    /// indicates a binary number, a radix of ten, decimal, and a radix of
358    /// sixteen, hexadecimal, to give some common values. Arbitrary
359    /// radices are supported.
360    ///
361    /// 'Digit' is defined to be only the following characters:
362    ///
363    /// * `0-9`
364    /// * `a-z`
365    /// * `A-Z`
366    ///
367    /// # Errors
368    ///
369    /// Returns `None` if the `char` does not refer to a digit in the given radix.
370    ///
371    /// # Panics
372    ///
373    /// Panics if given a radix smaller than 2 or larger than 36.
374    ///
375    /// # Examples
376    ///
377    /// Basic usage:
378    ///
379    /// ```
380    /// assert_eq!('1'.to_digit(10), Some(1));
381    /// assert_eq!('f'.to_digit(16), Some(15));
382    /// ```
383    ///
384    /// Passing a non-digit results in failure:
385    ///
386    /// ```
387    /// assert_eq!('f'.to_digit(10), None);
388    /// assert_eq!('z'.to_digit(16), None);
389    /// ```
390    ///
391    /// Passing a large radix, causing a panic:
392    ///
393    /// ```should_panic
394    /// // this panics
395    /// let _ = '1'.to_digit(37);
396    /// ```
397    /// Passing a small radix, causing a panic:
398    ///
399    /// ```should_panic
400    /// // this panics
401    /// let _ = '1'.to_digit(1);
402    /// ```
403    #[stable(feature = "rust1", since = "1.0.0")]
404    #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
405    #[rustc_diagnostic_item = "char_to_digit"]
406    #[must_use = "this returns the result of the operation, \
407                  without modifying the original"]
408    #[inline]
409    pub const fn to_digit(self, radix: u32) -> Option<u32> {
410        if !(radix >= 2 && radix <= 36) {
    {
        crate::panicking::panic_fmt(format_args!("to_digit: invalid radix -- radix must be in the range 2 to 36 inclusive"));
    }
};assert!(
411            radix >= 2 && radix <= 36,
412            "to_digit: invalid radix -- radix must be in the range 2 to 36 inclusive"
413        );
414        // check radix to remove letter handling code when radix is a known constant
415        let value = if self > '9' && radix > 10 {
416            // mask to convert ASCII letters to uppercase
417            const TO_UPPERCASE_MASK: u32 = !0b0010_0000;
418            // Converts an ASCII letter to its corresponding integer value:
419            // A-Z => 10-35, a-z => 10-35. Other characters produce values >= 36.
420            //
421            // Add Overflow Safety:
422            // By applying the mask after the subtraction, the first addendum is
423            // constrained such that it never exceeds u32::MAX - 0x20.
424            ((self as u32).wrapping_sub('A' as u32) & TO_UPPERCASE_MASK) + 10
425        } else {
426            // convert digit to value, non-digits wrap to values > 36
427            (self as u32).wrapping_sub('0' as u32)
428        };
429        // FIXME(const-hack): once then_some is const fn, use it here
430        if value < radix { Some(value) } else { None }
431    }
432
433    /// Returns an iterator that yields the hexadecimal Unicode escape of a
434    /// character as `char`s.
435    ///
436    /// This will escape characters with the Rust syntax of the form
437    /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
438    ///
439    /// # Examples
440    ///
441    /// As an iterator:
442    ///
443    /// ```
444    /// for c in '❤'.escape_unicode() {
445    ///     print!("{c}");
446    /// }
447    /// println!();
448    /// ```
449    ///
450    /// Using `println!` directly:
451    ///
452    /// ```
453    /// println!("{}", '❤'.escape_unicode());
454    /// ```
455    ///
456    /// Both are equivalent to:
457    ///
458    /// ```
459    /// println!("\\u{{2764}}");
460    /// ```
461    ///
462    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
463    ///
464    /// ```
465    /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
466    /// ```
467    #[must_use = "this returns the escaped char as an iterator, \
468                  without modifying the original"]
469    #[stable(feature = "rust1", since = "1.0.0")]
470    #[inline]
471    pub fn escape_unicode(self) -> EscapeUnicode {
472        EscapeUnicode::new(self)
473    }
474
475    /// An extended version of `escape_debug` that optionally permits escaping
476    /// single quotes and double quotes. This allows escaping single quotes in
477    /// characters, and double quotes in strings.
478    #[inline]
479    pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
480        match self {
481            // Special escapes
482            '\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark),
483            '\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe),
484            '\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus),
485            '\n' => EscapeDebug::backslash(ascii::Char::SmallN),
486            '\t' => EscapeDebug::backslash(ascii::Char::SmallT),
487            '\r' => EscapeDebug::backslash(ascii::Char::SmallR),
488            '\0' => EscapeDebug::backslash(ascii::Char::Digit0),
489
490            // ASCII fast path,
491            // plus U+FF9E HALFWIDTH KATAKANA VOICED SOUND MARK
492            // and U+FF9F HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
493            // which should not be escaped despite being grapheme extenders.
494            '\x20'..='\x7E' | '\u{FF9E}' | '\u{FF9F}' => EscapeDebug::printable(self),
495
496            _ if self.is_control()
497                || self.is_private_use()
498                || self.is_whitespace()
499                || self.is_grapheme_extender()
500                || self.is_default_ignorable()
501                || self.is_format_control()
502                || !self.is_assigned() =>
503            {
504                EscapeDebug::unicode(self)
505            }
506
507            _ => EscapeDebug::printable(self),
508        }
509    }
510
511    /// Returns an iterator that yields the literal escape code of a character
512    /// as `char`s.
513    ///
514    /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
515    /// of `str` or `char`.
516    ///
517    /// # Examples
518    ///
519    /// As an iterator:
520    ///
521    /// ```
522    /// for c in '\n'.escape_debug() {
523    ///     print!("{c}");
524    /// }
525    /// println!();
526    /// ```
527    ///
528    /// Using `println!` directly:
529    ///
530    /// ```
531    /// println!("{}", '\n'.escape_debug());
532    /// ```
533    ///
534    /// Both are equivalent to:
535    ///
536    /// ```
537    /// println!("\\n");
538    /// ```
539    ///
540    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
541    ///
542    /// ```
543    /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
544    /// ```
545    #[must_use = "this returns the escaped char as an iterator, \
546                  without modifying the original"]
547    #[stable(feature = "char_escape_debug", since = "1.20.0")]
548    #[inline]
549    pub fn escape_debug(self) -> EscapeDebug {
550        self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
551    }
552
553    /// Returns an iterator that yields the literal escape code of a character
554    /// as `char`s.
555    ///
556    /// The default is chosen with a bias toward producing literals that are
557    /// legal in a variety of languages, including C++11 and similar C-family
558    /// languages. The exact rules are:
559    ///
560    /// * Tab is escaped as `\t`.
561    /// * Carriage return is escaped as `\r`.
562    /// * Line feed is escaped as `\n`.
563    /// * Single quote is escaped as `\'`.
564    /// * Double quote is escaped as `\"`.
565    /// * Backslash is escaped as `\\`.
566    /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
567    ///   inclusive is not escaped.
568    /// * All other characters are given hexadecimal Unicode escapes; see
569    ///   [`escape_unicode`].
570    ///
571    /// [`escape_unicode`]: #method.escape_unicode
572    ///
573    /// # Examples
574    ///
575    /// As an iterator:
576    ///
577    /// ```
578    /// for c in '"'.escape_default() {
579    ///     print!("{c}");
580    /// }
581    /// println!();
582    /// ```
583    ///
584    /// Using `println!` directly:
585    ///
586    /// ```
587    /// println!("{}", '"'.escape_default());
588    /// ```
589    ///
590    /// Both are equivalent to:
591    ///
592    /// ```
593    /// println!("\\\"");
594    /// ```
595    ///
596    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
597    ///
598    /// ```
599    /// assert_eq!('"'.escape_default().to_string(), "\\\"");
600    /// ```
601    #[must_use = "this returns the escaped char as an iterator, \
602                  without modifying the original"]
603    #[stable(feature = "rust1", since = "1.0.0")]
604    #[inline]
605    pub fn escape_default(self) -> EscapeDefault {
606        match self {
607            '\t' => EscapeDefault::backslash(ascii::Char::SmallT),
608            '\r' => EscapeDefault::backslash(ascii::Char::SmallR),
609            '\n' => EscapeDefault::backslash(ascii::Char::SmallN),
610            '\\' | '\'' | '\"' => EscapeDefault::backslash(self.as_ascii().unwrap()),
611            '\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()),
612            _ => EscapeDefault::unicode(self),
613        }
614    }
615
616    /// Returns the number of bytes this `char` would need if encoded in UTF-8.
617    ///
618    /// That number of bytes is always between 1 and 4, inclusive.
619    ///
620    /// # Examples
621    ///
622    /// Basic usage:
623    ///
624    /// ```
625    /// let len = 'A'.len_utf8();
626    /// assert_eq!(len, 1);
627    ///
628    /// let len = 'ß'.len_utf8();
629    /// assert_eq!(len, 2);
630    ///
631    /// let len = 'ℝ'.len_utf8();
632    /// assert_eq!(len, 3);
633    ///
634    /// let len = '💣'.len_utf8();
635    /// assert_eq!(len, 4);
636    /// ```
637    ///
638    /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
639    /// would take if each code point was represented as a `char` vs in the `&str` itself:
640    ///
641    /// ```
642    /// // as chars
643    /// let eastern = '東';
644    /// let capital = '京';
645    ///
646    /// // both can be represented as three bytes
647    /// assert_eq!(3, eastern.len_utf8());
648    /// assert_eq!(3, capital.len_utf8());
649    ///
650    /// // as a &str, these two are encoded in UTF-8
651    /// let tokyo = "東京";
652    ///
653    /// let len = eastern.len_utf8() + capital.len_utf8();
654    ///
655    /// // we can see that they take six bytes total...
656    /// assert_eq!(6, tokyo.len());
657    ///
658    /// // ... just like the &str
659    /// assert_eq!(len, tokyo.len());
660    /// ```
661    #[stable(feature = "rust1", since = "1.0.0")]
662    #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
663    #[inline]
664    #[must_use]
665    pub const fn len_utf8(self) -> usize {
666        len_utf8(self as u32)
667    }
668
669    /// Returns the number of 16-bit code units this `char` would need if
670    /// encoded in UTF-16.
671    ///
672    /// That number of code units is always either 1 or 2, for unicode scalar values in
673    /// the [basic multilingual plane] or [supplementary planes] respectively.
674    ///
675    /// See the documentation for [`len_utf8()`] for more explanation of this
676    /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
677    ///
678    /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
679    /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
680    /// [`len_utf8()`]: #method.len_utf8
681    ///
682    /// # Examples
683    ///
684    /// Basic usage:
685    ///
686    /// ```
687    /// let n = 'ß'.len_utf16();
688    /// assert_eq!(n, 1);
689    ///
690    /// let len = '💣'.len_utf16();
691    /// assert_eq!(len, 2);
692    /// ```
693    #[stable(feature = "rust1", since = "1.0.0")]
694    #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
695    #[inline]
696    #[must_use]
697    pub const fn len_utf16(self) -> usize {
698        len_utf16(self as u32)
699    }
700
701    /// Encodes this character as UTF-8 into the provided byte buffer,
702    /// and then returns the subslice of the buffer that contains the encoded character.
703    ///
704    /// # Panics
705    ///
706    /// Panics if the buffer is not large enough.
707    /// A buffer of length four is large enough to encode any `char`.
708    ///
709    /// # Examples
710    ///
711    /// In both of these examples, 'ß' takes two bytes to encode.
712    ///
713    /// ```
714    /// let mut b = [0; 2];
715    ///
716    /// let result = 'ß'.encode_utf8(&mut b);
717    ///
718    /// assert_eq!(result, "ß");
719    ///
720    /// assert_eq!(result.len(), 2);
721    /// ```
722    ///
723    /// A buffer that's too small:
724    ///
725    /// ```should_panic
726    /// let mut b = [0; 1];
727    ///
728    /// // this panics
729    /// 'ß'.encode_utf8(&mut b);
730    /// ```
731    #[stable(feature = "unicode_encode_char", since = "1.15.0")]
732    #[rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0")]
733    #[inline]
734    pub const fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
735        // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
736        unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
737    }
738
739    /// Encodes this character as native endian UTF-16 into the provided `u16` buffer,
740    /// and then returns the subslice of the buffer that contains the encoded character.
741    ///
742    /// # Panics
743    ///
744    /// Panics if the buffer is not large enough.
745    /// A buffer of length 2 is large enough to encode any `char`.
746    ///
747    /// # Examples
748    ///
749    /// In both of these examples, '𝕊' takes two `u16`s to encode.
750    ///
751    /// ```
752    /// let mut b = [0; 2];
753    ///
754    /// let result = '𝕊'.encode_utf16(&mut b);
755    ///
756    /// assert_eq!(result.len(), 2);
757    /// ```
758    ///
759    /// A buffer that's too small:
760    ///
761    /// ```should_panic
762    /// let mut b = [0; 1];
763    ///
764    /// // this panics
765    /// '𝕊'.encode_utf16(&mut b);
766    /// ```
767    #[stable(feature = "unicode_encode_char", since = "1.15.0")]
768    #[rustc_const_stable(feature = "const_char_encode_utf16", since = "1.84.0")]
769    #[inline]
770    pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
771        encode_utf16_raw(self as u32, dst)
772    }
773
774    /// Returns `true` if this `char` has the `Alphabetic` property.
775    ///
776    /// `Alphabetic` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and
777    /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
778    ///
779    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G32524
780    /// [specified]: https://www.unicode.org/reports/tr44/#Alphabetic
781    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
782    ///
783    /// # Examples
784    ///
785    /// Basic usage:
786    ///
787    /// ```
788    /// assert!('a'.is_alphabetic());
789    /// assert!('京'.is_alphabetic());
790    ///
791    /// let c = '💝';
792    /// // love is many things, but it is not alphabetic
793    /// assert!(!c.is_alphabetic());
794    /// ```
795    #[must_use]
796    #[stable(feature = "rust1", since = "1.0.0")]
797    #[inline]
798    pub fn is_alphabetic(self) -> bool {
799        match self {
800            'a'..='z' | 'A'..='Z' => true,
801            '\0'..='\u{A9}' => false,
802            _ => unicode::Alphabetic(self),
803        }
804    }
805
806    /// Returns `true` if this `char` has the `Cased` property.
807    /// A character is cased if and only if it is uppercase, lowercase, or titlecase.
808    ///
809    /// `Cased` is [described] in Chapter 3 (Character Properties) of the Unicode Standard and
810    /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
811    ///
812    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G44595
813    /// [specified]: https://www.unicode.org/reports/tr44/#Cased
814    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
815    ///
816    /// # Examples
817    ///
818    /// Basic usage:
819    ///
820    /// ```
821    /// assert!('A'.is_cased());
822    /// assert!('a'.is_cased());
823    /// assert!(!'京'.is_cased());
824    /// ```
825    #[must_use]
826    #[stable(feature = "titlecase", since = "CURRENT_RUSTC_VERSION")]
827    #[inline]
828    pub fn is_cased(self) -> bool {
829        match self {
830            'a'..='z' | 'A'..='Z' => true,
831            '\0'..='\u{A9}' => false,
832            _ => unicode::Lowercase(self) || unicode::Uppercase(self) || unicode::Lt(self),
833        }
834    }
835
836    /// Returns the case of this character:
837    /// [`Some(CharCase::Upper)`][`CharCase::Upper`] if [`self.is_uppercase()`][`char::is_uppercase`],
838    /// [`Some(CharCase::Lower)`][`CharCase::Lower`] if [`self.is_lowercase()`][`char::is_lowercase`],
839    /// [`Some(CharCase::Title)`][`CharCase::Title`] if [`self.is_titlecase()`][`char::is_titlecase`], and
840    /// `None` if [`!self.is_cased()`][`char::is_cased`].
841    ///
842    /// # Examples
843    ///
844    /// ```
845    /// #![feature(char_case)]
846    /// use core::char::CharCase;
847    /// assert_eq!('a'.case(), Some(CharCase::Lower));
848    /// assert_eq!('δ'.case(), Some(CharCase::Lower));
849    /// assert_eq!('A'.case(), Some(CharCase::Upper));
850    /// assert_eq!('Δ'.case(), Some(CharCase::Upper));
851    /// assert_eq!('Dž'.case(), Some(CharCase::Title));
852    /// assert_eq!('中'.case(), None);
853    /// ```
854    #[must_use]
855    #[unstable(feature = "char_case", issue = "166360")]
856    #[inline]
857    pub fn case(self) -> Option<CharCase> {
858        match self {
859            'a'..='z' => Some(CharCase::Lower),
860            'A'..='Z' => Some(CharCase::Upper),
861            '\0'..='\u{A9}' => None,
862            _ if unicode::Lowercase(self) => Some(CharCase::Lower),
863            _ if unicode::Uppercase(self) => Some(CharCase::Upper),
864            _ if unicode::Lt(self) => Some(CharCase::Title),
865            _ => None,
866        }
867    }
868
869    /// Returns `true` if this `char` has the `Lowercase` property.
870    ///
871    /// `Lowercase` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and
872    /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
873    ///
874    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G136255
875    /// [specified]: https://www.unicode.org/reports/tr44/#Lowercase
876    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
877    ///
878    /// # Examples
879    ///
880    /// Basic usage:
881    ///
882    /// ```
883    /// assert!('a'.is_lowercase());
884    /// assert!('δ'.is_lowercase());
885    /// assert!(!'A'.is_lowercase());
886    /// assert!(!'Δ'.is_lowercase());
887    ///
888    /// // The various Chinese scripts and punctuation do not have case, and so:
889    /// assert!(!'中'.is_lowercase());
890    /// assert!(!' '.is_lowercase());
891    /// ```
892    ///
893    /// In a const context:
894    ///
895    /// ```
896    /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
897    /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
898    /// ```
899    #[must_use]
900    #[stable(feature = "rust1", since = "1.0.0")]
901    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
902    #[inline]
903    pub const fn is_lowercase(self) -> bool {
904        match self {
905            'a'..='z' => true,
906            '\0'..='\u{A9}' => false,
907            _ => unicode::Lowercase(self),
908        }
909    }
910
911    /// Returns `true` if this `char` is in the general category for titlecase letters.
912    /// Conceptually, these characters consist of an uppercase portion followed by a lowercase portion.
913    ///
914    /// Titlecase letters (code points with the general category of `Lt`) are [described] in Chapter 4
915    /// (Character Properties) of the Unicode Standard, and [specified] in the Unicode Character
916    /// Database [`UnicodeData.txt`].
917    ///
918    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G124722
919    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
920    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
921    ///
922    /// # Examples
923    ///
924    /// Basic usage:
925    ///
926    /// ```
927    /// assert!('Dž'.is_titlecase());
928    /// assert!('ῼ'.is_titlecase());
929    /// assert!(!'D'.is_titlecase());
930    /// assert!(!'z'.is_titlecase());
931    /// assert!(!'中'.is_titlecase());
932    /// assert!(!' '.is_titlecase());
933    /// ```
934    #[must_use]
935    #[stable(feature = "titlecase", since = "CURRENT_RUSTC_VERSION")]
936    #[inline]
937    pub fn is_titlecase(self) -> bool {
938        match self {
939            '\0'..='\u{01C4}' => false,
940            _ => unicode::Lt(self),
941        }
942    }
943
944    /// Returns `true` if this `char` has the `Uppercase` property.
945    ///
946    /// `Uppercase` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and
947    /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
948    ///
949    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G136255
950    /// [specified]: https://www.unicode.org/reports/tr44/#Uppercase
951    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
952    ///
953    /// # Examples
954    ///
955    /// Basic usage:
956    ///
957    /// ```
958    /// assert!(!'a'.is_uppercase());
959    /// assert!(!'δ'.is_uppercase());
960    /// assert!('A'.is_uppercase());
961    /// assert!('Δ'.is_uppercase());
962    ///
963    /// // The various Chinese scripts and punctuation do not have case, and so:
964    /// assert!(!'中'.is_uppercase());
965    /// assert!(!' '.is_uppercase());
966    /// ```
967    ///
968    /// In a const context:
969    ///
970    /// ```
971    /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
972    /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
973    /// ```
974    #[must_use]
975    #[stable(feature = "rust1", since = "1.0.0")]
976    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
977    #[inline]
978    pub const fn is_uppercase(self) -> bool {
979        match self {
980            'A'..='Z' => true,
981            '\0'..='\u{BF}' => false,
982            _ => unicode::Uppercase(self),
983        }
984    }
985
986    /// Returns `true` if this `char` has one of the general categories for numbers.
987    ///
988    /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
989    /// characters, and `No` for other numeric characters) are [specified] in the Unicode Character
990    /// Database [`UnicodeData.txt`].
991    ///
992    /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
993    /// If you want everything including characters with overlapping purposes, then you might want to use
994    /// a Unicode or language-processing library that exposes the appropriate character properties
995    /// (e.g. [`Numeric_Type`]) instead of looking at the Unicode categories.
996    ///
997    /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
998    /// `is_ascii_digit` or `is_digit` instead.
999    ///
1000    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1001    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1002    /// [`Numeric_Type`]: https://www.unicode.org/reports/tr44/#Numeric_Type
1003    ///
1004    /// # Examples
1005    ///
1006    /// Basic usage:
1007    ///
1008    /// ```
1009    /// assert!('٣'.is_numeric());
1010    /// assert!('7'.is_numeric());
1011    /// assert!('৬'.is_numeric());
1012    /// assert!('¾'.is_numeric());
1013    /// assert!('①'.is_numeric());
1014    /// assert!(!'K'.is_numeric());
1015    /// assert!(!'و'.is_numeric());
1016    /// assert!(!'藏'.is_numeric());
1017    /// assert!(!'三'.is_numeric());
1018    /// ```
1019    #[must_use]
1020    #[stable(feature = "rust1", since = "1.0.0")]
1021    #[inline]
1022    pub fn is_numeric(self) -> bool {
1023        match self {
1024            '0'..='9' => true,
1025            '\0'..='\u{B1}' => false,
1026            _ => unicode::N(self),
1027        }
1028    }
1029
1030    /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
1031    ///
1032    /// [`is_alphabetic()`]: Self::is_alphabetic
1033    /// [`is_numeric()`]: Self::is_numeric
1034    ///
1035    /// # Examples
1036    ///
1037    /// Basic usage:
1038    ///
1039    /// ```
1040    /// assert!('٣'.is_alphanumeric());
1041    /// assert!('7'.is_alphanumeric());
1042    /// assert!('৬'.is_alphanumeric());
1043    /// assert!('¾'.is_alphanumeric());
1044    /// assert!('①'.is_alphanumeric());
1045    /// assert!('K'.is_alphanumeric());
1046    /// assert!('و'.is_alphanumeric());
1047    /// assert!('藏'.is_alphanumeric());
1048    /// ```
1049    #[must_use]
1050    #[stable(feature = "rust1", since = "1.0.0")]
1051    #[inline]
1052    pub fn is_alphanumeric(self) -> bool {
1053        match self {
1054            'a'..='z' | 'A'..='Z' | '0'..='9' => true,
1055            '\0'..='\u{A9}' => false,
1056            _ => unicode::Alphabetic(self) || unicode::N(self),
1057        }
1058    }
1059
1060    /// Returns `true` if this `char` has the `White_Space` property.
1061    ///
1062    /// `White_Space` is [specified] in the Unicode Character Database [`PropList.txt`].
1063    ///
1064    /// [specified]: https://www.unicode.org/reports/tr44/#White_Space
1065    /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
1066    ///
1067    /// # Examples
1068    ///
1069    /// Basic usage:
1070    ///
1071    /// ```
1072    /// assert!(' '.is_whitespace());
1073    ///
1074    /// // line break
1075    /// assert!('\n'.is_whitespace());
1076    ///
1077    /// // a non-breaking space
1078    /// assert!('\u{A0}'.is_whitespace());
1079    ///
1080    /// assert!(!'越'.is_whitespace());
1081    /// ```
1082    #[must_use]
1083    #[stable(feature = "rust1", since = "1.0.0")]
1084    #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
1085    #[inline]
1086    pub const fn is_whitespace(self) -> bool {
1087        match self {
1088            ' ' | '\x09'..='\x0d' => true,
1089            '\0'..='\u{84}' => false,
1090            _ => unicode::White_Space(self),
1091        }
1092    }
1093
1094    /// Returns `true` if this `char` has the `XID_Continue` property.
1095    ///
1096    /// `XID_Continue` is [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1097    ///
1098    /// [specified]: https://www.unicode.org/reports/tr31
1099    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1100    ///
1101    /// New versions of Unicode may add new characters to this set, in accordance with its [stability policy].
1102    /// This is *not* considered a [breaking change].
1103    ///
1104    /// [stability policy]: https://www.unicode.org/policies/stability_policy.html#Identifier
1105    /// [breaking change]: char::UNICODE_VERSION
1106    ///
1107    /// # Examples
1108    ///
1109    /// Basic usage:
1110    ///
1111    /// ```
1112    /// #![feature(char_is_xid)]
1113    ///
1114    /// assert!('A'.is_xid_continue());
1115    /// assert!('9'.is_xid_continue());
1116    /// assert!('_'.is_xid_continue());
1117    ///
1118    /// assert!(!' '.is_xid_continue());
1119    /// ```
1120    #[must_use]
1121    #[unstable(feature = "char_is_xid", issue = "164841")]
1122    #[inline]
1123    pub fn is_xid_continue(self) -> bool {
1124        match self {
1125            'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => true,
1126            '\0'..='\u{A9}' => false,
1127            _ => unicode::XID_Continue(self),
1128        }
1129    }
1130
1131    /// Returns `true` if this `char` has the `XID_Start` property.
1132    ///
1133    /// `XID_Start` is [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1134    ///
1135    /// [specified]: https://www.unicode.org/reports/tr31
1136    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1137    ///
1138    /// New versions of Unicode may add new characters to this set, in accordance with its [stability policy].
1139    /// This is *not* considered a [breaking change].
1140    ///
1141    /// [stability policy]: https://www.unicode.org/policies/stability_policy.html#Identifier
1142    /// [breaking change]: char::UNICODE_VERSION
1143    ///
1144    /// # Examples
1145    ///
1146    /// Basic usage:
1147    ///
1148    /// ```
1149    /// #![feature(char_is_xid)]
1150    ///
1151    /// assert!('A'.is_xid_start());
1152    ///
1153    /// assert!(!' '.is_xid_start());
1154    /// assert!(!'9'.is_xid_start());
1155    /// assert!(!'_'.is_xid_start());
1156    /// ```
1157    #[must_use]
1158    #[unstable(feature = "char_is_xid", issue = "164841")]
1159    #[inline]
1160    pub fn is_xid_start(self) -> bool {
1161        match self {
1162            'a'..='z' | 'A'..='Z' => true,
1163            '\0'..='\u{A9}' => false,
1164            _ => unicode::XID_Start(self),
1165        }
1166    }
1167
1168    /// Returns `true` if this `char` has the general category for control codes.
1169    ///
1170    /// Control codes (code points with the general category of `Cc`) are [described] in Chapter 23
1171    /// (Special Areas and Format Characters) of the Unicode Standard, and [specified] in the Unicode Character
1172    /// Database [`UnicodeData.txt`]. The full set of Unicode control codes is
1173    /// `'\0'..='\x1f' | '\x7f'..='\u{9f}'`, and will never change.
1174    ///
1175    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-23/#G20365
1176    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1177    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1178    ///
1179    /// # Examples
1180    ///
1181    /// Basic usage:
1182    ///
1183    /// ```
1184    /// assert!('\t'.is_control());
1185    /// assert!('\n'.is_control());
1186    /// assert!('\u{9C}'.is_control()); // STRING TERMINATOR
1187    /// assert!(!'q'.is_control());
1188    /// ```
1189    #[must_use]
1190    #[stable(feature = "rust1", since = "1.0.0")]
1191    #[rustc_const_stable(feature = "const_is_control", since = "1.97.0")]
1192    #[inline]
1193    pub const fn is_control(self) -> bool {
1194        // According to
1195        // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1196        // the set of codepoints in `Cc` will never change.
1197        // So we can just hard-code the patterns to match against instead of using a table.
1198        #[allow(non_exhaustive_omitted_patterns)] match self {
    '\0'..='\x1f' | '\x7f'..='\u{9f}' => true,
    _ => false,
}matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}')
1199    }
1200
1201    /// Returns `true` if this `char` has the general category for [private-use characters].
1202    /// These characters do not have an interpretation specified by Unicode; individual programs
1203    /// and users are free to assign them whatever meaning they like.
1204    ///
1205    /// [private-use characters]: https://www.unicode.org/faq/private_use#private_use
1206    ///
1207    /// Private-use characters (code points with the general category of `Co`) are [described] in Chapter 23
1208    /// (Special Areas and Format Characters) of the Unicode Standard, and [specified] in the
1209    /// Unicode Character Database [`UnicodeData.txt`]. The full set of private-use characters is
1210    /// `'\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}'`,
1211    /// and will never change.
1212    ///
1213    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-23/#G19184
1214    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1215    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1216    ///
1217    #[must_use]
1218    #[unstable(feature = "char_unassigned_private_use", issue = "158322")]
1219    #[inline]
1220    pub const fn is_private_use(self) -> bool {
1221        // According to
1222        // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1223        // the set of codepoints in `Co` will never change.
1224        // So we can just hard-code the patterns to match against instead of using a table.
1225        #[allow(non_exhaustive_omitted_patterns)] match self {
    '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' |
        '\u{100000}'..='\u{10FFFD}' => true,
    _ => false,
}matches!(self, '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}')
1226    }
1227
1228    /// Returns `true` if this `char` has the general category for format control characters.
1229    ///
1230    /// Format controls (code points with the general category of `Cf`) are [described] in Chapter 4
1231    /// (Character Properties) of the Unicode Standard, and [specified] in the Unicode Character
1232    /// Database [`UnicodeData.txt`].
1233    ///
1234    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G134153
1235    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1236    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1237    ///
1238    /// # Examples
1239    ///
1240    /// Basic usage:
1241    ///
1242    /// ```ignore(private)
1243    /// assert!('\u{AD}'.is_format_control()); // SOFT HYPHEN
1244    /// assert!('\u{200B}'.is_format_control()); // ZERO WIDTH SPACE
1245    /// assert!('\u{E0041}'.is_format_control()); // TAG LATIN CAPITAL LETTER A
1246    /// assert!('۝'.is_format_control()); // ARABIC END OF AYAH
1247    /// assert!('𓐲'.is_format_control()); // EGYPTIAN HIEROGLYPH INSERT AT TOP START
1248    /// assert!(!'q'.is_format_control());
1249    /// ```
1250    #[must_use]
1251    #[inline]
1252    fn is_format_control(self) -> bool {
1253        self > '\u{AC}' && unicode::Cf(self)
1254    }
1255
1256    /// Returns `true` if this `char` has been assigned a meaning by Unicode, as of
1257    /// [`UNICODE_VERSION`].
1258    ///
1259    /// [`UNICODE_VERSION`]: Self::UNICODE_VERSION
1260    ///
1261    /// Many of Unicode's [stability policies] apply only to assigned characters.
1262    ///
1263    /// [stability policies]: https://www.unicode.org/policies/stability_policy.html
1264    ///
1265    /// Currently unassigned characters (characters for which this method returns `false`)
1266    /// may have a meaning assigned in a future version of Unicode,
1267    /// except for the 66 [noncharacters] which will never be assigned a meaning.
1268    ///
1269    /// [noncharacters]: https://www.unicode.org/faq/private_use.html#noncharacters
1270    ///
1271    /// A character is considered assigned if it is present in [`UnicodeData.txt`].
1272    /// Unassigned characters have general category `Cn`, as [described] in Chapter 4
1273    /// (Character Properties) of the Unicode Standard.
1274    ///
1275    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1276    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G134153
1277    ///
1278    /// # Examples
1279    ///
1280    /// Basic usage:
1281    ///
1282    /// ```
1283    /// #![feature(char_unassigned_private_use)]
1284    /// assert!('γ'.is_assigned()); // once a character is assigned, it stays assigned forever
1285    /// assert!(!'\u{FFFE}'.is_assigned()); // noncharacter, will never be assigned
1286    ///
1287    /// // Not currently assigned, but may be in the future,
1288    /// // so we shouldn't rely on the current status
1289    /// /* assert!(!'\u{7AAAA}'.is_assigned()); */
1290    /// ```
1291    #[must_use]
1292    #[unstable(feature = "char_unassigned_private_use", issue = "158322")]
1293    #[inline]
1294    pub fn is_assigned(self) -> bool {
1295        match self {
1296            '\0'..='\u{377}' => true,
1297            '\u{378}'..='\u{3FFFD}' => !unicode::Cn_planes_0_3(self),
1298            // Assigned character ranges in planes 4 and above.
1299            // `src/tools/unicode-table-generator/src/main.rs` asserts that this is correct
1300            '\u{E0001}'
1301            | '\u{E0020}'..='\u{E007F}'
1302            | '\u{E0100}'..='\u{E01EF}'
1303            | '\u{F0000}'..='\u{FFFFD}'
1304            | '\u{100000}'..='\u{10FFFD}' => true,
1305            _ => false,
1306        }
1307    }
1308
1309    /// Returns `true` if this `char` has the `Default_Ignorable_Code_Point` property.
1310    /// These characters [should be displayed as invisible in fallback rendering](https://www.unicode.org/faq/unsup_char#3).
1311    ///
1312    /// `Default_Ignorable_Code_Point` is [described] in Chapter 5 (Implementation Guidelines) of the Unicode Standard,
1313    /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1314    ///
1315    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-5/#G40120
1316    /// [specified]: https://www.unicode.org/reports/tr44/#Default_Ignorable_Code_Point
1317    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1318    ///
1319    /// # Examples
1320    ///
1321    /// Basic usage:
1322    ///
1323    /// ```
1324    /// #![feature(default_ignorable)]
1325    /// assert!('\u{AD}'.is_default_ignorable()); // SOFT HYPHEN
1326    /// assert!('\u{115F}'.is_default_ignorable()); // HANGUL CHOSEONG FILLER
1327    /// assert!('\u{200B}'.is_default_ignorable()); // ZERO WIDTH SPACE
1328    /// assert!('\u{E0041}'.is_default_ignorable()); // TAG LATIN CAPITAL LETTER A
1329    /// assert!(!'۝'.is_default_ignorable()); // ARABIC END OF AYAH
1330    /// assert!(!'𓐲'.is_default_ignorable()); // EGYPTIAN HIEROGLYPH INSERT AT TOP START
1331    /// assert!(!' '.is_default_ignorable());
1332    /// assert!(!'\n'.is_default_ignorable());
1333    /// assert!(!'\0'.is_default_ignorable());
1334    /// assert!(!'q'.is_default_ignorable());
1335    /// ```
1336    #[must_use]
1337    #[unstable(feature = "default_ignorable", issue = "160583")]
1338    #[inline]
1339    pub fn is_default_ignorable(self) -> bool {
1340        self > '\u{AC}' && unicode::Default_Ignorable_Code_Point(self)
1341    }
1342
1343    /// Returns `true` if this `char` has the `Grapheme_Extend` property.
1344    ///
1345    /// `Grapheme_Extend` is [described] in Chapter 3 (Conformance) of the Unicode Standard,
1346    /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1347    ///
1348    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G41165
1349    /// [specified]: https://www.unicode.org/reports/tr44/#Grapheme_Extend
1350    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1351    #[must_use]
1352    #[inline]
1353    fn is_grapheme_extender(self) -> bool {
1354        self > '\u{02FF}' && unicode::Grapheme_Extend(self)
1355    }
1356
1357    /// Returns `true` if this `char` has the `Case_Ignorable` property. This narrow-use property
1358    /// is used to implement context-dependent casing for the Greek letter sigma (uppercase 'Σ'),
1359    /// which has two lowercase forms.
1360    ///
1361    /// `Case_Ignorable` is [described] in Chapter 3 (Conformance) of the Unicode Core Specification,
1362    /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1363    /// See those resources, as well as [`to_lowercase()`]'s documentation, for more information.
1364    ///
1365    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G63116
1366    /// [specified]: https://www.unicode.org/reports/tr44/#Case_Ignorable
1367    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1368    /// [`to_lowercase()`]: Self::to_lowercase()
1369    ///
1370    /// # Examples
1371    ///
1372    /// Basic usage:
1373    ///
1374    /// ```
1375    /// assert!('.'.is_case_ignorable());
1376    /// assert!('\u{AD}'.is_case_ignorable()); // SOFT HYPHEN
1377    /// assert!('ʰ'.is_case_ignorable()); // MODIFIER LETTER SMALL H
1378    /// assert!('\u{0300}'.is_case_ignorable()); // COMBINING GRAVE ACCENT
1379    /// assert!('\u{0345}'.is_case_ignorable()); // COMBINING GREEK YPOGEGRAMMENI
1380    /// assert!(!'a'.is_case_ignorable());
1381    /// assert!(!' '.is_case_ignorable());
1382    /// assert!(!';'.is_case_ignorable());
1383    /// ```
1384    #[must_use]
1385    #[inline]
1386    #[stable(feature = "case_ignorable", since = "CURRENT_RUSTC_VERSION")]
1387    pub fn is_case_ignorable(self) -> bool {
1388        if self.is_ascii() {
1389            #[allow(non_exhaustive_omitted_patterns)] match self {
    '\'' | '.' | ':' | '^' | '`' => true,
    _ => false,
}matches!(self, '\'' | '.' | ':' | '^' | '`')
1390        } else {
1391            unicode::Case_Ignorable(self)
1392        }
1393    }
1394
1395    /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
1396    /// `char`s.
1397    ///
1398    /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
1399    ///
1400    /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
1401    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1402    ///
1403    /// [ucd]: https://www.unicode.org/reports/tr44/
1404    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1405    ///
1406    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1407    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1408    ///
1409    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1410    /// is independent of context and language. See [below](#notes-on-context-and-locale)
1411    /// for more information.
1412    ///
1413    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1414    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1415    ///
1416    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1417    ///
1418    /// # Examples
1419    ///
1420    /// As an iterator:
1421    ///
1422    /// ```
1423    /// for c in 'İ'.to_lowercase() {
1424    ///     print!("{c}");
1425    /// }
1426    /// println!();
1427    /// ```
1428    ///
1429    /// Using `println!` directly:
1430    ///
1431    /// ```
1432    /// println!("{}", 'İ'.to_lowercase());
1433    /// ```
1434    ///
1435    /// Both are equivalent to:
1436    ///
1437    /// ```
1438    /// println!("i\u{307}");
1439    /// ```
1440    ///
1441    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1442    ///
1443    /// ```
1444    /// assert_eq!('C'.to_lowercase().to_string(), "c");
1445    ///
1446    /// // Sometimes the result is more than one character:
1447    /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1448    ///
1449    /// // Characters that do not have both uppercase and lowercase
1450    /// // convert into themselves.
1451    /// assert_eq!('山'.to_lowercase().to_string(), "山");
1452    /// ```
1453    /// # Notes on context and locale
1454    ///
1455    /// As stated earlier, this method does not take into account language or context.
1456    /// Below is a non-exhaustive list of situations where this can be relevant.
1457    /// If you need to handle locale-depedendent casing in your code, consider using
1458    /// an external crate, like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1459    /// which is developed by Unicode.
1460    ///
1461    /// ## Greek sigma
1462    ///
1463    /// In Greek, the letter sigma (uppercase 'Σ') has two lowercase forms:
1464    /// 'σ' which is used in most situations, and 'ς' which appears only
1465    /// at the end of a word. [`char::to_lowercase()`] always uses the first form:
1466    ///
1467    /// ```
1468    /// assert_eq!('Σ'.to_lowercase().to_string(), "σ");
1469    /// ```
1470    ///
1471    /// `str::to_lowercase()` (only available with the `alloc` crate)
1472    /// *does* properly handle this contextual mapping,
1473    /// so prefer using that method if you can. Alternatively, you can use
1474    /// [`is_cased()`] and [`is_case_ignorable()`] to implement it yourself.
1475    /// See `Final_Sigma` in [Table 3.17] of the Unicode Standard,
1476    /// along with [`SpecialCasing.txt`], for more details.
1477    ///
1478    /// [`is_cased()`]: Self::is_cased()
1479    /// [`is_case_ignorable()`]: Self::is_case_ignorable()
1480    /// [Table 3.17]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G54277
1481    ///
1482    /// ## Turkish and Azeri I/ı/İ/i
1483    ///
1484    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1485    ///
1486    /// * 'Dotless': I / ı, sometimes written ï
1487    /// * 'Dotted': İ / i
1488    ///
1489    /// Note that the uppercase undotted 'I' is the same codepoint as the Latin. Therefore:
1490    ///
1491    /// ```
1492    /// let lower_i = 'I'.to_lowercase().to_string();
1493    /// ```
1494    ///
1495    /// `'I'`'s correct lowercase relies on the language of the text: if we're
1496    /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should
1497    /// be `"ı"`. `to_lowercase()` does not take this into account, and so:
1498    ///
1499    /// ```
1500    /// let lower_i = 'I'.to_lowercase().to_string();
1501    ///
1502    /// assert_eq!(lower_i, "i");
1503    /// ```
1504    ///
1505    /// holds across languages.
1506    ///
1507    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1508    #[must_use = "this returns the lowercased character as a new iterator, \
1509                  without modifying the original"]
1510    #[stable(feature = "rust1", since = "1.0.0")]
1511    #[inline]
1512    pub fn to_lowercase(self) -> ToLowercase {
1513        ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1514    }
1515
1516    /// Returns an iterator that yields the titlecase mapping of this `char` as one or more
1517    /// `char`s.
1518    ///
1519    /// This is usually, but not always, equivalent to the uppercase mapping
1520    /// returned by [`to_uppercase()`]. Prefer this method when seeking to capitalize
1521    /// Only The First Letter of a word, but use [`to_uppercase()`] for ALL CAPS.
1522    /// See [below](#difference-from-uppercase) for a thorough explanation
1523    /// of the difference between the two methods.
1524    ///
1525    /// If this `char` does not have a titlecase mapping, the iterator yields the same `char`.
1526    ///
1527    /// If this `char` has a one-to-one titlecase mapping given by the [Unicode Character
1528    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1529    ///
1530    /// [ucd]: https://www.unicode.org/reports/tr44/
1531    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1532    ///
1533    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1534    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1535    ///
1536    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1537    ///
1538    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1539    /// is independent of context and language. See [below](#note-on-locale)
1540    /// for more information.
1541    ///
1542    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1543    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1544    ///
1545    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1546    ///
1547    /// # Examples
1548    ///
1549    /// As an iterator:
1550    ///
1551    /// ```
1552    /// for c in 'ß'.to_titlecase() {
1553    ///     print!("{c}");
1554    /// }
1555    /// println!();
1556    /// ```
1557    ///
1558    /// Using `println!` directly:
1559    ///
1560    /// ```
1561    /// println!("{}", 'ß'.to_titlecase());
1562    /// ```
1563    ///
1564    /// Both are equivalent to:
1565    ///
1566    /// ```
1567    /// println!("Ss");
1568    /// ```
1569    ///
1570    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1571    ///
1572    /// ```
1573    /// assert_eq!('c'.to_titlecase().to_string(), "C");
1574    /// assert_eq!('ა'.to_titlecase().to_string(), "ა");
1575    /// assert_eq!('dž'.to_titlecase().to_string(), "Dž");
1576    /// assert_eq!('ᾨ'.to_titlecase().to_string(), "ᾨ");
1577    ///
1578    /// // Sometimes the result is more than one character:
1579    /// assert_eq!('ß'.to_titlecase().to_string(), "Ss");
1580    ///
1581    /// // Characters that do not have separate cased forms
1582    /// // convert into themselves.
1583    /// assert_eq!('山'.to_titlecase().to_string(), "山");
1584    /// ```
1585    ///
1586    /// # Difference from uppercase
1587    ///
1588    /// Currently, there are three classes of characters where [`to_uppercase()`]
1589    /// and `to_titlecase()` give different results:
1590    ///
1591    /// ## Georgian script
1592    ///
1593    /// Each letter in the modern Georgian alphabet can be written in one of two forms:
1594    /// the typical lowercase-like "mkhedruli" form, and a variant uppercase-like "mtavruli"
1595    /// form. However, unlike uppercase in most cased scripts, mtavruli is not typically used
1596    /// to start sentences, denote proper nouns, or for any other purpose
1597    /// in running text. It is instead confined to titles and headings, which are written entirely
1598    /// in mtavruli. For this reason, [`to_uppercase()`] applied to a Georgian letter
1599    /// will return the mtavruli form, but `to_titlecase()` will return the mkhedruli form.
1600    ///
1601    /// ```
1602    /// let ani = 'ა'; // First letter of the Georgian alphabet, in mkhedruli form
1603    ///
1604    /// // Titlecasing mkhedruli maps it to itself...
1605    /// assert_eq!(ani.to_titlecase().to_string(), ani.to_string());
1606    ///
1607    /// // but uppercasing it maps it to mtavruli
1608    /// assert_eq!(ani.to_uppercase().to_string(), "Ა");
1609    /// ```
1610    ///
1611    /// ## Compatibility digraphs for Latin-alphabet Serbo-Croatian
1612    ///
1613    /// The standard Latin alphabet for the Serbo-Croatian language
1614    /// (Bosnian, Croatian, Montenegrin, and Serbian) contains
1615    /// three digraphs: Dž, Lj, and Nj. These are usually represented as
1616    /// two characters. However, for compatibility with older character sets,
1617    /// Unicode includes single-character versions of these digraphs.
1618    /// Each has a uppercase, titlecase, and lowercase version:
1619    ///
1620    /// - `'DŽ'`, `'Dž'`, `'dž'`
1621    /// - `'LJ'`, `'Lj'`, `'lj'`
1622    /// - `'NJ'`, `'Nj'`, `'nj'`
1623    ///
1624    /// Unicode additionally encodes a casing triad for the Dz digraph
1625    /// without the caron: `'DZ'`, `'Dz'`, `'dz'`.
1626    ///
1627    /// ## Iota-subscritped Greek vowels
1628    ///
1629    /// In ancient Greek, the long vowels alpha (α), eta (η), and omega (ω)
1630    /// were sometimes followed by an iota (ι), forming a diphthong. Over time,
1631    /// the diphthong pronunciation was slowly lost, with the iota becoming mute.
1632    /// Eventually, the ι disappeared from the spelling as well.
1633    /// However, there remains a need to represent ancient texts faithfully.
1634    ///
1635    /// Modern editions of ancient Greek texts commonly use a reduced-sized
1636    /// ι symbol to denote mute iotas, while distinguishing them from ιs
1637    /// which continued to affect pronunciation. The exact standard differs
1638    /// between different publications. Some render the mute ι below its associated
1639    /// vowel (subscript), while others place it to the right of said vowel (adscript).
1640    /// The interaction of mute ι symbols with casing also varies.
1641    ///
1642    /// The Unicode Standard, for its default casing rules, chose to make lowercase
1643    /// Greek vowels with iota subscipt (e.g. `'ᾠ'`) titlecase to the uppercase vowel
1644    /// with iota subscript (`'ᾨ'`) but uppercase to the uppercase vowel followed by
1645    /// full-size uppercase iota (`"ὨΙ"`). This is just one convention among many
1646    /// in common use, but it is the one Unicode settled on,
1647    /// so it is what this method does also.
1648    ///
1649    /// # Note on locale
1650    ///
1651    /// As stated above, this method is locale-insensitive.
1652    /// If you need locale support, consider using an external crate,
1653    /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1654    /// which is developed by Unicode. A description of one common
1655    /// locale-dependent casing issue follows (there are others):
1656    ///
1657    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1658    ///
1659    /// * 'Dotless': I / ı, sometimes written ï
1660    /// * 'Dotted': İ / i
1661    ///
1662    /// Note that the lowercase dotted 'i' is the same codepoint as the Latin. Therefore:
1663    ///
1664    /// ```
1665    /// let upper_i = 'i'.to_titlecase().to_string();
1666    /// ```
1667    ///
1668    /// `'i'`'s correct titlecase relies on the language of the text: if we're
1669    /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1670    /// be `"İ"`. `to_titlecase()` does not take this into account, and so:
1671    ///
1672    /// ```
1673    /// let upper_i = 'i'.to_titlecase().to_string();
1674    ///
1675    /// assert_eq!(upper_i, "I");
1676    /// ```
1677    ///
1678    /// holds across languages.
1679    ///
1680    /// [`to_uppercase()`]: Self::to_uppercase()
1681    #[must_use = "this returns the titlecased character as a new iterator, \
1682                  without modifying the original"]
1683    #[stable(feature = "titlecase", since = "CURRENT_RUSTC_VERSION")]
1684    #[inline]
1685    pub fn to_titlecase(self) -> ToTitlecase {
1686        ToTitlecase(CaseMappingIter::new(conversions::to_title(self)))
1687    }
1688
1689    /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1690    /// `char`s.
1691    ///
1692    /// Prefer this method when converting a word into ALL CAPS, but consider [`to_titlecase()`]
1693    /// instead if you seek to capitalize Only The First Letter. See that method's documentation
1694    /// for more information on the difference between the two.
1695    ///
1696    /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1697    ///
1698    /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1699    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1700    ///
1701    /// [ucd]: https://www.unicode.org/reports/tr44/
1702    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1703    ///
1704    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1705    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1706    ///
1707    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1708    ///
1709    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1710    /// is independent of context and language. See [below](#note-on-locale)
1711    /// for more information.
1712    ///
1713    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1714    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1715    ///
1716    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1717    ///
1718    /// # Examples
1719    ///
1720    /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase.
1721    ///
1722    /// As an iterator:
1723    ///
1724    /// ```
1725    /// for c in 'ſt'.to_uppercase() {
1726    ///     print!("{c}");
1727    /// }
1728    /// println!();
1729    /// ```
1730    ///
1731    /// Using `println!` directly:
1732    ///
1733    /// ```
1734    /// println!("{}", 'ſt'.to_uppercase());
1735    /// ```
1736    ///
1737    /// Both are equivalent to:
1738    ///
1739    /// ```
1740    /// println!("ST");
1741    /// ```
1742    ///
1743    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1744    ///
1745    /// ```
1746    /// assert_eq!('c'.to_uppercase().to_string(), "C");
1747    /// assert_eq!('ა'.to_uppercase().to_string(), "Ა");
1748    /// assert_eq!('dž'.to_uppercase().to_string(), "DŽ");
1749    ///
1750    /// // Sometimes the result is more than one character:
1751    /// assert_eq!('ſt'.to_uppercase().to_string(), "ST");
1752    /// assert_eq!('ᾨ'.to_uppercase().to_string(), "ὨΙ");
1753    ///
1754    /// // Characters that do not have both uppercase and lowercase
1755    /// // convert into themselves.
1756    /// assert_eq!('山'.to_uppercase().to_string(), "山");
1757    /// ```
1758    ///
1759    /// # Note on locale
1760    ///
1761    /// As stated above, this method is locale-insensitive.
1762    /// If you need locale support, consider using an external crate,
1763    /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1764    /// which is developed by Unicode. A description of one common
1765    /// locale-dependent casing issue follows (there are others):
1766    ///
1767    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1768    ///
1769    /// * 'Dotless': I / ı, sometimes written ï
1770    /// * 'Dotted': İ / i
1771    ///
1772    /// Note that the lowercase dotted 'i' is the same codepoint as the Latin. Therefore:
1773    ///
1774    /// ```
1775    /// let upper_i = 'i'.to_uppercase().to_string();
1776    /// ```
1777    ///
1778    /// `'i'`'s correct uppercase relies on the language of the text: if we're
1779    /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1780    /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1781    ///
1782    /// ```
1783    /// let upper_i = 'i'.to_uppercase().to_string();
1784    ///
1785    /// assert_eq!(upper_i, "I");
1786    /// ```
1787    ///
1788    /// holds across languages.
1789    ///
1790    /// [`to_titlecase()`]: Self::to_titlecase()
1791    #[must_use = "this returns the uppercased character as a new iterator, \
1792                  without modifying the original"]
1793    #[stable(feature = "rust1", since = "1.0.0")]
1794    #[inline]
1795    pub fn to_uppercase(self) -> ToUppercase {
1796        ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1797    }
1798
1799    /// Returns an iterator that yields the case folding of this `char` as one or more
1800    /// `char`s.
1801    ///
1802    /// Case folding is meant to be used when performing case-insensitive string comparisons.
1803    /// Case-folded strings should not usually be exposed directly to users. For most,
1804    /// but not all, characters, the casefold mapping is identical to the lowercase one.
1805    ///
1806    /// This iterator yields the `char`(s) in the common or full case folding for this `char`,
1807    /// as given by the [Unicode Character Database][ucd] [`CaseFolding.txt`].
1808    /// The maximum number of `char`s in a case folding is 3.
1809    ///
1810    /// [ucd]: https://www.unicode.org/reports/tr44/
1811    /// [`CaseFolding.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt
1812    ///
1813    ///
1814    /// No [normalization] (e.g. NFC) is performed, so visually and semantically identical characters
1815    /// might still casefold differently. For example, `'ά'` (U+03AC GREEK SMALL LETTER ALPHA WITH TONOS)
1816    /// is considered distinct from `'ά'` (U+1F71 GREEK SMALL LETTER ALPHA WITH OXIA),
1817    /// even though Unicode considers them canonically equivalent.
1818    ///
1819    /// In addition, this method is independent of language/locale,
1820    /// so the special behavior of I/ı/İ/i in Turkish and Azeri is not handled.
1821    ///
1822    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case folding in
1823    /// general and Chapter 3 (Conformance) discusses the default algorithm for case folding.
1824    ///
1825    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1826    ///
1827    /// # Examples
1828    ///
1829    /// The German sharp S `'ß'` (U+DF) is a single Unicode code point
1830    /// that casefolds to `"ss"`. Its uppercase variant '`ẞ`' (U+1E9E)
1831    /// has the same case-folding.
1832    ///
1833    /// As an iterator:
1834    ///
1835    /// ```
1836    /// #![feature(casefold)]
1837    /// assert!('ß'.to_casefold_unnormalized().eq(['s', 's']));
1838    /// assert!('ẞ'.to_casefold_unnormalized().eq(['s', 's']));
1839    /// ```
1840    ///
1841    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1842    ///
1843    /// ```
1844    /// #![feature(casefold)]
1845    /// assert_eq!('ß'.to_casefold_unnormalized().to_string(), "ss");
1846    /// assert_eq!('ẞ'.to_casefold_unnormalized().to_string(), "ss");
1847    /// ```
1848    ///
1849    /// No [normalization] is performed:
1850    ///
1851    /// ```rust
1852    /// #![feature(casefold)]
1853    /// // These two characters are visually and semantically identical;
1854    /// // Unicode considers them to be canonically equivalent.
1855    /// let alpha_tonos = 'ά';
1856    /// let alpha_oxia = 'ά';
1857    ///
1858    /// // However, they are different codepoints:
1859    /// assert_eq!(alpha_tonos, '\u{03AC}');
1860    /// assert_eq!(alpha_oxia, '\u{1F71}');
1861    ///
1862    /// // Their case-foldings are likewise unequal:
1863    /// assert!(alpha_tonos.to_casefold_unnormalized().eq(['\u{03AC}']));
1864    /// assert!(alpha_oxia.to_casefold_unnormalized().eq(['\u{1F71}']));
1865    /// ```
1866    ///
1867    /// # Note on locale
1868    ///
1869    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1870    ///
1871    /// * 'Dotless': I / ı, sometimes written ï
1872    /// * 'Dotted': İ / i
1873    ///
1874    /// Note that the uppercase undotted 'I' is the same codepoint as the Latin. Therefore:
1875    ///
1876    /// ```
1877    /// #![feature(casefold)]
1878    /// let casefold_i = 'I'.to_casefold_unnormalized().to_string();
1879    /// ```
1880    ///
1881    /// `'I'`'s correct case folding relies on the language of the text: if we're
1882    /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should
1883    /// be `"ı"`. `to_casefold_unnormalized()` does not take this into account, and so:
1884    ///
1885    /// ```
1886    /// #![feature(casefold)]
1887    /// let casefold_i = 'I'.to_casefold_unnormalized().to_string();
1888    ///
1889    /// assert_eq!(casefold_i, "i");
1890    /// ```
1891    ///
1892    /// holds across languages.
1893    ///
1894    /// [normalization]: https://www.unicode.org/faq/normalization.html
1895    #[must_use = "this returns the case-folded character as a new iterator, \
1896                  without modifying the original"]
1897    #[unstable(feature = "casefold", issue = "157000")]
1898    #[inline]
1899    pub fn to_casefold_unnormalized(self) -> ToCasefold {
1900        ToCasefold(CaseMappingIter::new(conversions::to_casefold(self)))
1901    }
1902
1903    /// Returns the code point value as a `u32`.
1904    ///
1905    /// # Examples
1906    ///
1907    /// ```
1908    /// #![feature(char_to_u32)]
1909    ///
1910    /// let ascii = 'a';
1911    /// let heart = '❤';
1912    ///
1913    /// assert_eq!(ascii.to_u32(), 97_u32);
1914    /// assert_eq!(heart.to_u32(), 0x2764_u32);
1915    /// ```
1916    #[must_use = "this returns the result of the operation, \
1917                  without modifying the original"]
1918    #[unstable(feature = "char_to_u32", issue = "158938")]
1919    #[rustc_const_unstable(feature = "char_to_u32", issue = "158938")]
1920    #[inline(always)]
1921    pub const fn to_u32(self) -> u32 {
1922        self as u32
1923    }
1924
1925    /// Checks if the value is within the ASCII range.
1926    ///
1927    /// # Examples
1928    ///
1929    /// ```
1930    /// let ascii = 'a';
1931    /// let non_ascii = '❤';
1932    ///
1933    /// assert!(ascii.is_ascii());
1934    /// assert!(!non_ascii.is_ascii());
1935    /// ```
1936    #[must_use]
1937    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1938    #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1939    #[rustc_diagnostic_item = "char_is_ascii"]
1940    #[inline]
1941    pub const fn is_ascii(&self) -> bool {
1942        *self as u32 <= 0x7F
1943    }
1944
1945    /// Returns `Some` if the value is within the ASCII range,
1946    /// or `None` if it's not.
1947    ///
1948    /// This is preferred to [`Self::is_ascii`] when you're passing the value
1949    /// along to something else that can take [`ascii::Char`] rather than
1950    /// needing to check again for itself whether the value is in ASCII.
1951    #[must_use]
1952    #[unstable(feature = "ascii_char", issue = "110998")]
1953    #[inline]
1954    pub const fn as_ascii(&self) -> Option<ascii::Char> {
1955        if self.is_ascii() {
1956            // SAFETY: Just checked that this is ASCII.
1957            Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
1958        } else {
1959            None
1960        }
1961    }
1962
1963    /// Converts this char into an [ASCII character](`ascii::Char`), without
1964    /// checking whether it is valid.
1965    ///
1966    /// # Safety
1967    ///
1968    /// This char must be within the ASCII range, or else this is UB.
1969    #[must_use]
1970    #[unstable(feature = "ascii_char", issue = "110998")]
1971    #[inline]
1972    pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1973        {
    #[rustc_no_mir_inline]
    #[inline]
    #[rustc_nounwind]
    #[track_caller]
    const fn precondition_check(it: &char) {
        if !it.is_ascii() {
            let msg =
                "unsafe precondition(s) violated: as_ascii_unchecked requires that the char is valid ASCII\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
            ::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
                false);
        }
    }
    if ::core::ub_checks::check_library_ub() { precondition_check(self); }
};assert_unsafe_precondition!(
1974            check_library_ub,
1975            "as_ascii_unchecked requires that the char is valid ASCII",
1976            (it: &char = self) => it.is_ascii()
1977        );
1978
1979        // SAFETY: the caller promised that this char is ASCII.
1980        unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1981    }
1982
1983    /// Makes a copy of the value in its ASCII upper case equivalent.
1984    ///
1985    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1986    /// but non-ASCII letters are unchanged.
1987    ///
1988    /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1989    ///
1990    /// To uppercase ASCII characters in addition to non-ASCII characters, use
1991    /// [`to_uppercase()`].
1992    ///
1993    /// # Examples
1994    ///
1995    /// ```
1996    /// let ascii = 'a';
1997    /// let non_ascii = '❤';
1998    ///
1999    /// assert_eq!('A', ascii.to_ascii_uppercase());
2000    /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
2001    /// ```
2002    ///
2003    /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
2004    /// [`to_uppercase()`]: #method.to_uppercase
2005    #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
2006    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2007    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
2008    #[inline]
2009    pub const fn to_ascii_uppercase(&self) -> char {
2010        if self.is_ascii_lowercase() {
2011            (*self as u8).ascii_change_case_unchecked() as char
2012        } else {
2013            *self
2014        }
2015    }
2016
2017    /// Makes a copy of the value in its ASCII lower case equivalent.
2018    ///
2019    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2020    /// but non-ASCII letters are unchanged.
2021    ///
2022    /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
2023    ///
2024    /// To lowercase ASCII characters in addition to non-ASCII characters, use
2025    /// [`to_lowercase()`].
2026    ///
2027    /// # Examples
2028    ///
2029    /// ```
2030    /// let ascii = 'A';
2031    /// let non_ascii = '❤';
2032    ///
2033    /// assert_eq!('a', ascii.to_ascii_lowercase());
2034    /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
2035    /// ```
2036    ///
2037    /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
2038    /// [`to_lowercase()`]: #method.to_lowercase
2039    #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
2040    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2041    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
2042    #[inline]
2043    pub const fn to_ascii_lowercase(&self) -> char {
2044        if self.is_ascii_uppercase() {
2045            (*self as u8).ascii_change_case_unchecked() as char
2046        } else {
2047            *self
2048        }
2049    }
2050
2051    /// Checks that two values are an ASCII case-insensitive match.
2052    ///
2053    /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
2054    ///
2055    /// # Examples
2056    ///
2057    /// ```
2058    /// let upper_a = 'A';
2059    /// let lower_a = 'a';
2060    /// let lower_z = 'z';
2061    ///
2062    /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
2063    /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
2064    /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
2065    /// ```
2066    ///
2067    /// [to_ascii_lowercase]: #method.to_ascii_lowercase
2068    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2069    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
2070    #[expect(clippy::manual_ignore_case_cmp, reason = "implements eq_ignore_ascii_case")]
2071    #[inline]
2072    pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
2073        self.to_ascii_lowercase() == other.to_ascii_lowercase()
2074    }
2075
2076    /// Converts this type to its ASCII upper case equivalent in-place.
2077    ///
2078    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2079    /// but non-ASCII letters are unchanged.
2080    ///
2081    /// To return a new uppercased value without modifying the existing one, use
2082    /// [`to_ascii_uppercase()`].
2083    ///
2084    /// # Examples
2085    ///
2086    /// ```
2087    /// let mut ascii = 'a';
2088    ///
2089    /// ascii.make_ascii_uppercase();
2090    ///
2091    /// assert_eq!('A', ascii);
2092    /// ```
2093    ///
2094    /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2095    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2096    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2097    #[inline]
2098    pub const fn make_ascii_uppercase(&mut self) {
2099        *self = self.to_ascii_uppercase();
2100    }
2101
2102    /// Converts this type to its ASCII lower case equivalent in-place.
2103    ///
2104    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2105    /// but non-ASCII letters are unchanged.
2106    ///
2107    /// To return a new lowercased value without modifying the existing one, use
2108    /// [`to_ascii_lowercase()`].
2109    ///
2110    /// # Examples
2111    ///
2112    /// ```
2113    /// let mut ascii = 'A';
2114    ///
2115    /// ascii.make_ascii_lowercase();
2116    ///
2117    /// assert_eq!('a', ascii);
2118    /// ```
2119    ///
2120    /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2121    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2122    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2123    #[inline]
2124    pub const fn make_ascii_lowercase(&mut self) {
2125        *self = self.to_ascii_lowercase();
2126    }
2127
2128    /// Checks if the value is an ASCII alphabetic character:
2129    ///
2130    /// - U+0041 'A' ..= U+005A 'Z', or
2131    /// - U+0061 'a' ..= U+007A 'z'.
2132    ///
2133    /// # Examples
2134    ///
2135    /// ```
2136    /// let uppercase_a = 'A';
2137    /// let uppercase_g = 'G';
2138    /// let a = 'a';
2139    /// let g = 'g';
2140    /// let zero = '0';
2141    /// let percent = '%';
2142    /// let space = ' ';
2143    /// let lf = '\n';
2144    /// let esc = '\x1b';
2145    ///
2146    /// assert!(uppercase_a.is_ascii_alphabetic());
2147    /// assert!(uppercase_g.is_ascii_alphabetic());
2148    /// assert!(a.is_ascii_alphabetic());
2149    /// assert!(g.is_ascii_alphabetic());
2150    /// assert!(!zero.is_ascii_alphabetic());
2151    /// assert!(!percent.is_ascii_alphabetic());
2152    /// assert!(!space.is_ascii_alphabetic());
2153    /// assert!(!lf.is_ascii_alphabetic());
2154    /// assert!(!esc.is_ascii_alphabetic());
2155    /// ```
2156    #[must_use]
2157    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2158    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2159    #[inline]
2160    pub const fn is_ascii_alphabetic(&self) -> bool {
2161        #[allow(non_exhaustive_omitted_patterns)] match *self {
    'a'..='z' | 'A'..='Z' => true,
    _ => false,
}matches!(*self, 'a'..='z' | 'A'..='Z')
2162    }
2163
2164    /// Checks if the value is an ASCII uppercase character:
2165    /// U+0041 'A' ..= U+005A 'Z'.
2166    ///
2167    /// # Examples
2168    ///
2169    /// ```
2170    /// let uppercase_a = 'A';
2171    /// let uppercase_g = 'G';
2172    /// let a = 'a';
2173    /// let g = 'g';
2174    /// let zero = '0';
2175    /// let percent = '%';
2176    /// let space = ' ';
2177    /// let lf = '\n';
2178    /// let esc = '\x1b';
2179    ///
2180    /// assert!(uppercase_a.is_ascii_uppercase());
2181    /// assert!(uppercase_g.is_ascii_uppercase());
2182    /// assert!(!a.is_ascii_uppercase());
2183    /// assert!(!g.is_ascii_uppercase());
2184    /// assert!(!zero.is_ascii_uppercase());
2185    /// assert!(!percent.is_ascii_uppercase());
2186    /// assert!(!space.is_ascii_uppercase());
2187    /// assert!(!lf.is_ascii_uppercase());
2188    /// assert!(!esc.is_ascii_uppercase());
2189    /// ```
2190    #[must_use]
2191    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2192    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2193    #[inline]
2194    pub const fn is_ascii_uppercase(&self) -> bool {
2195        #[allow(non_exhaustive_omitted_patterns)] match *self {
    'A'..='Z' => true,
    _ => false,
}matches!(*self, 'A'..='Z')
2196    }
2197
2198    /// Checks if the value is an ASCII lowercase character:
2199    /// U+0061 'a' ..= U+007A 'z'.
2200    ///
2201    /// # Examples
2202    ///
2203    /// ```
2204    /// let uppercase_a = 'A';
2205    /// let uppercase_g = 'G';
2206    /// let a = 'a';
2207    /// let g = 'g';
2208    /// let zero = '0';
2209    /// let percent = '%';
2210    /// let space = ' ';
2211    /// let lf = '\n';
2212    /// let esc = '\x1b';
2213    ///
2214    /// assert!(!uppercase_a.is_ascii_lowercase());
2215    /// assert!(!uppercase_g.is_ascii_lowercase());
2216    /// assert!(a.is_ascii_lowercase());
2217    /// assert!(g.is_ascii_lowercase());
2218    /// assert!(!zero.is_ascii_lowercase());
2219    /// assert!(!percent.is_ascii_lowercase());
2220    /// assert!(!space.is_ascii_lowercase());
2221    /// assert!(!lf.is_ascii_lowercase());
2222    /// assert!(!esc.is_ascii_lowercase());
2223    /// ```
2224    #[must_use]
2225    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2226    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2227    #[inline]
2228    pub const fn is_ascii_lowercase(&self) -> bool {
2229        #[allow(non_exhaustive_omitted_patterns)] match *self {
    'a'..='z' => true,
    _ => false,
}matches!(*self, 'a'..='z')
2230    }
2231
2232    /// Checks if the value is an ASCII alphanumeric character:
2233    ///
2234    /// - U+0041 'A' ..= U+005A 'Z', or
2235    /// - U+0061 'a' ..= U+007A 'z', or
2236    /// - U+0030 '0' ..= U+0039 '9'.
2237    ///
2238    /// # Examples
2239    ///
2240    /// ```
2241    /// let uppercase_a = 'A';
2242    /// let uppercase_g = 'G';
2243    /// let a = 'a';
2244    /// let g = 'g';
2245    /// let zero = '0';
2246    /// let percent = '%';
2247    /// let space = ' ';
2248    /// let lf = '\n';
2249    /// let esc = '\x1b';
2250    ///
2251    /// assert!(uppercase_a.is_ascii_alphanumeric());
2252    /// assert!(uppercase_g.is_ascii_alphanumeric());
2253    /// assert!(a.is_ascii_alphanumeric());
2254    /// assert!(g.is_ascii_alphanumeric());
2255    /// assert!(zero.is_ascii_alphanumeric());
2256    /// assert!(!percent.is_ascii_alphanumeric());
2257    /// assert!(!space.is_ascii_alphanumeric());
2258    /// assert!(!lf.is_ascii_alphanumeric());
2259    /// assert!(!esc.is_ascii_alphanumeric());
2260    /// ```
2261    #[must_use]
2262    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2263    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2264    #[inline]
2265    pub const fn is_ascii_alphanumeric(&self) -> bool {
2266        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '0'..='9' => true,
    _ => false,
}matches!(*self, '0'..='9') | #[allow(non_exhaustive_omitted_patterns)] match *self {
    'A'..='Z' => true,
    _ => false,
}matches!(*self, 'A'..='Z') | #[allow(non_exhaustive_omitted_patterns)] match *self {
    'a'..='z' => true,
    _ => false,
}matches!(*self, 'a'..='z')
2267    }
2268
2269    /// Checks if the value is an ASCII decimal digit:
2270    /// U+0030 '0' ..= U+0039 '9'.
2271    ///
2272    /// # Examples
2273    ///
2274    /// ```
2275    /// let uppercase_a = 'A';
2276    /// let uppercase_g = 'G';
2277    /// let a = 'a';
2278    /// let g = 'g';
2279    /// let zero = '0';
2280    /// let percent = '%';
2281    /// let space = ' ';
2282    /// let lf = '\n';
2283    /// let esc = '\x1b';
2284    ///
2285    /// assert!(!uppercase_a.is_ascii_digit());
2286    /// assert!(!uppercase_g.is_ascii_digit());
2287    /// assert!(!a.is_ascii_digit());
2288    /// assert!(!g.is_ascii_digit());
2289    /// assert!(zero.is_ascii_digit());
2290    /// assert!(!percent.is_ascii_digit());
2291    /// assert!(!space.is_ascii_digit());
2292    /// assert!(!lf.is_ascii_digit());
2293    /// assert!(!esc.is_ascii_digit());
2294    /// ```
2295    #[must_use]
2296    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2297    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2298    #[inline]
2299    pub const fn is_ascii_digit(&self) -> bool {
2300        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '0'..='9' => true,
    _ => false,
}matches!(*self, '0'..='9')
2301    }
2302
2303    /// Checks if the value is an ASCII octal digit:
2304    /// U+0030 '0' ..= U+0037 '7'.
2305    ///
2306    /// # Examples
2307    ///
2308    /// ```
2309    /// #![feature(is_ascii_octdigit)]
2310    ///
2311    /// let uppercase_a = 'A';
2312    /// let a = 'a';
2313    /// let zero = '0';
2314    /// let seven = '7';
2315    /// let nine = '9';
2316    /// let percent = '%';
2317    /// let lf = '\n';
2318    ///
2319    /// assert!(!uppercase_a.is_ascii_octdigit());
2320    /// assert!(!a.is_ascii_octdigit());
2321    /// assert!(zero.is_ascii_octdigit());
2322    /// assert!(seven.is_ascii_octdigit());
2323    /// assert!(!nine.is_ascii_octdigit());
2324    /// assert!(!percent.is_ascii_octdigit());
2325    /// assert!(!lf.is_ascii_octdigit());
2326    /// ```
2327    #[must_use]
2328    #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
2329    #[inline]
2330    pub const fn is_ascii_octdigit(&self) -> bool {
2331        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '0'..='7' => true,
    _ => false,
}matches!(*self, '0'..='7')
2332    }
2333
2334    /// Checks if the value is an ASCII hexadecimal digit:
2335    ///
2336    /// - U+0030 '0' ..= U+0039 '9', or
2337    /// - U+0041 'A' ..= U+0046 'F', or
2338    /// - U+0061 'a' ..= U+0066 'f'.
2339    ///
2340    /// # Examples
2341    ///
2342    /// ```
2343    /// let uppercase_a = 'A';
2344    /// let uppercase_g = 'G';
2345    /// let a = 'a';
2346    /// let g = 'g';
2347    /// let zero = '0';
2348    /// let percent = '%';
2349    /// let space = ' ';
2350    /// let lf = '\n';
2351    /// let esc = '\x1b';
2352    ///
2353    /// assert!(uppercase_a.is_ascii_hexdigit());
2354    /// assert!(!uppercase_g.is_ascii_hexdigit());
2355    /// assert!(a.is_ascii_hexdigit());
2356    /// assert!(!g.is_ascii_hexdigit());
2357    /// assert!(zero.is_ascii_hexdigit());
2358    /// assert!(!percent.is_ascii_hexdigit());
2359    /// assert!(!space.is_ascii_hexdigit());
2360    /// assert!(!lf.is_ascii_hexdigit());
2361    /// assert!(!esc.is_ascii_hexdigit());
2362    /// ```
2363    #[must_use]
2364    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2365    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2366    #[inline]
2367    pub const fn is_ascii_hexdigit(&self) -> bool {
2368        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '0'..='9' => true,
    _ => false,
}matches!(*self, '0'..='9') | #[allow(non_exhaustive_omitted_patterns)] match *self {
    'A'..='F' => true,
    _ => false,
}matches!(*self, 'A'..='F') | #[allow(non_exhaustive_omitted_patterns)] match *self {
    'a'..='f' => true,
    _ => false,
}matches!(*self, 'a'..='f')
2369    }
2370
2371    /// Checks if the value is an ASCII punctuation or symbol character
2372    /// (i.e. not alphanumeric, whitespace, or control):
2373    ///
2374    /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
2375    /// - U+003A ..= U+0040 `: ; < = > ? @`, or
2376    /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
2377    /// - U+007B ..= U+007E `{ | } ~`
2378    ///
2379    /// # Examples
2380    ///
2381    /// ```
2382    /// let uppercase_a = 'A';
2383    /// let uppercase_g = 'G';
2384    /// let a = 'a';
2385    /// let g = 'g';
2386    /// let zero = '0';
2387    /// let percent = '%';
2388    /// let space = ' ';
2389    /// let lf = '\n';
2390    /// let esc = '\x1b';
2391    ///
2392    /// assert!(!uppercase_a.is_ascii_punctuation());
2393    /// assert!(!uppercase_g.is_ascii_punctuation());
2394    /// assert!(!a.is_ascii_punctuation());
2395    /// assert!(!g.is_ascii_punctuation());
2396    /// assert!(!zero.is_ascii_punctuation());
2397    /// assert!(percent.is_ascii_punctuation());
2398    /// assert!(!space.is_ascii_punctuation());
2399    /// assert!(!lf.is_ascii_punctuation());
2400    /// assert!(!esc.is_ascii_punctuation());
2401    /// ```
2402    #[must_use]
2403    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2404    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2405    #[inline]
2406    pub const fn is_ascii_punctuation(&self) -> bool {
2407        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '!'..='/' => true,
    _ => false,
}matches!(*self, '!'..='/')
2408            | #[allow(non_exhaustive_omitted_patterns)] match *self {
    ':'..='@' => true,
    _ => false,
}matches!(*self, ':'..='@')
2409            | #[allow(non_exhaustive_omitted_patterns)] match *self {
    '['..='`' => true,
    _ => false,
}matches!(*self, '['..='`')
2410            | #[allow(non_exhaustive_omitted_patterns)] match *self {
    '{'..='~' => true,
    _ => false,
}matches!(*self, '{'..='~')
2411    }
2412
2413    /// Checks if the value is an ASCII graphic character
2414    /// (i.e. not whitespace or control):
2415    /// U+0021 '!' ..= U+007E '~'.
2416    ///
2417    /// # Examples
2418    ///
2419    /// ```
2420    /// let uppercase_a = 'A';
2421    /// let uppercase_g = 'G';
2422    /// let a = 'a';
2423    /// let g = 'g';
2424    /// let zero = '0';
2425    /// let percent = '%';
2426    /// let space = ' ';
2427    /// let lf = '\n';
2428    /// let esc = '\x1b';
2429    ///
2430    /// assert!(uppercase_a.is_ascii_graphic());
2431    /// assert!(uppercase_g.is_ascii_graphic());
2432    /// assert!(a.is_ascii_graphic());
2433    /// assert!(g.is_ascii_graphic());
2434    /// assert!(zero.is_ascii_graphic());
2435    /// assert!(percent.is_ascii_graphic());
2436    /// assert!(!space.is_ascii_graphic());
2437    /// assert!(!lf.is_ascii_graphic());
2438    /// assert!(!esc.is_ascii_graphic());
2439    /// ```
2440    #[must_use]
2441    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2442    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2443    #[inline]
2444    pub const fn is_ascii_graphic(&self) -> bool {
2445        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '!'..='~' => true,
    _ => false,
}matches!(*self, '!'..='~')
2446    }
2447
2448    /// Checks if the value is an ASCII whitespace character:
2449    /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2450    /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2451    ///
2452    /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
2453    /// `c.is_ascii_whitespace()` is **not** equivalent to `c.is_ascii() && c.is_whitespace()`.
2454    ///
2455    /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2456    /// whitespace][infra-aw]. There are several other definitions in
2457    /// wide use. For instance, [the POSIX locale][pct] includes
2458    /// U+000B VERTICAL TAB as well as all the above characters,
2459    /// but—from the very same specification—[the default rule for
2460    /// "field splitting" in the Bourne shell][bfs] considers *only*
2461    /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2462    ///
2463    /// If you are writing a program that will process an existing
2464    /// file format, check what that format's definition of whitespace is
2465    /// before using this function.
2466    ///
2467    /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2468    /// [pct]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap07.html#tag_07_03_01
2469    /// [bfs]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_06_05
2470    ///
2471    /// # Examples
2472    ///
2473    /// ```
2474    /// let uppercase_a = 'A';
2475    /// let uppercase_g = 'G';
2476    /// let a = 'a';
2477    /// let g = 'g';
2478    /// let zero = '0';
2479    /// let percent = '%';
2480    /// let space = ' ';
2481    /// let lf = '\n';
2482    /// let esc = '\x1b';
2483    ///
2484    /// assert!(!uppercase_a.is_ascii_whitespace());
2485    /// assert!(!uppercase_g.is_ascii_whitespace());
2486    /// assert!(!a.is_ascii_whitespace());
2487    /// assert!(!g.is_ascii_whitespace());
2488    /// assert!(!zero.is_ascii_whitespace());
2489    /// assert!(!percent.is_ascii_whitespace());
2490    /// assert!(space.is_ascii_whitespace());
2491    /// assert!(lf.is_ascii_whitespace());
2492    /// assert!(!esc.is_ascii_whitespace());
2493    /// ```
2494    #[must_use]
2495    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2496    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2497    #[inline]
2498    pub const fn is_ascii_whitespace(&self) -> bool {
2499        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '\t' | '\n' | '\x0C' | '\r' | ' ' => true,
    _ => false,
}matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
2500    }
2501
2502    /// Checks if the value is an ASCII control character:
2503    /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
2504    /// Note that most ASCII whitespace characters are control
2505    /// characters, but SPACE is not.
2506    ///
2507    /// # Examples
2508    ///
2509    /// ```
2510    /// let uppercase_a = 'A';
2511    /// let uppercase_g = 'G';
2512    /// let a = 'a';
2513    /// let g = 'g';
2514    /// let zero = '0';
2515    /// let percent = '%';
2516    /// let space = ' ';
2517    /// let lf = '\n';
2518    /// let esc = '\x1b';
2519    ///
2520    /// assert!(!uppercase_a.is_ascii_control());
2521    /// assert!(!uppercase_g.is_ascii_control());
2522    /// assert!(!a.is_ascii_control());
2523    /// assert!(!g.is_ascii_control());
2524    /// assert!(!zero.is_ascii_control());
2525    /// assert!(!percent.is_ascii_control());
2526    /// assert!(!space.is_ascii_control());
2527    /// assert!(lf.is_ascii_control());
2528    /// assert!(esc.is_ascii_control());
2529    /// ```
2530    #[must_use]
2531    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2532    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2533    #[inline]
2534    pub const fn is_ascii_control(&self) -> bool {
2535        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '\0'..='\x1F' | '\x7F' => true,
    _ => false,
}matches!(*self, '\0'..='\x1F' | '\x7F')
2536    }
2537}
2538
2539pub(crate) struct EscapeDebugExtArgs {
2540    /// Escape single quotes?
2541    pub(crate) escape_single_quote: bool,
2542
2543    /// Escape double quotes?
2544    pub(crate) escape_double_quote: bool,
2545}
2546
2547impl EscapeDebugExtArgs {
2548    pub(crate) const ESCAPE_ALL: Self =
2549        Self { escape_single_quote: true, escape_double_quote: true };
2550}
2551
2552#[inline]
2553#[must_use]
2554const fn len_utf8(code: u32) -> usize {
2555    match code {
2556        ..MAX_ONE_B => 1,
2557        ..MAX_TWO_B => 2,
2558        ..MAX_THREE_B => 3,
2559        _ => 4,
2560    }
2561}
2562
2563#[inline]
2564#[must_use]
2565const fn len_utf16(code: u32) -> usize {
2566    if (code & 0xFFFF) == code { 1 } else { 2 }
2567}
2568
2569/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
2570/// and then returns the subslice of the buffer that contains the encoded character.
2571///
2572/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2573/// (Creating a `char` in the surrogate range is UB.)
2574/// The result is valid [generalized UTF-8] but not valid UTF-8.
2575///
2576/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2577///
2578/// # Panics
2579///
2580/// Panics if the buffer is not large enough.
2581/// A buffer of length four is large enough to encode any `char`.
2582#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2583#[doc(hidden)]
2584#[inline]
2585pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
2586    let len = len_utf8(code);
2587    if dst.len() < len {
2588        {
    #[rustc_allow_const_fn_unstable(const_eval_select)]
    #[inline(always)]
    #[track_caller]
    const fn do_panic(code: u32, len: usize, dst_len: usize) -> ! {
        {
            #[inline]
            #[track_caller]
            fn runtime(code: u32, len: usize, dst_len: usize) -> ! {
                {
                    {
                        crate::panicking::panic_fmt(format_args!("encode_utf8: need {0} bytes to encode U+{1:04X} but buffer has just {2}",
                                len, code, dst_len));
                    }
                }
            }
            #[inline]
            #[track_caller]
            const fn compiletime(code: u32, len: usize, dst_len: usize) -> ! {
                let _ = code;
                let _ = len;
                let _ = dst_len;
                {
                    {
                        crate::panicking::panic_fmt(format_args!("encode_utf8: buffer does not have enough bytes to encode code point"));
                    }
                }
            }
            const_eval_select((code, len, dst_len), compiletime, runtime)
        }
    }
    do_panic(code, len, dst.len())
};const_panic!(
2589            "encode_utf8: buffer does not have enough bytes to encode code point",
2590            "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2591            code: u32 = code,
2592            len: usize = len,
2593            dst_len: usize = dst.len(),
2594        );
2595    }
2596
2597    // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint.
2598    unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) };
2599
2600    // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2601    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2602}
2603
2604/// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`.
2605///
2606/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2607/// (Creating a `char` in the surrogate range is UB.)
2608/// The result is valid [generalized UTF-8] but not valid UTF-8.
2609///
2610/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2611///
2612/// # Safety
2613///
2614/// The behavior is undefined if the buffer pointed to by `dst` is not
2615/// large enough to hold the encoded codepoint. A buffer of length four
2616/// is large enough to encode any `char`.
2617///
2618/// For a safe version of this function, see the [`encode_utf8_raw`] function.
2619#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2620#[doc(hidden)]
2621#[inline]
2622pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
2623    let len = len_utf8(code);
2624    // SAFETY: The caller must guarantee that the buffer pointed to by `dst`
2625    // is at least `len` bytes long.
2626    unsafe {
2627        if len == 1 {
2628            *dst = code as u8;
2629            return;
2630        }
2631
2632        let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
2633        let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
2634        let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
2635        let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
2636
2637        if len == 2 {
2638            *dst = last2 | TAG_TWO_B;
2639            *dst.add(1) = last1;
2640            return;
2641        }
2642
2643        if len == 3 {
2644            *dst = last3 | TAG_THREE_B;
2645            *dst.add(1) = last2;
2646            *dst.add(2) = last1;
2647            return;
2648        }
2649
2650        *dst = last4;
2651        *dst.add(1) = last3;
2652        *dst.add(2) = last2;
2653        *dst.add(3) = last1;
2654    }
2655}
2656
2657/// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer,
2658/// and then returns the subslice of the buffer that contains the encoded character.
2659///
2660/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
2661/// (Creating a `char` in the surrogate range is UB.)
2662///
2663/// # Panics
2664///
2665/// Panics if the buffer is not large enough.
2666/// A buffer of length 2 is large enough to encode any `char`.
2667#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2668#[doc(hidden)]
2669#[inline]
2670pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
2671    let len = len_utf16(code);
2672    match (len, &mut *dst) {
2673        (1, [a, ..]) => {
2674            *a = code as u16;
2675        }
2676        (2, [a, b, ..]) => {
2677            code -= 0x1_0000;
2678            *a = (code >> 10) as u16 | 0xD800;
2679            *b = (code & 0x3FF) as u16 | 0xDC00;
2680        }
2681        _ => {
2682            {
    #[rustc_allow_const_fn_unstable(const_eval_select)]
    #[inline(always)]
    #[track_caller]
    const fn do_panic(code: u32, len: usize, dst_len: usize) -> ! {
        {
            #[inline]
            #[track_caller]
            fn runtime(code: u32, len: usize, dst_len: usize) -> ! {
                {
                    {
                        crate::panicking::panic_fmt(format_args!("encode_utf16: need {0} bytes to encode U+{1:04X} but buffer has just {2}",
                                len, code, dst_len));
                    }
                }
            }
            #[inline]
            #[track_caller]
            const fn compiletime(code: u32, len: usize, dst_len: usize) -> ! {
                let _ = code;
                let _ = len;
                let _ = dst_len;
                {
                    {
                        crate::panicking::panic_fmt(format_args!("encode_utf16: buffer does not have enough bytes to encode code point"));
                    }
                }
            }
            const_eval_select((code, len, dst_len), compiletime, runtime)
        }
    }
    do_panic(code, len, dst.len())
}const_panic!(
2683                "encode_utf16: buffer does not have enough bytes to encode code point",
2684                "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2685                code: u32 = code,
2686                len: usize = len,
2687                dst_len: usize = dst.len(),
2688            )
2689        }
2690    };
2691    // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2692    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2693}