Skip to main content

core/char/
methods.rs

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