Skip to main content

core/char/
methods.rs

1//! impl char {}
2
3use super::*;
4use crate::panic::const_panic;
5use crate::slice;
6use crate::str::from_utf8_unchecked_mut;
7use crate::ub_checks::assert_unsafe_precondition;
8use crate::unicode::printable::is_printable;
9use crate::unicode::{self, conversions};
10
11impl char {
12    /// The lowest valid code point a `char` can have, `'\0'`.
13    ///
14    /// Unlike integer types, `char` actually has a gap in the middle,
15    /// meaning that the range of possible `char`s is smaller than you
16    /// might expect. Ranges of `char` will automatically hop this gap
17    /// for you:
18    ///
19    /// ```
20    /// let dist = u32::from(char::MAX) - u32::from(char::MIN);
21    /// let size = (char::MIN..=char::MAX).count() as u32;
22    /// assert!(size < dist);
23    /// ```
24    ///
25    /// Despite this gap, the `MIN` and [`MAX`] values can be used as bounds for
26    /// all `char` values.
27    ///
28    /// [`MAX`]: char::MAX
29    ///
30    /// # Examples
31    ///
32    /// ```
33    /// # fn something_which_returns_char() -> char { 'a' }
34    /// let c: char = something_which_returns_char();
35    /// assert!(char::MIN <= c);
36    ///
37    /// let value_at_min = u32::from(char::MIN);
38    /// assert_eq!(char::from_u32(value_at_min), Some('\0'));
39    /// ```
40    #[stable(feature = "char_min", since = "1.83.0")]
41    pub const MIN: char = '\0';
42
43    /// The highest valid code point a `char` can have, `'\u{10FFFF}'`.
44    ///
45    /// Unlike integer types, `char` actually has a gap in the middle,
46    /// meaning that the range of possible `char`s is smaller than you
47    /// might expect. Ranges of `char` will automatically hop this gap
48    /// for you:
49    ///
50    /// ```
51    /// let dist = u32::from(char::MAX) - u32::from(char::MIN);
52    /// let size = (char::MIN..=char::MAX).count() as u32;
53    /// assert!(size < dist);
54    /// ```
55    ///
56    /// Despite this gap, the [`MIN`] and `MAX` values can be used as bounds for
57    /// all `char` values.
58    ///
59    /// [`MIN`]: char::MIN
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// # fn something_which_returns_char() -> char { 'a' }
65    /// let c: char = something_which_returns_char();
66    /// assert!(c <= char::MAX);
67    ///
68    /// let value_at_max = u32::from(char::MAX);
69    /// assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
70    /// assert_eq!(char::from_u32(value_at_max + 1), None);
71    /// ```
72    #[stable(feature = "assoc_char_consts", since = "1.52.0")]
73    pub const MAX: char = '\u{10FFFF}';
74
75    /// The maximum number of bytes required to [encode](char::encode_utf8) a `char` to
76    /// UTF-8 encoding.
77    #[stable(feature = "char_max_len_assoc", since = "1.93.0")]
78    pub const MAX_LEN_UTF8: usize = 4;
79
80    /// The maximum number of two-byte units required to [encode](char::encode_utf16) a `char`
81    /// to UTF-16 encoding.
82    #[stable(feature = "char_max_len_assoc", since = "1.93.0")]
83    pub const MAX_LEN_UTF16: usize = 2;
84
85    /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
86    /// decoding error.
87    ///
88    /// It can occur, for example, when giving ill-formed UTF-8 bytes to
89    /// [`String::from_utf8_lossy`](../std/string/struct.String.html#method.from_utf8_lossy).
90    #[stable(feature = "assoc_char_consts", since = "1.52.0")]
91    pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
92
93    /// The version of [Unicode](https://www.unicode.org/) that the Unicode parts of
94    /// `char` and `str` methods are based on.
95    ///
96    /// New versions of Unicode are released regularly and subsequently all methods
97    /// in the standard library depending on Unicode are updated. Therefore the
98    /// behavior of some `char` and `str` methods and the value of this constant
99    /// changes over time. This is *not* considered to be a breaking change.
100    ///
101    /// The version numbering scheme is explained in
102    /// [Unicode 11.0 or later, Section 3.1 Versions of the Unicode Standard](https://www.unicode.org/versions/Unicode11.0.0/ch03.pdf#page=4).
103    #[stable(feature = "assoc_char_consts", since = "1.52.0")]
104    pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION;
105
106    /// Creates an iterator over the native endian UTF-16 encoded code points in `iter`,
107    /// returning unpaired surrogates as `Err`s.
108    ///
109    /// # Examples
110    ///
111    /// Basic usage:
112    ///
113    /// ```
114    /// // 𝄞mus<invalid>ic<invalid>
115    /// let v = [
116    ///     0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
117    /// ];
118    ///
119    /// assert_eq!(
120    ///     char::decode_utf16(v)
121    ///         .map(|r| r.map_err(|e| e.unpaired_surrogate()))
122    ///         .collect::<Vec<_>>(),
123    ///     vec![
124    ///         Ok('𝄞'),
125    ///         Ok('m'), Ok('u'), Ok('s'),
126    ///         Err(0xDD1E),
127    ///         Ok('i'), Ok('c'),
128    ///         Err(0xD834)
129    ///     ]
130    /// );
131    /// ```
132    ///
133    /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
134    ///
135    /// ```
136    /// // 𝄞mus<invalid>ic<invalid>
137    /// let v = [
138    ///     0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
139    /// ];
140    ///
141    /// assert_eq!(
142    ///     char::decode_utf16(v)
143    ///        .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
144    ///        .collect::<String>(),
145    ///     "𝄞mus�ic�"
146    /// );
147    /// ```
148    #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
149    #[inline]
150    #[ferrocene::prevalidated]
151    pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
152        super::decode::decode_utf16(iter)
153    }
154
155    /// Converts a `u32` to a `char`.
156    ///
157    /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
158    /// [`as`](../std/keyword.as.html):
159    ///
160    /// ```
161    /// let c = '💯';
162    /// let i = c as u32;
163    ///
164    /// assert_eq!(128175, i);
165    /// ```
166    ///
167    /// However, the reverse is not true: not all valid [`u32`]s are valid
168    /// `char`s. `from_u32()` will return `None` if the input is not a valid value
169    /// for a `char`.
170    ///
171    /// For an unsafe version of this function which ignores these checks, see
172    /// [`from_u32_unchecked`].
173    ///
174    /// [`from_u32_unchecked`]: #method.from_u32_unchecked
175    ///
176    /// # Examples
177    ///
178    /// Basic usage:
179    ///
180    /// ```
181    /// let c = char::from_u32(0x2764);
182    ///
183    /// assert_eq!(Some('❤'), c);
184    /// ```
185    ///
186    /// Returning `None` when the input is not a valid `char`:
187    ///
188    /// ```
189    /// let c = char::from_u32(0x110000);
190    ///
191    /// assert_eq!(None, c);
192    /// ```
193    #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
194    #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
195    #[must_use]
196    #[inline]
197    pub const fn from_u32(i: u32) -> Option<char> {
198        super::convert::from_u32(i)
199    }
200
201    /// Converts a `u32` to a `char`, ignoring validity.
202    ///
203    /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
204    /// `as`:
205    ///
206    /// ```
207    /// let c = '💯';
208    /// let i = c as u32;
209    ///
210    /// assert_eq!(128175, i);
211    /// ```
212    ///
213    /// However, the reverse is not true: not all valid [`u32`]s are valid
214    /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to
215    /// `char`, possibly creating an invalid one.
216    ///
217    /// # Safety
218    ///
219    /// This function is unsafe, as it may construct invalid `char` values.
220    ///
221    /// For a safe version of this function, see the [`from_u32`] function.
222    ///
223    /// [`from_u32`]: #method.from_u32
224    ///
225    /// # Examples
226    ///
227    /// Basic usage:
228    ///
229    /// ```
230    /// let c = unsafe { char::from_u32_unchecked(0x2764) };
231    ///
232    /// assert_eq!('❤', c);
233    /// ```
234    #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
235    #[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")]
236    #[must_use]
237    #[inline]
238    #[ferrocene::prevalidated]
239    pub const unsafe fn from_u32_unchecked(i: u32) -> char {
240        // SAFETY: the safety contract must be upheld by the caller.
241        unsafe { super::convert::from_u32_unchecked(i) }
242    }
243
244    /// Converts a digit in the given radix to a `char`.
245    ///
246    /// A 'radix' here is sometimes also called a 'base'. A radix of two
247    /// indicates a binary number, a radix of ten, decimal, and a radix of
248    /// sixteen, hexadecimal, to give some common values. Arbitrary
249    /// radices are supported.
250    ///
251    /// `from_digit()` will return `None` if the input is not a digit in
252    /// the given radix.
253    ///
254    /// # Panics
255    ///
256    /// Panics if given a radix larger than 36.
257    ///
258    /// # Examples
259    ///
260    /// Basic usage:
261    ///
262    /// ```
263    /// let c = char::from_digit(4, 10);
264    ///
265    /// assert_eq!(Some('4'), c);
266    ///
267    /// // Decimal 11 is a single digit in base 16
268    /// let c = char::from_digit(11, 16);
269    ///
270    /// assert_eq!(Some('b'), c);
271    /// ```
272    ///
273    /// Returning `None` when the input is not a digit:
274    ///
275    /// ```
276    /// let c = char::from_digit(20, 10);
277    ///
278    /// assert_eq!(None, c);
279    /// ```
280    ///
281    /// Passing a large radix, causing a panic:
282    ///
283    /// ```should_panic
284    /// // this panics
285    /// let _c = char::from_digit(1, 37);
286    /// ```
287    #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
288    #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
289    #[must_use]
290    #[inline]
291    pub const fn from_digit(num: u32, radix: u32) -> Option<char> {
292        super::convert::from_digit(num, radix)
293    }
294
295    /// Checks if a `char` is a digit in the given radix.
296    ///
297    /// A 'radix' here is sometimes also called a 'base'. A radix of two
298    /// indicates a binary number, a radix of ten, decimal, and a radix of
299    /// sixteen, hexadecimal, to give some common values. Arbitrary
300    /// radices are supported.
301    ///
302    /// Compared to [`is_numeric()`], this function only recognizes the characters
303    /// `0-9`, `a-z` and `A-Z`.
304    ///
305    /// 'Digit' is defined to be only the following characters:
306    ///
307    /// * `0-9`
308    /// * `a-z`
309    /// * `A-Z`
310    ///
311    /// For a more comprehensive understanding of 'digit', see [`is_numeric()`].
312    ///
313    /// [`is_numeric()`]: #method.is_numeric
314    ///
315    /// # Panics
316    ///
317    /// Panics if given a radix smaller than 2 or larger than 36.
318    ///
319    /// # Examples
320    ///
321    /// Basic usage:
322    ///
323    /// ```
324    /// assert!('1'.is_digit(10));
325    /// assert!('f'.is_digit(16));
326    /// assert!(!'f'.is_digit(10));
327    /// ```
328    ///
329    /// Passing a large radix, causing a panic:
330    ///
331    /// ```should_panic
332    /// // this panics
333    /// '1'.is_digit(37);
334    /// ```
335    ///
336    /// Passing a small radix, causing a panic:
337    ///
338    /// ```should_panic
339    /// // this panics
340    /// '1'.is_digit(1);
341    /// ```
342    #[stable(feature = "rust1", since = "1.0.0")]
343    #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
344    #[inline]
345    pub const fn is_digit(self, radix: u32) -> bool {
346        self.to_digit(radix).is_some()
347    }
348
349    /// Converts a `char` to a digit in the given radix.
350    ///
351    /// A 'radix' here is sometimes also called a 'base'. A radix of two
352    /// indicates a binary number, a radix of ten, decimal, and a radix of
353    /// sixteen, hexadecimal, to give some common values. Arbitrary
354    /// radices are supported.
355    ///
356    /// 'Digit' is defined to be only the following characters:
357    ///
358    /// * `0-9`
359    /// * `a-z`
360    /// * `A-Z`
361    ///
362    /// # Errors
363    ///
364    /// Returns `None` if the `char` does not refer to a digit in the given radix.
365    ///
366    /// # Panics
367    ///
368    /// Panics if given a radix smaller than 2 or larger than 36.
369    ///
370    /// # Examples
371    ///
372    /// Basic usage:
373    ///
374    /// ```
375    /// assert_eq!('1'.to_digit(10), Some(1));
376    /// assert_eq!('f'.to_digit(16), Some(15));
377    /// ```
378    ///
379    /// Passing a non-digit results in failure:
380    ///
381    /// ```
382    /// assert_eq!('f'.to_digit(10), None);
383    /// assert_eq!('z'.to_digit(16), None);
384    /// ```
385    ///
386    /// Passing a large radix, causing a panic:
387    ///
388    /// ```should_panic
389    /// // this panics
390    /// let _ = '1'.to_digit(37);
391    /// ```
392    /// Passing a small radix, causing a panic:
393    ///
394    /// ```should_panic
395    /// // this panics
396    /// let _ = '1'.to_digit(1);
397    /// ```
398    #[stable(feature = "rust1", since = "1.0.0")]
399    #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
400    #[rustc_diagnostic_item = "char_to_digit"]
401    #[must_use = "this returns the result of the operation, \
402                  without modifying the original"]
403    #[inline]
404    #[ferrocene::prevalidated]
405    pub const fn to_digit(self, radix: u32) -> Option<u32> {
406        assert!(
407            radix >= 2 && radix <= 36,
408            "to_digit: invalid radix -- radix must be in the range 2 to 36 inclusive"
409        );
410        // check radix to remove letter handling code when radix is a known constant
411        let value = if self > '9' && radix > 10 {
412            // mask to convert ASCII letters to uppercase
413            const TO_UPPERCASE_MASK: u32 = !0b0010_0000;
414            // Converts an ASCII letter to its corresponding integer value:
415            // A-Z => 10-35, a-z => 10-35. Other characters produce values >= 36.
416            //
417            // Add Overflow Safety:
418            // By applying the mask after the subtraction, the first addendum is
419            // constrained such that it never exceeds u32::MAX - 0x20.
420            ((self as u32).wrapping_sub('A' as u32) & TO_UPPERCASE_MASK) + 10
421        } else {
422            // convert digit to value, non-digits wrap to values > 36
423            (self as u32).wrapping_sub('0' as u32)
424        };
425        // FIXME(const-hack): once then_some is const fn, use it here
426        if value < radix { Some(value) } else { None }
427    }
428
429    /// Returns an iterator that yields the hexadecimal Unicode escape of a
430    /// character as `char`s.
431    ///
432    /// This will escape characters with the Rust syntax of the form
433    /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
434    ///
435    /// # Examples
436    ///
437    /// As an iterator:
438    ///
439    /// ```
440    /// for c in '❤'.escape_unicode() {
441    ///     print!("{c}");
442    /// }
443    /// println!();
444    /// ```
445    ///
446    /// Using `println!` directly:
447    ///
448    /// ```
449    /// println!("{}", '❤'.escape_unicode());
450    /// ```
451    ///
452    /// Both are equivalent to:
453    ///
454    /// ```
455    /// println!("\\u{{2764}}");
456    /// ```
457    ///
458    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
459    ///
460    /// ```
461    /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
462    /// ```
463    #[must_use = "this returns the escaped char as an iterator, \
464                  without modifying the original"]
465    #[stable(feature = "rust1", since = "1.0.0")]
466    #[inline]
467    pub fn escape_unicode(self) -> EscapeUnicode {
468        EscapeUnicode::new(self)
469    }
470
471    /// An extended version of `escape_debug` that optionally permits escaping
472    /// Extended Grapheme codepoints, single quotes, and double quotes. This
473    /// allows us to format characters like nonspacing marks better when they're
474    /// at the start of a string, and allows escaping single quotes in
475    /// characters, and double quotes in strings.
476    #[inline]
477    #[ferrocene::prevalidated]
478    pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
479        match self {
480            '\0' => EscapeDebug::backslash(ascii::Char::Digit0),
481            '\t' => EscapeDebug::backslash(ascii::Char::SmallT),
482            '\r' => EscapeDebug::backslash(ascii::Char::SmallR),
483            '\n' => EscapeDebug::backslash(ascii::Char::SmallN),
484            '\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus),
485            '\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark),
486            '\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe),
487            _ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
488                EscapeDebug::unicode(self)
489            }
490            _ if is_printable(self) => EscapeDebug::printable(self),
491            _ => EscapeDebug::unicode(self),
492        }
493    }
494
495    /// Returns an iterator that yields the literal escape code of a character
496    /// as `char`s.
497    ///
498    /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
499    /// of `str` or `char`.
500    ///
501    /// # Examples
502    ///
503    /// As an iterator:
504    ///
505    /// ```
506    /// for c in '\n'.escape_debug() {
507    ///     print!("{c}");
508    /// }
509    /// println!();
510    /// ```
511    ///
512    /// Using `println!` directly:
513    ///
514    /// ```
515    /// println!("{}", '\n'.escape_debug());
516    /// ```
517    ///
518    /// Both are equivalent to:
519    ///
520    /// ```
521    /// println!("\\n");
522    /// ```
523    ///
524    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
525    ///
526    /// ```
527    /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
528    /// ```
529    #[must_use = "this returns the escaped char as an iterator, \
530                  without modifying the original"]
531    #[stable(feature = "char_escape_debug", since = "1.20.0")]
532    #[inline]
533    #[ferrocene::prevalidated]
534    pub fn escape_debug(self) -> EscapeDebug {
535        self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
536    }
537
538    /// Returns an iterator that yields the literal escape code of a character
539    /// as `char`s.
540    ///
541    /// The default is chosen with a bias toward producing literals that are
542    /// legal in a variety of languages, including C++11 and similar C-family
543    /// languages. The exact rules are:
544    ///
545    /// * Tab is escaped as `\t`.
546    /// * Carriage return is escaped as `\r`.
547    /// * Line feed is escaped as `\n`.
548    /// * Single quote is escaped as `\'`.
549    /// * Double quote is escaped as `\"`.
550    /// * Backslash is escaped as `\\`.
551    /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
552    ///   inclusive is not escaped.
553    /// * All other characters are given hexadecimal Unicode escapes; see
554    ///   [`escape_unicode`].
555    ///
556    /// [`escape_unicode`]: #method.escape_unicode
557    ///
558    /// # Examples
559    ///
560    /// As an iterator:
561    ///
562    /// ```
563    /// for c in '"'.escape_default() {
564    ///     print!("{c}");
565    /// }
566    /// println!();
567    /// ```
568    ///
569    /// Using `println!` directly:
570    ///
571    /// ```
572    /// println!("{}", '"'.escape_default());
573    /// ```
574    ///
575    /// Both are equivalent to:
576    ///
577    /// ```
578    /// println!("\\\"");
579    /// ```
580    ///
581    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
582    ///
583    /// ```
584    /// assert_eq!('"'.escape_default().to_string(), "\\\"");
585    /// ```
586    #[must_use = "this returns the escaped char as an iterator, \
587                  without modifying the original"]
588    #[stable(feature = "rust1", since = "1.0.0")]
589    #[inline]
590    pub fn escape_default(self) -> EscapeDefault {
591        match self {
592            '\t' => EscapeDefault::backslash(ascii::Char::SmallT),
593            '\r' => EscapeDefault::backslash(ascii::Char::SmallR),
594            '\n' => EscapeDefault::backslash(ascii::Char::SmallN),
595            '\\' | '\'' | '\"' => EscapeDefault::backslash(self.as_ascii().unwrap()),
596            '\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()),
597            _ => EscapeDefault::unicode(self),
598        }
599    }
600
601    /// Returns the number of bytes this `char` would need if encoded in UTF-8.
602    ///
603    /// That number of bytes is always between 1 and 4, inclusive.
604    ///
605    /// # Examples
606    ///
607    /// Basic usage:
608    ///
609    /// ```
610    /// let len = 'A'.len_utf8();
611    /// assert_eq!(len, 1);
612    ///
613    /// let len = 'ß'.len_utf8();
614    /// assert_eq!(len, 2);
615    ///
616    /// let len = 'ℝ'.len_utf8();
617    /// assert_eq!(len, 3);
618    ///
619    /// let len = '💣'.len_utf8();
620    /// assert_eq!(len, 4);
621    /// ```
622    ///
623    /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
624    /// would take if each code point was represented as a `char` vs in the `&str` itself:
625    ///
626    /// ```
627    /// // as chars
628    /// let eastern = '東';
629    /// let capital = '京';
630    ///
631    /// // both can be represented as three bytes
632    /// assert_eq!(3, eastern.len_utf8());
633    /// assert_eq!(3, capital.len_utf8());
634    ///
635    /// // as a &str, these two are encoded in UTF-8
636    /// let tokyo = "東京";
637    ///
638    /// let len = eastern.len_utf8() + capital.len_utf8();
639    ///
640    /// // we can see that they take six bytes total...
641    /// assert_eq!(6, tokyo.len());
642    ///
643    /// // ... just like the &str
644    /// assert_eq!(len, tokyo.len());
645    /// ```
646    #[stable(feature = "rust1", since = "1.0.0")]
647    #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
648    #[inline]
649    #[must_use]
650    #[ferrocene::prevalidated]
651    pub const fn len_utf8(self) -> usize {
652        len_utf8(self as u32)
653    }
654
655    /// Returns the number of 16-bit code units this `char` would need if
656    /// encoded in UTF-16.
657    ///
658    /// That number of code units is always either 1 or 2, for unicode scalar values in
659    /// the [basic multilingual plane] or [supplementary planes] respectively.
660    ///
661    /// See the documentation for [`len_utf8()`] for more explanation of this
662    /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
663    ///
664    /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
665    /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
666    /// [`len_utf8()`]: #method.len_utf8
667    ///
668    /// # Examples
669    ///
670    /// Basic usage:
671    ///
672    /// ```
673    /// let n = 'ß'.len_utf16();
674    /// assert_eq!(n, 1);
675    ///
676    /// let len = '💣'.len_utf16();
677    /// assert_eq!(len, 2);
678    /// ```
679    #[stable(feature = "rust1", since = "1.0.0")]
680    #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
681    #[inline]
682    #[must_use]
683    pub const fn len_utf16(self) -> usize {
684        len_utf16(self as u32)
685    }
686
687    /// Encodes this character as UTF-8 into the provided byte buffer,
688    /// and then returns the subslice of the buffer that contains the encoded character.
689    ///
690    /// # Panics
691    ///
692    /// Panics if the buffer is not large enough.
693    /// A buffer of length four is large enough to encode any `char`.
694    ///
695    /// # Examples
696    ///
697    /// In both of these examples, 'ß' takes two bytes to encode.
698    ///
699    /// ```
700    /// let mut b = [0; 2];
701    ///
702    /// let result = 'ß'.encode_utf8(&mut b);
703    ///
704    /// assert_eq!(result, "ß");
705    ///
706    /// assert_eq!(result.len(), 2);
707    /// ```
708    ///
709    /// A buffer that's too small:
710    ///
711    /// ```should_panic
712    /// let mut b = [0; 1];
713    ///
714    /// // this panics
715    /// 'ß'.encode_utf8(&mut b);
716    /// ```
717    #[stable(feature = "unicode_encode_char", since = "1.15.0")]
718    #[rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0")]
719    #[inline]
720    #[ferrocene::prevalidated]
721    pub const fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
722        // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
723        unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
724    }
725
726    /// Encodes this character as native endian UTF-16 into the provided `u16` buffer,
727    /// and then returns the subslice of the buffer that contains the encoded character.
728    ///
729    /// # Panics
730    ///
731    /// Panics if the buffer is not large enough.
732    /// A buffer of length 2 is large enough to encode any `char`.
733    ///
734    /// # Examples
735    ///
736    /// In both of these examples, '𝕊' takes two `u16`s to encode.
737    ///
738    /// ```
739    /// let mut b = [0; 2];
740    ///
741    /// let result = '𝕊'.encode_utf16(&mut b);
742    ///
743    /// assert_eq!(result.len(), 2);
744    /// ```
745    ///
746    /// A buffer that's too small:
747    ///
748    /// ```should_panic
749    /// let mut b = [0; 1];
750    ///
751    /// // this panics
752    /// '𝕊'.encode_utf16(&mut b);
753    /// ```
754    #[stable(feature = "unicode_encode_char", since = "1.15.0")]
755    #[rustc_const_stable(feature = "const_char_encode_utf16", since = "1.84.0")]
756    #[inline]
757    pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
758        encode_utf16_raw(self as u32, dst)
759    }
760
761    /// Returns `true` if this `char` has the `Alphabetic` property.
762    ///
763    /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
764    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
765    ///
766    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
767    /// [ucd]: https://www.unicode.org/reports/tr44/
768    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
769    ///
770    /// # Examples
771    ///
772    /// Basic usage:
773    ///
774    /// ```
775    /// assert!('a'.is_alphabetic());
776    /// assert!('京'.is_alphabetic());
777    ///
778    /// let c = '💝';
779    /// // love is many things, but it is not alphabetic
780    /// assert!(!c.is_alphabetic());
781    /// ```
782    #[must_use]
783    #[stable(feature = "rust1", since = "1.0.0")]
784    #[inline]
785    pub fn is_alphabetic(self) -> bool {
786        match self {
787            'a'..='z' | 'A'..='Z' => true,
788            '\0'..='\u{A9}' => false,
789            _ => unicode::Alphabetic(self),
790        }
791    }
792
793    /// Returns `true` if this `char` has the `Cased` property.
794    /// A character is cased if and only if it is uppercase, lowercase, or titlecase.
795    ///
796    /// `Cased` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
797    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
798    ///
799    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
800    /// [ucd]: https://www.unicode.org/reports/tr44/
801    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
802    ///
803    /// # Examples
804    ///
805    /// Basic usage:
806    ///
807    /// ```
808    /// #![feature(titlecase)]
809    /// assert!('A'.is_cased());
810    /// assert!('a'.is_cased());
811    /// assert!(!'京'.is_cased());
812    /// ```
813    #[must_use]
814    #[unstable(feature = "titlecase", issue = "153892")]
815    #[inline]
816    pub fn is_cased(self) -> bool {
817        match self {
818            'a'..='z' | 'A'..='Z' => true,
819            '\0'..='\u{A9}' => false,
820            _ => unicode::Cased(self),
821        }
822    }
823
824    /// Returns the case of this character:
825    /// [`Some(CharCase::Upper)`][`CharCase::Upper`] if [`self.is_uppercase()`][`char::is_uppercase`],
826    /// [`Some(CharCase::Lower)`][`CharCase::Lower`] if [`self.is_lowercase()`][`char::is_lowercase`],
827    /// [`Some(CharCase::Title)`][`CharCase::Title`] if [`self.is_titlecase()`][`char::is_titlecase`], and
828    /// `None` if [`!self.is_cased()`][`char::is_cased`].
829    ///
830    /// # Examples
831    ///
832    /// ```
833    /// #![feature(titlecase)]
834    /// use core::char::CharCase;
835    /// assert_eq!('a'.case(), Some(CharCase::Lower));
836    /// assert_eq!('δ'.case(), Some(CharCase::Lower));
837    /// assert_eq!('A'.case(), Some(CharCase::Upper));
838    /// assert_eq!('Δ'.case(), Some(CharCase::Upper));
839    /// assert_eq!('Dž'.case(), Some(CharCase::Title));
840    /// assert_eq!('中'.case(), None);
841    /// ```
842    #[must_use]
843    #[unstable(feature = "titlecase", issue = "153892")]
844    #[inline]
845    pub fn case(self) -> Option<CharCase> {
846        match self {
847            'a'..='z' => Some(CharCase::Lower),
848            'A'..='Z' => Some(CharCase::Upper),
849            '\0'..='\u{A9}' => None,
850            _ if !unicode::Cased(self) => None,
851            _ if unicode::Lowercase(self) => Some(CharCase::Lower),
852            _ if unicode::Uppercase(self) => Some(CharCase::Upper),
853            _ => Some(CharCase::Title),
854        }
855    }
856
857    /// Returns `true` if this `char` has the `Lowercase` property.
858    ///
859    /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
860    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
861    ///
862    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
863    /// [ucd]: https://www.unicode.org/reports/tr44/
864    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
865    ///
866    /// # Examples
867    ///
868    /// Basic usage:
869    ///
870    /// ```
871    /// assert!('a'.is_lowercase());
872    /// assert!('δ'.is_lowercase());
873    /// assert!(!'A'.is_lowercase());
874    /// assert!(!'Δ'.is_lowercase());
875    ///
876    /// // The various Chinese scripts and punctuation do not have case, and so:
877    /// assert!(!'中'.is_lowercase());
878    /// assert!(!' '.is_lowercase());
879    /// ```
880    ///
881    /// In a const context:
882    ///
883    /// ```
884    /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
885    /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
886    /// ```
887    #[must_use]
888    #[stable(feature = "rust1", since = "1.0.0")]
889    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
890    #[inline]
891    pub const fn is_lowercase(self) -> bool {
892        match self {
893            'a'..='z' => true,
894            '\0'..='\u{A9}' => false,
895            _ => unicode::Lowercase(self),
896        }
897    }
898
899    /// Returns `true` if this `char` has the general category for titlecase letters.
900    /// Conceptually, these characters consist of an uppercase portion followed by a lowercase portion.
901    ///
902    /// Titlecase letters (code points with the general category of `Lt`) are described in Chapter 4
903    /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
904    /// Database][ucd] [`UnicodeData.txt`].
905    ///
906    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
907    /// [ucd]: https://www.unicode.org/reports/tr44/
908    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
909    ///
910    /// # Examples
911    ///
912    /// Basic usage:
913    ///
914    /// ```
915    /// #![feature(titlecase)]
916    /// assert!('Dž'.is_titlecase());
917    /// assert!('ῼ'.is_titlecase());
918    /// assert!(!'D'.is_titlecase());
919    /// assert!(!'z'.is_titlecase());
920    /// assert!(!'中'.is_titlecase());
921    /// assert!(!' '.is_titlecase());
922    /// ```
923    #[must_use]
924    #[unstable(feature = "titlecase", issue = "153892")]
925    #[inline]
926    pub fn is_titlecase(self) -> bool {
927        match self {
928            '\0'..='\u{01C4}' => false,
929            _ => self.is_cased() && !self.is_lowercase() && !self.is_uppercase(),
930        }
931    }
932
933    /// Returns `true` if this `char` has the `Uppercase` property.
934    ///
935    /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
936    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
937    ///
938    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
939    /// [ucd]: https://www.unicode.org/reports/tr44/
940    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
941    ///
942    /// # Examples
943    ///
944    /// Basic usage:
945    ///
946    /// ```
947    /// assert!(!'a'.is_uppercase());
948    /// assert!(!'δ'.is_uppercase());
949    /// assert!('A'.is_uppercase());
950    /// assert!('Δ'.is_uppercase());
951    ///
952    /// // The various Chinese scripts and punctuation do not have case, and so:
953    /// assert!(!'中'.is_uppercase());
954    /// assert!(!' '.is_uppercase());
955    /// ```
956    ///
957    /// In a const context:
958    ///
959    /// ```
960    /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
961    /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
962    /// ```
963    #[must_use]
964    #[stable(feature = "rust1", since = "1.0.0")]
965    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
966    #[inline]
967    pub const fn is_uppercase(self) -> bool {
968        match self {
969            'A'..='Z' => true,
970            '\0'..='\u{BF}' => false,
971            _ => unicode::Uppercase(self),
972        }
973    }
974
975    /// Returns `true` if this `char` has the `White_Space` property.
976    ///
977    /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
978    ///
979    /// [ucd]: https://www.unicode.org/reports/tr44/
980    /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
981    ///
982    /// # Examples
983    ///
984    /// Basic usage:
985    ///
986    /// ```
987    /// assert!(' '.is_whitespace());
988    ///
989    /// // line break
990    /// assert!('\n'.is_whitespace());
991    ///
992    /// // a non-breaking space
993    /// assert!('\u{A0}'.is_whitespace());
994    ///
995    /// assert!(!'越'.is_whitespace());
996    /// ```
997    #[must_use]
998    #[stable(feature = "rust1", since = "1.0.0")]
999    #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
1000    #[inline]
1001    pub const fn is_whitespace(self) -> bool {
1002        match self {
1003            ' ' | '\x09'..='\x0d' => true,
1004            '\0'..='\u{84}' => false,
1005            _ => unicode::White_Space(self),
1006        }
1007    }
1008
1009    /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
1010    ///
1011    /// [`is_alphabetic()`]: #method.is_alphabetic
1012    /// [`is_numeric()`]: #method.is_numeric
1013    ///
1014    /// # Examples
1015    ///
1016    /// Basic usage:
1017    ///
1018    /// ```
1019    /// assert!('٣'.is_alphanumeric());
1020    /// assert!('7'.is_alphanumeric());
1021    /// assert!('৬'.is_alphanumeric());
1022    /// assert!('¾'.is_alphanumeric());
1023    /// assert!('①'.is_alphanumeric());
1024    /// assert!('K'.is_alphanumeric());
1025    /// assert!('و'.is_alphanumeric());
1026    /// assert!('藏'.is_alphanumeric());
1027    /// ```
1028    #[must_use]
1029    #[stable(feature = "rust1", since = "1.0.0")]
1030    #[inline]
1031    pub fn is_alphanumeric(self) -> bool {
1032        match self {
1033            'a'..='z' | 'A'..='Z' | '0'..='9' => true,
1034            '\0'..='\u{A9}' => false,
1035            _ => unicode::Alphabetic(self) || unicode::N(self),
1036        }
1037    }
1038
1039    /// Returns `true` if this `char` has the general category for control codes.
1040    ///
1041    /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
1042    /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
1043    /// Database][ucd] [`UnicodeData.txt`].
1044    ///
1045    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1046    /// [ucd]: https://www.unicode.org/reports/tr44/
1047    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1048    ///
1049    /// # Examples
1050    ///
1051    /// Basic usage:
1052    ///
1053    /// ```
1054    /// // U+009C, STRING TERMINATOR
1055    /// assert!('œ'.is_control());
1056    /// assert!(!'q'.is_control());
1057    /// ```
1058    #[must_use]
1059    #[stable(feature = "rust1", since = "1.0.0")]
1060    #[inline]
1061    pub fn is_control(self) -> bool {
1062        // According to
1063        // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1064        // the set of codepoints in `Cc` will never change.
1065        // So we can just hard-code the patterns to match against instead of using a table.
1066        matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}')
1067    }
1068
1069    /// Returns `true` if this `char` has the `Grapheme_Extend` property.
1070    ///
1071    /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
1072    /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
1073    /// [`DerivedCoreProperties.txt`].
1074    ///
1075    /// [uax29]: https://www.unicode.org/reports/tr29/
1076    /// [ucd]: https://www.unicode.org/reports/tr44/
1077    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1078    #[must_use]
1079    #[inline]
1080    #[ferrocene::prevalidated]
1081    pub(crate) fn is_grapheme_extended(self) -> bool {
1082        self > '\u{02FF}' && unicode::Grapheme_Extend(self)
1083    }
1084
1085    /// Returns `true` if this `char` has the `Case_Ignorable` property. This narrow-use property
1086    /// is used to implement context-dependent casing for the Greek letter sigma (uppercase Σ),
1087    /// which has two lowercase forms.
1088    ///
1089    /// `Case_Ignorable` is [described][D136] in Chapter 3 (Conformance) of the Unicode Core Specification,
1090    /// and specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`];
1091    /// see those resources for more information.
1092    ///
1093    /// [D136]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G63116
1094    /// [ucd]: https://www.unicode.org/reports/tr44/
1095    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1096    #[must_use]
1097    #[inline]
1098    #[unstable(feature = "case_ignorable", issue = "154848")]
1099    pub fn is_case_ignorable(self) -> bool {
1100        if self.is_ascii() {
1101            matches!(self, '\'' | '.' | ':' | '^' | '`')
1102        } else {
1103            unicode::Case_Ignorable(self)
1104        }
1105    }
1106
1107    /// Returns `true` if this `char` has one of the general categories for numbers.
1108    ///
1109    /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
1110    /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
1111    /// Database][ucd] [`UnicodeData.txt`].
1112    ///
1113    /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
1114    /// If you want everything including characters with overlapping purposes then you might want to use
1115    /// a unicode or language-processing library that exposes the appropriate character properties instead
1116    /// of looking at the unicode categories.
1117    ///
1118    /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
1119    /// `is_ascii_digit` or `is_digit` instead.
1120    ///
1121    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1122    /// [ucd]: https://www.unicode.org/reports/tr44/
1123    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1124    ///
1125    /// # Examples
1126    ///
1127    /// Basic usage:
1128    ///
1129    /// ```
1130    /// assert!('٣'.is_numeric());
1131    /// assert!('7'.is_numeric());
1132    /// assert!('৬'.is_numeric());
1133    /// assert!('¾'.is_numeric());
1134    /// assert!('①'.is_numeric());
1135    /// assert!(!'K'.is_numeric());
1136    /// assert!(!'و'.is_numeric());
1137    /// assert!(!'藏'.is_numeric());
1138    /// assert!(!'三'.is_numeric());
1139    /// ```
1140    #[must_use]
1141    #[stable(feature = "rust1", since = "1.0.0")]
1142    #[inline]
1143    pub fn is_numeric(self) -> bool {
1144        match self {
1145            '0'..='9' => true,
1146            '\0'..='\u{B1}' => false,
1147            _ => unicode::N(self),
1148        }
1149    }
1150
1151    /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
1152    /// `char`s.
1153    ///
1154    /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
1155    ///
1156    /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
1157    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1158    ///
1159    /// [ucd]: https://www.unicode.org/reports/tr44/
1160    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1161    ///
1162    /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1163    /// the `char`(s) given by [`SpecialCasing.txt`].
1164    ///
1165    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1166    ///
1167    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1168    /// is independent of context and language.
1169    ///
1170    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1171    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1172    ///
1173    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1174    ///
1175    /// # Examples
1176    ///
1177    /// As an iterator:
1178    ///
1179    /// ```
1180    /// for c in 'İ'.to_lowercase() {
1181    ///     print!("{c}");
1182    /// }
1183    /// println!();
1184    /// ```
1185    ///
1186    /// Using `println!` directly:
1187    ///
1188    /// ```
1189    /// println!("{}", 'İ'.to_lowercase());
1190    /// ```
1191    ///
1192    /// Both are equivalent to:
1193    ///
1194    /// ```
1195    /// println!("i\u{307}");
1196    /// ```
1197    ///
1198    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1199    ///
1200    /// ```
1201    /// assert_eq!('C'.to_lowercase().to_string(), "c");
1202    ///
1203    /// // Sometimes the result is more than one character:
1204    /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1205    ///
1206    /// // Characters that do not have both uppercase and lowercase
1207    /// // convert into themselves.
1208    /// assert_eq!('山'.to_lowercase().to_string(), "山");
1209    /// ```
1210    #[must_use = "this returns the lowercased character as a new iterator, \
1211                  without modifying the original"]
1212    #[stable(feature = "rust1", since = "1.0.0")]
1213    #[inline]
1214    pub fn to_lowercase(self) -> ToLowercase {
1215        ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1216    }
1217
1218    /// Returns an iterator that yields the titlecase mapping of this `char` as one or more
1219    /// `char`s.
1220    ///
1221    /// This is usually, but not always, equivalent to the uppercase mapping
1222    /// returned by [`Self::to_uppercase`]. Prefer this method when seeking to capitalize
1223    /// Only The First Letter of a word, but use [`Self::to_uppercase`] for ALL CAPS.
1224    ///
1225    /// If this `char` does not have a titlecase mapping, the iterator yields the same `char`.
1226    ///
1227    /// If this `char` has a one-to-one titlecase mapping given by the [Unicode Character
1228    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1229    ///
1230    /// [ucd]: https://www.unicode.org/reports/tr44/
1231    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1232    ///
1233    /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1234    /// the `char`(s) given by [`SpecialCasing.txt`].
1235    ///
1236    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1237    ///
1238    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1239    /// is independent of context and language.
1240    ///
1241    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1242    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1243    ///
1244    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1245    ///
1246    /// # Examples
1247    ///
1248    /// As an iterator:
1249    ///
1250    /// ```
1251    /// #![feature(titlecase)]
1252    /// for c in 'ß'.to_titlecase() {
1253    ///     print!("{c}");
1254    /// }
1255    /// println!();
1256    /// ```
1257    ///
1258    /// Using `println!` directly:
1259    ///
1260    /// ```
1261    /// #![feature(titlecase)]
1262    /// println!("{}", 'ß'.to_titlecase());
1263    /// ```
1264    ///
1265    /// Both are equivalent to:
1266    ///
1267    /// ```
1268    /// println!("Ss");
1269    /// ```
1270    ///
1271    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1272    ///
1273    /// ```
1274    /// #![feature(titlecase)]
1275    /// assert_eq!('c'.to_titlecase().to_string(), "C");
1276    /// assert_eq!('dž'.to_titlecase().to_string(), "Dž");
1277    /// assert_eq!('ῼ'.to_titlecase().to_string(), "ῼ");
1278    ///
1279    /// // Sometimes the result is more than one character:
1280    /// assert_eq!('ß'.to_titlecase().to_string(), "Ss");
1281    ///
1282    /// // Characters that do not have separate cased forms
1283    /// // convert into themselves.
1284    /// assert_eq!('山'.to_titlecase().to_string(), "山");
1285    /// ```
1286    ///
1287    /// # Note on locale
1288    ///
1289    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1290    ///
1291    /// * 'Dotless': I / ı, sometimes written ï
1292    /// * 'Dotted': İ / i
1293    ///
1294    /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1295    ///
1296    /// ```
1297    /// #![feature(titlecase)]
1298    /// let upper_i = 'i'.to_titlecase().to_string();
1299    /// ```
1300    ///
1301    /// The value of `upper_i` here relies on the language of the text: if we're
1302    /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1303    /// be `"İ"`. `to_titlecase()` does not take this into account, and so:
1304    ///
1305    /// ```
1306    /// #![feature(titlecase)]
1307    /// let upper_i = 'i'.to_titlecase().to_string();
1308    ///
1309    /// assert_eq!(upper_i, "I");
1310    /// ```
1311    ///
1312    /// holds across languages.
1313    #[must_use = "this returns the titlecased character as a new iterator, \
1314                  without modifying the original"]
1315    #[unstable(feature = "titlecase", issue = "153892")]
1316    #[inline]
1317    pub fn to_titlecase(self) -> ToTitlecase {
1318        ToTitlecase(CaseMappingIter::new(conversions::to_title(self)))
1319    }
1320
1321    /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1322    /// `char`s.
1323    ///
1324    /// Prefer this method when converting a word into ALL CAPS, but consider [`Self::to_titlecase`]
1325    /// instead if you seek to capitalize Only The First Letter.
1326    ///
1327    /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1328    ///
1329    /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1330    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1331    ///
1332    /// [ucd]: https://www.unicode.org/reports/tr44/
1333    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1334    ///
1335    /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1336    /// the `char`(s) given by [`SpecialCasing.txt`].
1337    ///
1338    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1339    ///
1340    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1341    /// is independent of context and language.
1342    ///
1343    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1344    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1345    ///
1346    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1347    ///
1348    /// # Examples
1349    /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase.
1350    ///
1351    /// As an iterator:
1352    ///
1353    /// ```
1354    /// for c in 'ſt'.to_uppercase() {
1355    ///     print!("{c}");
1356    /// }
1357    /// println!();
1358    /// ```
1359    ///
1360    /// Using `println!` directly:
1361    ///
1362    /// ```
1363    /// println!("{}", 'ſt'.to_uppercase());
1364    /// ```
1365    ///
1366    /// Both are equivalent to:
1367    ///
1368    /// ```
1369    /// println!("ST");
1370    /// ```
1371    ///
1372    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1373    ///
1374    /// ```
1375    /// assert_eq!('c'.to_uppercase().to_string(), "C");
1376    /// assert_eq!('dž'.to_uppercase().to_string(), "DŽ");
1377    ///
1378    /// // Sometimes the result is more than one character:
1379    /// assert_eq!('ſt'.to_uppercase().to_string(), "ST");
1380    /// assert_eq!('ῼ'.to_uppercase().to_string(), "ΩΙ");
1381    ///
1382    /// // Characters that do not have both uppercase and lowercase
1383    /// // convert into themselves.
1384    /// assert_eq!('山'.to_uppercase().to_string(), "山");
1385    /// ```
1386    ///
1387    /// # Note on locale
1388    ///
1389    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1390    ///
1391    /// * 'Dotless': I / ı, sometimes written ï
1392    /// * 'Dotted': İ / i
1393    ///
1394    /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1395    ///
1396    /// ```
1397    /// let upper_i = 'i'.to_uppercase().to_string();
1398    /// ```
1399    ///
1400    /// The value of `upper_i` here relies on the language of the text: if we're
1401    /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1402    /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1403    ///
1404    /// ```
1405    /// let upper_i = 'i'.to_uppercase().to_string();
1406    ///
1407    /// assert_eq!(upper_i, "I");
1408    /// ```
1409    ///
1410    /// holds across languages.
1411    #[must_use = "this returns the uppercased character as a new iterator, \
1412                  without modifying the original"]
1413    #[stable(feature = "rust1", since = "1.0.0")]
1414    #[inline]
1415    pub fn to_uppercase(self) -> ToUppercase {
1416        ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1417    }
1418
1419    /// Checks if the value is within the ASCII range.
1420    ///
1421    /// # Examples
1422    ///
1423    /// ```
1424    /// let ascii = 'a';
1425    /// let non_ascii = '❤';
1426    ///
1427    /// assert!(ascii.is_ascii());
1428    /// assert!(!non_ascii.is_ascii());
1429    /// ```
1430    #[must_use]
1431    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1432    #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1433    #[rustc_diagnostic_item = "char_is_ascii"]
1434    #[inline]
1435    #[ferrocene::prevalidated]
1436    pub const fn is_ascii(&self) -> bool {
1437        *self as u32 <= 0x7F
1438    }
1439
1440    /// Returns `Some` if the value is within the ASCII range,
1441    /// or `None` if it's not.
1442    ///
1443    /// This is preferred to [`Self::is_ascii`] when you're passing the value
1444    /// along to something else that can take [`ascii::Char`] rather than
1445    /// needing to check again for itself whether the value is in ASCII.
1446    #[must_use]
1447    #[unstable(feature = "ascii_char", issue = "110998")]
1448    #[inline]
1449    pub const fn as_ascii(&self) -> Option<ascii::Char> {
1450        if self.is_ascii() {
1451            // SAFETY: Just checked that this is ASCII.
1452            Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
1453        } else {
1454            None
1455        }
1456    }
1457
1458    /// Converts this char into an [ASCII character](`ascii::Char`), without
1459    /// checking whether it is valid.
1460    ///
1461    /// # Safety
1462    ///
1463    /// This char must be within the ASCII range, or else this is UB.
1464    #[must_use]
1465    #[unstable(feature = "ascii_char", issue = "110998")]
1466    #[inline]
1467    pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1468        assert_unsafe_precondition!(
1469            check_library_ub,
1470            "as_ascii_unchecked requires that the char is valid ASCII",
1471            (it: &char = self) => it.is_ascii()
1472        );
1473
1474        // SAFETY: the caller promised that this char is ASCII.
1475        unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1476    }
1477
1478    /// Makes a copy of the value in its ASCII upper case equivalent.
1479    ///
1480    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1481    /// but non-ASCII letters are unchanged.
1482    ///
1483    /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1484    ///
1485    /// To uppercase ASCII characters in addition to non-ASCII characters, use
1486    /// [`to_uppercase()`].
1487    ///
1488    /// # Examples
1489    ///
1490    /// ```
1491    /// let ascii = 'a';
1492    /// let non_ascii = '❤';
1493    ///
1494    /// assert_eq!('A', ascii.to_ascii_uppercase());
1495    /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1496    /// ```
1497    ///
1498    /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1499    /// [`to_uppercase()`]: #method.to_uppercase
1500    #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1501    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1502    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1503    #[inline]
1504    pub const fn to_ascii_uppercase(&self) -> char {
1505        if self.is_ascii_lowercase() {
1506            (*self as u8).ascii_change_case_unchecked() as char
1507        } else {
1508            *self
1509        }
1510    }
1511
1512    /// Makes a copy of the value in its ASCII lower case equivalent.
1513    ///
1514    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1515    /// but non-ASCII letters are unchanged.
1516    ///
1517    /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1518    ///
1519    /// To lowercase ASCII characters in addition to non-ASCII characters, use
1520    /// [`to_lowercase()`].
1521    ///
1522    /// # Examples
1523    ///
1524    /// ```
1525    /// let ascii = 'A';
1526    /// let non_ascii = '❤';
1527    ///
1528    /// assert_eq!('a', ascii.to_ascii_lowercase());
1529    /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1530    /// ```
1531    ///
1532    /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1533    /// [`to_lowercase()`]: #method.to_lowercase
1534    #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1535    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1536    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1537    #[inline]
1538    pub const fn to_ascii_lowercase(&self) -> char {
1539        if self.is_ascii_uppercase() {
1540            (*self as u8).ascii_change_case_unchecked() as char
1541        } else {
1542            *self
1543        }
1544    }
1545
1546    /// Checks that two values are an ASCII case-insensitive match.
1547    ///
1548    /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1549    ///
1550    /// # Examples
1551    ///
1552    /// ```
1553    /// let upper_a = 'A';
1554    /// let lower_a = 'a';
1555    /// let lower_z = 'z';
1556    ///
1557    /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1558    /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1559    /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1560    /// ```
1561    ///
1562    /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1563    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1564    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1565    #[inline]
1566    pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1567        self.to_ascii_lowercase() == other.to_ascii_lowercase()
1568    }
1569
1570    /// Converts this type to its ASCII upper case equivalent in-place.
1571    ///
1572    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1573    /// but non-ASCII letters are unchanged.
1574    ///
1575    /// To return a new uppercased value without modifying the existing one, use
1576    /// [`to_ascii_uppercase()`].
1577    ///
1578    /// # Examples
1579    ///
1580    /// ```
1581    /// let mut ascii = 'a';
1582    ///
1583    /// ascii.make_ascii_uppercase();
1584    ///
1585    /// assert_eq!('A', ascii);
1586    /// ```
1587    ///
1588    /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1589    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1590    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1591    #[inline]
1592    pub const fn make_ascii_uppercase(&mut self) {
1593        *self = self.to_ascii_uppercase();
1594    }
1595
1596    /// Converts this type to its ASCII lower case equivalent in-place.
1597    ///
1598    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1599    /// but non-ASCII letters are unchanged.
1600    ///
1601    /// To return a new lowercased value without modifying the existing one, use
1602    /// [`to_ascii_lowercase()`].
1603    ///
1604    /// # Examples
1605    ///
1606    /// ```
1607    /// let mut ascii = 'A';
1608    ///
1609    /// ascii.make_ascii_lowercase();
1610    ///
1611    /// assert_eq!('a', ascii);
1612    /// ```
1613    ///
1614    /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1615    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1616    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1617    #[inline]
1618    pub const fn make_ascii_lowercase(&mut self) {
1619        *self = self.to_ascii_lowercase();
1620    }
1621
1622    /// Checks if the value is an ASCII alphabetic character:
1623    ///
1624    /// - U+0041 'A' ..= U+005A 'Z', or
1625    /// - U+0061 'a' ..= U+007A 'z'.
1626    ///
1627    /// # Examples
1628    ///
1629    /// ```
1630    /// let uppercase_a = 'A';
1631    /// let uppercase_g = 'G';
1632    /// let a = 'a';
1633    /// let g = 'g';
1634    /// let zero = '0';
1635    /// let percent = '%';
1636    /// let space = ' ';
1637    /// let lf = '\n';
1638    /// let esc = '\x1b';
1639    ///
1640    /// assert!(uppercase_a.is_ascii_alphabetic());
1641    /// assert!(uppercase_g.is_ascii_alphabetic());
1642    /// assert!(a.is_ascii_alphabetic());
1643    /// assert!(g.is_ascii_alphabetic());
1644    /// assert!(!zero.is_ascii_alphabetic());
1645    /// assert!(!percent.is_ascii_alphabetic());
1646    /// assert!(!space.is_ascii_alphabetic());
1647    /// assert!(!lf.is_ascii_alphabetic());
1648    /// assert!(!esc.is_ascii_alphabetic());
1649    /// ```
1650    #[must_use]
1651    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1652    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1653    #[inline]
1654    pub const fn is_ascii_alphabetic(&self) -> bool {
1655        matches!(*self, 'a'..='z' | 'A'..='Z')
1656    }
1657
1658    /// Checks if the value is an ASCII uppercase character:
1659    /// U+0041 'A' ..= U+005A 'Z'.
1660    ///
1661    /// # Examples
1662    ///
1663    /// ```
1664    /// let uppercase_a = 'A';
1665    /// let uppercase_g = 'G';
1666    /// let a = 'a';
1667    /// let g = 'g';
1668    /// let zero = '0';
1669    /// let percent = '%';
1670    /// let space = ' ';
1671    /// let lf = '\n';
1672    /// let esc = '\x1b';
1673    ///
1674    /// assert!(uppercase_a.is_ascii_uppercase());
1675    /// assert!(uppercase_g.is_ascii_uppercase());
1676    /// assert!(!a.is_ascii_uppercase());
1677    /// assert!(!g.is_ascii_uppercase());
1678    /// assert!(!zero.is_ascii_uppercase());
1679    /// assert!(!percent.is_ascii_uppercase());
1680    /// assert!(!space.is_ascii_uppercase());
1681    /// assert!(!lf.is_ascii_uppercase());
1682    /// assert!(!esc.is_ascii_uppercase());
1683    /// ```
1684    #[must_use]
1685    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1686    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1687    #[inline]
1688    pub const fn is_ascii_uppercase(&self) -> bool {
1689        matches!(*self, 'A'..='Z')
1690    }
1691
1692    /// Checks if the value is an ASCII lowercase character:
1693    /// U+0061 'a' ..= U+007A 'z'.
1694    ///
1695    /// # Examples
1696    ///
1697    /// ```
1698    /// let uppercase_a = 'A';
1699    /// let uppercase_g = 'G';
1700    /// let a = 'a';
1701    /// let g = 'g';
1702    /// let zero = '0';
1703    /// let percent = '%';
1704    /// let space = ' ';
1705    /// let lf = '\n';
1706    /// let esc = '\x1b';
1707    ///
1708    /// assert!(!uppercase_a.is_ascii_lowercase());
1709    /// assert!(!uppercase_g.is_ascii_lowercase());
1710    /// assert!(a.is_ascii_lowercase());
1711    /// assert!(g.is_ascii_lowercase());
1712    /// assert!(!zero.is_ascii_lowercase());
1713    /// assert!(!percent.is_ascii_lowercase());
1714    /// assert!(!space.is_ascii_lowercase());
1715    /// assert!(!lf.is_ascii_lowercase());
1716    /// assert!(!esc.is_ascii_lowercase());
1717    /// ```
1718    #[must_use]
1719    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1720    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1721    #[inline]
1722    pub const fn is_ascii_lowercase(&self) -> bool {
1723        matches!(*self, 'a'..='z')
1724    }
1725
1726    /// Checks if the value is an ASCII alphanumeric character:
1727    ///
1728    /// - U+0041 'A' ..= U+005A 'Z', or
1729    /// - U+0061 'a' ..= U+007A 'z', or
1730    /// - U+0030 '0' ..= U+0039 '9'.
1731    ///
1732    /// # Examples
1733    ///
1734    /// ```
1735    /// let uppercase_a = 'A';
1736    /// let uppercase_g = 'G';
1737    /// let a = 'a';
1738    /// let g = 'g';
1739    /// let zero = '0';
1740    /// let percent = '%';
1741    /// let space = ' ';
1742    /// let lf = '\n';
1743    /// let esc = '\x1b';
1744    ///
1745    /// assert!(uppercase_a.is_ascii_alphanumeric());
1746    /// assert!(uppercase_g.is_ascii_alphanumeric());
1747    /// assert!(a.is_ascii_alphanumeric());
1748    /// assert!(g.is_ascii_alphanumeric());
1749    /// assert!(zero.is_ascii_alphanumeric());
1750    /// assert!(!percent.is_ascii_alphanumeric());
1751    /// assert!(!space.is_ascii_alphanumeric());
1752    /// assert!(!lf.is_ascii_alphanumeric());
1753    /// assert!(!esc.is_ascii_alphanumeric());
1754    /// ```
1755    #[must_use]
1756    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1757    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1758    #[inline]
1759    pub const fn is_ascii_alphanumeric(&self) -> bool {
1760        matches!(*self, '0'..='9') | matches!(*self, 'A'..='Z') | matches!(*self, 'a'..='z')
1761    }
1762
1763    /// Checks if the value is an ASCII decimal digit:
1764    /// U+0030 '0' ..= U+0039 '9'.
1765    ///
1766    /// # Examples
1767    ///
1768    /// ```
1769    /// let uppercase_a = 'A';
1770    /// let uppercase_g = 'G';
1771    /// let a = 'a';
1772    /// let g = 'g';
1773    /// let zero = '0';
1774    /// let percent = '%';
1775    /// let space = ' ';
1776    /// let lf = '\n';
1777    /// let esc = '\x1b';
1778    ///
1779    /// assert!(!uppercase_a.is_ascii_digit());
1780    /// assert!(!uppercase_g.is_ascii_digit());
1781    /// assert!(!a.is_ascii_digit());
1782    /// assert!(!g.is_ascii_digit());
1783    /// assert!(zero.is_ascii_digit());
1784    /// assert!(!percent.is_ascii_digit());
1785    /// assert!(!space.is_ascii_digit());
1786    /// assert!(!lf.is_ascii_digit());
1787    /// assert!(!esc.is_ascii_digit());
1788    /// ```
1789    #[must_use]
1790    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1791    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1792    #[inline]
1793    pub const fn is_ascii_digit(&self) -> bool {
1794        matches!(*self, '0'..='9')
1795    }
1796
1797    /// Checks if the value is an ASCII octal digit:
1798    /// U+0030 '0' ..= U+0037 '7'.
1799    ///
1800    /// # Examples
1801    ///
1802    /// ```
1803    /// #![feature(is_ascii_octdigit)]
1804    ///
1805    /// let uppercase_a = 'A';
1806    /// let a = 'a';
1807    /// let zero = '0';
1808    /// let seven = '7';
1809    /// let nine = '9';
1810    /// let percent = '%';
1811    /// let lf = '\n';
1812    ///
1813    /// assert!(!uppercase_a.is_ascii_octdigit());
1814    /// assert!(!a.is_ascii_octdigit());
1815    /// assert!(zero.is_ascii_octdigit());
1816    /// assert!(seven.is_ascii_octdigit());
1817    /// assert!(!nine.is_ascii_octdigit());
1818    /// assert!(!percent.is_ascii_octdigit());
1819    /// assert!(!lf.is_ascii_octdigit());
1820    /// ```
1821    #[must_use]
1822    #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
1823    #[inline]
1824    pub const fn is_ascii_octdigit(&self) -> bool {
1825        matches!(*self, '0'..='7')
1826    }
1827
1828    /// Checks if the value is an ASCII hexadecimal digit:
1829    ///
1830    /// - U+0030 '0' ..= U+0039 '9', or
1831    /// - U+0041 'A' ..= U+0046 'F', or
1832    /// - U+0061 'a' ..= U+0066 'f'.
1833    ///
1834    /// # Examples
1835    ///
1836    /// ```
1837    /// let uppercase_a = 'A';
1838    /// let uppercase_g = 'G';
1839    /// let a = 'a';
1840    /// let g = 'g';
1841    /// let zero = '0';
1842    /// let percent = '%';
1843    /// let space = ' ';
1844    /// let lf = '\n';
1845    /// let esc = '\x1b';
1846    ///
1847    /// assert!(uppercase_a.is_ascii_hexdigit());
1848    /// assert!(!uppercase_g.is_ascii_hexdigit());
1849    /// assert!(a.is_ascii_hexdigit());
1850    /// assert!(!g.is_ascii_hexdigit());
1851    /// assert!(zero.is_ascii_hexdigit());
1852    /// assert!(!percent.is_ascii_hexdigit());
1853    /// assert!(!space.is_ascii_hexdigit());
1854    /// assert!(!lf.is_ascii_hexdigit());
1855    /// assert!(!esc.is_ascii_hexdigit());
1856    /// ```
1857    #[must_use]
1858    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1859    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1860    #[inline]
1861    pub const fn is_ascii_hexdigit(&self) -> bool {
1862        matches!(*self, '0'..='9') | matches!(*self, 'A'..='F') | matches!(*self, 'a'..='f')
1863    }
1864
1865    /// Checks if the value is an ASCII punctuation character:
1866    ///
1867    /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1868    /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1869    /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1870    /// - U+007B ..= U+007E `{ | } ~`
1871    ///
1872    /// # Examples
1873    ///
1874    /// ```
1875    /// let uppercase_a = 'A';
1876    /// let uppercase_g = 'G';
1877    /// let a = 'a';
1878    /// let g = 'g';
1879    /// let zero = '0';
1880    /// let percent = '%';
1881    /// let space = ' ';
1882    /// let lf = '\n';
1883    /// let esc = '\x1b';
1884    ///
1885    /// assert!(!uppercase_a.is_ascii_punctuation());
1886    /// assert!(!uppercase_g.is_ascii_punctuation());
1887    /// assert!(!a.is_ascii_punctuation());
1888    /// assert!(!g.is_ascii_punctuation());
1889    /// assert!(!zero.is_ascii_punctuation());
1890    /// assert!(percent.is_ascii_punctuation());
1891    /// assert!(!space.is_ascii_punctuation());
1892    /// assert!(!lf.is_ascii_punctuation());
1893    /// assert!(!esc.is_ascii_punctuation());
1894    /// ```
1895    #[must_use]
1896    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1897    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1898    #[inline]
1899    pub const fn is_ascii_punctuation(&self) -> bool {
1900        matches!(*self, '!'..='/')
1901            | matches!(*self, ':'..='@')
1902            | matches!(*self, '['..='`')
1903            | matches!(*self, '{'..='~')
1904    }
1905
1906    /// Checks if the value is an ASCII graphic character:
1907    /// U+0021 '!' ..= U+007E '~'.
1908    ///
1909    /// # Examples
1910    ///
1911    /// ```
1912    /// let uppercase_a = 'A';
1913    /// let uppercase_g = 'G';
1914    /// let a = 'a';
1915    /// let g = 'g';
1916    /// let zero = '0';
1917    /// let percent = '%';
1918    /// let space = ' ';
1919    /// let lf = '\n';
1920    /// let esc = '\x1b';
1921    ///
1922    /// assert!(uppercase_a.is_ascii_graphic());
1923    /// assert!(uppercase_g.is_ascii_graphic());
1924    /// assert!(a.is_ascii_graphic());
1925    /// assert!(g.is_ascii_graphic());
1926    /// assert!(zero.is_ascii_graphic());
1927    /// assert!(percent.is_ascii_graphic());
1928    /// assert!(!space.is_ascii_graphic());
1929    /// assert!(!lf.is_ascii_graphic());
1930    /// assert!(!esc.is_ascii_graphic());
1931    /// ```
1932    #[must_use]
1933    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1934    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1935    #[inline]
1936    pub const fn is_ascii_graphic(&self) -> bool {
1937        matches!(*self, '!'..='~')
1938    }
1939
1940    /// Checks if the value is an ASCII whitespace character:
1941    /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1942    /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1943    ///
1944    /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1945    /// whitespace][infra-aw]. There are several other definitions in
1946    /// wide use. For instance, [the POSIX locale][pct] includes
1947    /// U+000B VERTICAL TAB as well as all the above characters,
1948    /// but—from the very same specification—[the default rule for
1949    /// "field splitting" in the Bourne shell][bfs] considers *only*
1950    /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1951    ///
1952    /// If you are writing a program that will process an existing
1953    /// file format, check what that format's definition of whitespace is
1954    /// before using this function.
1955    ///
1956    /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1957    /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1958    /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1959    ///
1960    /// # Examples
1961    ///
1962    /// ```
1963    /// let uppercase_a = 'A';
1964    /// let uppercase_g = 'G';
1965    /// let a = 'a';
1966    /// let g = 'g';
1967    /// let zero = '0';
1968    /// let percent = '%';
1969    /// let space = ' ';
1970    /// let lf = '\n';
1971    /// let esc = '\x1b';
1972    ///
1973    /// assert!(!uppercase_a.is_ascii_whitespace());
1974    /// assert!(!uppercase_g.is_ascii_whitespace());
1975    /// assert!(!a.is_ascii_whitespace());
1976    /// assert!(!g.is_ascii_whitespace());
1977    /// assert!(!zero.is_ascii_whitespace());
1978    /// assert!(!percent.is_ascii_whitespace());
1979    /// assert!(space.is_ascii_whitespace());
1980    /// assert!(lf.is_ascii_whitespace());
1981    /// assert!(!esc.is_ascii_whitespace());
1982    /// ```
1983    #[must_use]
1984    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1985    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1986    #[inline]
1987    pub const fn is_ascii_whitespace(&self) -> bool {
1988        matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1989    }
1990
1991    /// Checks if the value is an ASCII control character:
1992    /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1993    /// Note that most ASCII whitespace characters are control
1994    /// characters, but SPACE is not.
1995    ///
1996    /// # Examples
1997    ///
1998    /// ```
1999    /// let uppercase_a = 'A';
2000    /// let uppercase_g = 'G';
2001    /// let a = 'a';
2002    /// let g = 'g';
2003    /// let zero = '0';
2004    /// let percent = '%';
2005    /// let space = ' ';
2006    /// let lf = '\n';
2007    /// let esc = '\x1b';
2008    ///
2009    /// assert!(!uppercase_a.is_ascii_control());
2010    /// assert!(!uppercase_g.is_ascii_control());
2011    /// assert!(!a.is_ascii_control());
2012    /// assert!(!g.is_ascii_control());
2013    /// assert!(!zero.is_ascii_control());
2014    /// assert!(!percent.is_ascii_control());
2015    /// assert!(!space.is_ascii_control());
2016    /// assert!(lf.is_ascii_control());
2017    /// assert!(esc.is_ascii_control());
2018    /// ```
2019    #[must_use]
2020    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2021    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2022    #[inline]
2023    pub const fn is_ascii_control(&self) -> bool {
2024        matches!(*self, '\0'..='\x1F' | '\x7F')
2025    }
2026}
2027
2028#[ferrocene::prevalidated]
2029pub(crate) struct EscapeDebugExtArgs {
2030    /// Escape Extended Grapheme codepoints?
2031    pub(crate) escape_grapheme_extended: bool,
2032
2033    /// Escape single quotes?
2034    pub(crate) escape_single_quote: bool,
2035
2036    /// Escape double quotes?
2037    pub(crate) escape_double_quote: bool,
2038}
2039
2040impl EscapeDebugExtArgs {
2041    pub(crate) const ESCAPE_ALL: Self = Self {
2042        escape_grapheme_extended: true,
2043        escape_single_quote: true,
2044        escape_double_quote: true,
2045    };
2046}
2047
2048#[inline]
2049#[must_use]
2050#[ferrocene::prevalidated]
2051const fn len_utf8(code: u32) -> usize {
2052    match code {
2053        ..MAX_ONE_B => 1,
2054        ..MAX_TWO_B => 2,
2055        ..MAX_THREE_B => 3,
2056        _ => 4,
2057    }
2058}
2059
2060#[inline]
2061#[must_use]
2062const fn len_utf16(code: u32) -> usize {
2063    if (code & 0xFFFF) == code { 1 } else { 2 }
2064}
2065
2066/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
2067/// and then returns the subslice of the buffer that contains the encoded character.
2068///
2069/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2070/// (Creating a `char` in the surrogate range is UB.)
2071/// The result is valid [generalized UTF-8] but not valid UTF-8.
2072///
2073/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2074///
2075/// # Panics
2076///
2077/// Panics if the buffer is not large enough.
2078/// A buffer of length four is large enough to encode any `char`.
2079#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2080#[doc(hidden)]
2081#[inline]
2082#[ferrocene::prevalidated]
2083pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
2084    let len = len_utf8(code);
2085    if dst.len() < len {
2086        const_panic!(
2087            "encode_utf8: buffer does not have enough bytes to encode code point",
2088            "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2089            code: u32 = code,
2090            len: usize = len,
2091            dst_len: usize = dst.len(),
2092        );
2093    }
2094
2095    // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint.
2096    unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) };
2097
2098    // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2099    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2100}
2101
2102/// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`.
2103///
2104/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2105/// (Creating a `char` in the surrogate range is UB.)
2106/// The result is valid [generalized UTF-8] but not valid UTF-8.
2107///
2108/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2109///
2110/// # Safety
2111///
2112/// The behavior is undefined if the buffer pointed to by `dst` is not
2113/// large enough to hold the encoded codepoint. A buffer of length four
2114/// is large enough to encode any `char`.
2115///
2116/// For a safe version of this function, see the [`encode_utf8_raw`] function.
2117#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2118#[doc(hidden)]
2119#[inline]
2120#[ferrocene::prevalidated]
2121pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
2122    let len = len_utf8(code);
2123    // SAFETY: The caller must guarantee that the buffer pointed to by `dst`
2124    // is at least `len` bytes long.
2125    unsafe {
2126        if len == 1 {
2127            *dst = code as u8;
2128            return;
2129        }
2130
2131        let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
2132        let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
2133        let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
2134        let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
2135
2136        if len == 2 {
2137            *dst = last2 | TAG_TWO_B;
2138            *dst.add(1) = last1;
2139            return;
2140        }
2141
2142        if len == 3 {
2143            *dst = last3 | TAG_THREE_B;
2144            *dst.add(1) = last2;
2145            *dst.add(2) = last1;
2146            return;
2147        }
2148
2149        *dst = last4;
2150        *dst.add(1) = last3;
2151        *dst.add(2) = last2;
2152        *dst.add(3) = last1;
2153    }
2154}
2155
2156/// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer,
2157/// and then returns the subslice of the buffer that contains the encoded character.
2158///
2159/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
2160/// (Creating a `char` in the surrogate range is UB.)
2161///
2162/// # Panics
2163///
2164/// Panics if the buffer is not large enough.
2165/// A buffer of length 2 is large enough to encode any `char`.
2166#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2167#[doc(hidden)]
2168#[inline]
2169pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
2170    let len = len_utf16(code);
2171    match (len, &mut *dst) {
2172        (1, [a, ..]) => {
2173            *a = code as u16;
2174        }
2175        (2, [a, b, ..]) => {
2176            code -= 0x1_0000;
2177            *a = (code >> 10) as u16 | 0xD800;
2178            *b = (code & 0x3FF) as u16 | 0xDC00;
2179        }
2180        _ => {
2181            const_panic!(
2182                "encode_utf16: buffer does not have enough bytes to encode code point",
2183                "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2184                code: u32 = code,
2185                len: usize = len,
2186                dst_len: usize = dst.len(),
2187            )
2188        }
2189    };
2190    // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2191    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2192}