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            c => c > '\x7f' && unicode::Alphabetic(c),
789        }
790    }
791
792    /// Returns `true` if this `char` has the `Lowercase` property.
793    ///
794    /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
795    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
796    ///
797    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
798    /// [ucd]: https://www.unicode.org/reports/tr44/
799    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
800    ///
801    /// # Examples
802    ///
803    /// Basic usage:
804    ///
805    /// ```
806    /// assert!('a'.is_lowercase());
807    /// assert!('δ'.is_lowercase());
808    /// assert!(!'A'.is_lowercase());
809    /// assert!(!'Δ'.is_lowercase());
810    ///
811    /// // The various Chinese scripts and punctuation do not have case, and so:
812    /// assert!(!'中'.is_lowercase());
813    /// assert!(!' '.is_lowercase());
814    /// ```
815    ///
816    /// In a const context:
817    ///
818    /// ```
819    /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
820    /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
821    /// ```
822    #[must_use]
823    #[stable(feature = "rust1", since = "1.0.0")]
824    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
825    #[inline]
826    pub const fn is_lowercase(self) -> bool {
827        match self {
828            'a'..='z' => true,
829            c => c > '\x7f' && unicode::Lowercase(c),
830        }
831    }
832
833    /// Returns `true` if this `char` has the `Uppercase` property.
834    ///
835    /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
836    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
837    ///
838    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
839    /// [ucd]: https://www.unicode.org/reports/tr44/
840    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
841    ///
842    /// # Examples
843    ///
844    /// Basic usage:
845    ///
846    /// ```
847    /// assert!(!'a'.is_uppercase());
848    /// assert!(!'δ'.is_uppercase());
849    /// assert!('A'.is_uppercase());
850    /// assert!('Δ'.is_uppercase());
851    ///
852    /// // The various Chinese scripts and punctuation do not have case, and so:
853    /// assert!(!'中'.is_uppercase());
854    /// assert!(!' '.is_uppercase());
855    /// ```
856    ///
857    /// In a const context:
858    ///
859    /// ```
860    /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
861    /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
862    /// ```
863    #[must_use]
864    #[stable(feature = "rust1", since = "1.0.0")]
865    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
866    #[inline]
867    pub const fn is_uppercase(self) -> bool {
868        match self {
869            'A'..='Z' => true,
870            c => c > '\x7f' && unicode::Uppercase(c),
871        }
872    }
873
874    /// Returns `true` if this `char` has the `White_Space` property.
875    ///
876    /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
877    ///
878    /// [ucd]: https://www.unicode.org/reports/tr44/
879    /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
880    ///
881    /// # Examples
882    ///
883    /// Basic usage:
884    ///
885    /// ```
886    /// assert!(' '.is_whitespace());
887    ///
888    /// // line break
889    /// assert!('\n'.is_whitespace());
890    ///
891    /// // a non-breaking space
892    /// assert!('\u{A0}'.is_whitespace());
893    ///
894    /// assert!(!'越'.is_whitespace());
895    /// ```
896    #[must_use]
897    #[stable(feature = "rust1", since = "1.0.0")]
898    #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
899    #[inline]
900    pub const fn is_whitespace(self) -> bool {
901        match self {
902            ' ' | '\x09'..='\x0d' => true,
903            c => c > '\x7f' && unicode::White_Space(c),
904        }
905    }
906
907    /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
908    ///
909    /// [`is_alphabetic()`]: #method.is_alphabetic
910    /// [`is_numeric()`]: #method.is_numeric
911    ///
912    /// # Examples
913    ///
914    /// Basic usage:
915    ///
916    /// ```
917    /// assert!('٣'.is_alphanumeric());
918    /// assert!('7'.is_alphanumeric());
919    /// assert!('৬'.is_alphanumeric());
920    /// assert!('¾'.is_alphanumeric());
921    /// assert!('①'.is_alphanumeric());
922    /// assert!('K'.is_alphanumeric());
923    /// assert!('و'.is_alphanumeric());
924    /// assert!('藏'.is_alphanumeric());
925    /// ```
926    #[must_use]
927    #[stable(feature = "rust1", since = "1.0.0")]
928    #[inline]
929    pub fn is_alphanumeric(self) -> bool {
930        if self.is_ascii() {
931            self.is_ascii_alphanumeric()
932        } else {
933            unicode::Alphabetic(self) || unicode::N(self)
934        }
935    }
936
937    /// Returns `true` if this `char` has the general category for control codes.
938    ///
939    /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
940    /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
941    /// Database][ucd] [`UnicodeData.txt`].
942    ///
943    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
944    /// [ucd]: https://www.unicode.org/reports/tr44/
945    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
946    ///
947    /// # Examples
948    ///
949    /// Basic usage:
950    ///
951    /// ```
952    /// // U+009C, STRING TERMINATOR
953    /// assert!('œ'.is_control());
954    /// assert!(!'q'.is_control());
955    /// ```
956    #[must_use]
957    #[stable(feature = "rust1", since = "1.0.0")]
958    #[inline]
959    pub fn is_control(self) -> bool {
960        // According to
961        // https://www.unicode.org/policies/stability_policy.html#Property_Value,
962        // the set of codepoints in `Cc` will never change.
963        // So we can just hard-code the patterns to match against instead of using a table.
964        matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}')
965    }
966
967    /// Returns `true` if this `char` has the `Grapheme_Extend` property.
968    ///
969    /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
970    /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
971    /// [`DerivedCoreProperties.txt`].
972    ///
973    /// [uax29]: https://www.unicode.org/reports/tr29/
974    /// [ucd]: https://www.unicode.org/reports/tr44/
975    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
976    #[must_use]
977    #[inline]
978    #[ferrocene::prevalidated]
979    pub(crate) fn is_grapheme_extended(self) -> bool {
980        !self.is_ascii() && unicode::Grapheme_Extend(self)
981    }
982
983    /// Returns `true` if this `char` has the `Cased` property.
984    ///
985    /// `Cased` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
986    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
987    ///
988    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
989    /// [ucd]: https://www.unicode.org/reports/tr44/
990    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
991    #[must_use]
992    #[inline]
993    #[doc(hidden)]
994    #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
995    pub fn is_cased(self) -> bool {
996        if self.is_ascii() { self.is_ascii_alphabetic() } else { unicode::Cased(self) }
997    }
998
999    /// Returns `true` if this `char` has the `Case_Ignorable` property.
1000    ///
1001    /// `Case_Ignorable` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
1002    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
1003    ///
1004    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1005    /// [ucd]: https://www.unicode.org/reports/tr44/
1006    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1007    #[must_use]
1008    #[inline]
1009    #[doc(hidden)]
1010    #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1011    pub fn is_case_ignorable(self) -> bool {
1012        if self.is_ascii() {
1013            matches!(self, '\'' | '.' | ':' | '^' | '`')
1014        } else {
1015            unicode::Case_Ignorable(self)
1016        }
1017    }
1018
1019    /// Returns `true` if this `char` has one of the general categories for numbers.
1020    ///
1021    /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
1022    /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
1023    /// Database][ucd] [`UnicodeData.txt`].
1024    ///
1025    /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
1026    /// If you want everything including characters with overlapping purposes then you might want to use
1027    /// a unicode or language-processing library that exposes the appropriate character properties instead
1028    /// of looking at the unicode categories.
1029    ///
1030    /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
1031    /// `is_ascii_digit` or `is_digit` instead.
1032    ///
1033    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1034    /// [ucd]: https://www.unicode.org/reports/tr44/
1035    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1036    ///
1037    /// # Examples
1038    ///
1039    /// Basic usage:
1040    ///
1041    /// ```
1042    /// assert!('٣'.is_numeric());
1043    /// assert!('7'.is_numeric());
1044    /// assert!('৬'.is_numeric());
1045    /// assert!('¾'.is_numeric());
1046    /// assert!('①'.is_numeric());
1047    /// assert!(!'K'.is_numeric());
1048    /// assert!(!'و'.is_numeric());
1049    /// assert!(!'藏'.is_numeric());
1050    /// assert!(!'三'.is_numeric());
1051    /// ```
1052    #[must_use]
1053    #[stable(feature = "rust1", since = "1.0.0")]
1054    #[inline]
1055    pub fn is_numeric(self) -> bool {
1056        match self {
1057            '0'..='9' => true,
1058            c => c > '\x7f' && unicode::N(c),
1059        }
1060    }
1061
1062    /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
1063    /// `char`s.
1064    ///
1065    /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
1066    ///
1067    /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
1068    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1069    ///
1070    /// [ucd]: https://www.unicode.org/reports/tr44/
1071    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1072    ///
1073    /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1074    /// the `char`(s) given by [`SpecialCasing.txt`].
1075    ///
1076    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1077    ///
1078    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1079    /// is independent of context and language.
1080    ///
1081    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1082    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1083    ///
1084    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1085    ///
1086    /// # Examples
1087    ///
1088    /// As an iterator:
1089    ///
1090    /// ```
1091    /// for c in 'İ'.to_lowercase() {
1092    ///     print!("{c}");
1093    /// }
1094    /// println!();
1095    /// ```
1096    ///
1097    /// Using `println!` directly:
1098    ///
1099    /// ```
1100    /// println!("{}", 'İ'.to_lowercase());
1101    /// ```
1102    ///
1103    /// Both are equivalent to:
1104    ///
1105    /// ```
1106    /// println!("i\u{307}");
1107    /// ```
1108    ///
1109    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1110    ///
1111    /// ```
1112    /// assert_eq!('C'.to_lowercase().to_string(), "c");
1113    ///
1114    /// // Sometimes the result is more than one character:
1115    /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1116    ///
1117    /// // Characters that do not have both uppercase and lowercase
1118    /// // convert into themselves.
1119    /// assert_eq!('山'.to_lowercase().to_string(), "山");
1120    /// ```
1121    #[must_use = "this returns the lowercase character as a new iterator, \
1122                  without modifying the original"]
1123    #[stable(feature = "rust1", since = "1.0.0")]
1124    #[inline]
1125    pub fn to_lowercase(self) -> ToLowercase {
1126        ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1127    }
1128
1129    /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1130    /// `char`s.
1131    ///
1132    /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1133    ///
1134    /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1135    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1136    ///
1137    /// [ucd]: https://www.unicode.org/reports/tr44/
1138    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1139    ///
1140    /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1141    /// the `char`(s) given by [`SpecialCasing.txt`].
1142    ///
1143    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1144    ///
1145    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1146    /// is independent of context and language.
1147    ///
1148    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1149    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1150    ///
1151    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1152    ///
1153    /// # Examples
1154    /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase.
1155    ///
1156    /// As an iterator:
1157    ///
1158    /// ```
1159    /// for c in 'ſt'.to_uppercase() {
1160    ///     print!("{c}");
1161    /// }
1162    /// println!();
1163    /// ```
1164    ///
1165    /// Using `println!` directly:
1166    ///
1167    /// ```
1168    /// println!("{}", 'ſt'.to_uppercase());
1169    /// ```
1170    ///
1171    /// Both are equivalent to:
1172    ///
1173    /// ```
1174    /// println!("ST");
1175    /// ```
1176    ///
1177    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1178    ///
1179    /// ```
1180    /// assert_eq!('c'.to_uppercase().to_string(), "C");
1181    ///
1182    /// // Sometimes the result is more than one character:
1183    /// assert_eq!('ſt'.to_uppercase().to_string(), "ST");
1184    ///
1185    /// // Characters that do not have both uppercase and lowercase
1186    /// // convert into themselves.
1187    /// assert_eq!('山'.to_uppercase().to_string(), "山");
1188    /// ```
1189    ///
1190    /// # Note on locale
1191    ///
1192    /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1193    ///
1194    /// * 'Dotless': I / ı, sometimes written ï
1195    /// * 'Dotted': İ / i
1196    ///
1197    /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1198    ///
1199    /// ```
1200    /// let upper_i = 'i'.to_uppercase().to_string();
1201    /// ```
1202    ///
1203    /// The value of `upper_i` here relies on the language of the text: if we're
1204    /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
1205    /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1206    ///
1207    /// ```
1208    /// let upper_i = 'i'.to_uppercase().to_string();
1209    ///
1210    /// assert_eq!(upper_i, "I");
1211    /// ```
1212    ///
1213    /// holds across languages.
1214    #[must_use = "this returns the uppercase character as a new iterator, \
1215                  without modifying the original"]
1216    #[stable(feature = "rust1", since = "1.0.0")]
1217    #[inline]
1218    pub fn to_uppercase(self) -> ToUppercase {
1219        ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1220    }
1221
1222    /// Checks if the value is within the ASCII range.
1223    ///
1224    /// # Examples
1225    ///
1226    /// ```
1227    /// let ascii = 'a';
1228    /// let non_ascii = '❤';
1229    ///
1230    /// assert!(ascii.is_ascii());
1231    /// assert!(!non_ascii.is_ascii());
1232    /// ```
1233    #[must_use]
1234    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1235    #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1236    #[rustc_diagnostic_item = "char_is_ascii"]
1237    #[inline]
1238    #[ferrocene::prevalidated]
1239    pub const fn is_ascii(&self) -> bool {
1240        *self as u32 <= 0x7F
1241    }
1242
1243    /// Returns `Some` if the value is within the ASCII range,
1244    /// or `None` if it's not.
1245    ///
1246    /// This is preferred to [`Self::is_ascii`] when you're passing the value
1247    /// along to something else that can take [`ascii::Char`] rather than
1248    /// needing to check again for itself whether the value is in ASCII.
1249    #[must_use]
1250    #[unstable(feature = "ascii_char", issue = "110998")]
1251    #[inline]
1252    pub const fn as_ascii(&self) -> Option<ascii::Char> {
1253        if self.is_ascii() {
1254            // SAFETY: Just checked that this is ASCII.
1255            Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
1256        } else {
1257            None
1258        }
1259    }
1260
1261    /// Converts this char into an [ASCII character](`ascii::Char`), without
1262    /// checking whether it is valid.
1263    ///
1264    /// # Safety
1265    ///
1266    /// This char must be within the ASCII range, or else this is UB.
1267    #[must_use]
1268    #[unstable(feature = "ascii_char", issue = "110998")]
1269    #[inline]
1270    pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1271        assert_unsafe_precondition!(
1272            check_library_ub,
1273            "as_ascii_unchecked requires that the char is valid ASCII",
1274            (it: &char = self) => it.is_ascii()
1275        );
1276
1277        // SAFETY: the caller promised that this char is ASCII.
1278        unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1279    }
1280
1281    /// Makes a copy of the value in its ASCII upper case equivalent.
1282    ///
1283    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1284    /// but non-ASCII letters are unchanged.
1285    ///
1286    /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1287    ///
1288    /// To uppercase ASCII characters in addition to non-ASCII characters, use
1289    /// [`to_uppercase()`].
1290    ///
1291    /// # Examples
1292    ///
1293    /// ```
1294    /// let ascii = 'a';
1295    /// let non_ascii = '❤';
1296    ///
1297    /// assert_eq!('A', ascii.to_ascii_uppercase());
1298    /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1299    /// ```
1300    ///
1301    /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1302    /// [`to_uppercase()`]: #method.to_uppercase
1303    #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1304    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1305    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1306    #[inline]
1307    pub const fn to_ascii_uppercase(&self) -> char {
1308        if self.is_ascii_lowercase() {
1309            (*self as u8).ascii_change_case_unchecked() as char
1310        } else {
1311            *self
1312        }
1313    }
1314
1315    /// Makes a copy of the value in its ASCII lower case equivalent.
1316    ///
1317    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1318    /// but non-ASCII letters are unchanged.
1319    ///
1320    /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1321    ///
1322    /// To lowercase ASCII characters in addition to non-ASCII characters, use
1323    /// [`to_lowercase()`].
1324    ///
1325    /// # Examples
1326    ///
1327    /// ```
1328    /// let ascii = 'A';
1329    /// let non_ascii = '❤';
1330    ///
1331    /// assert_eq!('a', ascii.to_ascii_lowercase());
1332    /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1333    /// ```
1334    ///
1335    /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1336    /// [`to_lowercase()`]: #method.to_lowercase
1337    #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1338    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1339    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1340    #[inline]
1341    pub const fn to_ascii_lowercase(&self) -> char {
1342        if self.is_ascii_uppercase() {
1343            (*self as u8).ascii_change_case_unchecked() as char
1344        } else {
1345            *self
1346        }
1347    }
1348
1349    /// Checks that two values are an ASCII case-insensitive match.
1350    ///
1351    /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1352    ///
1353    /// # Examples
1354    ///
1355    /// ```
1356    /// let upper_a = 'A';
1357    /// let lower_a = 'a';
1358    /// let lower_z = 'z';
1359    ///
1360    /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1361    /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1362    /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1363    /// ```
1364    ///
1365    /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1366    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1367    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1368    #[inline]
1369    pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1370        self.to_ascii_lowercase() == other.to_ascii_lowercase()
1371    }
1372
1373    /// Converts this type to its ASCII upper case equivalent in-place.
1374    ///
1375    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1376    /// but non-ASCII letters are unchanged.
1377    ///
1378    /// To return a new uppercased value without modifying the existing one, use
1379    /// [`to_ascii_uppercase()`].
1380    ///
1381    /// # Examples
1382    ///
1383    /// ```
1384    /// let mut ascii = 'a';
1385    ///
1386    /// ascii.make_ascii_uppercase();
1387    ///
1388    /// assert_eq!('A', ascii);
1389    /// ```
1390    ///
1391    /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1392    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1393    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1394    #[inline]
1395    pub const fn make_ascii_uppercase(&mut self) {
1396        *self = self.to_ascii_uppercase();
1397    }
1398
1399    /// Converts this type to its ASCII lower case equivalent in-place.
1400    ///
1401    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1402    /// but non-ASCII letters are unchanged.
1403    ///
1404    /// To return a new lowercased value without modifying the existing one, use
1405    /// [`to_ascii_lowercase()`].
1406    ///
1407    /// # Examples
1408    ///
1409    /// ```
1410    /// let mut ascii = 'A';
1411    ///
1412    /// ascii.make_ascii_lowercase();
1413    ///
1414    /// assert_eq!('a', ascii);
1415    /// ```
1416    ///
1417    /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1418    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1419    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1420    #[inline]
1421    pub const fn make_ascii_lowercase(&mut self) {
1422        *self = self.to_ascii_lowercase();
1423    }
1424
1425    /// Checks if the value is an ASCII alphabetic character:
1426    ///
1427    /// - U+0041 'A' ..= U+005A 'Z', or
1428    /// - U+0061 'a' ..= U+007A 'z'.
1429    ///
1430    /// # Examples
1431    ///
1432    /// ```
1433    /// let uppercase_a = 'A';
1434    /// let uppercase_g = 'G';
1435    /// let a = 'a';
1436    /// let g = 'g';
1437    /// let zero = '0';
1438    /// let percent = '%';
1439    /// let space = ' ';
1440    /// let lf = '\n';
1441    /// let esc = '\x1b';
1442    ///
1443    /// assert!(uppercase_a.is_ascii_alphabetic());
1444    /// assert!(uppercase_g.is_ascii_alphabetic());
1445    /// assert!(a.is_ascii_alphabetic());
1446    /// assert!(g.is_ascii_alphabetic());
1447    /// assert!(!zero.is_ascii_alphabetic());
1448    /// assert!(!percent.is_ascii_alphabetic());
1449    /// assert!(!space.is_ascii_alphabetic());
1450    /// assert!(!lf.is_ascii_alphabetic());
1451    /// assert!(!esc.is_ascii_alphabetic());
1452    /// ```
1453    #[must_use]
1454    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1455    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1456    #[inline]
1457    pub const fn is_ascii_alphabetic(&self) -> bool {
1458        matches!(*self, 'A'..='Z' | 'a'..='z')
1459    }
1460
1461    /// Checks if the value is an ASCII uppercase character:
1462    /// U+0041 'A' ..= U+005A 'Z'.
1463    ///
1464    /// # Examples
1465    ///
1466    /// ```
1467    /// let uppercase_a = 'A';
1468    /// let uppercase_g = 'G';
1469    /// let a = 'a';
1470    /// let g = 'g';
1471    /// let zero = '0';
1472    /// let percent = '%';
1473    /// let space = ' ';
1474    /// let lf = '\n';
1475    /// let esc = '\x1b';
1476    ///
1477    /// assert!(uppercase_a.is_ascii_uppercase());
1478    /// assert!(uppercase_g.is_ascii_uppercase());
1479    /// assert!(!a.is_ascii_uppercase());
1480    /// assert!(!g.is_ascii_uppercase());
1481    /// assert!(!zero.is_ascii_uppercase());
1482    /// assert!(!percent.is_ascii_uppercase());
1483    /// assert!(!space.is_ascii_uppercase());
1484    /// assert!(!lf.is_ascii_uppercase());
1485    /// assert!(!esc.is_ascii_uppercase());
1486    /// ```
1487    #[must_use]
1488    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1489    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1490    #[inline]
1491    pub const fn is_ascii_uppercase(&self) -> bool {
1492        matches!(*self, 'A'..='Z')
1493    }
1494
1495    /// Checks if the value is an ASCII lowercase character:
1496    /// U+0061 'a' ..= U+007A 'z'.
1497    ///
1498    /// # Examples
1499    ///
1500    /// ```
1501    /// let uppercase_a = 'A';
1502    /// let uppercase_g = 'G';
1503    /// let a = 'a';
1504    /// let g = 'g';
1505    /// let zero = '0';
1506    /// let percent = '%';
1507    /// let space = ' ';
1508    /// let lf = '\n';
1509    /// let esc = '\x1b';
1510    ///
1511    /// assert!(!uppercase_a.is_ascii_lowercase());
1512    /// assert!(!uppercase_g.is_ascii_lowercase());
1513    /// assert!(a.is_ascii_lowercase());
1514    /// assert!(g.is_ascii_lowercase());
1515    /// assert!(!zero.is_ascii_lowercase());
1516    /// assert!(!percent.is_ascii_lowercase());
1517    /// assert!(!space.is_ascii_lowercase());
1518    /// assert!(!lf.is_ascii_lowercase());
1519    /// assert!(!esc.is_ascii_lowercase());
1520    /// ```
1521    #[must_use]
1522    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1523    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1524    #[inline]
1525    pub const fn is_ascii_lowercase(&self) -> bool {
1526        matches!(*self, 'a'..='z')
1527    }
1528
1529    /// Checks if the value is an ASCII alphanumeric character:
1530    ///
1531    /// - U+0041 'A' ..= U+005A 'Z', or
1532    /// - U+0061 'a' ..= U+007A 'z', or
1533    /// - U+0030 '0' ..= U+0039 '9'.
1534    ///
1535    /// # Examples
1536    ///
1537    /// ```
1538    /// let uppercase_a = 'A';
1539    /// let uppercase_g = 'G';
1540    /// let a = 'a';
1541    /// let g = 'g';
1542    /// let zero = '0';
1543    /// let percent = '%';
1544    /// let space = ' ';
1545    /// let lf = '\n';
1546    /// let esc = '\x1b';
1547    ///
1548    /// assert!(uppercase_a.is_ascii_alphanumeric());
1549    /// assert!(uppercase_g.is_ascii_alphanumeric());
1550    /// assert!(a.is_ascii_alphanumeric());
1551    /// assert!(g.is_ascii_alphanumeric());
1552    /// assert!(zero.is_ascii_alphanumeric());
1553    /// assert!(!percent.is_ascii_alphanumeric());
1554    /// assert!(!space.is_ascii_alphanumeric());
1555    /// assert!(!lf.is_ascii_alphanumeric());
1556    /// assert!(!esc.is_ascii_alphanumeric());
1557    /// ```
1558    #[must_use]
1559    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1560    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1561    #[inline]
1562    pub const fn is_ascii_alphanumeric(&self) -> bool {
1563        matches!(*self, '0'..='9') | matches!(*self, 'A'..='Z') | matches!(*self, 'a'..='z')
1564    }
1565
1566    /// Checks if the value is an ASCII decimal digit:
1567    /// U+0030 '0' ..= U+0039 '9'.
1568    ///
1569    /// # Examples
1570    ///
1571    /// ```
1572    /// let uppercase_a = 'A';
1573    /// let uppercase_g = 'G';
1574    /// let a = 'a';
1575    /// let g = 'g';
1576    /// let zero = '0';
1577    /// let percent = '%';
1578    /// let space = ' ';
1579    /// let lf = '\n';
1580    /// let esc = '\x1b';
1581    ///
1582    /// assert!(!uppercase_a.is_ascii_digit());
1583    /// assert!(!uppercase_g.is_ascii_digit());
1584    /// assert!(!a.is_ascii_digit());
1585    /// assert!(!g.is_ascii_digit());
1586    /// assert!(zero.is_ascii_digit());
1587    /// assert!(!percent.is_ascii_digit());
1588    /// assert!(!space.is_ascii_digit());
1589    /// assert!(!lf.is_ascii_digit());
1590    /// assert!(!esc.is_ascii_digit());
1591    /// ```
1592    #[must_use]
1593    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1594    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1595    #[inline]
1596    pub const fn is_ascii_digit(&self) -> bool {
1597        matches!(*self, '0'..='9')
1598    }
1599
1600    /// Checks if the value is an ASCII octal digit:
1601    /// U+0030 '0' ..= U+0037 '7'.
1602    ///
1603    /// # Examples
1604    ///
1605    /// ```
1606    /// #![feature(is_ascii_octdigit)]
1607    ///
1608    /// let uppercase_a = 'A';
1609    /// let a = 'a';
1610    /// let zero = '0';
1611    /// let seven = '7';
1612    /// let nine = '9';
1613    /// let percent = '%';
1614    /// let lf = '\n';
1615    ///
1616    /// assert!(!uppercase_a.is_ascii_octdigit());
1617    /// assert!(!a.is_ascii_octdigit());
1618    /// assert!(zero.is_ascii_octdigit());
1619    /// assert!(seven.is_ascii_octdigit());
1620    /// assert!(!nine.is_ascii_octdigit());
1621    /// assert!(!percent.is_ascii_octdigit());
1622    /// assert!(!lf.is_ascii_octdigit());
1623    /// ```
1624    #[must_use]
1625    #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
1626    #[inline]
1627    pub const fn is_ascii_octdigit(&self) -> bool {
1628        matches!(*self, '0'..='7')
1629    }
1630
1631    /// Checks if the value is an ASCII hexadecimal digit:
1632    ///
1633    /// - U+0030 '0' ..= U+0039 '9', or
1634    /// - U+0041 'A' ..= U+0046 'F', or
1635    /// - U+0061 'a' ..= U+0066 'f'.
1636    ///
1637    /// # Examples
1638    ///
1639    /// ```
1640    /// let uppercase_a = 'A';
1641    /// let uppercase_g = 'G';
1642    /// let a = 'a';
1643    /// let g = 'g';
1644    /// let zero = '0';
1645    /// let percent = '%';
1646    /// let space = ' ';
1647    /// let lf = '\n';
1648    /// let esc = '\x1b';
1649    ///
1650    /// assert!(uppercase_a.is_ascii_hexdigit());
1651    /// assert!(!uppercase_g.is_ascii_hexdigit());
1652    /// assert!(a.is_ascii_hexdigit());
1653    /// assert!(!g.is_ascii_hexdigit());
1654    /// assert!(zero.is_ascii_hexdigit());
1655    /// assert!(!percent.is_ascii_hexdigit());
1656    /// assert!(!space.is_ascii_hexdigit());
1657    /// assert!(!lf.is_ascii_hexdigit());
1658    /// assert!(!esc.is_ascii_hexdigit());
1659    /// ```
1660    #[must_use]
1661    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1662    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1663    #[inline]
1664    pub const fn is_ascii_hexdigit(&self) -> bool {
1665        matches!(*self, '0'..='9') | matches!(*self, 'A'..='F') | matches!(*self, 'a'..='f')
1666    }
1667
1668    /// Checks if the value is an ASCII punctuation character:
1669    ///
1670    /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1671    /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1672    /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1673    /// - U+007B ..= U+007E `{ | } ~`
1674    ///
1675    /// # Examples
1676    ///
1677    /// ```
1678    /// let uppercase_a = 'A';
1679    /// let uppercase_g = 'G';
1680    /// let a = 'a';
1681    /// let g = 'g';
1682    /// let zero = '0';
1683    /// let percent = '%';
1684    /// let space = ' ';
1685    /// let lf = '\n';
1686    /// let esc = '\x1b';
1687    ///
1688    /// assert!(!uppercase_a.is_ascii_punctuation());
1689    /// assert!(!uppercase_g.is_ascii_punctuation());
1690    /// assert!(!a.is_ascii_punctuation());
1691    /// assert!(!g.is_ascii_punctuation());
1692    /// assert!(!zero.is_ascii_punctuation());
1693    /// assert!(percent.is_ascii_punctuation());
1694    /// assert!(!space.is_ascii_punctuation());
1695    /// assert!(!lf.is_ascii_punctuation());
1696    /// assert!(!esc.is_ascii_punctuation());
1697    /// ```
1698    #[must_use]
1699    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1700    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1701    #[inline]
1702    pub const fn is_ascii_punctuation(&self) -> bool {
1703        matches!(*self, '!'..='/')
1704            | matches!(*self, ':'..='@')
1705            | matches!(*self, '['..='`')
1706            | matches!(*self, '{'..='~')
1707    }
1708
1709    /// Checks if the value is an ASCII graphic character:
1710    /// U+0021 '!' ..= U+007E '~'.
1711    ///
1712    /// # Examples
1713    ///
1714    /// ```
1715    /// let uppercase_a = 'A';
1716    /// let uppercase_g = 'G';
1717    /// let a = 'a';
1718    /// let g = 'g';
1719    /// let zero = '0';
1720    /// let percent = '%';
1721    /// let space = ' ';
1722    /// let lf = '\n';
1723    /// let esc = '\x1b';
1724    ///
1725    /// assert!(uppercase_a.is_ascii_graphic());
1726    /// assert!(uppercase_g.is_ascii_graphic());
1727    /// assert!(a.is_ascii_graphic());
1728    /// assert!(g.is_ascii_graphic());
1729    /// assert!(zero.is_ascii_graphic());
1730    /// assert!(percent.is_ascii_graphic());
1731    /// assert!(!space.is_ascii_graphic());
1732    /// assert!(!lf.is_ascii_graphic());
1733    /// assert!(!esc.is_ascii_graphic());
1734    /// ```
1735    #[must_use]
1736    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1737    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1738    #[inline]
1739    pub const fn is_ascii_graphic(&self) -> bool {
1740        matches!(*self, '!'..='~')
1741    }
1742
1743    /// Checks if the value is an ASCII whitespace character:
1744    /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1745    /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1746    ///
1747    /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1748    /// whitespace][infra-aw]. There are several other definitions in
1749    /// wide use. For instance, [the POSIX locale][pct] includes
1750    /// U+000B VERTICAL TAB as well as all the above characters,
1751    /// but—from the very same specification—[the default rule for
1752    /// "field splitting" in the Bourne shell][bfs] considers *only*
1753    /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1754    ///
1755    /// If you are writing a program that will process an existing
1756    /// file format, check what that format's definition of whitespace is
1757    /// before using this function.
1758    ///
1759    /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1760    /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1761    /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1762    ///
1763    /// # Examples
1764    ///
1765    /// ```
1766    /// let uppercase_a = 'A';
1767    /// let uppercase_g = 'G';
1768    /// let a = 'a';
1769    /// let g = 'g';
1770    /// let zero = '0';
1771    /// let percent = '%';
1772    /// let space = ' ';
1773    /// let lf = '\n';
1774    /// let esc = '\x1b';
1775    ///
1776    /// assert!(!uppercase_a.is_ascii_whitespace());
1777    /// assert!(!uppercase_g.is_ascii_whitespace());
1778    /// assert!(!a.is_ascii_whitespace());
1779    /// assert!(!g.is_ascii_whitespace());
1780    /// assert!(!zero.is_ascii_whitespace());
1781    /// assert!(!percent.is_ascii_whitespace());
1782    /// assert!(space.is_ascii_whitespace());
1783    /// assert!(lf.is_ascii_whitespace());
1784    /// assert!(!esc.is_ascii_whitespace());
1785    /// ```
1786    #[must_use]
1787    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1788    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1789    #[inline]
1790    pub const fn is_ascii_whitespace(&self) -> bool {
1791        matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1792    }
1793
1794    /// Checks if the value is an ASCII control character:
1795    /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1796    /// Note that most ASCII whitespace characters are control
1797    /// characters, but SPACE is not.
1798    ///
1799    /// # Examples
1800    ///
1801    /// ```
1802    /// let uppercase_a = 'A';
1803    /// let uppercase_g = 'G';
1804    /// let a = 'a';
1805    /// let g = 'g';
1806    /// let zero = '0';
1807    /// let percent = '%';
1808    /// let space = ' ';
1809    /// let lf = '\n';
1810    /// let esc = '\x1b';
1811    ///
1812    /// assert!(!uppercase_a.is_ascii_control());
1813    /// assert!(!uppercase_g.is_ascii_control());
1814    /// assert!(!a.is_ascii_control());
1815    /// assert!(!g.is_ascii_control());
1816    /// assert!(!zero.is_ascii_control());
1817    /// assert!(!percent.is_ascii_control());
1818    /// assert!(!space.is_ascii_control());
1819    /// assert!(lf.is_ascii_control());
1820    /// assert!(esc.is_ascii_control());
1821    /// ```
1822    #[must_use]
1823    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1824    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1825    #[inline]
1826    pub const fn is_ascii_control(&self) -> bool {
1827        matches!(*self, '\0'..='\x1F' | '\x7F')
1828    }
1829}
1830
1831#[ferrocene::prevalidated]
1832pub(crate) struct EscapeDebugExtArgs {
1833    /// Escape Extended Grapheme codepoints?
1834    pub(crate) escape_grapheme_extended: bool,
1835
1836    /// Escape single quotes?
1837    pub(crate) escape_single_quote: bool,
1838
1839    /// Escape double quotes?
1840    pub(crate) escape_double_quote: bool,
1841}
1842
1843impl EscapeDebugExtArgs {
1844    pub(crate) const ESCAPE_ALL: Self = Self {
1845        escape_grapheme_extended: true,
1846        escape_single_quote: true,
1847        escape_double_quote: true,
1848    };
1849}
1850
1851#[inline]
1852#[must_use]
1853#[ferrocene::prevalidated]
1854const fn len_utf8(code: u32) -> usize {
1855    match code {
1856        ..MAX_ONE_B => 1,
1857        ..MAX_TWO_B => 2,
1858        ..MAX_THREE_B => 3,
1859        _ => 4,
1860    }
1861}
1862
1863#[inline]
1864#[must_use]
1865const fn len_utf16(code: u32) -> usize {
1866    if (code & 0xFFFF) == code { 1 } else { 2 }
1867}
1868
1869/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
1870/// and then returns the subslice of the buffer that contains the encoded character.
1871///
1872/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1873/// (Creating a `char` in the surrogate range is UB.)
1874/// The result is valid [generalized UTF-8] but not valid UTF-8.
1875///
1876/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1877///
1878/// # Panics
1879///
1880/// Panics if the buffer is not large enough.
1881/// A buffer of length four is large enough to encode any `char`.
1882#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1883#[doc(hidden)]
1884#[inline]
1885#[ferrocene::prevalidated]
1886pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1887    let len = len_utf8(code);
1888    if dst.len() < len {
1889        const_panic!(
1890            "encode_utf8: buffer does not have enough bytes to encode code point",
1891            "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
1892            code: u32 = code,
1893            len: usize = len,
1894            dst_len: usize = dst.len(),
1895        );
1896    }
1897
1898    // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint.
1899    unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) };
1900
1901    // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
1902    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
1903}
1904
1905/// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`.
1906///
1907/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1908/// (Creating a `char` in the surrogate range is UB.)
1909/// The result is valid [generalized UTF-8] but not valid UTF-8.
1910///
1911/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1912///
1913/// # Safety
1914///
1915/// The behavior is undefined if the buffer pointed to by `dst` is not
1916/// large enough to hold the encoded codepoint. A buffer of length four
1917/// is large enough to encode any `char`.
1918///
1919/// For a safe version of this function, see the [`encode_utf8_raw`] function.
1920#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1921#[doc(hidden)]
1922#[inline]
1923#[ferrocene::prevalidated]
1924pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
1925    let len = len_utf8(code);
1926    // SAFETY: The caller must guarantee that the buffer pointed to by `dst`
1927    // is at least `len` bytes long.
1928    unsafe {
1929        if len == 1 {
1930            *dst = code as u8;
1931            return;
1932        }
1933
1934        let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
1935        let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1936        let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1937        let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
1938
1939        if len == 2 {
1940            *dst = last2 | TAG_TWO_B;
1941            *dst.add(1) = last1;
1942            return;
1943        }
1944
1945        if len == 3 {
1946            *dst = last3 | TAG_THREE_B;
1947            *dst.add(1) = last2;
1948            *dst.add(2) = last1;
1949            return;
1950        }
1951
1952        *dst = last4;
1953        *dst.add(1) = last3;
1954        *dst.add(2) = last2;
1955        *dst.add(3) = last1;
1956    }
1957}
1958
1959/// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer,
1960/// and then returns the subslice of the buffer that contains the encoded character.
1961///
1962/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1963/// (Creating a `char` in the surrogate range is UB.)
1964///
1965/// # Panics
1966///
1967/// Panics if the buffer is not large enough.
1968/// A buffer of length 2 is large enough to encode any `char`.
1969#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1970#[doc(hidden)]
1971#[inline]
1972pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1973    let len = len_utf16(code);
1974    match (len, &mut *dst) {
1975        (1, [a, ..]) => {
1976            *a = code as u16;
1977        }
1978        (2, [a, b, ..]) => {
1979            code -= 0x1_0000;
1980            *a = (code >> 10) as u16 | 0xD800;
1981            *b = (code & 0x3FF) as u16 | 0xDC00;
1982        }
1983        _ => {
1984            const_panic!(
1985                "encode_utf16: buffer does not have enough bytes to encode code point",
1986                "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
1987                code: u32 = code,
1988                len: usize = len,
1989                dst_len: usize = dst.len(),
1990            )
1991        }
1992    };
1993    // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
1994    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
1995}