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    /// #![feature(titlecase)]
822    /// assert!('A'.is_cased());
823    /// assert!('a'.is_cased());
824    /// assert!(!'京'.is_cased());
825    /// ```
826    #[must_use]
827    #[unstable(feature = "titlecase", issue = "153892")]
828    #[inline]
829    pub fn is_cased(self) -> bool {
830        match self {
831            'a'..='z' | 'A'..='Z' => true,
832            '\0'..='\u{A9}' => false,
833            _ => unicode::Lowercase(self) || unicode::Uppercase(self) || unicode::Lt(self),
834        }
835    }
836
837    /// Returns the case of this character:
838    /// [`Some(CharCase::Upper)`][`CharCase::Upper`] if [`self.is_uppercase()`][`char::is_uppercase`],
839    /// [`Some(CharCase::Lower)`][`CharCase::Lower`] if [`self.is_lowercase()`][`char::is_lowercase`],
840    /// [`Some(CharCase::Title)`][`CharCase::Title`] if [`self.is_titlecase()`][`char::is_titlecase`], and
841    /// `None` if [`!self.is_cased()`][`char::is_cased`].
842    ///
843    /// # Examples
844    ///
845    /// ```
846    /// #![feature(titlecase)]
847    /// use core::char::CharCase;
848    /// assert_eq!('a'.case(), Some(CharCase::Lower));
849    /// assert_eq!('δ'.case(), Some(CharCase::Lower));
850    /// assert_eq!('A'.case(), Some(CharCase::Upper));
851    /// assert_eq!('Δ'.case(), Some(CharCase::Upper));
852    /// assert_eq!('Dž'.case(), Some(CharCase::Title));
853    /// assert_eq!('中'.case(), None);
854    /// ```
855    #[must_use]
856    #[unstable(feature = "titlecase", issue = "153892")]
857    #[inline]
858    pub fn case(self) -> Option<CharCase> {
859        match self {
860            'a'..='z' => Some(CharCase::Lower),
861            'A'..='Z' => Some(CharCase::Upper),
862            '\0'..='\u{A9}' => None,
863            _ if unicode::Lowercase(self) => Some(CharCase::Lower),
864            _ if unicode::Uppercase(self) => Some(CharCase::Upper),
865            _ if unicode::Lt(self) => Some(CharCase::Title),
866            _ => None,
867        }
868    }
869
870    /// Returns `true` if this `char` has the `Lowercase` property.
871    ///
872    /// `Lowercase` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and
873    /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
874    ///
875    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G136255
876    /// [specified]: https://www.unicode.org/reports/tr44/#Lowercase
877    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
878    ///
879    /// # Examples
880    ///
881    /// Basic usage:
882    ///
883    /// ```
884    /// assert!('a'.is_lowercase());
885    /// assert!('δ'.is_lowercase());
886    /// assert!(!'A'.is_lowercase());
887    /// assert!(!'Δ'.is_lowercase());
888    ///
889    /// // The various Chinese scripts and punctuation do not have case, and so:
890    /// assert!(!'中'.is_lowercase());
891    /// assert!(!' '.is_lowercase());
892    /// ```
893    ///
894    /// In a const context:
895    ///
896    /// ```
897    /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
898    /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
899    /// ```
900    #[must_use]
901    #[stable(feature = "rust1", since = "1.0.0")]
902    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
903    #[inline]
904    pub const fn is_lowercase(self) -> bool {
905        match self {
906            'a'..='z' => true,
907            '\0'..='\u{A9}' => false,
908            _ => unicode::Lowercase(self),
909        }
910    }
911
912    /// Returns `true` if this `char` is in the general category for titlecase letters.
913    /// Conceptually, these characters consist of an uppercase portion followed by a lowercase portion.
914    ///
915    /// Titlecase letters (code points with the general category of `Lt`) are [described] in Chapter 4
916    /// (Character Properties) of the Unicode Standard, and [specified] in the Unicode Character
917    /// Database [`UnicodeData.txt`].
918    ///
919    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G124722
920    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
921    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
922    ///
923    /// # Examples
924    ///
925    /// Basic usage:
926    ///
927    /// ```
928    /// #![feature(titlecase)]
929    /// assert!('Dž'.is_titlecase());
930    /// assert!('ῼ'.is_titlecase());
931    /// assert!(!'D'.is_titlecase());
932    /// assert!(!'z'.is_titlecase());
933    /// assert!(!'中'.is_titlecase());
934    /// assert!(!' '.is_titlecase());
935    /// ```
936    #[must_use]
937    #[unstable(feature = "titlecase", issue = "153892")]
938    #[inline]
939    pub fn is_titlecase(self) -> bool {
940        match self {
941            '\0'..='\u{01C4}' => false,
942            _ => unicode::Lt(self),
943        }
944    }
945
946    /// Returns `true` if this `char` has the `Uppercase` property.
947    ///
948    /// `Uppercase` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and
949    /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
950    ///
951    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G136255
952    /// [specified]: https://www.unicode.org/reports/tr44/#Uppercase
953    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
954    ///
955    /// # Examples
956    ///
957    /// Basic usage:
958    ///
959    /// ```
960    /// assert!(!'a'.is_uppercase());
961    /// assert!(!'δ'.is_uppercase());
962    /// assert!('A'.is_uppercase());
963    /// assert!('Δ'.is_uppercase());
964    ///
965    /// // The various Chinese scripts and punctuation do not have case, and so:
966    /// assert!(!'中'.is_uppercase());
967    /// assert!(!' '.is_uppercase());
968    /// ```
969    ///
970    /// In a const context:
971    ///
972    /// ```
973    /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
974    /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
975    /// ```
976    #[must_use]
977    #[stable(feature = "rust1", since = "1.0.0")]
978    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
979    #[inline]
980    pub const fn is_uppercase(self) -> bool {
981        match self {
982            'A'..='Z' => true,
983            '\0'..='\u{BF}' => false,
984            _ => unicode::Uppercase(self),
985        }
986    }
987
988    /// Returns `true` if this `char` has one of the general categories for numbers.
989    ///
990    /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
991    /// characters, and `No` for other numeric characters) are [specified] in the Unicode Character
992    /// Database [`UnicodeData.txt`].
993    ///
994    /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
995    /// If you want everything including characters with overlapping purposes, then you might want to use
996    /// a Unicode or language-processing library that exposes the appropriate character properties
997    /// (e.g. [`Numeric_Type`]) instead of looking at the Unicode categories.
998    ///
999    /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
1000    /// `is_ascii_digit` or `is_digit` instead.
1001    ///
1002    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1003    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1004    /// [`Numeric_Type`]: https://www.unicode.org/reports/tr44/#Numeric_Type
1005    ///
1006    /// # Examples
1007    ///
1008    /// Basic usage:
1009    ///
1010    /// ```
1011    /// assert!('٣'.is_numeric());
1012    /// assert!('7'.is_numeric());
1013    /// assert!('৬'.is_numeric());
1014    /// assert!('¾'.is_numeric());
1015    /// assert!('①'.is_numeric());
1016    /// assert!(!'K'.is_numeric());
1017    /// assert!(!'و'.is_numeric());
1018    /// assert!(!'藏'.is_numeric());
1019    /// assert!(!'三'.is_numeric());
1020    /// ```
1021    #[must_use]
1022    #[stable(feature = "rust1", since = "1.0.0")]
1023    #[inline]
1024    pub fn is_numeric(self) -> bool {
1025        match self {
1026            '0'..='9' => true,
1027            '\0'..='\u{B1}' => false,
1028            _ => unicode::N(self),
1029        }
1030    }
1031
1032    /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
1033    ///
1034    /// [`is_alphabetic()`]: Self::is_alphabetic
1035    /// [`is_numeric()`]: Self::is_numeric
1036    ///
1037    /// # Examples
1038    ///
1039    /// Basic usage:
1040    ///
1041    /// ```
1042    /// assert!('٣'.is_alphanumeric());
1043    /// assert!('7'.is_alphanumeric());
1044    /// assert!('৬'.is_alphanumeric());
1045    /// assert!('¾'.is_alphanumeric());
1046    /// assert!('①'.is_alphanumeric());
1047    /// assert!('K'.is_alphanumeric());
1048    /// assert!('و'.is_alphanumeric());
1049    /// assert!('藏'.is_alphanumeric());
1050    /// ```
1051    #[must_use]
1052    #[stable(feature = "rust1", since = "1.0.0")]
1053    #[inline]
1054    pub fn is_alphanumeric(self) -> bool {
1055        match self {
1056            'a'..='z' | 'A'..='Z' | '0'..='9' => true,
1057            '\0'..='\u{A9}' => false,
1058            _ => unicode::Alphabetic(self) || unicode::N(self),
1059        }
1060    }
1061
1062    /// Returns `true` if this `char` has the `White_Space` property.
1063    ///
1064    /// `White_Space` is [specified] in the Unicode Character Database [`PropList.txt`].
1065    ///
1066    /// [specified]: https://www.unicode.org/reports/tr44/#White_Space
1067    /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
1068    ///
1069    /// # Examples
1070    ///
1071    /// Basic usage:
1072    ///
1073    /// ```
1074    /// assert!(' '.is_whitespace());
1075    ///
1076    /// // line break
1077    /// assert!('\n'.is_whitespace());
1078    ///
1079    /// // a non-breaking space
1080    /// assert!('\u{A0}'.is_whitespace());
1081    ///
1082    /// assert!(!'越'.is_whitespace());
1083    /// ```
1084    #[must_use]
1085    #[stable(feature = "rust1", since = "1.0.0")]
1086    #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
1087    #[inline]
1088    pub const fn is_whitespace(self) -> bool {
1089        match self {
1090            ' ' | '\x09'..='\x0d' => true,
1091            '\0'..='\u{84}' => false,
1092            _ => unicode::White_Space(self),
1093        }
1094    }
1095
1096    /// Returns `true` if this `char` has the general category for control codes.
1097    ///
1098    /// Control codes (code points with the general category of `Cc`) are [described] in Chapter 23
1099    /// (Special Areas and Format Characters) of the Unicode Standard, and [specified] in the Unicode Character
1100    /// Database [`UnicodeData.txt`]. The full set of Unicode control codes is
1101    /// `'\0'..='\x1f' | '\x7f'..='\u{9f}'`, and will never change.
1102    ///
1103    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-23/#G20365
1104    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1105    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1106    ///
1107    /// # Examples
1108    ///
1109    /// Basic usage:
1110    ///
1111    /// ```
1112    /// assert!('\t'.is_control());
1113    /// assert!('\n'.is_control());
1114    /// assert!('\u{9C}'.is_control()); // STRING TERMINATOR
1115    /// assert!(!'q'.is_control());
1116    /// ```
1117    #[must_use]
1118    #[stable(feature = "rust1", since = "1.0.0")]
1119    #[rustc_const_stable(feature = "const_is_control", since = "1.97.0")]
1120    #[inline]
1121    pub const fn is_control(self) -> bool {
1122        // According to
1123        // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1124        // the set of codepoints in `Cc` will never change.
1125        // So we can just hard-code the patterns to match against instead of using a table.
1126        #[allow(non_exhaustive_omitted_patterns)] match self {
    '\0'..='\x1f' | '\x7f'..='\u{9f}' => true,
    _ => false,
}matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}')
1127    }
1128
1129    /// Returns `true` if this `char` has the general category for [private-use characters].
1130    /// These characters do not have an interpretation specified by Unicode; individual programs
1131    /// and users are free to assign them whatever meaning they like.
1132    ///
1133    /// [private-use characters]: https://www.unicode.org/faq/private_use#private_use
1134    ///
1135    /// Private-use characters (code points with the general category of `Co`) are [described] in Chapter 23
1136    /// (Special Areas and Format Characters) of the Unicode Standard, and [specified] in the
1137    /// Unicode Character Database [`UnicodeData.txt`]. The full set of private-use characters is
1138    /// `'\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}'`,
1139    /// and will never change.
1140    ///
1141    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-23/#G19184
1142    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1143    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1144    ///
1145    #[must_use]
1146    #[unstable(feature = "char_unassigned_private_use", issue = "158322")]
1147    #[inline]
1148    pub const fn is_private_use(self) -> bool {
1149        // According to
1150        // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1151        // the set of codepoints in `Co` will never change.
1152        // So we can just hard-code the patterns to match against instead of using a table.
1153        #[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}')
1154    }
1155
1156    /// Returns `true` if this `char` has the general category for format control characters.
1157    ///
1158    /// Format controls (code points with the general category of `Cf`) are [described] in Chapter 4
1159    /// (Character Properties) of the Unicode Standard, and [specified] in the Unicode Character
1160    /// Database [`UnicodeData.txt`].
1161    ///
1162    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G134153
1163    /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1164    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1165    ///
1166    /// # Examples
1167    ///
1168    /// Basic usage:
1169    ///
1170    /// ```ignore(private)
1171    /// assert!('\u{AD}'.is_format_control()); // SOFT HYPHEN
1172    /// assert!('\u{200B}'.is_format_control()); // ZERO WIDTH SPACE
1173    /// assert!('\u{E0041}'.is_format_control()); // TAG LATIN CAPITAL LETTER A
1174    /// assert!('۝'.is_format_control()); // ARABIC END OF AYAH
1175    /// assert!('𓐲'.is_format_control()); // EGYPTIAN HIEROGLYPH INSERT AT TOP START
1176    /// assert!(!'q'.is_format_control());
1177    /// ```
1178    #[must_use]
1179    #[inline]
1180    fn is_format_control(self) -> bool {
1181        self > '\u{AC}' && unicode::Cf(self)
1182    }
1183
1184    /// Returns `true` if this `char` has been assigned a meaning by Unicode, as of
1185    /// [`UNICODE_VERSION`].
1186    ///
1187    /// [`UNICODE_VERSION`]: Self::UNICODE_VERSION
1188    ///
1189    /// Many of Unicode's [stability policies] apply only to assigned characters.
1190    ///
1191    /// [stability policies]: https://www.unicode.org/policies/stability_policy.html
1192    ///
1193    /// Currently unassigned characters (characters for which this method returns `false`)
1194    /// may have a meaning assigned in a future version of Unicode,
1195    /// except for the 66 [noncharacters] which will never be assigned a meaning.
1196    ///
1197    /// [noncharacters]: https://www.unicode.org/faq/private_use.html#noncharacters
1198    ///
1199    /// A character is considered assigned if it is present in [`UnicodeData.txt`].
1200    /// Unassigned characters have general category `Cn`, as [described] in Chapter 4
1201    /// (Character Properties) of the Unicode Standard.
1202    ///
1203    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1204    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G134153
1205    ///
1206    /// # Examples
1207    ///
1208    /// Basic usage:
1209    ///
1210    /// ```
1211    /// #![feature(char_unassigned_private_use)]
1212    /// assert!('γ'.is_assigned()); // once a character is assigned, it stays assigned forever
1213    /// assert!(!'\u{FFFE}'.is_assigned()); // noncharacter, will never be assigned
1214    ///
1215    /// // Not currently assigned, but may be in the future,
1216    /// // so we shouldn't rely on the current status
1217    /// /* assert!(!'\u{7AAAA}'.is_assigned()); */
1218    /// ```
1219    #[must_use]
1220    #[unstable(feature = "char_unassigned_private_use", issue = "158322")]
1221    #[inline]
1222    pub fn is_assigned(self) -> bool {
1223        match self {
1224            '\0'..='\u{377}' => true,
1225            '\u{378}'..='\u{3FFFD}' => !unicode::Cn_planes_0_3(self),
1226            // Assigned character ranges in planes 4 and above.
1227            // `src/tools/unicode-table-generator/src/main.rs` asserts that this is correct
1228            '\u{E0001}'
1229            | '\u{E0020}'..='\u{E007F}'
1230            | '\u{E0100}'..='\u{E01EF}'
1231            | '\u{F0000}'..='\u{FFFFD}'
1232            | '\u{100000}'..='\u{10FFFD}' => true,
1233            _ => false,
1234        }
1235    }
1236
1237    /// Returns `true` if this `char` has the `Default_Ignorable_Code_Point` property.
1238    /// These characters [should be displayed as invisible in fallback rendering](https://www.unicode.org/faq/unsup_char#3).
1239    ///
1240    /// `Default_Ignorable_Code_Point` is [described] in Chapter 5 (Implementation Guidelines) of the Unicode Standard,
1241    /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1242    ///
1243    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-5/#G40120
1244    /// [specified]: https://www.unicode.org/reports/tr44/#Default_Ignorable_Code_Point
1245    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1246    ///
1247    /// # Examples
1248    ///
1249    /// Basic usage:
1250    ///
1251    /// ```
1252    /// #![feature(default_ignorable)]
1253    /// assert!('\u{AD}'.is_default_ignorable()); // SOFT HYPHEN
1254    /// assert!('\u{115F}'.is_default_ignorable()); // HANGUL CHOSEONG FILLER
1255    /// assert!('\u{200B}'.is_default_ignorable()); // ZERO WIDTH SPACE
1256    /// assert!('\u{E0041}'.is_default_ignorable()); // TAG LATIN CAPITAL LETTER A
1257    /// assert!(!'۝'.is_default_ignorable()); // ARABIC END OF AYAH
1258    /// assert!(!'𓐲'.is_default_ignorable()); // EGYPTIAN HIEROGLYPH INSERT AT TOP START
1259    /// assert!(!' '.is_default_ignorable());
1260    /// assert!(!'\n'.is_default_ignorable());
1261    /// assert!(!'\0'.is_default_ignorable());
1262    /// assert!(!'q'.is_default_ignorable());
1263    /// ```
1264    #[must_use]
1265    #[unstable(feature = "default_ignorable", issue = "160583")]
1266    #[inline]
1267    pub fn is_default_ignorable(self) -> bool {
1268        self > '\u{AC}' && unicode::Default_Ignorable_Code_Point(self)
1269    }
1270
1271    /// Returns `true` if this `char` has the `Grapheme_Extend` property.
1272    ///
1273    /// `Grapheme_Extend` is [described] in Chapter 3 (Conformance) of the Unicode Standard,
1274    /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1275    ///
1276    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G41165
1277    /// [specified]: https://www.unicode.org/reports/tr44/#Grapheme_Extend
1278    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1279    #[must_use]
1280    #[inline]
1281    fn is_grapheme_extender(self) -> bool {
1282        self > '\u{02FF}' && unicode::Grapheme_Extend(self)
1283    }
1284
1285    /// Returns `true` if this `char` has the `Case_Ignorable` property. This narrow-use property
1286    /// is used to implement context-dependent casing for the Greek letter sigma (uppercase 'Σ'),
1287    /// which has two lowercase forms.
1288    ///
1289    /// `Case_Ignorable` is [described] in Chapter 3 (Conformance) of the Unicode Core Specification,
1290    /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1291    /// See those resources, as well as [`to_lowercase()`]'s documentation, for more information.
1292    ///
1293    /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G63116
1294    /// [specified]: https://www.unicode.org/reports/tr44/#Case_Ignorable
1295    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1296    /// [`to_lowercase()`]: Self::to_lowercase()
1297    #[must_use]
1298    #[inline]
1299    #[unstable(feature = "case_ignorable", issue = "154848")]
1300    pub fn is_case_ignorable(self) -> bool {
1301        if self.is_ascii() {
1302            #[allow(non_exhaustive_omitted_patterns)] match self {
    '\'' | '.' | ':' | '^' | '`' => true,
    _ => false,
}matches!(self, '\'' | '.' | ':' | '^' | '`')
1303        } else {
1304            unicode::Case_Ignorable(self)
1305        }
1306    }
1307
1308    /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
1309    /// `char`s.
1310    ///
1311    /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
1312    ///
1313    /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
1314    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1315    ///
1316    /// [ucd]: https://www.unicode.org/reports/tr44/
1317    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1318    ///
1319    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1320    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1321    ///
1322    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1323    /// is independent of context and language. See [below](#notes-on-context-and-locale)
1324    /// for more information.
1325    ///
1326    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1327    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1328    ///
1329    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1330    ///
1331    /// # Examples
1332    ///
1333    /// As an iterator:
1334    ///
1335    /// ```
1336    /// for c in 'İ'.to_lowercase() {
1337    ///     print!("{c}");
1338    /// }
1339    /// println!();
1340    /// ```
1341    ///
1342    /// Using `println!` directly:
1343    ///
1344    /// ```
1345    /// println!("{}", 'İ'.to_lowercase());
1346    /// ```
1347    ///
1348    /// Both are equivalent to:
1349    ///
1350    /// ```
1351    /// println!("i\u{307}");
1352    /// ```
1353    ///
1354    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1355    ///
1356    /// ```
1357    /// assert_eq!('C'.to_lowercase().to_string(), "c");
1358    ///
1359    /// // Sometimes the result is more than one character:
1360    /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1361    ///
1362    /// // Characters that do not have both uppercase and lowercase
1363    /// // convert into themselves.
1364    /// assert_eq!('山'.to_lowercase().to_string(), "山");
1365    /// ```
1366    /// # Notes on context and locale
1367    ///
1368    /// As stated earlier, this method does not take into account language or context.
1369    /// Below is a non-exhaustive list of situations where this can be relevant.
1370    /// If you need to handle locale-depedendent casing in your code, consider using
1371    /// an external crate, like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1372    /// which is developed by Unicode.
1373    ///
1374    /// ## Greek sigma
1375    ///
1376    /// In Greek, the letter simga (uppercase 'Σ') has two lowercase forms:
1377    /// 'σ' which is used in most situations, and 'ς' which appears only
1378    /// at the end of a word. [`char::to_lowercase()`] always uses the first form:
1379    ///
1380    /// ```
1381    /// assert_eq!('Σ'.to_lowercase().to_string(), "σ");
1382    /// ```
1383    ///
1384    /// `str::to_lowercase()` (only available with the `alloc` crate)
1385    /// *does* properly handle this contextual mapping,
1386    /// so prefer using that method if you can. Alternatively, you can use
1387    /// [`is_cased()`] and [`is_case_ignorable()`] to implement it yourself.
1388    /// See `Final_Sigma` in [Table 3.17] of the Unicode Standard,
1389    /// along with [`SpecialCasing.txt`], for more details.
1390    ///
1391    /// [`is_cased()`]: Self::is_cased()
1392    /// [`is_case_ignorable()`]: Self::is_case_ignorable()
1393    /// [Table 3.17]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G54277
1394    ///
1395    /// ## Turkish and Azeri I/ı/İ/i
1396    ///
1397    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1398    ///
1399    /// * 'Dotless': I / ı, sometimes written ï
1400    /// * 'Dotted': İ / i
1401    ///
1402    /// Note that the uppercase undotted 'I' is the same codepoint as the Latin. Therefore:
1403    ///
1404    /// ```
1405    /// let lower_i = 'I'.to_lowercase().to_string();
1406    /// ```
1407    ///
1408    /// `'I'`'s correct lowercase relies on the language of the text: if we're
1409    /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should
1410    /// be `"ı"`. `to_lowercase()` does not take this into account, and so:
1411    ///
1412    /// ```
1413    /// let lower_i = 'I'.to_lowercase().to_string();
1414    ///
1415    /// assert_eq!(lower_i, "i");
1416    /// ```
1417    ///
1418    /// holds across languages.
1419    ///
1420    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1421    #[must_use = "this returns the lowercased character as a new iterator, \
1422                  without modifying the original"]
1423    #[stable(feature = "rust1", since = "1.0.0")]
1424    #[inline]
1425    pub fn to_lowercase(self) -> ToLowercase {
1426        ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1427    }
1428
1429    /// Returns an iterator that yields the titlecase mapping of this `char` as one or more
1430    /// `char`s.
1431    ///
1432    /// This is usually, but not always, equivalent to the uppercase mapping
1433    /// returned by [`to_uppercase()`]. Prefer this method when seeking to capitalize
1434    /// Only The First Letter of a word, but use [`to_uppercase()`] for ALL CAPS.
1435    /// See [below](#difference-from-uppercase) for a thorough explanation
1436    /// of the difference between the two methods.
1437    ///
1438    /// If this `char` does not have a titlecase mapping, the iterator yields the same `char`.
1439    ///
1440    /// If this `char` has a one-to-one titlecase mapping given by the [Unicode Character
1441    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1442    ///
1443    /// [ucd]: https://www.unicode.org/reports/tr44/
1444    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1445    ///
1446    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1447    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1448    ///
1449    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1450    ///
1451    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1452    /// is independent of context and language. See [below](#note-on-locale)
1453    /// for more information.
1454    ///
1455    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1456    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1457    ///
1458    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1459    ///
1460    /// # Examples
1461    ///
1462    /// As an iterator:
1463    ///
1464    /// ```
1465    /// #![feature(titlecase)]
1466    /// for c in 'ß'.to_titlecase() {
1467    ///     print!("{c}");
1468    /// }
1469    /// println!();
1470    /// ```
1471    ///
1472    /// Using `println!` directly:
1473    ///
1474    /// ```
1475    /// #![feature(titlecase)]
1476    /// println!("{}", 'ß'.to_titlecase());
1477    /// ```
1478    ///
1479    /// Both are equivalent to:
1480    ///
1481    /// ```
1482    /// println!("Ss");
1483    /// ```
1484    ///
1485    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1486    ///
1487    /// ```
1488    /// #![feature(titlecase)]
1489    /// assert_eq!('c'.to_titlecase().to_string(), "C");
1490    /// assert_eq!('ა'.to_titlecase().to_string(), "ა");
1491    /// assert_eq!('dž'.to_titlecase().to_string(), "Dž");
1492    /// assert_eq!('ᾨ'.to_titlecase().to_string(), "ᾨ");
1493    ///
1494    /// // Sometimes the result is more than one character:
1495    /// assert_eq!('ß'.to_titlecase().to_string(), "Ss");
1496    ///
1497    /// // Characters that do not have separate cased forms
1498    /// // convert into themselves.
1499    /// assert_eq!('山'.to_titlecase().to_string(), "山");
1500    /// ```
1501    ///
1502    /// # Difference from uppercase
1503    ///
1504    /// Currently, there are three classes of characters where [`to_uppercase()`]
1505    /// and `to_titlecase()` give different results:
1506    ///
1507    /// ## Georgian script
1508    ///
1509    /// Each letter in the modern Georgian alphabet can be written in one of two forms:
1510    /// the typical lowercase-like "mkhedruli" form, and a variant uppercase-like "mtavruli"
1511    /// form. However, unlike uppercase in most cased scripts, mtavruli is not typically used
1512    /// to start sentences, denote proper nouns, or for any other purpose
1513    /// in running text. It is instead confined to titles and headings, which are written entirely
1514    /// in mtavruli. For this reason, [`to_uppercase()`] applied to a Georgian letter
1515    /// will return the mtavruli form, but `to_titlecase()` will return the mkhedruli form.
1516    ///
1517    /// ```
1518    /// #![feature(titlecase)]
1519    /// let ani = 'ა'; // First letter of the Georgian alphabet, in mkhedruli form
1520    ///
1521    /// // Titlecasing mkhedruli maps it to itself...
1522    /// assert_eq!(ani.to_titlecase().to_string(), ani.to_string());
1523    ///
1524    /// // but uppercasing it maps it to mtavruli
1525    /// assert_eq!(ani.to_uppercase().to_string(), "Ა");
1526    /// ```
1527    ///
1528    /// ## Compatibility digraphs for Latin-alphabet Serbo-Croatian
1529    ///
1530    /// The standard Latin alphabet for the Serbo-Croatian language
1531    /// (Bosnian, Croatian, Montenegrin, and Serbian) contains
1532    /// three digraphs: Dž, Lj, and Nj. These are usually represented as
1533    /// two characters. However, for compatibility with older character sets,
1534    /// Unicode includes single-character versions of these digraphs.
1535    /// Each has a uppercase, titlecase, and lowercase version:
1536    ///
1537    /// - `'DŽ'`, `'Dž'`, `'dž'`
1538    /// - `'LJ'`, `'Lj'`, `'lj'`
1539    /// - `'NJ'`, `'Nj'`, `'nj'`
1540    ///
1541    /// Unicode additionally encodes a casing triad for the Dz digraph
1542    /// without the caron: `'DZ'`, `'Dz'`, `'dz'`.
1543    ///
1544    /// ## Iota-subscritped Greek vowels
1545    ///
1546    /// In ancient Greek, the long vowels alpha (α), eta (η), and omega (ω)
1547    /// were sometimes followed by an iota (ι), forming a diphthong. Over time,
1548    /// the diphthong pronunciation was slowly lost, with the iota becoming mute.
1549    /// Eventually, the ι disappeared from the spelling as well.
1550    /// However, there remains a need to represent ancient texts faithfully.
1551    ///
1552    /// Modern editions of ancient Greek texts commonly use a reduced-sized
1553    /// ι symbol to denote mute iotas, while distinguishing them from ιs
1554    /// which continued to affect pronunciation. The exact standard differs
1555    /// between different publications. Some render the mute ι below its associated
1556    /// vowel (subscript), while others place it to the right of said vowel (adscript).
1557    /// The interaction of mute ι symbols with casing also varies.
1558    ///
1559    /// The Unicode Standard, for its default casing rules, chose to make lowercase
1560    /// Greek vowels with iota subscipt (e.g. `'ᾠ'`) titlecase to the uppercase vowel
1561    /// with iota subscript (`'ᾨ'`) but uppercase to the uppercase vowel followed by
1562    /// full-size uppercase iota (`"ὨΙ"`). This is just one convention among many
1563    /// in common use, but it is the one Unicode settled on,
1564    /// so it is what this method does also.
1565    ///
1566    /// # Note on locale
1567    ///
1568    /// As stated above, this method is locale-insensitive.
1569    /// If you need locale support, consider using an external crate,
1570    /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1571    /// which is developed by Unicode. A description of one common
1572    /// locale-dependent casing issue follows (there are others):
1573    ///
1574    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1575    ///
1576    /// * 'Dotless': I / ı, sometimes written ï
1577    /// * 'Dotted': İ / i
1578    ///
1579    /// Note that the lowercase dotted 'i' is the same codepoint as the Latin. Therefore:
1580    ///
1581    /// ```
1582    /// #![feature(titlecase)]
1583    /// let upper_i = 'i'.to_titlecase().to_string();
1584    /// ```
1585    ///
1586    /// `'i'`'s correct titlecase relies on the language of the text: if we're
1587    /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1588    /// be `"İ"`. `to_titlecase()` does not take this into account, and so:
1589    ///
1590    /// ```
1591    /// #![feature(titlecase)]
1592    /// let upper_i = 'i'.to_titlecase().to_string();
1593    ///
1594    /// assert_eq!(upper_i, "I");
1595    /// ```
1596    ///
1597    /// holds across languages.
1598    ///
1599    /// [`to_uppercase()`]: Self::to_uppercase()
1600    #[must_use = "this returns the titlecased character as a new iterator, \
1601                  without modifying the original"]
1602    #[unstable(feature = "titlecase", issue = "153892")]
1603    #[inline]
1604    pub fn to_titlecase(self) -> ToTitlecase {
1605        ToTitlecase(CaseMappingIter::new(conversions::to_title(self)))
1606    }
1607
1608    /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1609    /// `char`s.
1610    ///
1611    /// Prefer this method when converting a word into ALL CAPS, but consider [`to_titlecase()`]
1612    /// instead if you seek to capitalize Only The First Letter. See that method's documentation
1613    /// for more information on the difference between the two.
1614    ///
1615    /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1616    ///
1617    /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1618    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1619    ///
1620    /// [ucd]: https://www.unicode.org/reports/tr44/
1621    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1622    ///
1623    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1624    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1625    ///
1626    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1627    ///
1628    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1629    /// is independent of context and language. See [below](#note-on-locale)
1630    /// for more information.
1631    ///
1632    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1633    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1634    ///
1635    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1636    ///
1637    /// # Examples
1638    ///
1639    /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase.
1640    ///
1641    /// As an iterator:
1642    ///
1643    /// ```
1644    /// for c in 'ſt'.to_uppercase() {
1645    ///     print!("{c}");
1646    /// }
1647    /// println!();
1648    /// ```
1649    ///
1650    /// Using `println!` directly:
1651    ///
1652    /// ```
1653    /// println!("{}", 'ſt'.to_uppercase());
1654    /// ```
1655    ///
1656    /// Both are equivalent to:
1657    ///
1658    /// ```
1659    /// println!("ST");
1660    /// ```
1661    ///
1662    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1663    ///
1664    /// ```
1665    /// assert_eq!('c'.to_uppercase().to_string(), "C");
1666    /// assert_eq!('ა'.to_uppercase().to_string(), "Ა");
1667    /// assert_eq!('dž'.to_uppercase().to_string(), "DŽ");
1668    ///
1669    /// // Sometimes the result is more than one character:
1670    /// assert_eq!('ſt'.to_uppercase().to_string(), "ST");
1671    /// assert_eq!('ᾨ'.to_uppercase().to_string(), "ὨΙ");
1672    ///
1673    /// // Characters that do not have both uppercase and lowercase
1674    /// // convert into themselves.
1675    /// assert_eq!('山'.to_uppercase().to_string(), "山");
1676    /// ```
1677    ///
1678    /// # Note on locale
1679    ///
1680    /// As stated above, this method is locale-insensitive.
1681    /// If you need locale support, consider using an external crate,
1682    /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1683    /// which is developed by Unicode. A description of one common
1684    /// locale-dependent casing issue follows (there are others):
1685    ///
1686    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1687    ///
1688    /// * 'Dotless': I / ı, sometimes written ï
1689    /// * 'Dotted': İ / i
1690    ///
1691    /// Note that the lowercase dotted 'i' is the same codepoint as the Latin. Therefore:
1692    ///
1693    /// ```
1694    /// let upper_i = 'i'.to_uppercase().to_string();
1695    /// ```
1696    ///
1697    /// `'i'`'s correct uppercase relies on the language of the text: if we're
1698    /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1699    /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1700    ///
1701    /// ```
1702    /// let upper_i = 'i'.to_uppercase().to_string();
1703    ///
1704    /// assert_eq!(upper_i, "I");
1705    /// ```
1706    ///
1707    /// holds across languages.
1708    ///
1709    /// [`to_titlecase()`]: Self::to_titlecase()
1710    #[must_use = "this returns the uppercased character as a new iterator, \
1711                  without modifying the original"]
1712    #[stable(feature = "rust1", since = "1.0.0")]
1713    #[inline]
1714    pub fn to_uppercase(self) -> ToUppercase {
1715        ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1716    }
1717
1718    /// Returns an iterator that yields the case folding of this `char` as one or more
1719    /// `char`s.
1720    ///
1721    /// Case folding is meant to be used when performing case-insensitive string comparisons.
1722    /// Case-folded strings should not usually be exposed directly to users. For most,
1723    /// but not all, characters, the casefold mapping is identical to the lowercase one.
1724    ///
1725    /// This iterator yields the `char`(s) in the common or full case folding for this `char`,
1726    /// as given by the [Unicode Character Database][ucd] [`CaseFolding.txt`].
1727    /// The maximum number of `char`s in a case folding is 3.
1728    ///
1729    /// [ucd]: https://www.unicode.org/reports/tr44/
1730    /// [`CaseFolding.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt
1731    ///
1732    ///
1733    /// No [normalization] (e.g. NFC) is performed, so visually and semantically identical characters
1734    /// might still casefold differently. For example, `'ά'` (U+03AC GREEK SMALL LETTER ALPHA WITH TONOS)
1735    /// is considered distinct from `'ά'` (U+1F71 GREEK SMALL LETTER ALPHA WITH OXIA),
1736    /// even though Unicode considers them canonically equivalent.
1737    ///
1738    /// In addition, this method is independent of language/locale,
1739    /// so the special behavior of I/ı/İ/i in Turkish and Azeri is not handled.
1740    ///
1741    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case folding in
1742    /// general and Chapter 3 (Conformance) discusses the default algorithm for case folding.
1743    ///
1744    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1745    ///
1746    /// # Examples
1747    ///
1748    /// The German sharp S `'ß'` (U+DF) is a single Unicode code point
1749    /// that casefolds to `"ss"`. Its uppercase variant '`ẞ`' (U+1E9E)
1750    /// has the same case-folding.
1751    ///
1752    /// As an iterator:
1753    ///
1754    /// ```
1755    /// #![feature(casefold)]
1756    /// assert!('ß'.to_casefold_unnormalized().eq(['s', 's']));
1757    /// assert!('ẞ'.to_casefold_unnormalized().eq(['s', 's']));
1758    /// ```
1759    ///
1760    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1761    ///
1762    /// ```
1763    /// #![feature(casefold)]
1764    /// assert_eq!('ß'.to_casefold_unnormalized().to_string(), "ss");
1765    /// assert_eq!('ẞ'.to_casefold_unnormalized().to_string(), "ss");
1766    /// ```
1767    ///
1768    /// No [normalization] is performed:
1769    ///
1770    /// ```rust
1771    /// #![feature(casefold)]
1772    /// // These two characters are visually and semantically identical;
1773    /// // Unicode considers them to be canonically equivalent.
1774    /// let alpha_tonos = 'ά';
1775    /// let alpha_oxia = 'ά';
1776    ///
1777    /// // However, they are different codepoints:
1778    /// assert_eq!(alpha_tonos, '\u{03AC}');
1779    /// assert_eq!(alpha_oxia, '\u{1F71}');
1780    ///
1781    /// // Their case-foldings are likewise unequal:
1782    /// assert!(alpha_tonos.to_casefold_unnormalized().eq(['\u{03AC}']));
1783    /// assert!(alpha_oxia.to_casefold_unnormalized().eq(['\u{1F71}']));
1784    /// ```
1785    ///
1786    /// # Note on locale
1787    ///
1788    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1789    ///
1790    /// * 'Dotless': I / ı, sometimes written ï
1791    /// * 'Dotted': İ / i
1792    ///
1793    /// Note that the uppercase undotted 'I' is the same codepoint as the Latin. Therefore:
1794    ///
1795    /// ```
1796    /// #![feature(casefold)]
1797    /// let casefold_i = 'I'.to_casefold_unnormalized().to_string();
1798    /// ```
1799    ///
1800    /// `'I'`'s correct case folding relies on the language of the text: if we're
1801    /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should
1802    /// be `"ı"`. `to_casefold_unnormalized()` does not take this into account, and so:
1803    ///
1804    /// ```
1805    /// #![feature(casefold)]
1806    /// let casefold_i = 'I'.to_casefold_unnormalized().to_string();
1807    ///
1808    /// assert_eq!(casefold_i, "i");
1809    /// ```
1810    ///
1811    /// holds across languages.
1812    ///
1813    /// [normalization]: https://www.unicode.org/faq/normalization.html
1814    #[must_use = "this returns the case-folded character as a new iterator, \
1815                  without modifying the original"]
1816    #[unstable(feature = "casefold", issue = "157000")]
1817    #[inline]
1818    pub fn to_casefold_unnormalized(self) -> ToCasefold {
1819        ToCasefold(CaseMappingIter::new(conversions::to_casefold(self)))
1820    }
1821
1822    /// Returns the code point value as a `u32`.
1823    ///
1824    /// # Examples
1825    ///
1826    /// ```
1827    /// #![feature(char_to_u32)]
1828    ///
1829    /// let ascii = 'a';
1830    /// let heart = '❤';
1831    ///
1832    /// assert_eq!(ascii.to_u32(), 97_u32);
1833    /// assert_eq!(heart.to_u32(), 0x2764_u32);
1834    /// ```
1835    #[must_use = "this returns the result of the operation, \
1836                  without modifying the original"]
1837    #[unstable(feature = "char_to_u32", issue = "158938")]
1838    #[rustc_const_unstable(feature = "char_to_u32", issue = "158938")]
1839    #[inline(always)]
1840    pub const fn to_u32(self) -> u32 {
1841        self as u32
1842    }
1843
1844    /// Checks if the value is within the ASCII range.
1845    ///
1846    /// # Examples
1847    ///
1848    /// ```
1849    /// let ascii = 'a';
1850    /// let non_ascii = '❤';
1851    ///
1852    /// assert!(ascii.is_ascii());
1853    /// assert!(!non_ascii.is_ascii());
1854    /// ```
1855    #[must_use]
1856    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1857    #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1858    #[rustc_diagnostic_item = "char_is_ascii"]
1859    #[inline]
1860    pub const fn is_ascii(&self) -> bool {
1861        *self as u32 <= 0x7F
1862    }
1863
1864    /// Returns `Some` if the value is within the ASCII range,
1865    /// or `None` if it's not.
1866    ///
1867    /// This is preferred to [`Self::is_ascii`] when you're passing the value
1868    /// along to something else that can take [`ascii::Char`] rather than
1869    /// needing to check again for itself whether the value is in ASCII.
1870    #[must_use]
1871    #[unstable(feature = "ascii_char", issue = "110998")]
1872    #[inline]
1873    pub const fn as_ascii(&self) -> Option<ascii::Char> {
1874        if self.is_ascii() {
1875            // SAFETY: Just checked that this is ASCII.
1876            Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
1877        } else {
1878            None
1879        }
1880    }
1881
1882    /// Converts this char into an [ASCII character](`ascii::Char`), without
1883    /// checking whether it is valid.
1884    ///
1885    /// # Safety
1886    ///
1887    /// This char must be within the ASCII range, or else this is UB.
1888    #[must_use]
1889    #[unstable(feature = "ascii_char", issue = "110998")]
1890    #[inline]
1891    pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1892        {
    #[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!(
1893            check_library_ub,
1894            "as_ascii_unchecked requires that the char is valid ASCII",
1895            (it: &char = self) => it.is_ascii()
1896        );
1897
1898        // SAFETY: the caller promised that this char is ASCII.
1899        unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1900    }
1901
1902    /// Makes a copy of the value in its ASCII upper case equivalent.
1903    ///
1904    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1905    /// but non-ASCII letters are unchanged.
1906    ///
1907    /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1908    ///
1909    /// To uppercase ASCII characters in addition to non-ASCII characters, use
1910    /// [`to_uppercase()`].
1911    ///
1912    /// # Examples
1913    ///
1914    /// ```
1915    /// let ascii = 'a';
1916    /// let non_ascii = '❤';
1917    ///
1918    /// assert_eq!('A', ascii.to_ascii_uppercase());
1919    /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1920    /// ```
1921    ///
1922    /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1923    /// [`to_uppercase()`]: #method.to_uppercase
1924    #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1925    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1926    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1927    #[inline]
1928    pub const fn to_ascii_uppercase(&self) -> char {
1929        if self.is_ascii_lowercase() {
1930            (*self as u8).ascii_change_case_unchecked() as char
1931        } else {
1932            *self
1933        }
1934    }
1935
1936    /// Makes a copy of the value in its ASCII lower case equivalent.
1937    ///
1938    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1939    /// but non-ASCII letters are unchanged.
1940    ///
1941    /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1942    ///
1943    /// To lowercase ASCII characters in addition to non-ASCII characters, use
1944    /// [`to_lowercase()`].
1945    ///
1946    /// # Examples
1947    ///
1948    /// ```
1949    /// let ascii = 'A';
1950    /// let non_ascii = '❤';
1951    ///
1952    /// assert_eq!('a', ascii.to_ascii_lowercase());
1953    /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1954    /// ```
1955    ///
1956    /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1957    /// [`to_lowercase()`]: #method.to_lowercase
1958    #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1959    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1960    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1961    #[inline]
1962    pub const fn to_ascii_lowercase(&self) -> char {
1963        if self.is_ascii_uppercase() {
1964            (*self as u8).ascii_change_case_unchecked() as char
1965        } else {
1966            *self
1967        }
1968    }
1969
1970    /// Checks that two values are an ASCII case-insensitive match.
1971    ///
1972    /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1973    ///
1974    /// # Examples
1975    ///
1976    /// ```
1977    /// let upper_a = 'A';
1978    /// let lower_a = 'a';
1979    /// let lower_z = 'z';
1980    ///
1981    /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1982    /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1983    /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1984    /// ```
1985    ///
1986    /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1987    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1988    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1989    #[expect(clippy::manual_ignore_case_cmp, reason = "implements eq_ignore_ascii_case")]
1990    #[inline]
1991    pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1992        self.to_ascii_lowercase() == other.to_ascii_lowercase()
1993    }
1994
1995    /// Converts this type to its ASCII upper case equivalent in-place.
1996    ///
1997    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1998    /// but non-ASCII letters are unchanged.
1999    ///
2000    /// To return a new uppercased value without modifying the existing one, use
2001    /// [`to_ascii_uppercase()`].
2002    ///
2003    /// # Examples
2004    ///
2005    /// ```
2006    /// let mut ascii = 'a';
2007    ///
2008    /// ascii.make_ascii_uppercase();
2009    ///
2010    /// assert_eq!('A', ascii);
2011    /// ```
2012    ///
2013    /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2014    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2015    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2016    #[inline]
2017    pub const fn make_ascii_uppercase(&mut self) {
2018        *self = self.to_ascii_uppercase();
2019    }
2020
2021    /// Converts this type to its ASCII lower case equivalent in-place.
2022    ///
2023    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2024    /// but non-ASCII letters are unchanged.
2025    ///
2026    /// To return a new lowercased value without modifying the existing one, use
2027    /// [`to_ascii_lowercase()`].
2028    ///
2029    /// # Examples
2030    ///
2031    /// ```
2032    /// let mut ascii = 'A';
2033    ///
2034    /// ascii.make_ascii_lowercase();
2035    ///
2036    /// assert_eq!('a', ascii);
2037    /// ```
2038    ///
2039    /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2040    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2041    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2042    #[inline]
2043    pub const fn make_ascii_lowercase(&mut self) {
2044        *self = self.to_ascii_lowercase();
2045    }
2046
2047    /// Checks if the value is an ASCII alphabetic character:
2048    ///
2049    /// - U+0041 'A' ..= U+005A 'Z', or
2050    /// - U+0061 'a' ..= U+007A 'z'.
2051    ///
2052    /// # Examples
2053    ///
2054    /// ```
2055    /// let uppercase_a = 'A';
2056    /// let uppercase_g = 'G';
2057    /// let a = 'a';
2058    /// let g = 'g';
2059    /// let zero = '0';
2060    /// let percent = '%';
2061    /// let space = ' ';
2062    /// let lf = '\n';
2063    /// let esc = '\x1b';
2064    ///
2065    /// assert!(uppercase_a.is_ascii_alphabetic());
2066    /// assert!(uppercase_g.is_ascii_alphabetic());
2067    /// assert!(a.is_ascii_alphabetic());
2068    /// assert!(g.is_ascii_alphabetic());
2069    /// assert!(!zero.is_ascii_alphabetic());
2070    /// assert!(!percent.is_ascii_alphabetic());
2071    /// assert!(!space.is_ascii_alphabetic());
2072    /// assert!(!lf.is_ascii_alphabetic());
2073    /// assert!(!esc.is_ascii_alphabetic());
2074    /// ```
2075    #[must_use]
2076    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2077    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2078    #[inline]
2079    pub const fn is_ascii_alphabetic(&self) -> bool {
2080        #[allow(non_exhaustive_omitted_patterns)] match *self {
    'a'..='z' | 'A'..='Z' => true,
    _ => false,
}matches!(*self, 'a'..='z' | 'A'..='Z')
2081    }
2082
2083    /// Checks if the value is an ASCII uppercase character:
2084    /// U+0041 'A' ..= U+005A 'Z'.
2085    ///
2086    /// # Examples
2087    ///
2088    /// ```
2089    /// let uppercase_a = 'A';
2090    /// let uppercase_g = 'G';
2091    /// let a = 'a';
2092    /// let g = 'g';
2093    /// let zero = '0';
2094    /// let percent = '%';
2095    /// let space = ' ';
2096    /// let lf = '\n';
2097    /// let esc = '\x1b';
2098    ///
2099    /// assert!(uppercase_a.is_ascii_uppercase());
2100    /// assert!(uppercase_g.is_ascii_uppercase());
2101    /// assert!(!a.is_ascii_uppercase());
2102    /// assert!(!g.is_ascii_uppercase());
2103    /// assert!(!zero.is_ascii_uppercase());
2104    /// assert!(!percent.is_ascii_uppercase());
2105    /// assert!(!space.is_ascii_uppercase());
2106    /// assert!(!lf.is_ascii_uppercase());
2107    /// assert!(!esc.is_ascii_uppercase());
2108    /// ```
2109    #[must_use]
2110    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2111    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2112    #[inline]
2113    pub const fn is_ascii_uppercase(&self) -> bool {
2114        #[allow(non_exhaustive_omitted_patterns)] match *self {
    'A'..='Z' => true,
    _ => false,
}matches!(*self, 'A'..='Z')
2115    }
2116
2117    /// Checks if the value is an ASCII lowercase character:
2118    /// U+0061 'a' ..= U+007A 'z'.
2119    ///
2120    /// # Examples
2121    ///
2122    /// ```
2123    /// let uppercase_a = 'A';
2124    /// let uppercase_g = 'G';
2125    /// let a = 'a';
2126    /// let g = 'g';
2127    /// let zero = '0';
2128    /// let percent = '%';
2129    /// let space = ' ';
2130    /// let lf = '\n';
2131    /// let esc = '\x1b';
2132    ///
2133    /// assert!(!uppercase_a.is_ascii_lowercase());
2134    /// assert!(!uppercase_g.is_ascii_lowercase());
2135    /// assert!(a.is_ascii_lowercase());
2136    /// assert!(g.is_ascii_lowercase());
2137    /// assert!(!zero.is_ascii_lowercase());
2138    /// assert!(!percent.is_ascii_lowercase());
2139    /// assert!(!space.is_ascii_lowercase());
2140    /// assert!(!lf.is_ascii_lowercase());
2141    /// assert!(!esc.is_ascii_lowercase());
2142    /// ```
2143    #[must_use]
2144    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2145    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2146    #[inline]
2147    pub const fn is_ascii_lowercase(&self) -> bool {
2148        #[allow(non_exhaustive_omitted_patterns)] match *self {
    'a'..='z' => true,
    _ => false,
}matches!(*self, 'a'..='z')
2149    }
2150
2151    /// Checks if the value is an ASCII alphanumeric character:
2152    ///
2153    /// - U+0041 'A' ..= U+005A 'Z', or
2154    /// - U+0061 'a' ..= U+007A 'z', or
2155    /// - U+0030 '0' ..= U+0039 '9'.
2156    ///
2157    /// # Examples
2158    ///
2159    /// ```
2160    /// let uppercase_a = 'A';
2161    /// let uppercase_g = 'G';
2162    /// let a = 'a';
2163    /// let g = 'g';
2164    /// let zero = '0';
2165    /// let percent = '%';
2166    /// let space = ' ';
2167    /// let lf = '\n';
2168    /// let esc = '\x1b';
2169    ///
2170    /// assert!(uppercase_a.is_ascii_alphanumeric());
2171    /// assert!(uppercase_g.is_ascii_alphanumeric());
2172    /// assert!(a.is_ascii_alphanumeric());
2173    /// assert!(g.is_ascii_alphanumeric());
2174    /// assert!(zero.is_ascii_alphanumeric());
2175    /// assert!(!percent.is_ascii_alphanumeric());
2176    /// assert!(!space.is_ascii_alphanumeric());
2177    /// assert!(!lf.is_ascii_alphanumeric());
2178    /// assert!(!esc.is_ascii_alphanumeric());
2179    /// ```
2180    #[must_use]
2181    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2182    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2183    #[inline]
2184    pub const fn is_ascii_alphanumeric(&self) -> bool {
2185        #[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')
2186    }
2187
2188    /// Checks if the value is an ASCII decimal digit:
2189    /// U+0030 '0' ..= U+0039 '9'.
2190    ///
2191    /// # Examples
2192    ///
2193    /// ```
2194    /// let uppercase_a = 'A';
2195    /// let uppercase_g = 'G';
2196    /// let a = 'a';
2197    /// let g = 'g';
2198    /// let zero = '0';
2199    /// let percent = '%';
2200    /// let space = ' ';
2201    /// let lf = '\n';
2202    /// let esc = '\x1b';
2203    ///
2204    /// assert!(!uppercase_a.is_ascii_digit());
2205    /// assert!(!uppercase_g.is_ascii_digit());
2206    /// assert!(!a.is_ascii_digit());
2207    /// assert!(!g.is_ascii_digit());
2208    /// assert!(zero.is_ascii_digit());
2209    /// assert!(!percent.is_ascii_digit());
2210    /// assert!(!space.is_ascii_digit());
2211    /// assert!(!lf.is_ascii_digit());
2212    /// assert!(!esc.is_ascii_digit());
2213    /// ```
2214    #[must_use]
2215    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2216    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2217    #[inline]
2218    pub const fn is_ascii_digit(&self) -> bool {
2219        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '0'..='9' => true,
    _ => false,
}matches!(*self, '0'..='9')
2220    }
2221
2222    /// Checks if the value is an ASCII octal digit:
2223    /// U+0030 '0' ..= U+0037 '7'.
2224    ///
2225    /// # Examples
2226    ///
2227    /// ```
2228    /// #![feature(is_ascii_octdigit)]
2229    ///
2230    /// let uppercase_a = 'A';
2231    /// let a = 'a';
2232    /// let zero = '0';
2233    /// let seven = '7';
2234    /// let nine = '9';
2235    /// let percent = '%';
2236    /// let lf = '\n';
2237    ///
2238    /// assert!(!uppercase_a.is_ascii_octdigit());
2239    /// assert!(!a.is_ascii_octdigit());
2240    /// assert!(zero.is_ascii_octdigit());
2241    /// assert!(seven.is_ascii_octdigit());
2242    /// assert!(!nine.is_ascii_octdigit());
2243    /// assert!(!percent.is_ascii_octdigit());
2244    /// assert!(!lf.is_ascii_octdigit());
2245    /// ```
2246    #[must_use]
2247    #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
2248    #[inline]
2249    pub const fn is_ascii_octdigit(&self) -> bool {
2250        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '0'..='7' => true,
    _ => false,
}matches!(*self, '0'..='7')
2251    }
2252
2253    /// Checks if the value is an ASCII hexadecimal digit:
2254    ///
2255    /// - U+0030 '0' ..= U+0039 '9', or
2256    /// - U+0041 'A' ..= U+0046 'F', or
2257    /// - U+0061 'a' ..= U+0066 'f'.
2258    ///
2259    /// # Examples
2260    ///
2261    /// ```
2262    /// let uppercase_a = 'A';
2263    /// let uppercase_g = 'G';
2264    /// let a = 'a';
2265    /// let g = 'g';
2266    /// let zero = '0';
2267    /// let percent = '%';
2268    /// let space = ' ';
2269    /// let lf = '\n';
2270    /// let esc = '\x1b';
2271    ///
2272    /// assert!(uppercase_a.is_ascii_hexdigit());
2273    /// assert!(!uppercase_g.is_ascii_hexdigit());
2274    /// assert!(a.is_ascii_hexdigit());
2275    /// assert!(!g.is_ascii_hexdigit());
2276    /// assert!(zero.is_ascii_hexdigit());
2277    /// assert!(!percent.is_ascii_hexdigit());
2278    /// assert!(!space.is_ascii_hexdigit());
2279    /// assert!(!lf.is_ascii_hexdigit());
2280    /// assert!(!esc.is_ascii_hexdigit());
2281    /// ```
2282    #[must_use]
2283    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2284    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2285    #[inline]
2286    pub const fn is_ascii_hexdigit(&self) -> bool {
2287        #[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')
2288    }
2289
2290    /// Checks if the value is an ASCII punctuation or symbol character
2291    /// (i.e. not alphanumeric, whitespace, or control):
2292    ///
2293    /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
2294    /// - U+003A ..= U+0040 `: ; < = > ? @`, or
2295    /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
2296    /// - U+007B ..= U+007E `{ | } ~`
2297    ///
2298    /// # Examples
2299    ///
2300    /// ```
2301    /// let uppercase_a = 'A';
2302    /// let uppercase_g = 'G';
2303    /// let a = 'a';
2304    /// let g = 'g';
2305    /// let zero = '0';
2306    /// let percent = '%';
2307    /// let space = ' ';
2308    /// let lf = '\n';
2309    /// let esc = '\x1b';
2310    ///
2311    /// assert!(!uppercase_a.is_ascii_punctuation());
2312    /// assert!(!uppercase_g.is_ascii_punctuation());
2313    /// assert!(!a.is_ascii_punctuation());
2314    /// assert!(!g.is_ascii_punctuation());
2315    /// assert!(!zero.is_ascii_punctuation());
2316    /// assert!(percent.is_ascii_punctuation());
2317    /// assert!(!space.is_ascii_punctuation());
2318    /// assert!(!lf.is_ascii_punctuation());
2319    /// assert!(!esc.is_ascii_punctuation());
2320    /// ```
2321    #[must_use]
2322    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2323    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2324    #[inline]
2325    pub const fn is_ascii_punctuation(&self) -> bool {
2326        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '!'..='/' => true,
    _ => false,
}matches!(*self, '!'..='/')
2327            | #[allow(non_exhaustive_omitted_patterns)] match *self {
    ':'..='@' => true,
    _ => false,
}matches!(*self, ':'..='@')
2328            | #[allow(non_exhaustive_omitted_patterns)] match *self {
    '['..='`' => true,
    _ => false,
}matches!(*self, '['..='`')
2329            | #[allow(non_exhaustive_omitted_patterns)] match *self {
    '{'..='~' => true,
    _ => false,
}matches!(*self, '{'..='~')
2330    }
2331
2332    /// Checks if the value is an ASCII graphic character
2333    /// (i.e. not whitespace or control):
2334    /// U+0021 '!' ..= U+007E '~'.
2335    ///
2336    /// # Examples
2337    ///
2338    /// ```
2339    /// let uppercase_a = 'A';
2340    /// let uppercase_g = 'G';
2341    /// let a = 'a';
2342    /// let g = 'g';
2343    /// let zero = '0';
2344    /// let percent = '%';
2345    /// let space = ' ';
2346    /// let lf = '\n';
2347    /// let esc = '\x1b';
2348    ///
2349    /// assert!(uppercase_a.is_ascii_graphic());
2350    /// assert!(uppercase_g.is_ascii_graphic());
2351    /// assert!(a.is_ascii_graphic());
2352    /// assert!(g.is_ascii_graphic());
2353    /// assert!(zero.is_ascii_graphic());
2354    /// assert!(percent.is_ascii_graphic());
2355    /// assert!(!space.is_ascii_graphic());
2356    /// assert!(!lf.is_ascii_graphic());
2357    /// assert!(!esc.is_ascii_graphic());
2358    /// ```
2359    #[must_use]
2360    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2361    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2362    #[inline]
2363    pub const fn is_ascii_graphic(&self) -> bool {
2364        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '!'..='~' => true,
    _ => false,
}matches!(*self, '!'..='~')
2365    }
2366
2367    /// Checks if the value is an ASCII whitespace character:
2368    /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2369    /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2370    ///
2371    /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
2372    /// `c.is_ascii_whitespace()` is **not** equivalent to `c.is_ascii() && c.is_whitespace()`.
2373    ///
2374    /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2375    /// whitespace][infra-aw]. There are several other definitions in
2376    /// wide use. For instance, [the POSIX locale][pct] includes
2377    /// U+000B VERTICAL TAB as well as all the above characters,
2378    /// but—from the very same specification—[the default rule for
2379    /// "field splitting" in the Bourne shell][bfs] considers *only*
2380    /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2381    ///
2382    /// If you are writing a program that will process an existing
2383    /// file format, check what that format's definition of whitespace is
2384    /// before using this function.
2385    ///
2386    /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2387    /// [pct]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap07.html#tag_07_03_01
2388    /// [bfs]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_06_05
2389    ///
2390    /// # Examples
2391    ///
2392    /// ```
2393    /// let uppercase_a = 'A';
2394    /// let uppercase_g = 'G';
2395    /// let a = 'a';
2396    /// let g = 'g';
2397    /// let zero = '0';
2398    /// let percent = '%';
2399    /// let space = ' ';
2400    /// let lf = '\n';
2401    /// let esc = '\x1b';
2402    ///
2403    /// assert!(!uppercase_a.is_ascii_whitespace());
2404    /// assert!(!uppercase_g.is_ascii_whitespace());
2405    /// assert!(!a.is_ascii_whitespace());
2406    /// assert!(!g.is_ascii_whitespace());
2407    /// assert!(!zero.is_ascii_whitespace());
2408    /// assert!(!percent.is_ascii_whitespace());
2409    /// assert!(space.is_ascii_whitespace());
2410    /// assert!(lf.is_ascii_whitespace());
2411    /// assert!(!esc.is_ascii_whitespace());
2412    /// ```
2413    #[must_use]
2414    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2415    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2416    #[inline]
2417    pub const fn is_ascii_whitespace(&self) -> bool {
2418        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '\t' | '\n' | '\x0C' | '\r' | ' ' => true,
    _ => false,
}matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
2419    }
2420
2421    /// Checks if the value is an ASCII control character:
2422    /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
2423    /// Note that most ASCII whitespace characters are control
2424    /// characters, but SPACE is not.
2425    ///
2426    /// # Examples
2427    ///
2428    /// ```
2429    /// let uppercase_a = 'A';
2430    /// let uppercase_g = 'G';
2431    /// let a = 'a';
2432    /// let g = 'g';
2433    /// let zero = '0';
2434    /// let percent = '%';
2435    /// let space = ' ';
2436    /// let lf = '\n';
2437    /// let esc = '\x1b';
2438    ///
2439    /// assert!(!uppercase_a.is_ascii_control());
2440    /// assert!(!uppercase_g.is_ascii_control());
2441    /// assert!(!a.is_ascii_control());
2442    /// assert!(!g.is_ascii_control());
2443    /// assert!(!zero.is_ascii_control());
2444    /// assert!(!percent.is_ascii_control());
2445    /// assert!(!space.is_ascii_control());
2446    /// assert!(lf.is_ascii_control());
2447    /// assert!(esc.is_ascii_control());
2448    /// ```
2449    #[must_use]
2450    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2451    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2452    #[inline]
2453    pub const fn is_ascii_control(&self) -> bool {
2454        #[allow(non_exhaustive_omitted_patterns)] match *self {
    '\0'..='\x1F' | '\x7F' => true,
    _ => false,
}matches!(*self, '\0'..='\x1F' | '\x7F')
2455    }
2456}
2457
2458pub(crate) struct EscapeDebugExtArgs {
2459    /// Escape single quotes?
2460    pub(crate) escape_single_quote: bool,
2461
2462    /// Escape double quotes?
2463    pub(crate) escape_double_quote: bool,
2464}
2465
2466impl EscapeDebugExtArgs {
2467    pub(crate) const ESCAPE_ALL: Self =
2468        Self { escape_single_quote: true, escape_double_quote: true };
2469}
2470
2471#[inline]
2472#[must_use]
2473const fn len_utf8(code: u32) -> usize {
2474    match code {
2475        ..MAX_ONE_B => 1,
2476        ..MAX_TWO_B => 2,
2477        ..MAX_THREE_B => 3,
2478        _ => 4,
2479    }
2480}
2481
2482#[inline]
2483#[must_use]
2484const fn len_utf16(code: u32) -> usize {
2485    if (code & 0xFFFF) == code { 1 } else { 2 }
2486}
2487
2488/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
2489/// and then returns the subslice of the buffer that contains the encoded character.
2490///
2491/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2492/// (Creating a `char` in the surrogate range is UB.)
2493/// The result is valid [generalized UTF-8] but not valid UTF-8.
2494///
2495/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2496///
2497/// # Panics
2498///
2499/// Panics if the buffer is not large enough.
2500/// A buffer of length four is large enough to encode any `char`.
2501#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2502#[doc(hidden)]
2503#[inline]
2504pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
2505    let len = len_utf8(code);
2506    if dst.len() < len {
2507        {
    #[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!(
2508            "encode_utf8: buffer does not have enough bytes to encode code point",
2509            "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2510            code: u32 = code,
2511            len: usize = len,
2512            dst_len: usize = dst.len(),
2513        );
2514    }
2515
2516    // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint.
2517    unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) };
2518
2519    // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2520    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2521}
2522
2523/// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`.
2524///
2525/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2526/// (Creating a `char` in the surrogate range is UB.)
2527/// The result is valid [generalized UTF-8] but not valid UTF-8.
2528///
2529/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2530///
2531/// # Safety
2532///
2533/// The behavior is undefined if the buffer pointed to by `dst` is not
2534/// large enough to hold the encoded codepoint. A buffer of length four
2535/// is large enough to encode any `char`.
2536///
2537/// For a safe version of this function, see the [`encode_utf8_raw`] function.
2538#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2539#[doc(hidden)]
2540#[inline]
2541pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
2542    let len = len_utf8(code);
2543    // SAFETY: The caller must guarantee that the buffer pointed to by `dst`
2544    // is at least `len` bytes long.
2545    unsafe {
2546        if len == 1 {
2547            *dst = code as u8;
2548            return;
2549        }
2550
2551        let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
2552        let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
2553        let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
2554        let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
2555
2556        if len == 2 {
2557            *dst = last2 | TAG_TWO_B;
2558            *dst.add(1) = last1;
2559            return;
2560        }
2561
2562        if len == 3 {
2563            *dst = last3 | TAG_THREE_B;
2564            *dst.add(1) = last2;
2565            *dst.add(2) = last1;
2566            return;
2567        }
2568
2569        *dst = last4;
2570        *dst.add(1) = last3;
2571        *dst.add(2) = last2;
2572        *dst.add(3) = last1;
2573    }
2574}
2575
2576/// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer,
2577/// and then returns the subslice of the buffer that contains the encoded character.
2578///
2579/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
2580/// (Creating a `char` in the surrogate range is UB.)
2581///
2582/// # Panics
2583///
2584/// Panics if the buffer is not large enough.
2585/// A buffer of length 2 is large enough to encode any `char`.
2586#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2587#[doc(hidden)]
2588#[inline]
2589pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
2590    let len = len_utf16(code);
2591    match (len, &mut *dst) {
2592        (1, [a, ..]) => {
2593            *a = code as u16;
2594        }
2595        (2, [a, b, ..]) => {
2596            code -= 0x1_0000;
2597            *a = (code >> 10) as u16 | 0xD800;
2598            *b = (code & 0x3FF) as u16 | 0xDC00;
2599        }
2600        _ => {
2601            {
    #[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!(
2602                "encode_utf16: buffer does not have enough bytes to encode code point",
2603                "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2604                code: u32 = code,
2605                len: usize = len,
2606                dst_len: usize = dst.len(),
2607            )
2608        }
2609    };
2610    // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2611    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2612}