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    #[ferrocene::prevalidated]
468    pub fn escape_unicode(self) -> EscapeUnicode {
469        EscapeUnicode::new(self)
470    }
471
472    /// An extended version of `escape_debug` that optionally permits escaping
473    /// Extended Grapheme codepoints, single quotes, and double quotes. This
474    /// allows us to format characters like nonspacing marks better when they're
475    /// at the start of a string, and allows escaping single quotes in
476    /// characters, and double quotes in strings.
477    #[inline]
478    #[ferrocene::prevalidated]
479    pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
480        match self {
481            '\0' => EscapeDebug::backslash(ascii::Char::Digit0),
482            '\t' => EscapeDebug::backslash(ascii::Char::SmallT),
483            '\r' => EscapeDebug::backslash(ascii::Char::SmallR),
484            '\n' => EscapeDebug::backslash(ascii::Char::SmallN),
485            '\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus),
486            '\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark),
487            '\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe),
488            _ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
489                EscapeDebug::unicode(self)
490            }
491            _ if is_printable(self) => EscapeDebug::printable(self),
492            _ => EscapeDebug::unicode(self),
493        }
494    }
495
496    /// Returns an iterator that yields the literal escape code of a character
497    /// as `char`s.
498    ///
499    /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
500    /// of `str` or `char`.
501    ///
502    /// # Examples
503    ///
504    /// As an iterator:
505    ///
506    /// ```
507    /// for c in '\n'.escape_debug() {
508    ///     print!("{c}");
509    /// }
510    /// println!();
511    /// ```
512    ///
513    /// Using `println!` directly:
514    ///
515    /// ```
516    /// println!("{}", '\n'.escape_debug());
517    /// ```
518    ///
519    /// Both are equivalent to:
520    ///
521    /// ```
522    /// println!("\\n");
523    /// ```
524    ///
525    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
526    ///
527    /// ```
528    /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
529    /// ```
530    #[must_use = "this returns the escaped char as an iterator, \
531                  without modifying the original"]
532    #[stable(feature = "char_escape_debug", since = "1.20.0")]
533    #[inline]
534    #[ferrocene::prevalidated]
535    pub fn escape_debug(self) -> EscapeDebug {
536        self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
537    }
538
539    /// Returns an iterator that yields the literal escape code of a character
540    /// as `char`s.
541    ///
542    /// The default is chosen with a bias toward producing literals that are
543    /// legal in a variety of languages, including C++11 and similar C-family
544    /// languages. The exact rules are:
545    ///
546    /// * Tab is escaped as `\t`.
547    /// * Carriage return is escaped as `\r`.
548    /// * Line feed is escaped as `\n`.
549    /// * Single quote is escaped as `\'`.
550    /// * Double quote is escaped as `\"`.
551    /// * Backslash is escaped as `\\`.
552    /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
553    ///   inclusive is not escaped.
554    /// * All other characters are given hexadecimal Unicode escapes; see
555    ///   [`escape_unicode`].
556    ///
557    /// [`escape_unicode`]: #method.escape_unicode
558    ///
559    /// # Examples
560    ///
561    /// As an iterator:
562    ///
563    /// ```
564    /// for c in '"'.escape_default() {
565    ///     print!("{c}");
566    /// }
567    /// println!();
568    /// ```
569    ///
570    /// Using `println!` directly:
571    ///
572    /// ```
573    /// println!("{}", '"'.escape_default());
574    /// ```
575    ///
576    /// Both are equivalent to:
577    ///
578    /// ```
579    /// println!("\\\"");
580    /// ```
581    ///
582    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
583    ///
584    /// ```
585    /// assert_eq!('"'.escape_default().to_string(), "\\\"");
586    /// ```
587    #[must_use = "this returns the escaped char as an iterator, \
588                  without modifying the original"]
589    #[stable(feature = "rust1", since = "1.0.0")]
590    #[inline]
591    #[ferrocene::prevalidated]
592    pub fn escape_default(self) -> EscapeDefault {
593        match self {
594            '\t' => EscapeDefault::backslash(ascii::Char::SmallT),
595            '\r' => EscapeDefault::backslash(ascii::Char::SmallR),
596            '\n' => EscapeDefault::backslash(ascii::Char::SmallN),
597            '\\' | '\'' | '\"' => EscapeDefault::backslash(self.as_ascii().unwrap()),
598            '\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()),
599            _ => EscapeDefault::unicode(self),
600        }
601    }
602
603    /// Returns the number of bytes this `char` would need if encoded in UTF-8.
604    ///
605    /// That number of bytes is always between 1 and 4, inclusive.
606    ///
607    /// # Examples
608    ///
609    /// Basic usage:
610    ///
611    /// ```
612    /// let len = 'A'.len_utf8();
613    /// assert_eq!(len, 1);
614    ///
615    /// let len = 'ß'.len_utf8();
616    /// assert_eq!(len, 2);
617    ///
618    /// let len = 'ℝ'.len_utf8();
619    /// assert_eq!(len, 3);
620    ///
621    /// let len = '💣'.len_utf8();
622    /// assert_eq!(len, 4);
623    /// ```
624    ///
625    /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
626    /// would take if each code point was represented as a `char` vs in the `&str` itself:
627    ///
628    /// ```
629    /// // as chars
630    /// let eastern = '東';
631    /// let capital = '京';
632    ///
633    /// // both can be represented as three bytes
634    /// assert_eq!(3, eastern.len_utf8());
635    /// assert_eq!(3, capital.len_utf8());
636    ///
637    /// // as a &str, these two are encoded in UTF-8
638    /// let tokyo = "東京";
639    ///
640    /// let len = eastern.len_utf8() + capital.len_utf8();
641    ///
642    /// // we can see that they take six bytes total...
643    /// assert_eq!(6, tokyo.len());
644    ///
645    /// // ... just like the &str
646    /// assert_eq!(len, tokyo.len());
647    /// ```
648    #[stable(feature = "rust1", since = "1.0.0")]
649    #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
650    #[inline]
651    #[must_use]
652    #[ferrocene::prevalidated]
653    pub const fn len_utf8(self) -> usize {
654        len_utf8(self as u32)
655    }
656
657    /// Returns the number of 16-bit code units this `char` would need if
658    /// encoded in UTF-16.
659    ///
660    /// That number of code units is always either 1 or 2, for unicode scalar values in
661    /// the [basic multilingual plane] or [supplementary planes] respectively.
662    ///
663    /// See the documentation for [`len_utf8()`] for more explanation of this
664    /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
665    ///
666    /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
667    /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
668    /// [`len_utf8()`]: #method.len_utf8
669    ///
670    /// # Examples
671    ///
672    /// Basic usage:
673    ///
674    /// ```
675    /// let n = 'ß'.len_utf16();
676    /// assert_eq!(n, 1);
677    ///
678    /// let len = '💣'.len_utf16();
679    /// assert_eq!(len, 2);
680    /// ```
681    #[stable(feature = "rust1", since = "1.0.0")]
682    #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
683    #[inline]
684    #[must_use]
685    pub const fn len_utf16(self) -> usize {
686        len_utf16(self as u32)
687    }
688
689    /// Encodes this character as UTF-8 into the provided byte buffer,
690    /// and then returns the subslice of the buffer that contains the encoded character.
691    ///
692    /// # Panics
693    ///
694    /// Panics if the buffer is not large enough.
695    /// A buffer of length four is large enough to encode any `char`.
696    ///
697    /// # Examples
698    ///
699    /// In both of these examples, 'ß' takes two bytes to encode.
700    ///
701    /// ```
702    /// let mut b = [0; 2];
703    ///
704    /// let result = 'ß'.encode_utf8(&mut b);
705    ///
706    /// assert_eq!(result, "ß");
707    ///
708    /// assert_eq!(result.len(), 2);
709    /// ```
710    ///
711    /// A buffer that's too small:
712    ///
713    /// ```should_panic
714    /// let mut b = [0; 1];
715    ///
716    /// // this panics
717    /// 'ß'.encode_utf8(&mut b);
718    /// ```
719    #[stable(feature = "unicode_encode_char", since = "1.15.0")]
720    #[rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0")]
721    #[inline]
722    #[ferrocene::prevalidated]
723    pub const fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
724        // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
725        unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
726    }
727
728    /// Encodes this character as native endian UTF-16 into the provided `u16` buffer,
729    /// and then returns the subslice of the buffer that contains the encoded character.
730    ///
731    /// # Panics
732    ///
733    /// Panics if the buffer is not large enough.
734    /// A buffer of length 2 is large enough to encode any `char`.
735    ///
736    /// # Examples
737    ///
738    /// In both of these examples, '𝕊' takes two `u16`s to encode.
739    ///
740    /// ```
741    /// let mut b = [0; 2];
742    ///
743    /// let result = '𝕊'.encode_utf16(&mut b);
744    ///
745    /// assert_eq!(result.len(), 2);
746    /// ```
747    ///
748    /// A buffer that's too small:
749    ///
750    /// ```should_panic
751    /// let mut b = [0; 1];
752    ///
753    /// // this panics
754    /// '𝕊'.encode_utf16(&mut b);
755    /// ```
756    #[stable(feature = "unicode_encode_char", since = "1.15.0")]
757    #[rustc_const_stable(feature = "const_char_encode_utf16", since = "1.84.0")]
758    #[inline]
759    pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
760        encode_utf16_raw(self as u32, dst)
761    }
762
763    /// Returns `true` if this `char` has the `Alphabetic` property.
764    ///
765    /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
766    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
767    ///
768    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
769    /// [ucd]: https://www.unicode.org/reports/tr44/
770    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
771    ///
772    /// # Examples
773    ///
774    /// Basic usage:
775    ///
776    /// ```
777    /// assert!('a'.is_alphabetic());
778    /// assert!('京'.is_alphabetic());
779    ///
780    /// let c = '💝';
781    /// // love is many things, but it is not alphabetic
782    /// assert!(!c.is_alphabetic());
783    /// ```
784    #[must_use]
785    #[stable(feature = "rust1", since = "1.0.0")]
786    #[inline]
787    pub fn is_alphabetic(self) -> bool {
788        match self {
789            'a'..='z' | 'A'..='Z' => true,
790            '\0'..='\u{A9}' => false,
791            _ => unicode::Alphabetic(self),
792        }
793    }
794
795    /// Returns `true` if this `char` has the `Cased` property.
796    /// A character is cased if and only if it is uppercase, lowercase, or titlecase.
797    ///
798    /// `Cased` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
799    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
800    ///
801    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
802    /// [ucd]: https://www.unicode.org/reports/tr44/
803    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
804    ///
805    /// # Examples
806    ///
807    /// Basic usage:
808    ///
809    /// ```
810    /// #![feature(titlecase)]
811    /// assert!('A'.is_cased());
812    /// assert!('a'.is_cased());
813    /// assert!(!'京'.is_cased());
814    /// ```
815    #[must_use]
816    #[unstable(feature = "titlecase", issue = "153892")]
817    #[inline]
818    pub fn is_cased(self) -> bool {
819        match self {
820            'a'..='z' | 'A'..='Z' => true,
821            '\0'..='\u{A9}' => false,
822            _ => unicode::Lowercase(self) || unicode::Uppercase(self) || unicode::Lt(self),
823        }
824    }
825
826    /// Returns the case of this character:
827    /// [`Some(CharCase::Upper)`][`CharCase::Upper`] if [`self.is_uppercase()`][`char::is_uppercase`],
828    /// [`Some(CharCase::Lower)`][`CharCase::Lower`] if [`self.is_lowercase()`][`char::is_lowercase`],
829    /// [`Some(CharCase::Title)`][`CharCase::Title`] if [`self.is_titlecase()`][`char::is_titlecase`], and
830    /// `None` if [`!self.is_cased()`][`char::is_cased`].
831    ///
832    /// # Examples
833    ///
834    /// ```
835    /// #![feature(titlecase)]
836    /// use core::char::CharCase;
837    /// assert_eq!('a'.case(), Some(CharCase::Lower));
838    /// assert_eq!('δ'.case(), Some(CharCase::Lower));
839    /// assert_eq!('A'.case(), Some(CharCase::Upper));
840    /// assert_eq!('Δ'.case(), Some(CharCase::Upper));
841    /// assert_eq!('Dž'.case(), Some(CharCase::Title));
842    /// assert_eq!('中'.case(), None);
843    /// ```
844    #[must_use]
845    #[unstable(feature = "titlecase", issue = "153892")]
846    #[inline]
847    pub fn case(self) -> Option<CharCase> {
848        match self {
849            'a'..='z' => Some(CharCase::Lower),
850            'A'..='Z' => Some(CharCase::Upper),
851            '\0'..='\u{A9}' => None,
852            _ if unicode::Lowercase(self) => Some(CharCase::Lower),
853            _ if unicode::Uppercase(self) => Some(CharCase::Upper),
854            _ if unicode::Lt(self) => Some(CharCase::Title),
855            _ => None,
856        }
857    }
858
859    /// Returns `true` if this `char` has the `Lowercase` property.
860    ///
861    /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
862    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
863    ///
864    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
865    /// [ucd]: https://www.unicode.org/reports/tr44/
866    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
867    ///
868    /// # Examples
869    ///
870    /// Basic usage:
871    ///
872    /// ```
873    /// assert!('a'.is_lowercase());
874    /// assert!('δ'.is_lowercase());
875    /// assert!(!'A'.is_lowercase());
876    /// assert!(!'Δ'.is_lowercase());
877    ///
878    /// // The various Chinese scripts and punctuation do not have case, and so:
879    /// assert!(!'中'.is_lowercase());
880    /// assert!(!' '.is_lowercase());
881    /// ```
882    ///
883    /// In a const context:
884    ///
885    /// ```
886    /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
887    /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
888    /// ```
889    #[must_use]
890    #[stable(feature = "rust1", since = "1.0.0")]
891    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
892    #[inline]
893    pub const fn is_lowercase(self) -> bool {
894        match self {
895            'a'..='z' => true,
896            '\0'..='\u{A9}' => false,
897            _ => unicode::Lowercase(self),
898        }
899    }
900
901    /// Returns `true` if this `char` has the general category for titlecase letters.
902    /// Conceptually, these characters consist of an uppercase portion followed by a lowercase portion.
903    ///
904    /// Titlecase letters (code points with the general category of `Lt`) are described in Chapter 4
905    /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
906    /// Database][ucd] [`UnicodeData.txt`].
907    ///
908    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
909    /// [ucd]: https://www.unicode.org/reports/tr44/
910    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
911    ///
912    /// # Examples
913    ///
914    /// Basic usage:
915    ///
916    /// ```
917    /// #![feature(titlecase)]
918    /// assert!('Dž'.is_titlecase());
919    /// assert!('ῼ'.is_titlecase());
920    /// assert!(!'D'.is_titlecase());
921    /// assert!(!'z'.is_titlecase());
922    /// assert!(!'中'.is_titlecase());
923    /// assert!(!' '.is_titlecase());
924    /// ```
925    #[must_use]
926    #[unstable(feature = "titlecase", issue = "153892")]
927    #[inline]
928    pub fn is_titlecase(self) -> bool {
929        match self {
930            '\0'..='\u{01C4}' => false,
931            _ => unicode::Lt(self),
932        }
933    }
934
935    /// Returns `true` if this `char` has the `Uppercase` property.
936    ///
937    /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
938    /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
939    ///
940    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
941    /// [ucd]: https://www.unicode.org/reports/tr44/
942    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
943    ///
944    /// # Examples
945    ///
946    /// Basic usage:
947    ///
948    /// ```
949    /// assert!(!'a'.is_uppercase());
950    /// assert!(!'δ'.is_uppercase());
951    /// assert!('A'.is_uppercase());
952    /// assert!('Δ'.is_uppercase());
953    ///
954    /// // The various Chinese scripts and punctuation do not have case, and so:
955    /// assert!(!'中'.is_uppercase());
956    /// assert!(!' '.is_uppercase());
957    /// ```
958    ///
959    /// In a const context:
960    ///
961    /// ```
962    /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
963    /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
964    /// ```
965    #[must_use]
966    #[stable(feature = "rust1", since = "1.0.0")]
967    #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
968    #[inline]
969    pub const fn is_uppercase(self) -> bool {
970        match self {
971            'A'..='Z' => true,
972            '\0'..='\u{BF}' => false,
973            _ => unicode::Uppercase(self),
974        }
975    }
976
977    /// Returns `true` if this `char` has the `White_Space` property.
978    ///
979    /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
980    ///
981    /// [ucd]: https://www.unicode.org/reports/tr44/
982    /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
983    ///
984    /// # Examples
985    ///
986    /// Basic usage:
987    ///
988    /// ```
989    /// assert!(' '.is_whitespace());
990    ///
991    /// // line break
992    /// assert!('\n'.is_whitespace());
993    ///
994    /// // a non-breaking space
995    /// assert!('\u{A0}'.is_whitespace());
996    ///
997    /// assert!(!'越'.is_whitespace());
998    /// ```
999    #[must_use]
1000    #[stable(feature = "rust1", since = "1.0.0")]
1001    #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
1002    #[inline]
1003    #[ferrocene::prevalidated]
1004    pub const fn is_whitespace(self) -> bool {
1005        match self {
1006            ' ' | '\x09'..='\x0d' => true,
1007            '\0'..='\u{84}' => false,
1008            _ => unicode::White_Space(self),
1009        }
1010    }
1011
1012    /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
1013    ///
1014    /// [`is_alphabetic()`]: #method.is_alphabetic
1015    /// [`is_numeric()`]: #method.is_numeric
1016    ///
1017    /// # Examples
1018    ///
1019    /// Basic usage:
1020    ///
1021    /// ```
1022    /// assert!('٣'.is_alphanumeric());
1023    /// assert!('7'.is_alphanumeric());
1024    /// assert!('৬'.is_alphanumeric());
1025    /// assert!('¾'.is_alphanumeric());
1026    /// assert!('①'.is_alphanumeric());
1027    /// assert!('K'.is_alphanumeric());
1028    /// assert!('و'.is_alphanumeric());
1029    /// assert!('藏'.is_alphanumeric());
1030    /// ```
1031    #[must_use]
1032    #[stable(feature = "rust1", since = "1.0.0")]
1033    #[inline]
1034    pub fn is_alphanumeric(self) -> bool {
1035        match self {
1036            'a'..='z' | 'A'..='Z' | '0'..='9' => true,
1037            '\0'..='\u{A9}' => false,
1038            _ => unicode::Alphabetic(self) || unicode::N(self),
1039        }
1040    }
1041
1042    /// Returns `true` if this `char` has the general category for control codes.
1043    ///
1044    /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
1045    /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
1046    /// Database][ucd] [`UnicodeData.txt`].
1047    ///
1048    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1049    /// [ucd]: https://www.unicode.org/reports/tr44/
1050    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1051    ///
1052    /// # Examples
1053    ///
1054    /// Basic usage:
1055    ///
1056    /// ```
1057    /// // U+009C, STRING TERMINATOR
1058    /// assert!('œ'.is_control());
1059    /// assert!(!'q'.is_control());
1060    /// ```
1061    #[must_use]
1062    #[stable(feature = "rust1", since = "1.0.0")]
1063    #[rustc_const_stable(feature = "const_is_control", since = "CURRENT_RUSTC_VERSION")]
1064    #[inline]
1065    pub const fn is_control(self) -> bool {
1066        // According to
1067        // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1068        // the set of codepoints in `Cc` will never change.
1069        // So we can just hard-code the patterns to match against instead of using a table.
1070        matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}')
1071    }
1072
1073    /// Returns `true` if this `char` has the `Grapheme_Extend` property.
1074    ///
1075    /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
1076    /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
1077    /// [`DerivedCoreProperties.txt`].
1078    ///
1079    /// [uax29]: https://www.unicode.org/reports/tr29/
1080    /// [ucd]: https://www.unicode.org/reports/tr44/
1081    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1082    #[must_use]
1083    #[inline]
1084    #[ferrocene::prevalidated]
1085    pub(crate) fn is_grapheme_extended(self) -> bool {
1086        self > '\u{02FF}' && unicode::Grapheme_Extend(self)
1087    }
1088
1089    /// Returns `true` if this `char` has the `Case_Ignorable` property. This narrow-use property
1090    /// is used to implement context-dependent casing for the Greek letter sigma (uppercase Σ),
1091    /// which has two lowercase forms.
1092    ///
1093    /// `Case_Ignorable` is [described][D136] in Chapter 3 (Conformance) of the Unicode Core Specification,
1094    /// and specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`];
1095    /// see those resources for more information.
1096    ///
1097    /// [D136]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G63116
1098    /// [ucd]: https://www.unicode.org/reports/tr44/
1099    /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1100    #[must_use]
1101    #[inline]
1102    #[unstable(feature = "case_ignorable", issue = "154848")]
1103    pub fn is_case_ignorable(self) -> bool {
1104        if self.is_ascii() {
1105            matches!(self, '\'' | '.' | ':' | '^' | '`')
1106        } else {
1107            unicode::Case_Ignorable(self)
1108        }
1109    }
1110
1111    /// Returns `true` if this `char` has one of the general categories for numbers.
1112    ///
1113    /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
1114    /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
1115    /// Database][ucd] [`UnicodeData.txt`].
1116    ///
1117    /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
1118    /// If you want everything including characters with overlapping purposes then you might want to use
1119    /// a unicode or language-processing library that exposes the appropriate character properties instead
1120    /// of looking at the unicode categories.
1121    ///
1122    /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
1123    /// `is_ascii_digit` or `is_digit` instead.
1124    ///
1125    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1126    /// [ucd]: https://www.unicode.org/reports/tr44/
1127    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1128    ///
1129    /// # Examples
1130    ///
1131    /// Basic usage:
1132    ///
1133    /// ```
1134    /// assert!('٣'.is_numeric());
1135    /// assert!('7'.is_numeric());
1136    /// assert!('৬'.is_numeric());
1137    /// assert!('¾'.is_numeric());
1138    /// assert!('①'.is_numeric());
1139    /// assert!(!'K'.is_numeric());
1140    /// assert!(!'و'.is_numeric());
1141    /// assert!(!'藏'.is_numeric());
1142    /// assert!(!'三'.is_numeric());
1143    /// ```
1144    #[must_use]
1145    #[stable(feature = "rust1", since = "1.0.0")]
1146    #[inline]
1147    pub fn is_numeric(self) -> bool {
1148        match self {
1149            '0'..='9' => true,
1150            '\0'..='\u{B1}' => false,
1151            _ => unicode::N(self),
1152        }
1153    }
1154
1155    /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
1156    /// `char`s.
1157    ///
1158    /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
1159    ///
1160    /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
1161    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1162    ///
1163    /// [ucd]: https://www.unicode.org/reports/tr44/
1164    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1165    ///
1166    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1167    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1168    ///
1169    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1170    ///
1171    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1172    /// is independent of context and language. See [below](#notes-on-context-and-locale)
1173    /// for more information.
1174    ///
1175    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1176    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1177    ///
1178    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1179    ///
1180    /// # Examples
1181    ///
1182    /// As an iterator:
1183    ///
1184    /// ```
1185    /// for c in 'İ'.to_lowercase() {
1186    ///     print!("{c}");
1187    /// }
1188    /// println!();
1189    /// ```
1190    ///
1191    /// Using `println!` directly:
1192    ///
1193    /// ```
1194    /// println!("{}", 'İ'.to_lowercase());
1195    /// ```
1196    ///
1197    /// Both are equivalent to:
1198    ///
1199    /// ```
1200    /// println!("i\u{307}");
1201    /// ```
1202    ///
1203    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1204    ///
1205    /// ```
1206    /// assert_eq!('C'.to_lowercase().to_string(), "c");
1207    ///
1208    /// // Sometimes the result is more than one character:
1209    /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1210    ///
1211    /// // Characters that do not have both uppercase and lowercase
1212    /// // convert into themselves.
1213    /// assert_eq!('山'.to_lowercase().to_string(), "山");
1214    /// ```
1215    /// # Notes on context and locale
1216    ///
1217    /// As stated earlier, this method does not take into account language or context.
1218    /// Below is a non-exhaustive list of situations where this can be relevant.
1219    /// If you need to handle locale-depedendent casing in your code, consider using
1220    /// an external crate, like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1221    /// which is developed by Unicode.
1222    ///
1223    /// ## Greek sigma
1224    ///
1225    /// In Greek, the letter simga (uppercase Σ) has two lowercase forms:
1226    /// ς which is used only at the end of a word, and σ which is used everywhere else.
1227    /// `to_lowercase()` always uses the second form:
1228    ///
1229    /// ```
1230    /// assert_eq!('Σ'.to_lowercase().to_string(), "σ");
1231    /// ```
1232    ///
1233    /// ## Turkish and Azeri I/ı/İ/i
1234    ///
1235    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1236    ///
1237    /// * 'Dotless': I / ı, sometimes written ï
1238    /// * 'Dotted': İ / i
1239    ///
1240    /// Note that the uppercase undotted 'I' is the same as the Latin. Therefore:
1241    ///
1242    /// ```
1243    /// let lower_i = 'I'.to_lowercase().to_string();
1244    /// ```
1245    ///
1246    /// The value of `lower_i` here relies on the language of the text: if we're
1247    /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should
1248    /// be `"ı"`. `to_lowercase()` does not take this into account, and so:
1249    ///
1250    /// ```
1251    /// let lower_i = 'I'.to_lowercase().to_string();
1252    ///
1253    /// assert_eq!(lower_i, "i");
1254    /// ```
1255    ///
1256    /// holds across languages.
1257    #[must_use = "this returns the lowercased character as a new iterator, \
1258                  without modifying the original"]
1259    #[stable(feature = "rust1", since = "1.0.0")]
1260    #[inline]
1261    pub fn to_lowercase(self) -> ToLowercase {
1262        ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1263    }
1264
1265    /// Returns an iterator that yields the titlecase mapping of this `char` as one or more
1266    /// `char`s.
1267    ///
1268    /// This is usually, but not always, equivalent to the uppercase mapping
1269    /// returned by [`to_uppercase()`]. Prefer this method when seeking to capitalize
1270    /// Only The First Letter of a word, but use [`to_uppercase()`] for ALL CAPS.
1271    /// See [below](#difference-from-uppercase) for a thorough explanation
1272    /// of the difference between the two methods.
1273    ///
1274    /// If this `char` does not have a titlecase mapping, the iterator yields the same `char`.
1275    ///
1276    /// If this `char` has a one-to-one titlecase mapping given by the [Unicode Character
1277    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1278    ///
1279    /// [ucd]: https://www.unicode.org/reports/tr44/
1280    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1281    ///
1282    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1283    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1284    ///
1285    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1286    ///
1287    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1288    /// is independent of context and language. See [below](#note-on-locale)
1289    /// for more information.
1290    ///
1291    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1292    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1293    ///
1294    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1295    ///
1296    /// # Examples
1297    ///
1298    /// As an iterator:
1299    ///
1300    /// ```
1301    /// #![feature(titlecase)]
1302    /// for c in 'ß'.to_titlecase() {
1303    ///     print!("{c}");
1304    /// }
1305    /// println!();
1306    /// ```
1307    ///
1308    /// Using `println!` directly:
1309    ///
1310    /// ```
1311    /// #![feature(titlecase)]
1312    /// println!("{}", 'ß'.to_titlecase());
1313    /// ```
1314    ///
1315    /// Both are equivalent to:
1316    ///
1317    /// ```
1318    /// println!("Ss");
1319    /// ```
1320    ///
1321    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1322    ///
1323    /// ```
1324    /// #![feature(titlecase)]
1325    /// assert_eq!('c'.to_titlecase().to_string(), "C");
1326    /// assert_eq!('ა'.to_titlecase().to_string(), "ა");
1327    /// assert_eq!('dž'.to_titlecase().to_string(), "Dž");
1328    /// assert_eq!('ᾨ'.to_titlecase().to_string(), "ᾨ");
1329    ///
1330    /// // Sometimes the result is more than one character:
1331    /// assert_eq!('ß'.to_titlecase().to_string(), "Ss");
1332    ///
1333    /// // Characters that do not have separate cased forms
1334    /// // convert into themselves.
1335    /// assert_eq!('山'.to_titlecase().to_string(), "山");
1336    /// ```
1337    ///
1338    /// # Difference from uppercase
1339    ///
1340    /// Currently, there are three classes of characters where [`to_uppercase()`]
1341    /// and `to_titlecase()` give different results:
1342    ///
1343    /// ## Georgian script
1344    ///
1345    /// Each letter in the modern Georgian alphabet can be written in one of two forms:
1346    /// the typical lowercase-like "mkhedruli" form, and a variant uppercase-like "mtavruli"
1347    /// form. However, unlike uppercase in most cased scripts, mtavruli is not typically used
1348    /// to start sentences, denote proper nouns, or for any other purpose
1349    /// in running text. It is instead confined to titles and headings, which are written entirely
1350    /// in mtavruli. For this reason, [`to_uppercase()`] applied to a Georgian letter
1351    /// will return the mtavruli form, but `to_titlecase()` will return the mkhedruli form.
1352    ///
1353    /// ```
1354    /// #![feature(titlecase)]
1355    /// let ani = 'ა'; // First letter of the Georgian alphabet, in mkhedruli form
1356    ///
1357    /// // Titlecasing mkhedruli maps it to itself...
1358    /// assert_eq!(ani.to_titlecase().to_string(), ani.to_string());
1359    ///
1360    /// // but uppercasing it maps it to mtavruli
1361    /// assert_eq!(ani.to_uppercase().to_string(), "Ა");
1362    /// ```
1363    ///
1364    /// ## Compatibility digraphs for Latin-alphabet Serbo-Croatian
1365    ///
1366    /// The standard Latin alphabet for the Serbo-Croatian language
1367    /// (Bosnian, Croatian, Montenegrin, and Serbian) contains
1368    /// three digraphs: Dž, Lj, and Nj. These are usually represented as
1369    /// two characters. However, for compatibility with older character sets,
1370    /// Unicode includes single-character versions of these digraphs.
1371    /// Each has a uppercase, titlecase, and lowercase version:
1372    ///
1373    /// - `'DŽ'`, `'Dž'`, `'dž'`
1374    /// - `'LJ'`, `'Lj'`, `'lj'`
1375    /// - `'NJ'`, `'Nj'`, `'nj'`
1376    ///
1377    /// Unicode additionally encodes a casing triad for the Dz digraph
1378    /// without the caron: `'DZ'`, `'Dz'`, `'dz'`.
1379    ///
1380    /// ## Iota-subscritped Greek vowels
1381    ///
1382    /// In ancient Greek, the long vowels alpha (α), eta (η), and omega (ω)
1383    /// were sometimes followed by an iota (ι), forming a diphthong. Over time,
1384    /// the diphthong pronunciation was slowly lost, with the iota becoming mute.
1385    /// Eventually, the ι disappeared from the spelling as well.
1386    /// However, there remains a need to represent ancient texts faithfully.
1387    ///
1388    /// Modern editions of ancient Greek texts commonly use a reduced-sized
1389    /// ι symbol to denote mute iotas, while distinguishing them from ιs
1390    /// which continued to affect pronunciation. The exact standard differs
1391    /// between different publications. Some render the mute ι below its associated
1392    /// vowel (subscript), while others place it to the right of said vowel (adscript).
1393    /// The interaction of mute ι symbols with casing also varies.
1394    ///
1395    /// The Unicode Standard, for its default casing rules, chose to make lowercase
1396    /// Greek vowels with iota subscipt (e.g. `'ᾠ'`) titlecase to the uppercase vowel
1397    /// with iota subscript (`'ᾨ'`) but uppercase to the uppercase vowel followed by
1398    /// full-size uppercase iota (`"ὨΙ"`). This is just one convention among many
1399    /// in common use, but it is the one Unicode settled on,
1400    /// so it is what this method does also.
1401    ///
1402    /// # Note on locale
1403    ///
1404    /// As stated above, this method is locale-insensitive.
1405    /// If you need locale support, consider using an external crate,
1406    /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1407    /// which is developed by Unicode. A description of a common
1408    /// locale-dependent casing issue follows:
1409    ///
1410    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1411    ///
1412    /// * 'Dotless': I / ı, sometimes written ï
1413    /// * 'Dotted': İ / i
1414    ///
1415    /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1416    ///
1417    /// ```
1418    /// #![feature(titlecase)]
1419    /// let upper_i = 'i'.to_titlecase().to_string();
1420    /// ```
1421    ///
1422    /// The value of `upper_i` here relies on the language of the text: if we're
1423    /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1424    /// be `"İ"`. `to_titlecase()` does not take this into account, and so:
1425    ///
1426    /// ```
1427    /// #![feature(titlecase)]
1428    /// let upper_i = 'i'.to_titlecase().to_string();
1429    ///
1430    /// assert_eq!(upper_i, "I");
1431    /// ```
1432    ///
1433    /// holds across languages.
1434    ///
1435    /// [`to_uppercase()`]: Self::to_uppercase()
1436    #[must_use = "this returns the titlecased character as a new iterator, \
1437                  without modifying the original"]
1438    #[unstable(feature = "titlecase", issue = "153892")]
1439    #[inline]
1440    pub fn to_titlecase(self) -> ToTitlecase {
1441        ToTitlecase(CaseMappingIter::new(conversions::to_title(self)))
1442    }
1443
1444    /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1445    /// `char`s.
1446    ///
1447    /// Prefer this method when converting a word into ALL CAPS, but consider [`to_titlecase()`]
1448    /// instead if you seek to capitalize Only The First Letter. See that method's documentation
1449    /// for more information on the difference between the two.
1450    ///
1451    /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1452    ///
1453    /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1454    /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1455    ///
1456    /// [ucd]: https://www.unicode.org/reports/tr44/
1457    /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1458    ///
1459    /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1460    /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1461    ///
1462    /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1463    ///
1464    /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1465    /// is independent of context and language. See [below](#note-on-locale)
1466    /// for more information.
1467    ///
1468    /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1469    /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1470    ///
1471    /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1472    ///
1473    /// # Examples
1474    ///
1475    /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase.
1476    ///
1477    /// As an iterator:
1478    ///
1479    /// ```
1480    /// for c in 'ſt'.to_uppercase() {
1481    ///     print!("{c}");
1482    /// }
1483    /// println!();
1484    /// ```
1485    ///
1486    /// Using `println!` directly:
1487    ///
1488    /// ```
1489    /// println!("{}", 'ſt'.to_uppercase());
1490    /// ```
1491    ///
1492    /// Both are equivalent to:
1493    ///
1494    /// ```
1495    /// println!("ST");
1496    /// ```
1497    ///
1498    /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1499    ///
1500    /// ```
1501    /// assert_eq!('c'.to_uppercase().to_string(), "C");
1502    /// assert_eq!('ა'.to_uppercase().to_string(), "Ა");
1503    /// assert_eq!('dž'.to_uppercase().to_string(), "DŽ");
1504    ///
1505    /// // Sometimes the result is more than one character:
1506    /// assert_eq!('ſt'.to_uppercase().to_string(), "ST");
1507    /// assert_eq!('ᾨ'.to_uppercase().to_string(), "ὨΙ");
1508    ///
1509    /// // Characters that do not have both uppercase and lowercase
1510    /// // convert into themselves.
1511    /// assert_eq!('山'.to_uppercase().to_string(), "山");
1512    /// ```
1513    ///
1514    /// # Note on locale
1515    ///
1516    /// As stated above, this method is locale-insensitive.
1517    /// If you need locale support, consider using an external crate,
1518    /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1519    /// which is developed by Unicode. A description of a common
1520    /// locale-dependent casing issue follows:
1521    ///
1522    /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1523    ///
1524    /// * 'Dotless': I / ı, sometimes written ï
1525    /// * 'Dotted': İ / i
1526    ///
1527    /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1528    ///
1529    /// ```
1530    /// let upper_i = 'i'.to_uppercase().to_string();
1531    /// ```
1532    ///
1533    /// The value of `upper_i` here relies on the language of the text: if we're
1534    /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1535    /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1536    ///
1537    /// ```
1538    /// let upper_i = 'i'.to_uppercase().to_string();
1539    ///
1540    /// assert_eq!(upper_i, "I");
1541    /// ```
1542    ///
1543    /// holds across languages.
1544    ///
1545    /// [`to_titlecase()`]: Self::to_titlecase()
1546    #[must_use = "this returns the uppercased character as a new iterator, \
1547                  without modifying the original"]
1548    #[stable(feature = "rust1", since = "1.0.0")]
1549    #[inline]
1550    pub fn to_uppercase(self) -> ToUppercase {
1551        ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1552    }
1553
1554    /// Checks if the value is within the ASCII range.
1555    ///
1556    /// # Examples
1557    ///
1558    /// ```
1559    /// let ascii = 'a';
1560    /// let non_ascii = '❤';
1561    ///
1562    /// assert!(ascii.is_ascii());
1563    /// assert!(!non_ascii.is_ascii());
1564    /// ```
1565    #[must_use]
1566    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1567    #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1568    #[rustc_diagnostic_item = "char_is_ascii"]
1569    #[inline]
1570    #[ferrocene::prevalidated]
1571    pub const fn is_ascii(&self) -> bool {
1572        *self as u32 <= 0x7F
1573    }
1574
1575    /// Returns `Some` if the value is within the ASCII range,
1576    /// or `None` if it's not.
1577    ///
1578    /// This is preferred to [`Self::is_ascii`] when you're passing the value
1579    /// along to something else that can take [`ascii::Char`] rather than
1580    /// needing to check again for itself whether the value is in ASCII.
1581    #[must_use]
1582    #[unstable(feature = "ascii_char", issue = "110998")]
1583    #[inline]
1584    #[ferrocene::prevalidated]
1585    pub const fn as_ascii(&self) -> Option<ascii::Char> {
1586        if self.is_ascii() {
1587            // SAFETY: Just checked that this is ASCII.
1588            Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
1589        } else {
1590            None
1591        }
1592    }
1593
1594    /// Converts this char into an [ASCII character](`ascii::Char`), without
1595    /// checking whether it is valid.
1596    ///
1597    /// # Safety
1598    ///
1599    /// This char must be within the ASCII range, or else this is UB.
1600    #[must_use]
1601    #[unstable(feature = "ascii_char", issue = "110998")]
1602    #[inline]
1603    pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1604        assert_unsafe_precondition!(
1605            check_library_ub,
1606            "as_ascii_unchecked requires that the char is valid ASCII",
1607            (it: &char = self) => it.is_ascii()
1608        );
1609
1610        // SAFETY: the caller promised that this char is ASCII.
1611        unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1612    }
1613
1614    /// Makes a copy of the value in its ASCII upper case equivalent.
1615    ///
1616    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1617    /// but non-ASCII letters are unchanged.
1618    ///
1619    /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1620    ///
1621    /// To uppercase ASCII characters in addition to non-ASCII characters, use
1622    /// [`to_uppercase()`].
1623    ///
1624    /// # Examples
1625    ///
1626    /// ```
1627    /// let ascii = 'a';
1628    /// let non_ascii = '❤';
1629    ///
1630    /// assert_eq!('A', ascii.to_ascii_uppercase());
1631    /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1632    /// ```
1633    ///
1634    /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1635    /// [`to_uppercase()`]: #method.to_uppercase
1636    #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1637    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1638    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1639    #[inline]
1640    pub const fn to_ascii_uppercase(&self) -> char {
1641        if self.is_ascii_lowercase() {
1642            (*self as u8).ascii_change_case_unchecked() as char
1643        } else {
1644            *self
1645        }
1646    }
1647
1648    /// Makes a copy of the value in its ASCII lower case equivalent.
1649    ///
1650    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1651    /// but non-ASCII letters are unchanged.
1652    ///
1653    /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1654    ///
1655    /// To lowercase ASCII characters in addition to non-ASCII characters, use
1656    /// [`to_lowercase()`].
1657    ///
1658    /// # Examples
1659    ///
1660    /// ```
1661    /// let ascii = 'A';
1662    /// let non_ascii = '❤';
1663    ///
1664    /// assert_eq!('a', ascii.to_ascii_lowercase());
1665    /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1666    /// ```
1667    ///
1668    /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1669    /// [`to_lowercase()`]: #method.to_lowercase
1670    #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1671    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1672    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1673    #[inline]
1674    pub const fn to_ascii_lowercase(&self) -> char {
1675        if self.is_ascii_uppercase() {
1676            (*self as u8).ascii_change_case_unchecked() as char
1677        } else {
1678            *self
1679        }
1680    }
1681
1682    /// Checks that two values are an ASCII case-insensitive match.
1683    ///
1684    /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1685    ///
1686    /// # Examples
1687    ///
1688    /// ```
1689    /// let upper_a = 'A';
1690    /// let lower_a = 'a';
1691    /// let lower_z = 'z';
1692    ///
1693    /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1694    /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1695    /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1696    /// ```
1697    ///
1698    /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1699    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1700    #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1701    #[inline]
1702    pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1703        self.to_ascii_lowercase() == other.to_ascii_lowercase()
1704    }
1705
1706    /// Converts this type to its ASCII upper case equivalent in-place.
1707    ///
1708    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1709    /// but non-ASCII letters are unchanged.
1710    ///
1711    /// To return a new uppercased value without modifying the existing one, use
1712    /// [`to_ascii_uppercase()`].
1713    ///
1714    /// # Examples
1715    ///
1716    /// ```
1717    /// let mut ascii = 'a';
1718    ///
1719    /// ascii.make_ascii_uppercase();
1720    ///
1721    /// assert_eq!('A', ascii);
1722    /// ```
1723    ///
1724    /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1725    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1726    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1727    #[inline]
1728    pub const fn make_ascii_uppercase(&mut self) {
1729        *self = self.to_ascii_uppercase();
1730    }
1731
1732    /// Converts this type to its ASCII lower case equivalent in-place.
1733    ///
1734    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1735    /// but non-ASCII letters are unchanged.
1736    ///
1737    /// To return a new lowercased value without modifying the existing one, use
1738    /// [`to_ascii_lowercase()`].
1739    ///
1740    /// # Examples
1741    ///
1742    /// ```
1743    /// let mut ascii = 'A';
1744    ///
1745    /// ascii.make_ascii_lowercase();
1746    ///
1747    /// assert_eq!('a', ascii);
1748    /// ```
1749    ///
1750    /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1751    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1752    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1753    #[inline]
1754    pub const fn make_ascii_lowercase(&mut self) {
1755        *self = self.to_ascii_lowercase();
1756    }
1757
1758    /// Checks if the value is an ASCII alphabetic character:
1759    ///
1760    /// - U+0041 'A' ..= U+005A 'Z', or
1761    /// - U+0061 'a' ..= U+007A 'z'.
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_alphabetic());
1777    /// assert!(uppercase_g.is_ascii_alphabetic());
1778    /// assert!(a.is_ascii_alphabetic());
1779    /// assert!(g.is_ascii_alphabetic());
1780    /// assert!(!zero.is_ascii_alphabetic());
1781    /// assert!(!percent.is_ascii_alphabetic());
1782    /// assert!(!space.is_ascii_alphabetic());
1783    /// assert!(!lf.is_ascii_alphabetic());
1784    /// assert!(!esc.is_ascii_alphabetic());
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_alphabetic(&self) -> bool {
1791        matches!(*self, 'a'..='z' | 'A'..='Z')
1792    }
1793
1794    /// Checks if the value is an ASCII uppercase character:
1795    /// U+0041 'A' ..= U+005A 'Z'.
1796    ///
1797    /// # Examples
1798    ///
1799    /// ```
1800    /// let uppercase_a = 'A';
1801    /// let uppercase_g = 'G';
1802    /// let a = 'a';
1803    /// let g = 'g';
1804    /// let zero = '0';
1805    /// let percent = '%';
1806    /// let space = ' ';
1807    /// let lf = '\n';
1808    /// let esc = '\x1b';
1809    ///
1810    /// assert!(uppercase_a.is_ascii_uppercase());
1811    /// assert!(uppercase_g.is_ascii_uppercase());
1812    /// assert!(!a.is_ascii_uppercase());
1813    /// assert!(!g.is_ascii_uppercase());
1814    /// assert!(!zero.is_ascii_uppercase());
1815    /// assert!(!percent.is_ascii_uppercase());
1816    /// assert!(!space.is_ascii_uppercase());
1817    /// assert!(!lf.is_ascii_uppercase());
1818    /// assert!(!esc.is_ascii_uppercase());
1819    /// ```
1820    #[must_use]
1821    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1822    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1823    #[inline]
1824    pub const fn is_ascii_uppercase(&self) -> bool {
1825        matches!(*self, 'A'..='Z')
1826    }
1827
1828    /// Checks if the value is an ASCII lowercase character:
1829    /// U+0061 'a' ..= U+007A 'z'.
1830    ///
1831    /// # Examples
1832    ///
1833    /// ```
1834    /// let uppercase_a = 'A';
1835    /// let uppercase_g = 'G';
1836    /// let a = 'a';
1837    /// let g = 'g';
1838    /// let zero = '0';
1839    /// let percent = '%';
1840    /// let space = ' ';
1841    /// let lf = '\n';
1842    /// let esc = '\x1b';
1843    ///
1844    /// assert!(!uppercase_a.is_ascii_lowercase());
1845    /// assert!(!uppercase_g.is_ascii_lowercase());
1846    /// assert!(a.is_ascii_lowercase());
1847    /// assert!(g.is_ascii_lowercase());
1848    /// assert!(!zero.is_ascii_lowercase());
1849    /// assert!(!percent.is_ascii_lowercase());
1850    /// assert!(!space.is_ascii_lowercase());
1851    /// assert!(!lf.is_ascii_lowercase());
1852    /// assert!(!esc.is_ascii_lowercase());
1853    /// ```
1854    #[must_use]
1855    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1856    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1857    #[inline]
1858    pub const fn is_ascii_lowercase(&self) -> bool {
1859        matches!(*self, 'a'..='z')
1860    }
1861
1862    /// Checks if the value is an ASCII alphanumeric character:
1863    ///
1864    /// - U+0041 'A' ..= U+005A 'Z', or
1865    /// - U+0061 'a' ..= U+007A 'z', or
1866    /// - U+0030 '0' ..= U+0039 '9'.
1867    ///
1868    /// # Examples
1869    ///
1870    /// ```
1871    /// let uppercase_a = 'A';
1872    /// let uppercase_g = 'G';
1873    /// let a = 'a';
1874    /// let g = 'g';
1875    /// let zero = '0';
1876    /// let percent = '%';
1877    /// let space = ' ';
1878    /// let lf = '\n';
1879    /// let esc = '\x1b';
1880    ///
1881    /// assert!(uppercase_a.is_ascii_alphanumeric());
1882    /// assert!(uppercase_g.is_ascii_alphanumeric());
1883    /// assert!(a.is_ascii_alphanumeric());
1884    /// assert!(g.is_ascii_alphanumeric());
1885    /// assert!(zero.is_ascii_alphanumeric());
1886    /// assert!(!percent.is_ascii_alphanumeric());
1887    /// assert!(!space.is_ascii_alphanumeric());
1888    /// assert!(!lf.is_ascii_alphanumeric());
1889    /// assert!(!esc.is_ascii_alphanumeric());
1890    /// ```
1891    #[must_use]
1892    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1893    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1894    #[inline]
1895    pub const fn is_ascii_alphanumeric(&self) -> bool {
1896        matches!(*self, '0'..='9') | matches!(*self, 'A'..='Z') | matches!(*self, 'a'..='z')
1897    }
1898
1899    /// Checks if the value is an ASCII decimal digit:
1900    /// U+0030 '0' ..= U+0039 '9'.
1901    ///
1902    /// # Examples
1903    ///
1904    /// ```
1905    /// let uppercase_a = 'A';
1906    /// let uppercase_g = 'G';
1907    /// let a = 'a';
1908    /// let g = 'g';
1909    /// let zero = '0';
1910    /// let percent = '%';
1911    /// let space = ' ';
1912    /// let lf = '\n';
1913    /// let esc = '\x1b';
1914    ///
1915    /// assert!(!uppercase_a.is_ascii_digit());
1916    /// assert!(!uppercase_g.is_ascii_digit());
1917    /// assert!(!a.is_ascii_digit());
1918    /// assert!(!g.is_ascii_digit());
1919    /// assert!(zero.is_ascii_digit());
1920    /// assert!(!percent.is_ascii_digit());
1921    /// assert!(!space.is_ascii_digit());
1922    /// assert!(!lf.is_ascii_digit());
1923    /// assert!(!esc.is_ascii_digit());
1924    /// ```
1925    #[must_use]
1926    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1927    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1928    #[inline]
1929    pub const fn is_ascii_digit(&self) -> bool {
1930        matches!(*self, '0'..='9')
1931    }
1932
1933    /// Checks if the value is an ASCII octal digit:
1934    /// U+0030 '0' ..= U+0037 '7'.
1935    ///
1936    /// # Examples
1937    ///
1938    /// ```
1939    /// #![feature(is_ascii_octdigit)]
1940    ///
1941    /// let uppercase_a = 'A';
1942    /// let a = 'a';
1943    /// let zero = '0';
1944    /// let seven = '7';
1945    /// let nine = '9';
1946    /// let percent = '%';
1947    /// let lf = '\n';
1948    ///
1949    /// assert!(!uppercase_a.is_ascii_octdigit());
1950    /// assert!(!a.is_ascii_octdigit());
1951    /// assert!(zero.is_ascii_octdigit());
1952    /// assert!(seven.is_ascii_octdigit());
1953    /// assert!(!nine.is_ascii_octdigit());
1954    /// assert!(!percent.is_ascii_octdigit());
1955    /// assert!(!lf.is_ascii_octdigit());
1956    /// ```
1957    #[must_use]
1958    #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
1959    #[inline]
1960    pub const fn is_ascii_octdigit(&self) -> bool {
1961        matches!(*self, '0'..='7')
1962    }
1963
1964    /// Checks if the value is an ASCII hexadecimal digit:
1965    ///
1966    /// - U+0030 '0' ..= U+0039 '9', or
1967    /// - U+0041 'A' ..= U+0046 'F', or
1968    /// - U+0061 'a' ..= U+0066 'f'.
1969    ///
1970    /// # Examples
1971    ///
1972    /// ```
1973    /// let uppercase_a = 'A';
1974    /// let uppercase_g = 'G';
1975    /// let a = 'a';
1976    /// let g = 'g';
1977    /// let zero = '0';
1978    /// let percent = '%';
1979    /// let space = ' ';
1980    /// let lf = '\n';
1981    /// let esc = '\x1b';
1982    ///
1983    /// assert!(uppercase_a.is_ascii_hexdigit());
1984    /// assert!(!uppercase_g.is_ascii_hexdigit());
1985    /// assert!(a.is_ascii_hexdigit());
1986    /// assert!(!g.is_ascii_hexdigit());
1987    /// assert!(zero.is_ascii_hexdigit());
1988    /// assert!(!percent.is_ascii_hexdigit());
1989    /// assert!(!space.is_ascii_hexdigit());
1990    /// assert!(!lf.is_ascii_hexdigit());
1991    /// assert!(!esc.is_ascii_hexdigit());
1992    /// ```
1993    #[must_use]
1994    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1995    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1996    #[inline]
1997    pub const fn is_ascii_hexdigit(&self) -> bool {
1998        matches!(*self, '0'..='9') | matches!(*self, 'A'..='F') | matches!(*self, 'a'..='f')
1999    }
2000
2001    /// Checks if the value is an ASCII punctuation or symbol character
2002    /// (i.e. not alphanumeric, whitespace, or control):
2003    ///
2004    /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
2005    /// - U+003A ..= U+0040 `: ; < = > ? @`, or
2006    /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
2007    /// - U+007B ..= U+007E `{ | } ~`
2008    ///
2009    /// # Examples
2010    ///
2011    /// ```
2012    /// let uppercase_a = 'A';
2013    /// let uppercase_g = 'G';
2014    /// let a = 'a';
2015    /// let g = 'g';
2016    /// let zero = '0';
2017    /// let percent = '%';
2018    /// let space = ' ';
2019    /// let lf = '\n';
2020    /// let esc = '\x1b';
2021    ///
2022    /// assert!(!uppercase_a.is_ascii_punctuation());
2023    /// assert!(!uppercase_g.is_ascii_punctuation());
2024    /// assert!(!a.is_ascii_punctuation());
2025    /// assert!(!g.is_ascii_punctuation());
2026    /// assert!(!zero.is_ascii_punctuation());
2027    /// assert!(percent.is_ascii_punctuation());
2028    /// assert!(!space.is_ascii_punctuation());
2029    /// assert!(!lf.is_ascii_punctuation());
2030    /// assert!(!esc.is_ascii_punctuation());
2031    /// ```
2032    #[must_use]
2033    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2034    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2035    #[inline]
2036    pub const fn is_ascii_punctuation(&self) -> bool {
2037        matches!(*self, '!'..='/')
2038            | matches!(*self, ':'..='@')
2039            | matches!(*self, '['..='`')
2040            | matches!(*self, '{'..='~')
2041    }
2042
2043    /// Checks if the value is an ASCII graphic character
2044    /// (i.e. not whitespace or control):
2045    /// U+0021 '!' ..= U+007E '~'.
2046    ///
2047    /// # Examples
2048    ///
2049    /// ```
2050    /// let uppercase_a = 'A';
2051    /// let uppercase_g = 'G';
2052    /// let a = 'a';
2053    /// let g = 'g';
2054    /// let zero = '0';
2055    /// let percent = '%';
2056    /// let space = ' ';
2057    /// let lf = '\n';
2058    /// let esc = '\x1b';
2059    ///
2060    /// assert!(uppercase_a.is_ascii_graphic());
2061    /// assert!(uppercase_g.is_ascii_graphic());
2062    /// assert!(a.is_ascii_graphic());
2063    /// assert!(g.is_ascii_graphic());
2064    /// assert!(zero.is_ascii_graphic());
2065    /// assert!(percent.is_ascii_graphic());
2066    /// assert!(!space.is_ascii_graphic());
2067    /// assert!(!lf.is_ascii_graphic());
2068    /// assert!(!esc.is_ascii_graphic());
2069    /// ```
2070    #[must_use]
2071    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2072    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2073    #[inline]
2074    pub const fn is_ascii_graphic(&self) -> bool {
2075        matches!(*self, '!'..='~')
2076    }
2077
2078    /// Checks if the value is an ASCII whitespace character:
2079    /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2080    /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2081    ///
2082    /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
2083    /// `c.is_ascii_whitespace()` is **not** equivalent to `c.is_ascii() && c.is_whitespace()`.
2084    ///
2085    /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2086    /// whitespace][infra-aw]. There are several other definitions in
2087    /// wide use. For instance, [the POSIX locale][pct] includes
2088    /// U+000B VERTICAL TAB as well as all the above characters,
2089    /// but—from the very same specification—[the default rule for
2090    /// "field splitting" in the Bourne shell][bfs] considers *only*
2091    /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2092    ///
2093    /// If you are writing a program that will process an existing
2094    /// file format, check what that format's definition of whitespace is
2095    /// before using this function.
2096    ///
2097    /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2098    /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
2099    /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
2100    ///
2101    /// # Examples
2102    ///
2103    /// ```
2104    /// let uppercase_a = 'A';
2105    /// let uppercase_g = 'G';
2106    /// let a = 'a';
2107    /// let g = 'g';
2108    /// let zero = '0';
2109    /// let percent = '%';
2110    /// let space = ' ';
2111    /// let lf = '\n';
2112    /// let esc = '\x1b';
2113    ///
2114    /// assert!(!uppercase_a.is_ascii_whitespace());
2115    /// assert!(!uppercase_g.is_ascii_whitespace());
2116    /// assert!(!a.is_ascii_whitespace());
2117    /// assert!(!g.is_ascii_whitespace());
2118    /// assert!(!zero.is_ascii_whitespace());
2119    /// assert!(!percent.is_ascii_whitespace());
2120    /// assert!(space.is_ascii_whitespace());
2121    /// assert!(lf.is_ascii_whitespace());
2122    /// assert!(!esc.is_ascii_whitespace());
2123    /// ```
2124    #[must_use]
2125    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2126    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2127    #[inline]
2128    #[ferrocene::prevalidated]
2129    pub const fn is_ascii_whitespace(&self) -> bool {
2130        matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
2131    }
2132
2133    /// Checks if the value is an ASCII control character:
2134    /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
2135    /// Note that most ASCII whitespace characters are control
2136    /// characters, but SPACE is not.
2137    ///
2138    /// # Examples
2139    ///
2140    /// ```
2141    /// let uppercase_a = 'A';
2142    /// let uppercase_g = 'G';
2143    /// let a = 'a';
2144    /// let g = 'g';
2145    /// let zero = '0';
2146    /// let percent = '%';
2147    /// let space = ' ';
2148    /// let lf = '\n';
2149    /// let esc = '\x1b';
2150    ///
2151    /// assert!(!uppercase_a.is_ascii_control());
2152    /// assert!(!uppercase_g.is_ascii_control());
2153    /// assert!(!a.is_ascii_control());
2154    /// assert!(!g.is_ascii_control());
2155    /// assert!(!zero.is_ascii_control());
2156    /// assert!(!percent.is_ascii_control());
2157    /// assert!(!space.is_ascii_control());
2158    /// assert!(lf.is_ascii_control());
2159    /// assert!(esc.is_ascii_control());
2160    /// ```
2161    #[must_use]
2162    #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2163    #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2164    #[inline]
2165    pub const fn is_ascii_control(&self) -> bool {
2166        matches!(*self, '\0'..='\x1F' | '\x7F')
2167    }
2168}
2169
2170#[ferrocene::prevalidated]
2171pub(crate) struct EscapeDebugExtArgs {
2172    /// Escape Extended Grapheme codepoints?
2173    pub(crate) escape_grapheme_extended: bool,
2174
2175    /// Escape single quotes?
2176    pub(crate) escape_single_quote: bool,
2177
2178    /// Escape double quotes?
2179    pub(crate) escape_double_quote: bool,
2180}
2181
2182impl EscapeDebugExtArgs {
2183    pub(crate) const ESCAPE_ALL: Self = Self {
2184        escape_grapheme_extended: true,
2185        escape_single_quote: true,
2186        escape_double_quote: true,
2187    };
2188}
2189
2190#[inline]
2191#[must_use]
2192#[ferrocene::prevalidated]
2193const fn len_utf8(code: u32) -> usize {
2194    match code {
2195        ..MAX_ONE_B => 1,
2196        ..MAX_TWO_B => 2,
2197        ..MAX_THREE_B => 3,
2198        _ => 4,
2199    }
2200}
2201
2202#[inline]
2203#[must_use]
2204const fn len_utf16(code: u32) -> usize {
2205    if (code & 0xFFFF) == code { 1 } else { 2 }
2206}
2207
2208/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
2209/// and then returns the subslice of the buffer that contains the encoded character.
2210///
2211/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2212/// (Creating a `char` in the surrogate range is UB.)
2213/// The result is valid [generalized UTF-8] but not valid UTF-8.
2214///
2215/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2216///
2217/// # Panics
2218///
2219/// Panics if the buffer is not large enough.
2220/// A buffer of length four is large enough to encode any `char`.
2221#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2222#[doc(hidden)]
2223#[inline]
2224#[ferrocene::prevalidated]
2225pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
2226    let len = len_utf8(code);
2227    if dst.len() < len {
2228        const_panic!(
2229            "encode_utf8: buffer does not have enough bytes to encode code point",
2230            "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2231            code: u32 = code,
2232            len: usize = len,
2233            dst_len: usize = dst.len(),
2234        );
2235    }
2236
2237    // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint.
2238    unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) };
2239
2240    // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2241    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2242}
2243
2244/// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`.
2245///
2246/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2247/// (Creating a `char` in the surrogate range is UB.)
2248/// The result is valid [generalized UTF-8] but not valid UTF-8.
2249///
2250/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2251///
2252/// # Safety
2253///
2254/// The behavior is undefined if the buffer pointed to by `dst` is not
2255/// large enough to hold the encoded codepoint. A buffer of length four
2256/// is large enough to encode any `char`.
2257///
2258/// For a safe version of this function, see the [`encode_utf8_raw`] function.
2259#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2260#[doc(hidden)]
2261#[inline]
2262#[ferrocene::prevalidated]
2263pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
2264    let len = len_utf8(code);
2265    // SAFETY: The caller must guarantee that the buffer pointed to by `dst`
2266    // is at least `len` bytes long.
2267    unsafe {
2268        if len == 1 {
2269            *dst = code as u8;
2270            return;
2271        }
2272
2273        let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
2274        let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
2275        let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
2276        let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
2277
2278        if len == 2 {
2279            *dst = last2 | TAG_TWO_B;
2280            *dst.add(1) = last1;
2281            return;
2282        }
2283
2284        if len == 3 {
2285            *dst = last3 | TAG_THREE_B;
2286            *dst.add(1) = last2;
2287            *dst.add(2) = last1;
2288            return;
2289        }
2290
2291        *dst = last4;
2292        *dst.add(1) = last3;
2293        *dst.add(2) = last2;
2294        *dst.add(3) = last1;
2295    }
2296}
2297
2298/// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer,
2299/// and then returns the subslice of the buffer that contains the encoded character.
2300///
2301/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
2302/// (Creating a `char` in the surrogate range is UB.)
2303///
2304/// # Panics
2305///
2306/// Panics if the buffer is not large enough.
2307/// A buffer of length 2 is large enough to encode any `char`.
2308#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2309#[doc(hidden)]
2310#[inline]
2311pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
2312    let len = len_utf16(code);
2313    match (len, &mut *dst) {
2314        (1, [a, ..]) => {
2315            *a = code as u16;
2316        }
2317        (2, [a, b, ..]) => {
2318            code -= 0x1_0000;
2319            *a = (code >> 10) as u16 | 0xD800;
2320            *b = (code & 0x3FF) as u16 | 0xDC00;
2321        }
2322        _ => {
2323            const_panic!(
2324                "encode_utf16: buffer does not have enough bytes to encode code point",
2325                "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2326                code: u32 = code,
2327                len: usize = len,
2328                dst_len: usize = dst.len(),
2329            )
2330        }
2331    };
2332    // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2333    unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2334}