]> git.lizzy.rs Git - rust.git/blob - library/core/src/char/methods.rs
Rollup merge of #101445 - TaKO8Ki:suggest-introducing-explicit-lifetime, r=oli-obk
[rust.git] / library / core / src / char / methods.rs
1 //! impl char {}
2
3 use crate::slice;
4 use crate::str::from_utf8_unchecked_mut;
5 use crate::unicode::printable::is_printable;
6 use crate::unicode::{self, conversions};
7
8 use super::*;
9
10 impl char {
11     /// The highest valid code point a `char` can have, `'\u{10FFFF}'`.
12     ///
13     /// # Examples
14     ///
15     /// ```
16     /// # fn something_which_returns_char() -> char { 'a' }
17     /// let c: char = something_which_returns_char();
18     /// assert!(c <= char::MAX);
19     ///
20     /// let value_at_max = char::MAX as u32;
21     /// assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
22     /// assert_eq!(char::from_u32(value_at_max + 1), None);
23     /// ```
24     #[stable(feature = "assoc_char_consts", since = "1.52.0")]
25     pub const MAX: char = '\u{10ffff}';
26
27     /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
28     /// decoding error.
29     ///
30     /// It can occur, for example, when giving ill-formed UTF-8 bytes to
31     /// [`String::from_utf8_lossy`](../std/string/struct.String.html#method.from_utf8_lossy).
32     #[stable(feature = "assoc_char_consts", since = "1.52.0")]
33     pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
34
35     /// The version of [Unicode](https://www.unicode.org/) that the Unicode parts of
36     /// `char` and `str` methods are based on.
37     ///
38     /// New versions of Unicode are released regularly and subsequently all methods
39     /// in the standard library depending on Unicode are updated. Therefore the
40     /// behavior of some `char` and `str` methods and the value of this constant
41     /// changes over time. This is *not* considered to be a breaking change.
42     ///
43     /// The version numbering scheme is explained in
44     /// [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).
45     #[stable(feature = "assoc_char_consts", since = "1.52.0")]
46     pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION;
47
48     /// Creates an iterator over the UTF-16 encoded code points in `iter`,
49     /// returning unpaired surrogates as `Err`s.
50     ///
51     /// # Examples
52     ///
53     /// Basic usage:
54     ///
55     /// ```
56     /// use std::char::decode_utf16;
57     ///
58     /// // 𝄞mus<invalid>ic<invalid>
59     /// let v = [
60     ///     0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
61     /// ];
62     ///
63     /// assert_eq!(
64     ///     decode_utf16(v)
65     ///         .map(|r| r.map_err(|e| e.unpaired_surrogate()))
66     ///         .collect::<Vec<_>>(),
67     ///     vec![
68     ///         Ok('𝄞'),
69     ///         Ok('m'), Ok('u'), Ok('s'),
70     ///         Err(0xDD1E),
71     ///         Ok('i'), Ok('c'),
72     ///         Err(0xD834)
73     ///     ]
74     /// );
75     /// ```
76     ///
77     /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
78     ///
79     /// ```
80     /// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
81     ///
82     /// // 𝄞mus<invalid>ic<invalid>
83     /// let v = [
84     ///     0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
85     /// ];
86     ///
87     /// assert_eq!(
88     ///     decode_utf16(v)
89     ///        .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
90     ///        .collect::<String>(),
91     ///     "𝄞mus�ic�"
92     /// );
93     /// ```
94     #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
95     #[inline]
96     pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
97         super::decode::decode_utf16(iter)
98     }
99
100     /// Converts a `u32` to a `char`.
101     ///
102     /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
103     /// [`as`](../std/keyword.as.html):
104     ///
105     /// ```
106     /// let c = '💯';
107     /// let i = c as u32;
108     ///
109     /// assert_eq!(128175, i);
110     /// ```
111     ///
112     /// However, the reverse is not true: not all valid [`u32`]s are valid
113     /// `char`s. `from_u32()` will return `None` if the input is not a valid value
114     /// for a `char`.
115     ///
116     /// For an unsafe version of this function which ignores these checks, see
117     /// [`from_u32_unchecked`].
118     ///
119     /// [`from_u32_unchecked`]: #method.from_u32_unchecked
120     ///
121     /// # Examples
122     ///
123     /// Basic usage:
124     ///
125     /// ```
126     /// use std::char;
127     ///
128     /// let c = char::from_u32(0x2764);
129     ///
130     /// assert_eq!(Some('❤'), c);
131     /// ```
132     ///
133     /// Returning `None` when the input is not a valid `char`:
134     ///
135     /// ```
136     /// use std::char;
137     ///
138     /// let c = char::from_u32(0x110000);
139     ///
140     /// assert_eq!(None, c);
141     /// ```
142     #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
143     #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
144     #[must_use]
145     #[inline]
146     pub const fn from_u32(i: u32) -> Option<char> {
147         super::convert::from_u32(i)
148     }
149
150     /// Converts a `u32` to a `char`, ignoring validity.
151     ///
152     /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
153     /// `as`:
154     ///
155     /// ```
156     /// let c = '💯';
157     /// let i = c as u32;
158     ///
159     /// assert_eq!(128175, i);
160     /// ```
161     ///
162     /// However, the reverse is not true: not all valid [`u32`]s are valid
163     /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to
164     /// `char`, possibly creating an invalid one.
165     ///
166     /// # Safety
167     ///
168     /// This function is unsafe, as it may construct invalid `char` values.
169     ///
170     /// For a safe version of this function, see the [`from_u32`] function.
171     ///
172     /// [`from_u32`]: #method.from_u32
173     ///
174     /// # Examples
175     ///
176     /// Basic usage:
177     ///
178     /// ```
179     /// use std::char;
180     ///
181     /// let c = unsafe { char::from_u32_unchecked(0x2764) };
182     ///
183     /// assert_eq!('❤', c);
184     /// ```
185     #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
186     #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
187     #[must_use]
188     #[inline]
189     pub const unsafe fn from_u32_unchecked(i: u32) -> char {
190         // SAFETY: the safety contract must be upheld by the caller.
191         unsafe { super::convert::from_u32_unchecked(i) }
192     }
193
194     /// Converts a digit in the given radix to a `char`.
195     ///
196     /// A 'radix' here is sometimes also called a 'base'. A radix of two
197     /// indicates a binary number, a radix of ten, decimal, and a radix of
198     /// sixteen, hexadecimal, to give some common values. Arbitrary
199     /// radices are supported.
200     ///
201     /// `from_digit()` will return `None` if the input is not a digit in
202     /// the given radix.
203     ///
204     /// # Panics
205     ///
206     /// Panics if given a radix larger than 36.
207     ///
208     /// # Examples
209     ///
210     /// Basic usage:
211     ///
212     /// ```
213     /// use std::char;
214     ///
215     /// let c = char::from_digit(4, 10);
216     ///
217     /// assert_eq!(Some('4'), c);
218     ///
219     /// // Decimal 11 is a single digit in base 16
220     /// let c = char::from_digit(11, 16);
221     ///
222     /// assert_eq!(Some('b'), c);
223     /// ```
224     ///
225     /// Returning `None` when the input is not a digit:
226     ///
227     /// ```
228     /// use std::char;
229     ///
230     /// let c = char::from_digit(20, 10);
231     ///
232     /// assert_eq!(None, c);
233     /// ```
234     ///
235     /// Passing a large radix, causing a panic:
236     ///
237     /// ```should_panic
238     /// use std::char;
239     ///
240     /// // this panics
241     /// let _c = char::from_digit(1, 37);
242     /// ```
243     #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
244     #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
245     #[must_use]
246     #[inline]
247     pub const fn from_digit(num: u32, radix: u32) -> Option<char> {
248         super::convert::from_digit(num, radix)
249     }
250
251     /// Checks if a `char` is a digit in the given radix.
252     ///
253     /// A 'radix' here is sometimes also called a 'base'. A radix of two
254     /// indicates a binary number, a radix of ten, decimal, and a radix of
255     /// sixteen, hexadecimal, to give some common values. Arbitrary
256     /// radices are supported.
257     ///
258     /// Compared to [`is_numeric()`], this function only recognizes the characters
259     /// `0-9`, `a-z` and `A-Z`.
260     ///
261     /// 'Digit' is defined to be only the following characters:
262     ///
263     /// * `0-9`
264     /// * `a-z`
265     /// * `A-Z`
266     ///
267     /// For a more comprehensive understanding of 'digit', see [`is_numeric()`].
268     ///
269     /// [`is_numeric()`]: #method.is_numeric
270     ///
271     /// # Panics
272     ///
273     /// Panics if given a radix larger than 36.
274     ///
275     /// # Examples
276     ///
277     /// Basic usage:
278     ///
279     /// ```
280     /// assert!('1'.is_digit(10));
281     /// assert!('f'.is_digit(16));
282     /// assert!(!'f'.is_digit(10));
283     /// ```
284     ///
285     /// Passing a large radix, causing a panic:
286     ///
287     /// ```should_panic
288     /// // this panics
289     /// '1'.is_digit(37);
290     /// ```
291     #[stable(feature = "rust1", since = "1.0.0")]
292     #[inline]
293     pub fn is_digit(self, radix: u32) -> bool {
294         self.to_digit(radix).is_some()
295     }
296
297     /// Converts a `char` to a digit in the given radix.
298     ///
299     /// A 'radix' here is sometimes also called a 'base'. A radix of two
300     /// indicates a binary number, a radix of ten, decimal, and a radix of
301     /// sixteen, hexadecimal, to give some common values. Arbitrary
302     /// radices are supported.
303     ///
304     /// 'Digit' is defined to be only the following characters:
305     ///
306     /// * `0-9`
307     /// * `a-z`
308     /// * `A-Z`
309     ///
310     /// # Errors
311     ///
312     /// Returns `None` if the `char` does not refer to a digit in the given radix.
313     ///
314     /// # Panics
315     ///
316     /// Panics if given a radix larger than 36.
317     ///
318     /// # Examples
319     ///
320     /// Basic usage:
321     ///
322     /// ```
323     /// assert_eq!('1'.to_digit(10), Some(1));
324     /// assert_eq!('f'.to_digit(16), Some(15));
325     /// ```
326     ///
327     /// Passing a non-digit results in failure:
328     ///
329     /// ```
330     /// assert_eq!('f'.to_digit(10), None);
331     /// assert_eq!('z'.to_digit(16), None);
332     /// ```
333     ///
334     /// Passing a large radix, causing a panic:
335     ///
336     /// ```should_panic
337     /// // this panics
338     /// let _ = '1'.to_digit(37);
339     /// ```
340     #[stable(feature = "rust1", since = "1.0.0")]
341     #[rustc_const_unstable(feature = "const_char_convert", issue = "89259")]
342     #[must_use = "this returns the result of the operation, \
343                   without modifying the original"]
344     #[inline]
345     pub const fn to_digit(self, radix: u32) -> Option<u32> {
346         // If not a digit, a number greater than radix will be created.
347         let mut digit = (self as u32).wrapping_sub('0' as u32);
348         if radix > 10 {
349             assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
350             if digit < 10 {
351                 return Some(digit);
352             }
353             // Force the 6th bit to be set to ensure ascii is lower case.
354             digit = (self as u32 | 0b10_0000).wrapping_sub('a' as u32).saturating_add(10);
355         }
356         // FIXME: once then_some is const fn, use it here
357         if digit < radix { Some(digit) } else { None }
358     }
359
360     /// Returns an iterator that yields the hexadecimal Unicode escape of a
361     /// character as `char`s.
362     ///
363     /// This will escape characters with the Rust syntax of the form
364     /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
365     ///
366     /// # Examples
367     ///
368     /// As an iterator:
369     ///
370     /// ```
371     /// for c in '❤'.escape_unicode() {
372     ///     print!("{c}");
373     /// }
374     /// println!();
375     /// ```
376     ///
377     /// Using `println!` directly:
378     ///
379     /// ```
380     /// println!("{}", '❤'.escape_unicode());
381     /// ```
382     ///
383     /// Both are equivalent to:
384     ///
385     /// ```
386     /// println!("\\u{{2764}}");
387     /// ```
388     ///
389     /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
390     ///
391     /// ```
392     /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
393     /// ```
394     #[must_use = "this returns the escaped char as an iterator, \
395                   without modifying the original"]
396     #[stable(feature = "rust1", since = "1.0.0")]
397     #[inline]
398     pub fn escape_unicode(self) -> EscapeUnicode {
399         let c = self as u32;
400
401         // or-ing 1 ensures that for c==0 the code computes that one
402         // digit should be printed and (which is the same) avoids the
403         // (31 - 32) underflow
404         let msb = 31 - (c | 1).leading_zeros();
405
406         // the index of the most significant hex digit
407         let ms_hex_digit = msb / 4;
408         EscapeUnicode {
409             c: self,
410             state: EscapeUnicodeState::Backslash,
411             hex_digit_idx: ms_hex_digit as usize,
412         }
413     }
414
415     /// An extended version of `escape_debug` that optionally permits escaping
416     /// Extended Grapheme codepoints, single quotes, and double quotes. This
417     /// allows us to format characters like nonspacing marks better when they're
418     /// at the start of a string, and allows escaping single quotes in
419     /// characters, and double quotes in strings.
420     #[inline]
421     pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
422         let init_state = match self {
423             '\0' => EscapeDefaultState::Backslash('0'),
424             '\t' => EscapeDefaultState::Backslash('t'),
425             '\r' => EscapeDefaultState::Backslash('r'),
426             '\n' => EscapeDefaultState::Backslash('n'),
427             '\\' => EscapeDefaultState::Backslash(self),
428             '"' if args.escape_double_quote => EscapeDefaultState::Backslash(self),
429             '\'' if args.escape_single_quote => EscapeDefaultState::Backslash(self),
430             _ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
431                 EscapeDefaultState::Unicode(self.escape_unicode())
432             }
433             _ if is_printable(self) => EscapeDefaultState::Char(self),
434             _ => EscapeDefaultState::Unicode(self.escape_unicode()),
435         };
436         EscapeDebug(EscapeDefault { state: init_state })
437     }
438
439     /// Returns an iterator that yields the literal escape code of a character
440     /// as `char`s.
441     ///
442     /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
443     /// of `str` or `char`.
444     ///
445     /// # Examples
446     ///
447     /// As an iterator:
448     ///
449     /// ```
450     /// for c in '\n'.escape_debug() {
451     ///     print!("{c}");
452     /// }
453     /// println!();
454     /// ```
455     ///
456     /// Using `println!` directly:
457     ///
458     /// ```
459     /// println!("{}", '\n'.escape_debug());
460     /// ```
461     ///
462     /// Both are equivalent to:
463     ///
464     /// ```
465     /// println!("\\n");
466     /// ```
467     ///
468     /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
469     ///
470     /// ```
471     /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
472     /// ```
473     #[must_use = "this returns the escaped char as an iterator, \
474                   without modifying the original"]
475     #[stable(feature = "char_escape_debug", since = "1.20.0")]
476     #[inline]
477     pub fn escape_debug(self) -> EscapeDebug {
478         self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
479     }
480
481     /// Returns an iterator that yields the literal escape code of a character
482     /// as `char`s.
483     ///
484     /// The default is chosen with a bias toward producing literals that are
485     /// legal in a variety of languages, including C++11 and similar C-family
486     /// languages. The exact rules are:
487     ///
488     /// * Tab is escaped as `\t`.
489     /// * Carriage return is escaped as `\r`.
490     /// * Line feed is escaped as `\n`.
491     /// * Single quote is escaped as `\'`.
492     /// * Double quote is escaped as `\"`.
493     /// * Backslash is escaped as `\\`.
494     /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
495     ///   inclusive is not escaped.
496     /// * All other characters are given hexadecimal Unicode escapes; see
497     ///   [`escape_unicode`].
498     ///
499     /// [`escape_unicode`]: #method.escape_unicode
500     ///
501     /// # Examples
502     ///
503     /// As an iterator:
504     ///
505     /// ```
506     /// for c in '"'.escape_default() {
507     ///     print!("{c}");
508     /// }
509     /// println!();
510     /// ```
511     ///
512     /// Using `println!` directly:
513     ///
514     /// ```
515     /// println!("{}", '"'.escape_default());
516     /// ```
517     ///
518     /// Both are equivalent to:
519     ///
520     /// ```
521     /// println!("\\\"");
522     /// ```
523     ///
524     /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
525     ///
526     /// ```
527     /// assert_eq!('"'.escape_default().to_string(), "\\\"");
528     /// ```
529     #[must_use = "this returns the escaped char as an iterator, \
530                   without modifying the original"]
531     #[stable(feature = "rust1", since = "1.0.0")]
532     #[inline]
533     pub fn escape_default(self) -> EscapeDefault {
534         let init_state = match self {
535             '\t' => EscapeDefaultState::Backslash('t'),
536             '\r' => EscapeDefaultState::Backslash('r'),
537             '\n' => EscapeDefaultState::Backslash('n'),
538             '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
539             '\x20'..='\x7e' => EscapeDefaultState::Char(self),
540             _ => EscapeDefaultState::Unicode(self.escape_unicode()),
541         };
542         EscapeDefault { state: init_state }
543     }
544
545     /// Returns the number of bytes this `char` would need if encoded in UTF-8.
546     ///
547     /// That number of bytes is always between 1 and 4, inclusive.
548     ///
549     /// # Examples
550     ///
551     /// Basic usage:
552     ///
553     /// ```
554     /// let len = 'A'.len_utf8();
555     /// assert_eq!(len, 1);
556     ///
557     /// let len = 'ß'.len_utf8();
558     /// assert_eq!(len, 2);
559     ///
560     /// let len = 'ℝ'.len_utf8();
561     /// assert_eq!(len, 3);
562     ///
563     /// let len = '💣'.len_utf8();
564     /// assert_eq!(len, 4);
565     /// ```
566     ///
567     /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
568     /// would take if each code point was represented as a `char` vs in the `&str` itself:
569     ///
570     /// ```
571     /// // as chars
572     /// let eastern = '東';
573     /// let capital = '京';
574     ///
575     /// // both can be represented as three bytes
576     /// assert_eq!(3, eastern.len_utf8());
577     /// assert_eq!(3, capital.len_utf8());
578     ///
579     /// // as a &str, these two are encoded in UTF-8
580     /// let tokyo = "東京";
581     ///
582     /// let len = eastern.len_utf8() + capital.len_utf8();
583     ///
584     /// // we can see that they take six bytes total...
585     /// assert_eq!(6, tokyo.len());
586     ///
587     /// // ... just like the &str
588     /// assert_eq!(len, tokyo.len());
589     /// ```
590     #[stable(feature = "rust1", since = "1.0.0")]
591     #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
592     #[inline]
593     pub const fn len_utf8(self) -> usize {
594         len_utf8(self as u32)
595     }
596
597     /// Returns the number of 16-bit code units this `char` would need if
598     /// encoded in UTF-16.
599     ///
600     /// See the documentation for [`len_utf8()`] for more explanation of this
601     /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
602     ///
603     /// [`len_utf8()`]: #method.len_utf8
604     ///
605     /// # Examples
606     ///
607     /// Basic usage:
608     ///
609     /// ```
610     /// let n = 'ß'.len_utf16();
611     /// assert_eq!(n, 1);
612     ///
613     /// let len = '💣'.len_utf16();
614     /// assert_eq!(len, 2);
615     /// ```
616     #[stable(feature = "rust1", since = "1.0.0")]
617     #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
618     #[inline]
619     pub const fn len_utf16(self) -> usize {
620         let ch = self as u32;
621         if (ch & 0xFFFF) == ch { 1 } else { 2 }
622     }
623
624     /// Encodes this character as UTF-8 into the provided byte buffer,
625     /// and then returns the subslice of the buffer that contains the encoded character.
626     ///
627     /// # Panics
628     ///
629     /// Panics if the buffer is not large enough.
630     /// A buffer of length four is large enough to encode any `char`.
631     ///
632     /// # Examples
633     ///
634     /// In both of these examples, 'ß' takes two bytes to encode.
635     ///
636     /// ```
637     /// let mut b = [0; 2];
638     ///
639     /// let result = 'ß'.encode_utf8(&mut b);
640     ///
641     /// assert_eq!(result, "ß");
642     ///
643     /// assert_eq!(result.len(), 2);
644     /// ```
645     ///
646     /// A buffer that's too small:
647     ///
648     /// ```should_panic
649     /// let mut b = [0; 1];
650     ///
651     /// // this panics
652     /// 'ß'.encode_utf8(&mut b);
653     /// ```
654     #[stable(feature = "unicode_encode_char", since = "1.15.0")]
655     #[inline]
656     pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
657         // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
658         unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
659     }
660
661     /// Encodes this character as UTF-16 into the provided `u16` buffer,
662     /// and then returns the subslice of the buffer that contains the encoded character.
663     ///
664     /// # Panics
665     ///
666     /// Panics if the buffer is not large enough.
667     /// A buffer of length 2 is large enough to encode any `char`.
668     ///
669     /// # Examples
670     ///
671     /// In both of these examples, '𝕊' takes two `u16`s to encode.
672     ///
673     /// ```
674     /// let mut b = [0; 2];
675     ///
676     /// let result = '𝕊'.encode_utf16(&mut b);
677     ///
678     /// assert_eq!(result.len(), 2);
679     /// ```
680     ///
681     /// A buffer that's too small:
682     ///
683     /// ```should_panic
684     /// let mut b = [0; 1];
685     ///
686     /// // this panics
687     /// '𝕊'.encode_utf16(&mut b);
688     /// ```
689     #[stable(feature = "unicode_encode_char", since = "1.15.0")]
690     #[inline]
691     pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
692         encode_utf16_raw(self as u32, dst)
693     }
694
695     /// Returns `true` if this `char` has the `Alphabetic` property.
696     ///
697     /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
698     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
699     ///
700     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
701     /// [ucd]: https://www.unicode.org/reports/tr44/
702     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
703     ///
704     /// # Examples
705     ///
706     /// Basic usage:
707     ///
708     /// ```
709     /// assert!('a'.is_alphabetic());
710     /// assert!('京'.is_alphabetic());
711     ///
712     /// let c = '💝';
713     /// // love is many things, but it is not alphabetic
714     /// assert!(!c.is_alphabetic());
715     /// ```
716     #[must_use]
717     #[stable(feature = "rust1", since = "1.0.0")]
718     #[inline]
719     pub fn is_alphabetic(self) -> bool {
720         match self {
721             'a'..='z' | 'A'..='Z' => true,
722             c => c > '\x7f' && unicode::Alphabetic(c),
723         }
724     }
725
726     /// Returns `true` if this `char` has the `Lowercase` property.
727     ///
728     /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
729     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
730     ///
731     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
732     /// [ucd]: https://www.unicode.org/reports/tr44/
733     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
734     ///
735     /// # Examples
736     ///
737     /// Basic usage:
738     ///
739     /// ```
740     /// assert!('a'.is_lowercase());
741     /// assert!('δ'.is_lowercase());
742     /// assert!(!'A'.is_lowercase());
743     /// assert!(!'Δ'.is_lowercase());
744     ///
745     /// // The various Chinese scripts and punctuation do not have case, and so:
746     /// assert!(!'中'.is_lowercase());
747     /// assert!(!' '.is_lowercase());
748     /// ```
749     ///
750     /// In a const context:
751     ///
752     /// ```
753     /// #![feature(const_unicode_case_lookup)]
754     /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
755     /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
756     /// ```
757     #[must_use]
758     #[stable(feature = "rust1", since = "1.0.0")]
759     #[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
760     #[inline]
761     pub const fn is_lowercase(self) -> bool {
762         match self {
763             'a'..='z' => true,
764             c => c > '\x7f' && unicode::Lowercase(c),
765         }
766     }
767
768     /// Returns `true` if this `char` has the `Uppercase` property.
769     ///
770     /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
771     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
772     ///
773     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
774     /// [ucd]: https://www.unicode.org/reports/tr44/
775     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
776     ///
777     /// # Examples
778     ///
779     /// Basic usage:
780     ///
781     /// ```
782     /// assert!(!'a'.is_uppercase());
783     /// assert!(!'δ'.is_uppercase());
784     /// assert!('A'.is_uppercase());
785     /// assert!('Δ'.is_uppercase());
786     ///
787     /// // The various Chinese scripts and punctuation do not have case, and so:
788     /// assert!(!'中'.is_uppercase());
789     /// assert!(!' '.is_uppercase());
790     /// ```
791     ///
792     /// In a const context:
793     ///
794     /// ```
795     /// #![feature(const_unicode_case_lookup)]
796     /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
797     /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
798     /// ```
799     #[must_use]
800     #[stable(feature = "rust1", since = "1.0.0")]
801     #[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
802     #[inline]
803     pub const fn is_uppercase(self) -> bool {
804         match self {
805             'A'..='Z' => true,
806             c => c > '\x7f' && unicode::Uppercase(c),
807         }
808     }
809
810     /// Returns `true` if this `char` has the `White_Space` property.
811     ///
812     /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
813     ///
814     /// [ucd]: https://www.unicode.org/reports/tr44/
815     /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
816     ///
817     /// # Examples
818     ///
819     /// Basic usage:
820     ///
821     /// ```
822     /// assert!(' '.is_whitespace());
823     ///
824     /// // line break
825     /// assert!('\n'.is_whitespace());
826     ///
827     /// // a non-breaking space
828     /// assert!('\u{A0}'.is_whitespace());
829     ///
830     /// assert!(!'越'.is_whitespace());
831     /// ```
832     #[must_use]
833     #[stable(feature = "rust1", since = "1.0.0")]
834     #[inline]
835     pub fn is_whitespace(self) -> bool {
836         match self {
837             ' ' | '\x09'..='\x0d' => true,
838             c => c > '\x7f' && unicode::White_Space(c),
839         }
840     }
841
842     /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
843     ///
844     /// [`is_alphabetic()`]: #method.is_alphabetic
845     /// [`is_numeric()`]: #method.is_numeric
846     ///
847     /// # Examples
848     ///
849     /// Basic usage:
850     ///
851     /// ```
852     /// assert!('٣'.is_alphanumeric());
853     /// assert!('7'.is_alphanumeric());
854     /// assert!('৬'.is_alphanumeric());
855     /// assert!('¾'.is_alphanumeric());
856     /// assert!('①'.is_alphanumeric());
857     /// assert!('K'.is_alphanumeric());
858     /// assert!('و'.is_alphanumeric());
859     /// assert!('藏'.is_alphanumeric());
860     /// ```
861     #[must_use]
862     #[stable(feature = "rust1", since = "1.0.0")]
863     #[inline]
864     pub fn is_alphanumeric(self) -> bool {
865         self.is_alphabetic() || self.is_numeric()
866     }
867
868     /// Returns `true` if this `char` has the general category for control codes.
869     ///
870     /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
871     /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
872     /// Database][ucd] [`UnicodeData.txt`].
873     ///
874     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
875     /// [ucd]: https://www.unicode.org/reports/tr44/
876     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
877     ///
878     /// # Examples
879     ///
880     /// Basic usage:
881     ///
882     /// ```
883     /// // U+009C, STRING TERMINATOR
884     /// assert!('\9c'.is_control());
885     /// assert!(!'q'.is_control());
886     /// ```
887     #[must_use]
888     #[stable(feature = "rust1", since = "1.0.0")]
889     #[inline]
890     pub fn is_control(self) -> bool {
891         unicode::Cc(self)
892     }
893
894     /// Returns `true` if this `char` has the `Grapheme_Extend` property.
895     ///
896     /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
897     /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
898     /// [`DerivedCoreProperties.txt`].
899     ///
900     /// [uax29]: https://www.unicode.org/reports/tr29/
901     /// [ucd]: https://www.unicode.org/reports/tr44/
902     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
903     #[must_use]
904     #[inline]
905     pub(crate) fn is_grapheme_extended(self) -> bool {
906         unicode::Grapheme_Extend(self)
907     }
908
909     /// Returns `true` if this `char` has one of the general categories for numbers.
910     ///
911     /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
912     /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
913     /// Database][ucd] [`UnicodeData.txt`].
914     ///
915     /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
916     /// If you want everything including characters with overlapping purposes then you might want to use
917     /// a unicode or language-processing library that exposes the appropriate character properties instead
918     /// of looking at the unicode categories.
919     ///
920     /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
921     /// `is_ascii_digit` or `is_digit` instead.
922     ///
923     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
924     /// [ucd]: https://www.unicode.org/reports/tr44/
925     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
926     ///
927     /// # Examples
928     ///
929     /// Basic usage:
930     ///
931     /// ```
932     /// assert!('٣'.is_numeric());
933     /// assert!('7'.is_numeric());
934     /// assert!('৬'.is_numeric());
935     /// assert!('¾'.is_numeric());
936     /// assert!('①'.is_numeric());
937     /// assert!(!'K'.is_numeric());
938     /// assert!(!'و'.is_numeric());
939     /// assert!(!'藏'.is_numeric());
940     /// assert!(!'三'.is_numeric());
941     /// ```
942     #[must_use]
943     #[stable(feature = "rust1", since = "1.0.0")]
944     #[inline]
945     pub fn is_numeric(self) -> bool {
946         match self {
947             '0'..='9' => true,
948             c => c > '\x7f' && unicode::N(c),
949         }
950     }
951
952     /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
953     /// `char`s.
954     ///
955     /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
956     ///
957     /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
958     /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
959     ///
960     /// [ucd]: https://www.unicode.org/reports/tr44/
961     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
962     ///
963     /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
964     /// the `char`(s) given by [`SpecialCasing.txt`].
965     ///
966     /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
967     ///
968     /// This operation performs an unconditional mapping without tailoring. That is, the conversion
969     /// is independent of context and language.
970     ///
971     /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
972     /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
973     ///
974     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
975     ///
976     /// # Examples
977     ///
978     /// As an iterator:
979     ///
980     /// ```
981     /// for c in 'İ'.to_lowercase() {
982     ///     print!("{c}");
983     /// }
984     /// println!();
985     /// ```
986     ///
987     /// Using `println!` directly:
988     ///
989     /// ```
990     /// println!("{}", 'İ'.to_lowercase());
991     /// ```
992     ///
993     /// Both are equivalent to:
994     ///
995     /// ```
996     /// println!("i\u{307}");
997     /// ```
998     ///
999     /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1000     ///
1001     /// ```
1002     /// assert_eq!('C'.to_lowercase().to_string(), "c");
1003     ///
1004     /// // Sometimes the result is more than one character:
1005     /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1006     ///
1007     /// // Characters that do not have both uppercase and lowercase
1008     /// // convert into themselves.
1009     /// assert_eq!('山'.to_lowercase().to_string(), "山");
1010     /// ```
1011     #[must_use = "this returns the lowercase character as a new iterator, \
1012                   without modifying the original"]
1013     #[stable(feature = "rust1", since = "1.0.0")]
1014     #[inline]
1015     pub fn to_lowercase(self) -> ToLowercase {
1016         ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1017     }
1018
1019     /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1020     /// `char`s.
1021     ///
1022     /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1023     ///
1024     /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1025     /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1026     ///
1027     /// [ucd]: https://www.unicode.org/reports/tr44/
1028     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1029     ///
1030     /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1031     /// the `char`(s) given by [`SpecialCasing.txt`].
1032     ///
1033     /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1034     ///
1035     /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1036     /// is independent of context and language.
1037     ///
1038     /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1039     /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1040     ///
1041     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1042     ///
1043     /// # Examples
1044     ///
1045     /// As an iterator:
1046     ///
1047     /// ```
1048     /// for c in 'ß'.to_uppercase() {
1049     ///     print!("{c}");
1050     /// }
1051     /// println!();
1052     /// ```
1053     ///
1054     /// Using `println!` directly:
1055     ///
1056     /// ```
1057     /// println!("{}", 'ß'.to_uppercase());
1058     /// ```
1059     ///
1060     /// Both are equivalent to:
1061     ///
1062     /// ```
1063     /// println!("SS");
1064     /// ```
1065     ///
1066     /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1067     ///
1068     /// ```
1069     /// assert_eq!('c'.to_uppercase().to_string(), "C");
1070     ///
1071     /// // Sometimes the result is more than one character:
1072     /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
1073     ///
1074     /// // Characters that do not have both uppercase and lowercase
1075     /// // convert into themselves.
1076     /// assert_eq!('山'.to_uppercase().to_string(), "山");
1077     /// ```
1078     ///
1079     /// # Note on locale
1080     ///
1081     /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1082     ///
1083     /// * 'Dotless': I / ı, sometimes written ï
1084     /// * 'Dotted': İ / i
1085     ///
1086     /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1087     ///
1088     /// ```
1089     /// let upper_i = 'i'.to_uppercase().to_string();
1090     /// ```
1091     ///
1092     /// The value of `upper_i` here relies on the language of the text: if we're
1093     /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
1094     /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1095     ///
1096     /// ```
1097     /// let upper_i = 'i'.to_uppercase().to_string();
1098     ///
1099     /// assert_eq!(upper_i, "I");
1100     /// ```
1101     ///
1102     /// holds across languages.
1103     #[must_use = "this returns the uppercase character as a new iterator, \
1104                   without modifying the original"]
1105     #[stable(feature = "rust1", since = "1.0.0")]
1106     #[inline]
1107     pub fn to_uppercase(self) -> ToUppercase {
1108         ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1109     }
1110
1111     /// Checks if the value is within the ASCII range.
1112     ///
1113     /// # Examples
1114     ///
1115     /// ```
1116     /// let ascii = 'a';
1117     /// let non_ascii = '❤';
1118     ///
1119     /// assert!(ascii.is_ascii());
1120     /// assert!(!non_ascii.is_ascii());
1121     /// ```
1122     #[must_use]
1123     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1124     #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1125     #[inline]
1126     pub const fn is_ascii(&self) -> bool {
1127         *self as u32 <= 0x7F
1128     }
1129
1130     /// Makes a copy of the value in its ASCII upper case equivalent.
1131     ///
1132     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1133     /// but non-ASCII letters are unchanged.
1134     ///
1135     /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1136     ///
1137     /// To uppercase ASCII characters in addition to non-ASCII characters, use
1138     /// [`to_uppercase()`].
1139     ///
1140     /// # Examples
1141     ///
1142     /// ```
1143     /// let ascii = 'a';
1144     /// let non_ascii = '❤';
1145     ///
1146     /// assert_eq!('A', ascii.to_ascii_uppercase());
1147     /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1148     /// ```
1149     ///
1150     /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1151     /// [`to_uppercase()`]: #method.to_uppercase
1152     #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1153     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1154     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1155     #[inline]
1156     pub const fn to_ascii_uppercase(&self) -> char {
1157         if self.is_ascii_lowercase() {
1158             (*self as u8).ascii_change_case_unchecked() as char
1159         } else {
1160             *self
1161         }
1162     }
1163
1164     /// Makes a copy of the value in its ASCII lower case equivalent.
1165     ///
1166     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1167     /// but non-ASCII letters are unchanged.
1168     ///
1169     /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1170     ///
1171     /// To lowercase ASCII characters in addition to non-ASCII characters, use
1172     /// [`to_lowercase()`].
1173     ///
1174     /// # Examples
1175     ///
1176     /// ```
1177     /// let ascii = 'A';
1178     /// let non_ascii = '❤';
1179     ///
1180     /// assert_eq!('a', ascii.to_ascii_lowercase());
1181     /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1182     /// ```
1183     ///
1184     /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1185     /// [`to_lowercase()`]: #method.to_lowercase
1186     #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1187     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1188     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1189     #[inline]
1190     pub const fn to_ascii_lowercase(&self) -> char {
1191         if self.is_ascii_uppercase() {
1192             (*self as u8).ascii_change_case_unchecked() as char
1193         } else {
1194             *self
1195         }
1196     }
1197
1198     /// Checks that two values are an ASCII case-insensitive match.
1199     ///
1200     /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1201     ///
1202     /// # Examples
1203     ///
1204     /// ```
1205     /// let upper_a = 'A';
1206     /// let lower_a = 'a';
1207     /// let lower_z = 'z';
1208     ///
1209     /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1210     /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1211     /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1212     /// ```
1213     ///
1214     /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1215     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1216     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1217     #[inline]
1218     pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1219         self.to_ascii_lowercase() == other.to_ascii_lowercase()
1220     }
1221
1222     /// Converts this type to its ASCII upper case equivalent in-place.
1223     ///
1224     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1225     /// but non-ASCII letters are unchanged.
1226     ///
1227     /// To return a new uppercased value without modifying the existing one, use
1228     /// [`to_ascii_uppercase()`].
1229     ///
1230     /// # Examples
1231     ///
1232     /// ```
1233     /// let mut ascii = 'a';
1234     ///
1235     /// ascii.make_ascii_uppercase();
1236     ///
1237     /// assert_eq!('A', ascii);
1238     /// ```
1239     ///
1240     /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1241     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1242     #[inline]
1243     pub fn make_ascii_uppercase(&mut self) {
1244         *self = self.to_ascii_uppercase();
1245     }
1246
1247     /// Converts this type to its ASCII lower case equivalent in-place.
1248     ///
1249     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1250     /// but non-ASCII letters are unchanged.
1251     ///
1252     /// To return a new lowercased value without modifying the existing one, use
1253     /// [`to_ascii_lowercase()`].
1254     ///
1255     /// # Examples
1256     ///
1257     /// ```
1258     /// let mut ascii = 'A';
1259     ///
1260     /// ascii.make_ascii_lowercase();
1261     ///
1262     /// assert_eq!('a', ascii);
1263     /// ```
1264     ///
1265     /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1266     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1267     #[inline]
1268     pub fn make_ascii_lowercase(&mut self) {
1269         *self = self.to_ascii_lowercase();
1270     }
1271
1272     /// Checks if the value is an ASCII alphabetic character:
1273     ///
1274     /// - U+0041 'A' ..= U+005A 'Z', or
1275     /// - U+0061 'a' ..= U+007A 'z'.
1276     ///
1277     /// # Examples
1278     ///
1279     /// ```
1280     /// let uppercase_a = 'A';
1281     /// let uppercase_g = 'G';
1282     /// let a = 'a';
1283     /// let g = 'g';
1284     /// let zero = '0';
1285     /// let percent = '%';
1286     /// let space = ' ';
1287     /// let lf = '\n';
1288     /// let esc = '\x1b';
1289     ///
1290     /// assert!(uppercase_a.is_ascii_alphabetic());
1291     /// assert!(uppercase_g.is_ascii_alphabetic());
1292     /// assert!(a.is_ascii_alphabetic());
1293     /// assert!(g.is_ascii_alphabetic());
1294     /// assert!(!zero.is_ascii_alphabetic());
1295     /// assert!(!percent.is_ascii_alphabetic());
1296     /// assert!(!space.is_ascii_alphabetic());
1297     /// assert!(!lf.is_ascii_alphabetic());
1298     /// assert!(!esc.is_ascii_alphabetic());
1299     /// ```
1300     #[must_use]
1301     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1302     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1303     #[inline]
1304     pub const fn is_ascii_alphabetic(&self) -> bool {
1305         matches!(*self, 'A'..='Z' | 'a'..='z')
1306     }
1307
1308     /// Checks if the value is an ASCII uppercase character:
1309     /// U+0041 'A' ..= U+005A 'Z'.
1310     ///
1311     /// # Examples
1312     ///
1313     /// ```
1314     /// let uppercase_a = 'A';
1315     /// let uppercase_g = 'G';
1316     /// let a = 'a';
1317     /// let g = 'g';
1318     /// let zero = '0';
1319     /// let percent = '%';
1320     /// let space = ' ';
1321     /// let lf = '\n';
1322     /// let esc = '\x1b';
1323     ///
1324     /// assert!(uppercase_a.is_ascii_uppercase());
1325     /// assert!(uppercase_g.is_ascii_uppercase());
1326     /// assert!(!a.is_ascii_uppercase());
1327     /// assert!(!g.is_ascii_uppercase());
1328     /// assert!(!zero.is_ascii_uppercase());
1329     /// assert!(!percent.is_ascii_uppercase());
1330     /// assert!(!space.is_ascii_uppercase());
1331     /// assert!(!lf.is_ascii_uppercase());
1332     /// assert!(!esc.is_ascii_uppercase());
1333     /// ```
1334     #[must_use]
1335     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1336     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1337     #[inline]
1338     pub const fn is_ascii_uppercase(&self) -> bool {
1339         matches!(*self, 'A'..='Z')
1340     }
1341
1342     /// Checks if the value is an ASCII lowercase character:
1343     /// U+0061 'a' ..= U+007A 'z'.
1344     ///
1345     /// # Examples
1346     ///
1347     /// ```
1348     /// let uppercase_a = 'A';
1349     /// let uppercase_g = 'G';
1350     /// let a = 'a';
1351     /// let g = 'g';
1352     /// let zero = '0';
1353     /// let percent = '%';
1354     /// let space = ' ';
1355     /// let lf = '\n';
1356     /// let esc = '\x1b';
1357     ///
1358     /// assert!(!uppercase_a.is_ascii_lowercase());
1359     /// assert!(!uppercase_g.is_ascii_lowercase());
1360     /// assert!(a.is_ascii_lowercase());
1361     /// assert!(g.is_ascii_lowercase());
1362     /// assert!(!zero.is_ascii_lowercase());
1363     /// assert!(!percent.is_ascii_lowercase());
1364     /// assert!(!space.is_ascii_lowercase());
1365     /// assert!(!lf.is_ascii_lowercase());
1366     /// assert!(!esc.is_ascii_lowercase());
1367     /// ```
1368     #[must_use]
1369     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1370     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1371     #[inline]
1372     pub const fn is_ascii_lowercase(&self) -> bool {
1373         matches!(*self, 'a'..='z')
1374     }
1375
1376     /// Checks if the value is an ASCII alphanumeric character:
1377     ///
1378     /// - U+0041 'A' ..= U+005A 'Z', or
1379     /// - U+0061 'a' ..= U+007A 'z', or
1380     /// - U+0030 '0' ..= U+0039 '9'.
1381     ///
1382     /// # Examples
1383     ///
1384     /// ```
1385     /// let uppercase_a = 'A';
1386     /// let uppercase_g = 'G';
1387     /// let a = 'a';
1388     /// let g = 'g';
1389     /// let zero = '0';
1390     /// let percent = '%';
1391     /// let space = ' ';
1392     /// let lf = '\n';
1393     /// let esc = '\x1b';
1394     ///
1395     /// assert!(uppercase_a.is_ascii_alphanumeric());
1396     /// assert!(uppercase_g.is_ascii_alphanumeric());
1397     /// assert!(a.is_ascii_alphanumeric());
1398     /// assert!(g.is_ascii_alphanumeric());
1399     /// assert!(zero.is_ascii_alphanumeric());
1400     /// assert!(!percent.is_ascii_alphanumeric());
1401     /// assert!(!space.is_ascii_alphanumeric());
1402     /// assert!(!lf.is_ascii_alphanumeric());
1403     /// assert!(!esc.is_ascii_alphanumeric());
1404     /// ```
1405     #[must_use]
1406     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1407     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1408     #[inline]
1409     pub const fn is_ascii_alphanumeric(&self) -> bool {
1410         matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1411     }
1412
1413     /// Checks if the value is an ASCII decimal digit:
1414     /// U+0030 '0' ..= U+0039 '9'.
1415     ///
1416     /// # Examples
1417     ///
1418     /// ```
1419     /// let uppercase_a = 'A';
1420     /// let uppercase_g = 'G';
1421     /// let a = 'a';
1422     /// let g = 'g';
1423     /// let zero = '0';
1424     /// let percent = '%';
1425     /// let space = ' ';
1426     /// let lf = '\n';
1427     /// let esc = '\x1b';
1428     ///
1429     /// assert!(!uppercase_a.is_ascii_digit());
1430     /// assert!(!uppercase_g.is_ascii_digit());
1431     /// assert!(!a.is_ascii_digit());
1432     /// assert!(!g.is_ascii_digit());
1433     /// assert!(zero.is_ascii_digit());
1434     /// assert!(!percent.is_ascii_digit());
1435     /// assert!(!space.is_ascii_digit());
1436     /// assert!(!lf.is_ascii_digit());
1437     /// assert!(!esc.is_ascii_digit());
1438     /// ```
1439     #[must_use]
1440     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1441     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1442     #[inline]
1443     pub const fn is_ascii_digit(&self) -> bool {
1444         matches!(*self, '0'..='9')
1445     }
1446
1447     /// Checks if the value is an ASCII hexadecimal digit:
1448     ///
1449     /// - U+0030 '0' ..= U+0039 '9', or
1450     /// - U+0041 'A' ..= U+0046 'F', or
1451     /// - U+0061 'a' ..= U+0066 'f'.
1452     ///
1453     /// # Examples
1454     ///
1455     /// ```
1456     /// let uppercase_a = 'A';
1457     /// let uppercase_g = 'G';
1458     /// let a = 'a';
1459     /// let g = 'g';
1460     /// let zero = '0';
1461     /// let percent = '%';
1462     /// let space = ' ';
1463     /// let lf = '\n';
1464     /// let esc = '\x1b';
1465     ///
1466     /// assert!(uppercase_a.is_ascii_hexdigit());
1467     /// assert!(!uppercase_g.is_ascii_hexdigit());
1468     /// assert!(a.is_ascii_hexdigit());
1469     /// assert!(!g.is_ascii_hexdigit());
1470     /// assert!(zero.is_ascii_hexdigit());
1471     /// assert!(!percent.is_ascii_hexdigit());
1472     /// assert!(!space.is_ascii_hexdigit());
1473     /// assert!(!lf.is_ascii_hexdigit());
1474     /// assert!(!esc.is_ascii_hexdigit());
1475     /// ```
1476     #[must_use]
1477     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1478     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1479     #[inline]
1480     pub const fn is_ascii_hexdigit(&self) -> bool {
1481         matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1482     }
1483
1484     /// Checks if the value is an ASCII punctuation character:
1485     ///
1486     /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1487     /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1488     /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1489     /// - U+007B ..= U+007E `{ | } ~`
1490     ///
1491     /// # Examples
1492     ///
1493     /// ```
1494     /// let uppercase_a = 'A';
1495     /// let uppercase_g = 'G';
1496     /// let a = 'a';
1497     /// let g = 'g';
1498     /// let zero = '0';
1499     /// let percent = '%';
1500     /// let space = ' ';
1501     /// let lf = '\n';
1502     /// let esc = '\x1b';
1503     ///
1504     /// assert!(!uppercase_a.is_ascii_punctuation());
1505     /// assert!(!uppercase_g.is_ascii_punctuation());
1506     /// assert!(!a.is_ascii_punctuation());
1507     /// assert!(!g.is_ascii_punctuation());
1508     /// assert!(!zero.is_ascii_punctuation());
1509     /// assert!(percent.is_ascii_punctuation());
1510     /// assert!(!space.is_ascii_punctuation());
1511     /// assert!(!lf.is_ascii_punctuation());
1512     /// assert!(!esc.is_ascii_punctuation());
1513     /// ```
1514     #[must_use]
1515     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1516     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1517     #[inline]
1518     pub const fn is_ascii_punctuation(&self) -> bool {
1519         matches!(*self, '!'..='/' | ':'..='@' | '['..='`' | '{'..='~')
1520     }
1521
1522     /// Checks if the value is an ASCII graphic character:
1523     /// U+0021 '!' ..= U+007E '~'.
1524     ///
1525     /// # Examples
1526     ///
1527     /// ```
1528     /// let uppercase_a = 'A';
1529     /// let uppercase_g = 'G';
1530     /// let a = 'a';
1531     /// let g = 'g';
1532     /// let zero = '0';
1533     /// let percent = '%';
1534     /// let space = ' ';
1535     /// let lf = '\n';
1536     /// let esc = '\x1b';
1537     ///
1538     /// assert!(uppercase_a.is_ascii_graphic());
1539     /// assert!(uppercase_g.is_ascii_graphic());
1540     /// assert!(a.is_ascii_graphic());
1541     /// assert!(g.is_ascii_graphic());
1542     /// assert!(zero.is_ascii_graphic());
1543     /// assert!(percent.is_ascii_graphic());
1544     /// assert!(!space.is_ascii_graphic());
1545     /// assert!(!lf.is_ascii_graphic());
1546     /// assert!(!esc.is_ascii_graphic());
1547     /// ```
1548     #[must_use]
1549     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1550     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1551     #[inline]
1552     pub const fn is_ascii_graphic(&self) -> bool {
1553         matches!(*self, '!'..='~')
1554     }
1555
1556     /// Checks if the value is an ASCII whitespace character:
1557     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1558     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1559     ///
1560     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1561     /// whitespace][infra-aw]. There are several other definitions in
1562     /// wide use. For instance, [the POSIX locale][pct] includes
1563     /// U+000B VERTICAL TAB as well as all the above characters,
1564     /// but—from the very same specification—[the default rule for
1565     /// "field splitting" in the Bourne shell][bfs] considers *only*
1566     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1567     ///
1568     /// If you are writing a program that will process an existing
1569     /// file format, check what that format's definition of whitespace is
1570     /// before using this function.
1571     ///
1572     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1573     /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1574     /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1575     ///
1576     /// # Examples
1577     ///
1578     /// ```
1579     /// let uppercase_a = 'A';
1580     /// let uppercase_g = 'G';
1581     /// let a = 'a';
1582     /// let g = 'g';
1583     /// let zero = '0';
1584     /// let percent = '%';
1585     /// let space = ' ';
1586     /// let lf = '\n';
1587     /// let esc = '\x1b';
1588     ///
1589     /// assert!(!uppercase_a.is_ascii_whitespace());
1590     /// assert!(!uppercase_g.is_ascii_whitespace());
1591     /// assert!(!a.is_ascii_whitespace());
1592     /// assert!(!g.is_ascii_whitespace());
1593     /// assert!(!zero.is_ascii_whitespace());
1594     /// assert!(!percent.is_ascii_whitespace());
1595     /// assert!(space.is_ascii_whitespace());
1596     /// assert!(lf.is_ascii_whitespace());
1597     /// assert!(!esc.is_ascii_whitespace());
1598     /// ```
1599     #[must_use]
1600     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1601     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1602     #[inline]
1603     pub const fn is_ascii_whitespace(&self) -> bool {
1604         matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1605     }
1606
1607     /// Checks if the value is an ASCII control character:
1608     /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1609     /// Note that most ASCII whitespace characters are control
1610     /// characters, but SPACE is not.
1611     ///
1612     /// # Examples
1613     ///
1614     /// ```
1615     /// let uppercase_a = 'A';
1616     /// let uppercase_g = 'G';
1617     /// let a = 'a';
1618     /// let g = 'g';
1619     /// let zero = '0';
1620     /// let percent = '%';
1621     /// let space = ' ';
1622     /// let lf = '\n';
1623     /// let esc = '\x1b';
1624     ///
1625     /// assert!(!uppercase_a.is_ascii_control());
1626     /// assert!(!uppercase_g.is_ascii_control());
1627     /// assert!(!a.is_ascii_control());
1628     /// assert!(!g.is_ascii_control());
1629     /// assert!(!zero.is_ascii_control());
1630     /// assert!(!percent.is_ascii_control());
1631     /// assert!(!space.is_ascii_control());
1632     /// assert!(lf.is_ascii_control());
1633     /// assert!(esc.is_ascii_control());
1634     /// ```
1635     #[must_use]
1636     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1637     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1638     #[inline]
1639     pub const fn is_ascii_control(&self) -> bool {
1640         matches!(*self, '\0'..='\x1F' | '\x7F')
1641     }
1642 }
1643
1644 pub(crate) struct EscapeDebugExtArgs {
1645     /// Escape Extended Grapheme codepoints?
1646     pub(crate) escape_grapheme_extended: bool,
1647
1648     /// Escape single quotes?
1649     pub(crate) escape_single_quote: bool,
1650
1651     /// Escape double quotes?
1652     pub(crate) escape_double_quote: bool,
1653 }
1654
1655 impl EscapeDebugExtArgs {
1656     pub(crate) const ESCAPE_ALL: Self = Self {
1657         escape_grapheme_extended: true,
1658         escape_single_quote: true,
1659         escape_double_quote: true,
1660     };
1661 }
1662
1663 #[inline]
1664 const fn len_utf8(code: u32) -> usize {
1665     if code < MAX_ONE_B {
1666         1
1667     } else if code < MAX_TWO_B {
1668         2
1669     } else if code < MAX_THREE_B {
1670         3
1671     } else {
1672         4
1673     }
1674 }
1675
1676 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1677 /// and then returns the subslice of the buffer that contains the encoded character.
1678 ///
1679 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1680 /// (Creating a `char` in the surrogate range is UB.)
1681 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1682 ///
1683 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1684 ///
1685 /// # Panics
1686 ///
1687 /// Panics if the buffer is not large enough.
1688 /// A buffer of length four is large enough to encode any `char`.
1689 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1690 #[doc(hidden)]
1691 #[inline]
1692 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1693     let len = len_utf8(code);
1694     match (len, &mut dst[..]) {
1695         (1, [a, ..]) => {
1696             *a = code as u8;
1697         }
1698         (2, [a, b, ..]) => {
1699             *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
1700             *b = (code & 0x3F) as u8 | TAG_CONT;
1701         }
1702         (3, [a, b, c, ..]) => {
1703             *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
1704             *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1705             *c = (code & 0x3F) as u8 | TAG_CONT;
1706         }
1707         (4, [a, b, c, d, ..]) => {
1708             *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
1709             *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1710             *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1711             *d = (code & 0x3F) as u8 | TAG_CONT;
1712         }
1713         _ => panic!(
1714             "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1715             len,
1716             code,
1717             dst.len(),
1718         ),
1719     };
1720     &mut dst[..len]
1721 }
1722
1723 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1724 /// and then returns the subslice of the buffer that contains the encoded character.
1725 ///
1726 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1727 /// (Creating a `char` in the surrogate range is UB.)
1728 ///
1729 /// # Panics
1730 ///
1731 /// Panics if the buffer is not large enough.
1732 /// A buffer of length 2 is large enough to encode any `char`.
1733 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1734 #[doc(hidden)]
1735 #[inline]
1736 pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1737     // SAFETY: each arm checks whether there are enough bits to write into
1738     unsafe {
1739         if (code & 0xFFFF) == code && !dst.is_empty() {
1740             // The BMP falls through
1741             *dst.get_unchecked_mut(0) = code as u16;
1742             slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
1743         } else if dst.len() >= 2 {
1744             // Supplementary planes break into surrogates.
1745             code -= 0x1_0000;
1746             *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
1747             *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
1748             slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
1749         } else {
1750             panic!(
1751                 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1752                 from_u32_unchecked(code).len_utf16(),
1753                 code,
1754                 dst.len(),
1755             )
1756         }
1757     }
1758 }