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