]> git.lizzy.rs Git - rust.git/blob - library/core/src/char/methods.rs
Auto merge of #105550 - gimbles:master, r=Nilstrieb
[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_stable(feature = "const_char_convert", since = "CURRENT_RUSTC_VERSION")]
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_from_u32_unchecked", 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_stable(feature = "const_char_convert", since = "CURRENT_RUSTC_VERSION")]
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_stable(feature = "const_char_convert", since = "CURRENT_RUSTC_VERSION")]
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     /// That number of code units is always either 1 or 2, for unicode scalar values in
601     /// the [basic multilingual plane] or [supplementary planes] respectively.
602     ///
603     /// See the documentation for [`len_utf8()`] for more explanation of this
604     /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
605     ///
606     /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
607     /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
608     /// [`len_utf8()`]: #method.len_utf8
609     ///
610     /// # Examples
611     ///
612     /// Basic usage:
613     ///
614     /// ```
615     /// let n = 'ß'.len_utf16();
616     /// assert_eq!(n, 1);
617     ///
618     /// let len = '💣'.len_utf16();
619     /// assert_eq!(len, 2);
620     /// ```
621     #[stable(feature = "rust1", since = "1.0.0")]
622     #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
623     #[inline]
624     pub const fn len_utf16(self) -> usize {
625         let ch = self as u32;
626         if (ch & 0xFFFF) == ch { 1 } else { 2 }
627     }
628
629     /// Encodes this character as UTF-8 into the provided byte buffer,
630     /// and then returns the subslice of the buffer that contains the encoded character.
631     ///
632     /// # Panics
633     ///
634     /// Panics if the buffer is not large enough.
635     /// A buffer of length four is large enough to encode any `char`.
636     ///
637     /// # Examples
638     ///
639     /// In both of these examples, 'ß' takes two bytes to encode.
640     ///
641     /// ```
642     /// let mut b = [0; 2];
643     ///
644     /// let result = 'ß'.encode_utf8(&mut b);
645     ///
646     /// assert_eq!(result, "ß");
647     ///
648     /// assert_eq!(result.len(), 2);
649     /// ```
650     ///
651     /// A buffer that's too small:
652     ///
653     /// ```should_panic
654     /// let mut b = [0; 1];
655     ///
656     /// // this panics
657     /// 'ß'.encode_utf8(&mut b);
658     /// ```
659     #[stable(feature = "unicode_encode_char", since = "1.15.0")]
660     #[inline]
661     pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
662         // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
663         unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
664     }
665
666     /// Encodes this character as UTF-16 into the provided `u16` buffer,
667     /// and then returns the subslice of the buffer that contains the encoded character.
668     ///
669     /// # Panics
670     ///
671     /// Panics if the buffer is not large enough.
672     /// A buffer of length 2 is large enough to encode any `char`.
673     ///
674     /// # Examples
675     ///
676     /// In both of these examples, '𝕊' takes two `u16`s to encode.
677     ///
678     /// ```
679     /// let mut b = [0; 2];
680     ///
681     /// let result = '𝕊'.encode_utf16(&mut b);
682     ///
683     /// assert_eq!(result.len(), 2);
684     /// ```
685     ///
686     /// A buffer that's too small:
687     ///
688     /// ```should_panic
689     /// let mut b = [0; 1];
690     ///
691     /// // this panics
692     /// '𝕊'.encode_utf16(&mut b);
693     /// ```
694     #[stable(feature = "unicode_encode_char", since = "1.15.0")]
695     #[inline]
696     pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
697         encode_utf16_raw(self as u32, dst)
698     }
699
700     /// Returns `true` if this `char` has the `Alphabetic` property.
701     ///
702     /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
703     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
704     ///
705     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
706     /// [ucd]: https://www.unicode.org/reports/tr44/
707     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
708     ///
709     /// # Examples
710     ///
711     /// Basic usage:
712     ///
713     /// ```
714     /// assert!('a'.is_alphabetic());
715     /// assert!('京'.is_alphabetic());
716     ///
717     /// let c = '💝';
718     /// // love is many things, but it is not alphabetic
719     /// assert!(!c.is_alphabetic());
720     /// ```
721     #[must_use]
722     #[stable(feature = "rust1", since = "1.0.0")]
723     #[inline]
724     pub fn is_alphabetic(self) -> bool {
725         match self {
726             'a'..='z' | 'A'..='Z' => true,
727             c => c > '\x7f' && unicode::Alphabetic(c),
728         }
729     }
730
731     /// Returns `true` if this `char` has the `Lowercase` property.
732     ///
733     /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
734     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
735     ///
736     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
737     /// [ucd]: https://www.unicode.org/reports/tr44/
738     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
739     ///
740     /// # Examples
741     ///
742     /// Basic usage:
743     ///
744     /// ```
745     /// assert!('a'.is_lowercase());
746     /// assert!('δ'.is_lowercase());
747     /// assert!(!'A'.is_lowercase());
748     /// assert!(!'Δ'.is_lowercase());
749     ///
750     /// // The various Chinese scripts and punctuation do not have case, and so:
751     /// assert!(!'中'.is_lowercase());
752     /// assert!(!' '.is_lowercase());
753     /// ```
754     ///
755     /// In a const context:
756     ///
757     /// ```
758     /// #![feature(const_unicode_case_lookup)]
759     /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
760     /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
761     /// ```
762     #[must_use]
763     #[stable(feature = "rust1", since = "1.0.0")]
764     #[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
765     #[inline]
766     pub const fn is_lowercase(self) -> bool {
767         match self {
768             'a'..='z' => true,
769             c => c > '\x7f' && unicode::Lowercase(c),
770         }
771     }
772
773     /// Returns `true` if this `char` has the `Uppercase` property.
774     ///
775     /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
776     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
777     ///
778     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
779     /// [ucd]: https://www.unicode.org/reports/tr44/
780     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
781     ///
782     /// # Examples
783     ///
784     /// Basic usage:
785     ///
786     /// ```
787     /// assert!(!'a'.is_uppercase());
788     /// assert!(!'δ'.is_uppercase());
789     /// assert!('A'.is_uppercase());
790     /// assert!('Δ'.is_uppercase());
791     ///
792     /// // The various Chinese scripts and punctuation do not have case, and so:
793     /// assert!(!'中'.is_uppercase());
794     /// assert!(!' '.is_uppercase());
795     /// ```
796     ///
797     /// In a const context:
798     ///
799     /// ```
800     /// #![feature(const_unicode_case_lookup)]
801     /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
802     /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
803     /// ```
804     #[must_use]
805     #[stable(feature = "rust1", since = "1.0.0")]
806     #[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
807     #[inline]
808     pub const fn is_uppercase(self) -> bool {
809         match self {
810             'A'..='Z' => true,
811             c => c > '\x7f' && unicode::Uppercase(c),
812         }
813     }
814
815     /// Returns `true` if this `char` has the `White_Space` property.
816     ///
817     /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
818     ///
819     /// [ucd]: https://www.unicode.org/reports/tr44/
820     /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
821     ///
822     /// # Examples
823     ///
824     /// Basic usage:
825     ///
826     /// ```
827     /// assert!(' '.is_whitespace());
828     ///
829     /// // line break
830     /// assert!('\n'.is_whitespace());
831     ///
832     /// // a non-breaking space
833     /// assert!('\u{A0}'.is_whitespace());
834     ///
835     /// assert!(!'越'.is_whitespace());
836     /// ```
837     #[must_use]
838     #[stable(feature = "rust1", since = "1.0.0")]
839     #[inline]
840     pub fn is_whitespace(self) -> bool {
841         match self {
842             ' ' | '\x09'..='\x0d' => true,
843             c => c > '\x7f' && unicode::White_Space(c),
844         }
845     }
846
847     /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
848     ///
849     /// [`is_alphabetic()`]: #method.is_alphabetic
850     /// [`is_numeric()`]: #method.is_numeric
851     ///
852     /// # Examples
853     ///
854     /// Basic usage:
855     ///
856     /// ```
857     /// assert!('٣'.is_alphanumeric());
858     /// assert!('7'.is_alphanumeric());
859     /// assert!('৬'.is_alphanumeric());
860     /// assert!('¾'.is_alphanumeric());
861     /// assert!('①'.is_alphanumeric());
862     /// assert!('K'.is_alphanumeric());
863     /// assert!('و'.is_alphanumeric());
864     /// assert!('藏'.is_alphanumeric());
865     /// ```
866     #[must_use]
867     #[stable(feature = "rust1", since = "1.0.0")]
868     #[inline]
869     pub fn is_alphanumeric(self) -> bool {
870         self.is_alphabetic() || self.is_numeric()
871     }
872
873     /// Returns `true` if this `char` has the general category for control codes.
874     ///
875     /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
876     /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
877     /// Database][ucd] [`UnicodeData.txt`].
878     ///
879     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
880     /// [ucd]: https://www.unicode.org/reports/tr44/
881     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
882     ///
883     /// # Examples
884     ///
885     /// Basic usage:
886     ///
887     /// ```
888     /// // U+009C, STRING TERMINATOR
889     /// assert!('\9c'.is_control());
890     /// assert!(!'q'.is_control());
891     /// ```
892     #[must_use]
893     #[stable(feature = "rust1", since = "1.0.0")]
894     #[inline]
895     pub fn is_control(self) -> bool {
896         unicode::Cc(self)
897     }
898
899     /// Returns `true` if this `char` has the `Grapheme_Extend` property.
900     ///
901     /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
902     /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
903     /// [`DerivedCoreProperties.txt`].
904     ///
905     /// [uax29]: https://www.unicode.org/reports/tr29/
906     /// [ucd]: https://www.unicode.org/reports/tr44/
907     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
908     #[must_use]
909     #[inline]
910     pub(crate) fn is_grapheme_extended(self) -> bool {
911         unicode::Grapheme_Extend(self)
912     }
913
914     /// Returns `true` if this `char` has one of the general categories for numbers.
915     ///
916     /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
917     /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
918     /// Database][ucd] [`UnicodeData.txt`].
919     ///
920     /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
921     /// If you want everything including characters with overlapping purposes then you might want to use
922     /// a unicode or language-processing library that exposes the appropriate character properties instead
923     /// of looking at the unicode categories.
924     ///
925     /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
926     /// `is_ascii_digit` or `is_digit` instead.
927     ///
928     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
929     /// [ucd]: https://www.unicode.org/reports/tr44/
930     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
931     ///
932     /// # Examples
933     ///
934     /// Basic usage:
935     ///
936     /// ```
937     /// assert!('٣'.is_numeric());
938     /// assert!('7'.is_numeric());
939     /// assert!('৬'.is_numeric());
940     /// assert!('¾'.is_numeric());
941     /// assert!('①'.is_numeric());
942     /// assert!(!'K'.is_numeric());
943     /// assert!(!'و'.is_numeric());
944     /// assert!(!'藏'.is_numeric());
945     /// assert!(!'三'.is_numeric());
946     /// ```
947     #[must_use]
948     #[stable(feature = "rust1", since = "1.0.0")]
949     #[inline]
950     pub fn is_numeric(self) -> bool {
951         match self {
952             '0'..='9' => true,
953             c => c > '\x7f' && unicode::N(c),
954         }
955     }
956
957     /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
958     /// `char`s.
959     ///
960     /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
961     ///
962     /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
963     /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
964     ///
965     /// [ucd]: https://www.unicode.org/reports/tr44/
966     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
967     ///
968     /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
969     /// the `char`(s) given by [`SpecialCasing.txt`].
970     ///
971     /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
972     ///
973     /// This operation performs an unconditional mapping without tailoring. That is, the conversion
974     /// is independent of context and language.
975     ///
976     /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
977     /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
978     ///
979     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
980     ///
981     /// # Examples
982     ///
983     /// As an iterator:
984     ///
985     /// ```
986     /// for c in 'İ'.to_lowercase() {
987     ///     print!("{c}");
988     /// }
989     /// println!();
990     /// ```
991     ///
992     /// Using `println!` directly:
993     ///
994     /// ```
995     /// println!("{}", 'İ'.to_lowercase());
996     /// ```
997     ///
998     /// Both are equivalent to:
999     ///
1000     /// ```
1001     /// println!("i\u{307}");
1002     /// ```
1003     ///
1004     /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1005     ///
1006     /// ```
1007     /// assert_eq!('C'.to_lowercase().to_string(), "c");
1008     ///
1009     /// // Sometimes the result is more than one character:
1010     /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1011     ///
1012     /// // Characters that do not have both uppercase and lowercase
1013     /// // convert into themselves.
1014     /// assert_eq!('山'.to_lowercase().to_string(), "山");
1015     /// ```
1016     #[must_use = "this returns the lowercase character as a new iterator, \
1017                   without modifying the original"]
1018     #[stable(feature = "rust1", since = "1.0.0")]
1019     #[inline]
1020     pub fn to_lowercase(self) -> ToLowercase {
1021         ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1022     }
1023
1024     /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1025     /// `char`s.
1026     ///
1027     /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1028     ///
1029     /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1030     /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1031     ///
1032     /// [ucd]: https://www.unicode.org/reports/tr44/
1033     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1034     ///
1035     /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1036     /// the `char`(s) given by [`SpecialCasing.txt`].
1037     ///
1038     /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1039     ///
1040     /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1041     /// is independent of context and language.
1042     ///
1043     /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1044     /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1045     ///
1046     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1047     ///
1048     /// # Examples
1049     ///
1050     /// As an iterator:
1051     ///
1052     /// ```
1053     /// for c in 'ß'.to_uppercase() {
1054     ///     print!("{c}");
1055     /// }
1056     /// println!();
1057     /// ```
1058     ///
1059     /// Using `println!` directly:
1060     ///
1061     /// ```
1062     /// println!("{}", 'ß'.to_uppercase());
1063     /// ```
1064     ///
1065     /// Both are equivalent to:
1066     ///
1067     /// ```
1068     /// println!("SS");
1069     /// ```
1070     ///
1071     /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1072     ///
1073     /// ```
1074     /// assert_eq!('c'.to_uppercase().to_string(), "C");
1075     ///
1076     /// // Sometimes the result is more than one character:
1077     /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
1078     ///
1079     /// // Characters that do not have both uppercase and lowercase
1080     /// // convert into themselves.
1081     /// assert_eq!('山'.to_uppercase().to_string(), "山");
1082     /// ```
1083     ///
1084     /// # Note on locale
1085     ///
1086     /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1087     ///
1088     /// * 'Dotless': I / ı, sometimes written ï
1089     /// * 'Dotted': İ / i
1090     ///
1091     /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1092     ///
1093     /// ```
1094     /// let upper_i = 'i'.to_uppercase().to_string();
1095     /// ```
1096     ///
1097     /// The value of `upper_i` here relies on the language of the text: if we're
1098     /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
1099     /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1100     ///
1101     /// ```
1102     /// let upper_i = 'i'.to_uppercase().to_string();
1103     ///
1104     /// assert_eq!(upper_i, "I");
1105     /// ```
1106     ///
1107     /// holds across languages.
1108     #[must_use = "this returns the uppercase character as a new iterator, \
1109                   without modifying the original"]
1110     #[stable(feature = "rust1", since = "1.0.0")]
1111     #[inline]
1112     pub fn to_uppercase(self) -> ToUppercase {
1113         ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1114     }
1115
1116     /// Checks if the value is within the ASCII range.
1117     ///
1118     /// # Examples
1119     ///
1120     /// ```
1121     /// let ascii = 'a';
1122     /// let non_ascii = '❤';
1123     ///
1124     /// assert!(ascii.is_ascii());
1125     /// assert!(!non_ascii.is_ascii());
1126     /// ```
1127     #[must_use]
1128     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1129     #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1130     #[inline]
1131     pub const fn is_ascii(&self) -> bool {
1132         *self as u32 <= 0x7F
1133     }
1134
1135     /// Makes a copy of the value in its ASCII upper case equivalent.
1136     ///
1137     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1138     /// but non-ASCII letters are unchanged.
1139     ///
1140     /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1141     ///
1142     /// To uppercase ASCII characters in addition to non-ASCII characters, use
1143     /// [`to_uppercase()`].
1144     ///
1145     /// # Examples
1146     ///
1147     /// ```
1148     /// let ascii = 'a';
1149     /// let non_ascii = '❤';
1150     ///
1151     /// assert_eq!('A', ascii.to_ascii_uppercase());
1152     /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1153     /// ```
1154     ///
1155     /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1156     /// [`to_uppercase()`]: #method.to_uppercase
1157     #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1158     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1159     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1160     #[inline]
1161     pub const fn to_ascii_uppercase(&self) -> char {
1162         if self.is_ascii_lowercase() {
1163             (*self as u8).ascii_change_case_unchecked() as char
1164         } else {
1165             *self
1166         }
1167     }
1168
1169     /// Makes a copy of the value in its ASCII lower case equivalent.
1170     ///
1171     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1172     /// but non-ASCII letters are unchanged.
1173     ///
1174     /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1175     ///
1176     /// To lowercase ASCII characters in addition to non-ASCII characters, use
1177     /// [`to_lowercase()`].
1178     ///
1179     /// # Examples
1180     ///
1181     /// ```
1182     /// let ascii = 'A';
1183     /// let non_ascii = '❤';
1184     ///
1185     /// assert_eq!('a', ascii.to_ascii_lowercase());
1186     /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1187     /// ```
1188     ///
1189     /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1190     /// [`to_lowercase()`]: #method.to_lowercase
1191     #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1192     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1193     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1194     #[inline]
1195     pub const fn to_ascii_lowercase(&self) -> char {
1196         if self.is_ascii_uppercase() {
1197             (*self as u8).ascii_change_case_unchecked() as char
1198         } else {
1199             *self
1200         }
1201     }
1202
1203     /// Checks that two values are an ASCII case-insensitive match.
1204     ///
1205     /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1206     ///
1207     /// # Examples
1208     ///
1209     /// ```
1210     /// let upper_a = 'A';
1211     /// let lower_a = 'a';
1212     /// let lower_z = 'z';
1213     ///
1214     /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1215     /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1216     /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1217     /// ```
1218     ///
1219     /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1220     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1221     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1222     #[inline]
1223     pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1224         self.to_ascii_lowercase() == other.to_ascii_lowercase()
1225     }
1226
1227     /// Converts this type to its ASCII upper case equivalent in-place.
1228     ///
1229     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1230     /// but non-ASCII letters are unchanged.
1231     ///
1232     /// To return a new uppercased value without modifying the existing one, use
1233     /// [`to_ascii_uppercase()`].
1234     ///
1235     /// # Examples
1236     ///
1237     /// ```
1238     /// let mut ascii = 'a';
1239     ///
1240     /// ascii.make_ascii_uppercase();
1241     ///
1242     /// assert_eq!('A', ascii);
1243     /// ```
1244     ///
1245     /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1246     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1247     #[inline]
1248     pub fn make_ascii_uppercase(&mut self) {
1249         *self = self.to_ascii_uppercase();
1250     }
1251
1252     /// Converts this type to its ASCII lower case equivalent in-place.
1253     ///
1254     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1255     /// but non-ASCII letters are unchanged.
1256     ///
1257     /// To return a new lowercased value without modifying the existing one, use
1258     /// [`to_ascii_lowercase()`].
1259     ///
1260     /// # Examples
1261     ///
1262     /// ```
1263     /// let mut ascii = 'A';
1264     ///
1265     /// ascii.make_ascii_lowercase();
1266     ///
1267     /// assert_eq!('a', ascii);
1268     /// ```
1269     ///
1270     /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1271     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1272     #[inline]
1273     pub fn make_ascii_lowercase(&mut self) {
1274         *self = self.to_ascii_lowercase();
1275     }
1276
1277     /// Checks if the value is an ASCII alphabetic character:
1278     ///
1279     /// - U+0041 'A' ..= U+005A 'Z', or
1280     /// - U+0061 'a' ..= U+007A 'z'.
1281     ///
1282     /// # Examples
1283     ///
1284     /// ```
1285     /// let uppercase_a = 'A';
1286     /// let uppercase_g = 'G';
1287     /// let a = 'a';
1288     /// let g = 'g';
1289     /// let zero = '0';
1290     /// let percent = '%';
1291     /// let space = ' ';
1292     /// let lf = '\n';
1293     /// let esc = '\x1b';
1294     ///
1295     /// assert!(uppercase_a.is_ascii_alphabetic());
1296     /// assert!(uppercase_g.is_ascii_alphabetic());
1297     /// assert!(a.is_ascii_alphabetic());
1298     /// assert!(g.is_ascii_alphabetic());
1299     /// assert!(!zero.is_ascii_alphabetic());
1300     /// assert!(!percent.is_ascii_alphabetic());
1301     /// assert!(!space.is_ascii_alphabetic());
1302     /// assert!(!lf.is_ascii_alphabetic());
1303     /// assert!(!esc.is_ascii_alphabetic());
1304     /// ```
1305     #[must_use]
1306     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1307     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1308     #[inline]
1309     pub const fn is_ascii_alphabetic(&self) -> bool {
1310         matches!(*self, 'A'..='Z' | 'a'..='z')
1311     }
1312
1313     /// Checks if the value is an ASCII uppercase character:
1314     /// U+0041 'A' ..= U+005A 'Z'.
1315     ///
1316     /// # Examples
1317     ///
1318     /// ```
1319     /// let uppercase_a = 'A';
1320     /// let uppercase_g = 'G';
1321     /// let a = 'a';
1322     /// let g = 'g';
1323     /// let zero = '0';
1324     /// let percent = '%';
1325     /// let space = ' ';
1326     /// let lf = '\n';
1327     /// let esc = '\x1b';
1328     ///
1329     /// assert!(uppercase_a.is_ascii_uppercase());
1330     /// assert!(uppercase_g.is_ascii_uppercase());
1331     /// assert!(!a.is_ascii_uppercase());
1332     /// assert!(!g.is_ascii_uppercase());
1333     /// assert!(!zero.is_ascii_uppercase());
1334     /// assert!(!percent.is_ascii_uppercase());
1335     /// assert!(!space.is_ascii_uppercase());
1336     /// assert!(!lf.is_ascii_uppercase());
1337     /// assert!(!esc.is_ascii_uppercase());
1338     /// ```
1339     #[must_use]
1340     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1341     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1342     #[inline]
1343     pub const fn is_ascii_uppercase(&self) -> bool {
1344         matches!(*self, 'A'..='Z')
1345     }
1346
1347     /// Checks if the value is an ASCII lowercase character:
1348     /// U+0061 'a' ..= U+007A 'z'.
1349     ///
1350     /// # Examples
1351     ///
1352     /// ```
1353     /// let uppercase_a = 'A';
1354     /// let uppercase_g = 'G';
1355     /// let a = 'a';
1356     /// let g = 'g';
1357     /// let zero = '0';
1358     /// let percent = '%';
1359     /// let space = ' ';
1360     /// let lf = '\n';
1361     /// let esc = '\x1b';
1362     ///
1363     /// assert!(!uppercase_a.is_ascii_lowercase());
1364     /// assert!(!uppercase_g.is_ascii_lowercase());
1365     /// assert!(a.is_ascii_lowercase());
1366     /// assert!(g.is_ascii_lowercase());
1367     /// assert!(!zero.is_ascii_lowercase());
1368     /// assert!(!percent.is_ascii_lowercase());
1369     /// assert!(!space.is_ascii_lowercase());
1370     /// assert!(!lf.is_ascii_lowercase());
1371     /// assert!(!esc.is_ascii_lowercase());
1372     /// ```
1373     #[must_use]
1374     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1375     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1376     #[inline]
1377     pub const fn is_ascii_lowercase(&self) -> bool {
1378         matches!(*self, 'a'..='z')
1379     }
1380
1381     /// Checks if the value is an ASCII alphanumeric character:
1382     ///
1383     /// - U+0041 'A' ..= U+005A 'Z', or
1384     /// - U+0061 'a' ..= U+007A 'z', or
1385     /// - U+0030 '0' ..= U+0039 '9'.
1386     ///
1387     /// # Examples
1388     ///
1389     /// ```
1390     /// let uppercase_a = 'A';
1391     /// let uppercase_g = 'G';
1392     /// let a = 'a';
1393     /// let g = 'g';
1394     /// let zero = '0';
1395     /// let percent = '%';
1396     /// let space = ' ';
1397     /// let lf = '\n';
1398     /// let esc = '\x1b';
1399     ///
1400     /// assert!(uppercase_a.is_ascii_alphanumeric());
1401     /// assert!(uppercase_g.is_ascii_alphanumeric());
1402     /// assert!(a.is_ascii_alphanumeric());
1403     /// assert!(g.is_ascii_alphanumeric());
1404     /// assert!(zero.is_ascii_alphanumeric());
1405     /// assert!(!percent.is_ascii_alphanumeric());
1406     /// assert!(!space.is_ascii_alphanumeric());
1407     /// assert!(!lf.is_ascii_alphanumeric());
1408     /// assert!(!esc.is_ascii_alphanumeric());
1409     /// ```
1410     #[must_use]
1411     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1412     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1413     #[inline]
1414     pub const fn is_ascii_alphanumeric(&self) -> bool {
1415         matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1416     }
1417
1418     /// Checks if the value is an ASCII decimal digit:
1419     /// U+0030 '0' ..= U+0039 '9'.
1420     ///
1421     /// # Examples
1422     ///
1423     /// ```
1424     /// let uppercase_a = 'A';
1425     /// let uppercase_g = 'G';
1426     /// let a = 'a';
1427     /// let g = 'g';
1428     /// let zero = '0';
1429     /// let percent = '%';
1430     /// let space = ' ';
1431     /// let lf = '\n';
1432     /// let esc = '\x1b';
1433     ///
1434     /// assert!(!uppercase_a.is_ascii_digit());
1435     /// assert!(!uppercase_g.is_ascii_digit());
1436     /// assert!(!a.is_ascii_digit());
1437     /// assert!(!g.is_ascii_digit());
1438     /// assert!(zero.is_ascii_digit());
1439     /// assert!(!percent.is_ascii_digit());
1440     /// assert!(!space.is_ascii_digit());
1441     /// assert!(!lf.is_ascii_digit());
1442     /// assert!(!esc.is_ascii_digit());
1443     /// ```
1444     #[must_use]
1445     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1446     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1447     #[inline]
1448     pub const fn is_ascii_digit(&self) -> bool {
1449         matches!(*self, '0'..='9')
1450     }
1451
1452     /// Checks if the value is an ASCII octal digit:
1453     /// U+0030 '0' ..= U+0037 '7'.
1454     ///
1455     /// # Examples
1456     ///
1457     /// ```
1458     /// #![feature(is_ascii_octdigit)]
1459     ///
1460     /// let uppercase_a = 'A';
1461     /// let a = 'a';
1462     /// let zero = '0';
1463     /// let seven = '7';
1464     /// let nine = '9';
1465     /// let percent = '%';
1466     /// let lf = '\n';
1467     ///
1468     /// assert!(!uppercase_a.is_ascii_octdigit());
1469     /// assert!(!a.is_ascii_octdigit());
1470     /// assert!(zero.is_ascii_octdigit());
1471     /// assert!(seven.is_ascii_octdigit());
1472     /// assert!(!nine.is_ascii_octdigit());
1473     /// assert!(!percent.is_ascii_octdigit());
1474     /// assert!(!lf.is_ascii_octdigit());
1475     /// ```
1476     #[must_use]
1477     #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
1478     #[rustc_const_unstable(feature = "is_ascii_octdigit", issue = "101288")]
1479     #[inline]
1480     pub const fn is_ascii_octdigit(&self) -> bool {
1481         matches!(*self, '0'..='7')
1482     }
1483
1484     /// Checks if the value is an ASCII hexadecimal digit:
1485     ///
1486     /// - U+0030 '0' ..= U+0039 '9', or
1487     /// - U+0041 'A' ..= U+0046 'F', or
1488     /// - U+0061 'a' ..= U+0066 'f'.
1489     ///
1490     /// # Examples
1491     ///
1492     /// ```
1493     /// let uppercase_a = 'A';
1494     /// let uppercase_g = 'G';
1495     /// let a = 'a';
1496     /// let g = 'g';
1497     /// let zero = '0';
1498     /// let percent = '%';
1499     /// let space = ' ';
1500     /// let lf = '\n';
1501     /// let esc = '\x1b';
1502     ///
1503     /// assert!(uppercase_a.is_ascii_hexdigit());
1504     /// assert!(!uppercase_g.is_ascii_hexdigit());
1505     /// assert!(a.is_ascii_hexdigit());
1506     /// assert!(!g.is_ascii_hexdigit());
1507     /// assert!(zero.is_ascii_hexdigit());
1508     /// assert!(!percent.is_ascii_hexdigit());
1509     /// assert!(!space.is_ascii_hexdigit());
1510     /// assert!(!lf.is_ascii_hexdigit());
1511     /// assert!(!esc.is_ascii_hexdigit());
1512     /// ```
1513     #[must_use]
1514     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1515     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1516     #[inline]
1517     pub const fn is_ascii_hexdigit(&self) -> bool {
1518         matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1519     }
1520
1521     /// Checks if the value is an ASCII punctuation character:
1522     ///
1523     /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1524     /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1525     /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1526     /// - U+007B ..= U+007E `{ | } ~`
1527     ///
1528     /// # Examples
1529     ///
1530     /// ```
1531     /// let uppercase_a = 'A';
1532     /// let uppercase_g = 'G';
1533     /// let a = 'a';
1534     /// let g = 'g';
1535     /// let zero = '0';
1536     /// let percent = '%';
1537     /// let space = ' ';
1538     /// let lf = '\n';
1539     /// let esc = '\x1b';
1540     ///
1541     /// assert!(!uppercase_a.is_ascii_punctuation());
1542     /// assert!(!uppercase_g.is_ascii_punctuation());
1543     /// assert!(!a.is_ascii_punctuation());
1544     /// assert!(!g.is_ascii_punctuation());
1545     /// assert!(!zero.is_ascii_punctuation());
1546     /// assert!(percent.is_ascii_punctuation());
1547     /// assert!(!space.is_ascii_punctuation());
1548     /// assert!(!lf.is_ascii_punctuation());
1549     /// assert!(!esc.is_ascii_punctuation());
1550     /// ```
1551     #[must_use]
1552     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1553     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1554     #[inline]
1555     pub const fn is_ascii_punctuation(&self) -> bool {
1556         matches!(*self, '!'..='/' | ':'..='@' | '['..='`' | '{'..='~')
1557     }
1558
1559     /// Checks if the value is an ASCII graphic character:
1560     /// U+0021 '!' ..= U+007E '~'.
1561     ///
1562     /// # Examples
1563     ///
1564     /// ```
1565     /// let uppercase_a = 'A';
1566     /// let uppercase_g = 'G';
1567     /// let a = 'a';
1568     /// let g = 'g';
1569     /// let zero = '0';
1570     /// let percent = '%';
1571     /// let space = ' ';
1572     /// let lf = '\n';
1573     /// let esc = '\x1b';
1574     ///
1575     /// assert!(uppercase_a.is_ascii_graphic());
1576     /// assert!(uppercase_g.is_ascii_graphic());
1577     /// assert!(a.is_ascii_graphic());
1578     /// assert!(g.is_ascii_graphic());
1579     /// assert!(zero.is_ascii_graphic());
1580     /// assert!(percent.is_ascii_graphic());
1581     /// assert!(!space.is_ascii_graphic());
1582     /// assert!(!lf.is_ascii_graphic());
1583     /// assert!(!esc.is_ascii_graphic());
1584     /// ```
1585     #[must_use]
1586     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1587     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1588     #[inline]
1589     pub const fn is_ascii_graphic(&self) -> bool {
1590         matches!(*self, '!'..='~')
1591     }
1592
1593     /// Checks if the value is an ASCII whitespace character:
1594     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1595     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1596     ///
1597     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1598     /// whitespace][infra-aw]. There are several other definitions in
1599     /// wide use. For instance, [the POSIX locale][pct] includes
1600     /// U+000B VERTICAL TAB as well as all the above characters,
1601     /// but—from the very same specification—[the default rule for
1602     /// "field splitting" in the Bourne shell][bfs] considers *only*
1603     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1604     ///
1605     /// If you are writing a program that will process an existing
1606     /// file format, check what that format's definition of whitespace is
1607     /// before using this function.
1608     ///
1609     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1610     /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1611     /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1612     ///
1613     /// # Examples
1614     ///
1615     /// ```
1616     /// let uppercase_a = 'A';
1617     /// let uppercase_g = 'G';
1618     /// let a = 'a';
1619     /// let g = 'g';
1620     /// let zero = '0';
1621     /// let percent = '%';
1622     /// let space = ' ';
1623     /// let lf = '\n';
1624     /// let esc = '\x1b';
1625     ///
1626     /// assert!(!uppercase_a.is_ascii_whitespace());
1627     /// assert!(!uppercase_g.is_ascii_whitespace());
1628     /// assert!(!a.is_ascii_whitespace());
1629     /// assert!(!g.is_ascii_whitespace());
1630     /// assert!(!zero.is_ascii_whitespace());
1631     /// assert!(!percent.is_ascii_whitespace());
1632     /// assert!(space.is_ascii_whitespace());
1633     /// assert!(lf.is_ascii_whitespace());
1634     /// assert!(!esc.is_ascii_whitespace());
1635     /// ```
1636     #[must_use]
1637     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1638     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1639     #[inline]
1640     pub const fn is_ascii_whitespace(&self) -> bool {
1641         matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1642     }
1643
1644     /// Checks if the value is an ASCII control character:
1645     /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1646     /// Note that most ASCII whitespace characters are control
1647     /// characters, but SPACE is not.
1648     ///
1649     /// # Examples
1650     ///
1651     /// ```
1652     /// let uppercase_a = 'A';
1653     /// let uppercase_g = 'G';
1654     /// let a = 'a';
1655     /// let g = 'g';
1656     /// let zero = '0';
1657     /// let percent = '%';
1658     /// let space = ' ';
1659     /// let lf = '\n';
1660     /// let esc = '\x1b';
1661     ///
1662     /// assert!(!uppercase_a.is_ascii_control());
1663     /// assert!(!uppercase_g.is_ascii_control());
1664     /// assert!(!a.is_ascii_control());
1665     /// assert!(!g.is_ascii_control());
1666     /// assert!(!zero.is_ascii_control());
1667     /// assert!(!percent.is_ascii_control());
1668     /// assert!(!space.is_ascii_control());
1669     /// assert!(lf.is_ascii_control());
1670     /// assert!(esc.is_ascii_control());
1671     /// ```
1672     #[must_use]
1673     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1674     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1675     #[inline]
1676     pub const fn is_ascii_control(&self) -> bool {
1677         matches!(*self, '\0'..='\x1F' | '\x7F')
1678     }
1679 }
1680
1681 pub(crate) struct EscapeDebugExtArgs {
1682     /// Escape Extended Grapheme codepoints?
1683     pub(crate) escape_grapheme_extended: bool,
1684
1685     /// Escape single quotes?
1686     pub(crate) escape_single_quote: bool,
1687
1688     /// Escape double quotes?
1689     pub(crate) escape_double_quote: bool,
1690 }
1691
1692 impl EscapeDebugExtArgs {
1693     pub(crate) const ESCAPE_ALL: Self = Self {
1694         escape_grapheme_extended: true,
1695         escape_single_quote: true,
1696         escape_double_quote: true,
1697     };
1698 }
1699
1700 #[inline]
1701 const fn len_utf8(code: u32) -> usize {
1702     if code < MAX_ONE_B {
1703         1
1704     } else if code < MAX_TWO_B {
1705         2
1706     } else if code < MAX_THREE_B {
1707         3
1708     } else {
1709         4
1710     }
1711 }
1712
1713 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1714 /// and then returns the subslice of the buffer that contains the encoded character.
1715 ///
1716 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1717 /// (Creating a `char` in the surrogate range is UB.)
1718 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1719 ///
1720 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1721 ///
1722 /// # Panics
1723 ///
1724 /// Panics if the buffer is not large enough.
1725 /// A buffer of length four is large enough to encode any `char`.
1726 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1727 #[doc(hidden)]
1728 #[inline]
1729 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1730     let len = len_utf8(code);
1731     match (len, &mut dst[..]) {
1732         (1, [a, ..]) => {
1733             *a = code as u8;
1734         }
1735         (2, [a, b, ..]) => {
1736             *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
1737             *b = (code & 0x3F) as u8 | TAG_CONT;
1738         }
1739         (3, [a, b, c, ..]) => {
1740             *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
1741             *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1742             *c = (code & 0x3F) as u8 | TAG_CONT;
1743         }
1744         (4, [a, b, c, d, ..]) => {
1745             *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
1746             *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1747             *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1748             *d = (code & 0x3F) as u8 | TAG_CONT;
1749         }
1750         _ => panic!(
1751             "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1752             len,
1753             code,
1754             dst.len(),
1755         ),
1756     };
1757     &mut dst[..len]
1758 }
1759
1760 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1761 /// and then returns the subslice of the buffer that contains the encoded character.
1762 ///
1763 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1764 /// (Creating a `char` in the surrogate range is UB.)
1765 ///
1766 /// # Panics
1767 ///
1768 /// Panics if the buffer is not large enough.
1769 /// A buffer of length 2 is large enough to encode any `char`.
1770 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1771 #[doc(hidden)]
1772 #[inline]
1773 pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1774     // SAFETY: each arm checks whether there are enough bits to write into
1775     unsafe {
1776         if (code & 0xFFFF) == code && !dst.is_empty() {
1777             // The BMP falls through
1778             *dst.get_unchecked_mut(0) = code as u16;
1779             slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
1780         } else if dst.len() >= 2 {
1781             // Supplementary planes break into surrogates.
1782             code -= 0x1_0000;
1783             *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
1784             *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
1785             slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
1786         } else {
1787             panic!(
1788                 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1789                 from_u32_unchecked(code).len_utf16(),
1790                 code,
1791                 dst.len(),
1792             )
1793         }
1794     }
1795 }