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