]> git.lizzy.rs Git - rust.git/blob - library/core/src/char/methods.rs
Rollup merge of #82174 - est31:master, r=oli-obk
[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     #[inline]
388     pub fn escape_unicode(self) -> EscapeUnicode {
389         let c = self as u32;
390
391         // or-ing 1 ensures that for c==0 the code computes that one
392         // digit should be printed and (which is the same) avoids the
393         // (31 - 32) underflow
394         let msb = 31 - (c | 1).leading_zeros();
395
396         // the index of the most significant hex digit
397         let ms_hex_digit = msb / 4;
398         EscapeUnicode {
399             c: self,
400             state: EscapeUnicodeState::Backslash,
401             hex_digit_idx: ms_hex_digit as usize,
402         }
403     }
404
405     /// An extended version of `escape_debug` that optionally permits escaping
406     /// Extended Grapheme codepoints. This allows us to format characters like
407     /// nonspacing marks better when they're at the start of a string.
408     #[inline]
409     pub(crate) fn escape_debug_ext(self, escape_grapheme_extended: bool) -> EscapeDebug {
410         let init_state = match self {
411             '\t' => EscapeDefaultState::Backslash('t'),
412             '\r' => EscapeDefaultState::Backslash('r'),
413             '\n' => EscapeDefaultState::Backslash('n'),
414             '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
415             _ if escape_grapheme_extended && self.is_grapheme_extended() => {
416                 EscapeDefaultState::Unicode(self.escape_unicode())
417             }
418             _ if is_printable(self) => EscapeDefaultState::Char(self),
419             _ => EscapeDefaultState::Unicode(self.escape_unicode()),
420         };
421         EscapeDebug(EscapeDefault { state: init_state })
422     }
423
424     /// Returns an iterator that yields the literal escape code of a character
425     /// as `char`s.
426     ///
427     /// This will escape the characters similar to the `Debug` implementations
428     /// of `str` or `char`.
429     ///
430     /// # Examples
431     ///
432     /// As an iterator:
433     ///
434     /// ```
435     /// for c in '\n'.escape_debug() {
436     ///     print!("{}", c);
437     /// }
438     /// println!();
439     /// ```
440     ///
441     /// Using `println!` directly:
442     ///
443     /// ```
444     /// println!("{}", '\n'.escape_debug());
445     /// ```
446     ///
447     /// Both are equivalent to:
448     ///
449     /// ```
450     /// println!("\\n");
451     /// ```
452     ///
453     /// Using `to_string`:
454     ///
455     /// ```
456     /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
457     /// ```
458     #[stable(feature = "char_escape_debug", since = "1.20.0")]
459     #[inline]
460     pub fn escape_debug(self) -> EscapeDebug {
461         self.escape_debug_ext(true)
462     }
463
464     /// Returns an iterator that yields the literal escape code of a character
465     /// as `char`s.
466     ///
467     /// The default is chosen with a bias toward producing literals that are
468     /// legal in a variety of languages, including C++11 and similar C-family
469     /// languages. The exact rules are:
470     ///
471     /// * Tab is escaped as `\t`.
472     /// * Carriage return is escaped as `\r`.
473     /// * Line feed is escaped as `\n`.
474     /// * Single quote is escaped as `\'`.
475     /// * Double quote is escaped as `\"`.
476     /// * Backslash is escaped as `\\`.
477     /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
478     ///   inclusive is not escaped.
479     /// * All other characters are given hexadecimal Unicode escapes; see
480     ///   [`escape_unicode`].
481     ///
482     /// [`escape_unicode`]: #method.escape_unicode
483     ///
484     /// # Examples
485     ///
486     /// As an iterator:
487     ///
488     /// ```
489     /// for c in '"'.escape_default() {
490     ///     print!("{}", c);
491     /// }
492     /// println!();
493     /// ```
494     ///
495     /// Using `println!` directly:
496     ///
497     /// ```
498     /// println!("{}", '"'.escape_default());
499     /// ```
500     ///
501     /// Both are equivalent to:
502     ///
503     /// ```
504     /// println!("\\\"");
505     /// ```
506     ///
507     /// Using `to_string`:
508     ///
509     /// ```
510     /// assert_eq!('"'.escape_default().to_string(), "\\\"");
511     /// ```
512     #[stable(feature = "rust1", since = "1.0.0")]
513     #[inline]
514     pub fn escape_default(self) -> EscapeDefault {
515         let init_state = match self {
516             '\t' => EscapeDefaultState::Backslash('t'),
517             '\r' => EscapeDefaultState::Backslash('r'),
518             '\n' => EscapeDefaultState::Backslash('n'),
519             '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self),
520             '\x20'..='\x7e' => EscapeDefaultState::Char(self),
521             _ => EscapeDefaultState::Unicode(self.escape_unicode()),
522         };
523         EscapeDefault { state: init_state }
524     }
525
526     /// Returns the number of bytes this `char` would need if encoded in UTF-8.
527     ///
528     /// That number of bytes is always between 1 and 4, inclusive.
529     ///
530     /// # Examples
531     ///
532     /// Basic usage:
533     ///
534     /// ```
535     /// let len = 'A'.len_utf8();
536     /// assert_eq!(len, 1);
537     ///
538     /// let len = 'ß'.len_utf8();
539     /// assert_eq!(len, 2);
540     ///
541     /// let len = 'ℝ'.len_utf8();
542     /// assert_eq!(len, 3);
543     ///
544     /// let len = '💣'.len_utf8();
545     /// assert_eq!(len, 4);
546     /// ```
547     ///
548     /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
549     /// would take if each code point was represented as a `char` vs in the `&str` itself:
550     ///
551     /// ```
552     /// // as chars
553     /// let eastern = '東';
554     /// let capital = '京';
555     ///
556     /// // both can be represented as three bytes
557     /// assert_eq!(3, eastern.len_utf8());
558     /// assert_eq!(3, capital.len_utf8());
559     ///
560     /// // as a &str, these two are encoded in UTF-8
561     /// let tokyo = "東京";
562     ///
563     /// let len = eastern.len_utf8() + capital.len_utf8();
564     ///
565     /// // we can see that they take six bytes total...
566     /// assert_eq!(6, tokyo.len());
567     ///
568     /// // ... just like the &str
569     /// assert_eq!(len, tokyo.len());
570     /// ```
571     #[stable(feature = "rust1", since = "1.0.0")]
572     #[inline]
573     pub fn len_utf8(self) -> usize {
574         len_utf8(self as u32)
575     }
576
577     /// Returns the number of 16-bit code units this `char` would need if
578     /// encoded in UTF-16.
579     ///
580     /// See the documentation for [`len_utf8()`] for more explanation of this
581     /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
582     ///
583     /// [`len_utf8()`]: #method.len_utf8
584     ///
585     /// # Examples
586     ///
587     /// Basic usage:
588     ///
589     /// ```
590     /// let n = 'ß'.len_utf16();
591     /// assert_eq!(n, 1);
592     ///
593     /// let len = '💣'.len_utf16();
594     /// assert_eq!(len, 2);
595     /// ```
596     #[stable(feature = "rust1", since = "1.0.0")]
597     #[inline]
598     pub fn len_utf16(self) -> usize {
599         let ch = self as u32;
600         if (ch & 0xFFFF) == ch { 1 } else { 2 }
601     }
602
603     /// Encodes this character as UTF-8 into the provided byte buffer,
604     /// and then returns the subslice of the buffer that contains the encoded character.
605     ///
606     /// # Panics
607     ///
608     /// Panics if the buffer is not large enough.
609     /// A buffer of length four is large enough to encode any `char`.
610     ///
611     /// # Examples
612     ///
613     /// In both of these examples, 'ß' takes two bytes to encode.
614     ///
615     /// ```
616     /// let mut b = [0; 2];
617     ///
618     /// let result = 'ß'.encode_utf8(&mut b);
619     ///
620     /// assert_eq!(result, "ß");
621     ///
622     /// assert_eq!(result.len(), 2);
623     /// ```
624     ///
625     /// A buffer that's too small:
626     ///
627     /// ```should_panic
628     /// let mut b = [0; 1];
629     ///
630     /// // this panics
631     /// 'ß'.encode_utf8(&mut b);
632     /// ```
633     #[stable(feature = "unicode_encode_char", since = "1.15.0")]
634     #[inline]
635     pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
636         // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
637         unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
638     }
639
640     /// Encodes this character as UTF-16 into the provided `u16` buffer,
641     /// and then returns the subslice of the buffer that contains the encoded character.
642     ///
643     /// # Panics
644     ///
645     /// Panics if the buffer is not large enough.
646     /// A buffer of length 2 is large enough to encode any `char`.
647     ///
648     /// # Examples
649     ///
650     /// In both of these examples, '𝕊' takes two `u16`s to encode.
651     ///
652     /// ```
653     /// let mut b = [0; 2];
654     ///
655     /// let result = '𝕊'.encode_utf16(&mut b);
656     ///
657     /// assert_eq!(result.len(), 2);
658     /// ```
659     ///
660     /// A buffer that's too small:
661     ///
662     /// ```should_panic
663     /// let mut b = [0; 1];
664     ///
665     /// // this panics
666     /// '𝕊'.encode_utf16(&mut b);
667     /// ```
668     #[stable(feature = "unicode_encode_char", since = "1.15.0")]
669     #[inline]
670     pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
671         encode_utf16_raw(self as u32, dst)
672     }
673
674     /// Returns `true` if this `char` has the `Alphabetic` property.
675     ///
676     /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
677     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
678     ///
679     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
680     /// [ucd]: https://www.unicode.org/reports/tr44/
681     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
682     ///
683     /// # Examples
684     ///
685     /// Basic usage:
686     ///
687     /// ```
688     /// assert!('a'.is_alphabetic());
689     /// assert!('京'.is_alphabetic());
690     ///
691     /// let c = '💝';
692     /// // love is many things, but it is not alphabetic
693     /// assert!(!c.is_alphabetic());
694     /// ```
695     #[stable(feature = "rust1", since = "1.0.0")]
696     #[inline]
697     pub fn is_alphabetic(self) -> bool {
698         match self {
699             'a'..='z' | 'A'..='Z' => true,
700             c => c > '\x7f' && unicode::Alphabetic(c),
701         }
702     }
703
704     /// Returns `true` if this `char` has the `Lowercase` property.
705     ///
706     /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
707     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
708     ///
709     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
710     /// [ucd]: https://www.unicode.org/reports/tr44/
711     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
712     ///
713     /// # Examples
714     ///
715     /// Basic usage:
716     ///
717     /// ```
718     /// assert!('a'.is_lowercase());
719     /// assert!('δ'.is_lowercase());
720     /// assert!(!'A'.is_lowercase());
721     /// assert!(!'Δ'.is_lowercase());
722     ///
723     /// // The various Chinese scripts and punctuation do not have case, and so:
724     /// assert!(!'中'.is_lowercase());
725     /// assert!(!' '.is_lowercase());
726     /// ```
727     #[stable(feature = "rust1", since = "1.0.0")]
728     #[inline]
729     pub fn is_lowercase(self) -> bool {
730         match self {
731             'a'..='z' => true,
732             c => c > '\x7f' && unicode::Lowercase(c),
733         }
734     }
735
736     /// Returns `true` if this `char` has the `Uppercase` property.
737     ///
738     /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
739     /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
740     ///
741     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
742     /// [ucd]: https://www.unicode.org/reports/tr44/
743     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
744     ///
745     /// # Examples
746     ///
747     /// Basic usage:
748     ///
749     /// ```
750     /// assert!(!'a'.is_uppercase());
751     /// assert!(!'δ'.is_uppercase());
752     /// assert!('A'.is_uppercase());
753     /// assert!('Δ'.is_uppercase());
754     ///
755     /// // The various Chinese scripts and punctuation do not have case, and so:
756     /// assert!(!'中'.is_uppercase());
757     /// assert!(!' '.is_uppercase());
758     /// ```
759     #[stable(feature = "rust1", since = "1.0.0")]
760     #[inline]
761     pub fn is_uppercase(self) -> bool {
762         match self {
763             'A'..='Z' => true,
764             c => c > '\x7f' && unicode::Uppercase(c),
765         }
766     }
767
768     /// Returns `true` if this `char` has the `White_Space` property.
769     ///
770     /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
771     ///
772     /// [ucd]: https://www.unicode.org/reports/tr44/
773     /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
774     ///
775     /// # Examples
776     ///
777     /// Basic usage:
778     ///
779     /// ```
780     /// assert!(' '.is_whitespace());
781     ///
782     /// // a non-breaking space
783     /// assert!('\u{A0}'.is_whitespace());
784     ///
785     /// assert!(!'越'.is_whitespace());
786     /// ```
787     #[stable(feature = "rust1", since = "1.0.0")]
788     #[inline]
789     pub fn is_whitespace(self) -> bool {
790         match self {
791             ' ' | '\x09'..='\x0d' => true,
792             c => c > '\x7f' && unicode::White_Space(c),
793         }
794     }
795
796     /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
797     ///
798     /// [`is_alphabetic()`]: #method.is_alphabetic
799     /// [`is_numeric()`]: #method.is_numeric
800     ///
801     /// # Examples
802     ///
803     /// Basic usage:
804     ///
805     /// ```
806     /// assert!('٣'.is_alphanumeric());
807     /// assert!('7'.is_alphanumeric());
808     /// assert!('৬'.is_alphanumeric());
809     /// assert!('¾'.is_alphanumeric());
810     /// assert!('①'.is_alphanumeric());
811     /// assert!('K'.is_alphanumeric());
812     /// assert!('و'.is_alphanumeric());
813     /// assert!('藏'.is_alphanumeric());
814     /// ```
815     #[stable(feature = "rust1", since = "1.0.0")]
816     #[inline]
817     pub fn is_alphanumeric(self) -> bool {
818         self.is_alphabetic() || self.is_numeric()
819     }
820
821     /// Returns `true` if this `char` has the general category for control codes.
822     ///
823     /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
824     /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
825     /// Database][ucd] [`UnicodeData.txt`].
826     ///
827     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
828     /// [ucd]: https://www.unicode.org/reports/tr44/
829     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
830     ///
831     /// # Examples
832     ///
833     /// Basic usage:
834     ///
835     /// ```
836     /// // U+009C, STRING TERMINATOR
837     /// assert!('\9c'.is_control());
838     /// assert!(!'q'.is_control());
839     /// ```
840     #[stable(feature = "rust1", since = "1.0.0")]
841     #[inline]
842     pub fn is_control(self) -> bool {
843         unicode::Cc(self)
844     }
845
846     /// Returns `true` if this `char` has the `Grapheme_Extend` property.
847     ///
848     /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
849     /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
850     /// [`DerivedCoreProperties.txt`].
851     ///
852     /// [uax29]: https://www.unicode.org/reports/tr29/
853     /// [ucd]: https://www.unicode.org/reports/tr44/
854     /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
855     #[inline]
856     pub(crate) fn is_grapheme_extended(self) -> bool {
857         unicode::Grapheme_Extend(self)
858     }
859
860     /// Returns `true` if this `char` has one of the general categories for numbers.
861     ///
862     /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
863     /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
864     /// Database][ucd] [`UnicodeData.txt`].
865     ///
866     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
867     /// [ucd]: https://www.unicode.org/reports/tr44/
868     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
869     ///
870     /// # Examples
871     ///
872     /// Basic usage:
873     ///
874     /// ```
875     /// assert!('٣'.is_numeric());
876     /// assert!('7'.is_numeric());
877     /// assert!('৬'.is_numeric());
878     /// assert!('¾'.is_numeric());
879     /// assert!('①'.is_numeric());
880     /// assert!(!'K'.is_numeric());
881     /// assert!(!'و'.is_numeric());
882     /// assert!(!'藏'.is_numeric());
883     /// ```
884     #[stable(feature = "rust1", since = "1.0.0")]
885     #[inline]
886     pub fn is_numeric(self) -> bool {
887         match self {
888             '0'..='9' => true,
889             c => c > '\x7f' && unicode::N(c),
890         }
891     }
892
893     /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
894     /// `char`s.
895     ///
896     /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
897     ///
898     /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
899     /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
900     ///
901     /// [ucd]: https://www.unicode.org/reports/tr44/
902     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
903     ///
904     /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
905     /// the `char`(s) given by [`SpecialCasing.txt`].
906     ///
907     /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
908     ///
909     /// This operation performs an unconditional mapping without tailoring. That is, the conversion
910     /// is independent of context and language.
911     ///
912     /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
913     /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
914     ///
915     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
916     ///
917     /// # Examples
918     ///
919     /// As an iterator:
920     ///
921     /// ```
922     /// for c in 'İ'.to_lowercase() {
923     ///     print!("{}", c);
924     /// }
925     /// println!();
926     /// ```
927     ///
928     /// Using `println!` directly:
929     ///
930     /// ```
931     /// println!("{}", 'İ'.to_lowercase());
932     /// ```
933     ///
934     /// Both are equivalent to:
935     ///
936     /// ```
937     /// println!("i\u{307}");
938     /// ```
939     ///
940     /// Using `to_string`:
941     ///
942     /// ```
943     /// assert_eq!('C'.to_lowercase().to_string(), "c");
944     ///
945     /// // Sometimes the result is more than one character:
946     /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
947     ///
948     /// // Characters that do not have both uppercase and lowercase
949     /// // convert into themselves.
950     /// assert_eq!('山'.to_lowercase().to_string(), "山");
951     /// ```
952     #[stable(feature = "rust1", since = "1.0.0")]
953     #[inline]
954     pub fn to_lowercase(self) -> ToLowercase {
955         ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
956     }
957
958     /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
959     /// `char`s.
960     ///
961     /// If this `char` does not have a uppercase mapping, the iterator yields the same `char`.
962     ///
963     /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
964     /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
965     ///
966     /// [ucd]: https://www.unicode.org/reports/tr44/
967     /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
968     ///
969     /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
970     /// the `char`(s) given by [`SpecialCasing.txt`].
971     ///
972     /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
973     ///
974     /// This operation performs an unconditional mapping without tailoring. That is, the conversion
975     /// is independent of context and language.
976     ///
977     /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
978     /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
979     ///
980     /// [Unicode Standard]: https://www.unicode.org/versions/latest/
981     ///
982     /// # Examples
983     ///
984     /// As an iterator:
985     ///
986     /// ```
987     /// for c in 'ß'.to_uppercase() {
988     ///     print!("{}", c);
989     /// }
990     /// println!();
991     /// ```
992     ///
993     /// Using `println!` directly:
994     ///
995     /// ```
996     /// println!("{}", 'ß'.to_uppercase());
997     /// ```
998     ///
999     /// Both are equivalent to:
1000     ///
1001     /// ```
1002     /// println!("SS");
1003     /// ```
1004     ///
1005     /// Using `to_string`:
1006     ///
1007     /// ```
1008     /// assert_eq!('c'.to_uppercase().to_string(), "C");
1009     ///
1010     /// // Sometimes the result is more than one character:
1011     /// assert_eq!('ß'.to_uppercase().to_string(), "SS");
1012     ///
1013     /// // Characters that do not have both uppercase and lowercase
1014     /// // convert into themselves.
1015     /// assert_eq!('山'.to_uppercase().to_string(), "山");
1016     /// ```
1017     ///
1018     /// # Note on locale
1019     ///
1020     /// In Turkish, the equivalent of 'i' in Latin has five forms instead of two:
1021     ///
1022     /// * 'Dotless': I / ı, sometimes written ï
1023     /// * 'Dotted': İ / i
1024     ///
1025     /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1026     ///
1027     /// ```
1028     /// let upper_i = 'i'.to_uppercase().to_string();
1029     /// ```
1030     ///
1031     /// The value of `upper_i` here relies on the language of the text: if we're
1032     /// in `en-US`, it should be `"I"`, but if we're in `tr_TR`, it should
1033     /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1034     ///
1035     /// ```
1036     /// let upper_i = 'i'.to_uppercase().to_string();
1037     ///
1038     /// assert_eq!(upper_i, "I");
1039     /// ```
1040     ///
1041     /// holds across languages.
1042     #[stable(feature = "rust1", since = "1.0.0")]
1043     #[inline]
1044     pub fn to_uppercase(self) -> ToUppercase {
1045         ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1046     }
1047
1048     /// Checks if the value is within the ASCII range.
1049     ///
1050     /// # Examples
1051     ///
1052     /// ```
1053     /// let ascii = 'a';
1054     /// let non_ascii = '❤';
1055     ///
1056     /// assert!(ascii.is_ascii());
1057     /// assert!(!non_ascii.is_ascii());
1058     /// ```
1059     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1060     #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.32.0")]
1061     #[inline]
1062     pub const fn is_ascii(&self) -> bool {
1063         *self as u32 <= 0x7F
1064     }
1065
1066     /// Makes a copy of the value in its ASCII upper case equivalent.
1067     ///
1068     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1069     /// but non-ASCII letters are unchanged.
1070     ///
1071     /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1072     ///
1073     /// To uppercase ASCII characters in addition to non-ASCII characters, use
1074     /// [`to_uppercase()`].
1075     ///
1076     /// # Examples
1077     ///
1078     /// ```
1079     /// let ascii = 'a';
1080     /// let non_ascii = '❤';
1081     ///
1082     /// assert_eq!('A', ascii.to_ascii_uppercase());
1083     /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1084     /// ```
1085     ///
1086     /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1087     /// [`to_uppercase()`]: #method.to_uppercase
1088     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1089     #[inline]
1090     pub fn to_ascii_uppercase(&self) -> char {
1091         if self.is_ascii() { (*self as u8).to_ascii_uppercase() as char } else { *self }
1092     }
1093
1094     /// Makes a copy of the value in its ASCII lower case equivalent.
1095     ///
1096     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1097     /// but non-ASCII letters are unchanged.
1098     ///
1099     /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1100     ///
1101     /// To lowercase ASCII characters in addition to non-ASCII characters, use
1102     /// [`to_lowercase()`].
1103     ///
1104     /// # Examples
1105     ///
1106     /// ```
1107     /// let ascii = 'A';
1108     /// let non_ascii = '❤';
1109     ///
1110     /// assert_eq!('a', ascii.to_ascii_lowercase());
1111     /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1112     /// ```
1113     ///
1114     /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1115     /// [`to_lowercase()`]: #method.to_lowercase
1116     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1117     #[inline]
1118     pub fn to_ascii_lowercase(&self) -> char {
1119         if self.is_ascii() { (*self as u8).to_ascii_lowercase() as char } else { *self }
1120     }
1121
1122     /// Checks that two values are an ASCII case-insensitive match.
1123     ///
1124     /// Equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
1125     ///
1126     /// # Examples
1127     ///
1128     /// ```
1129     /// let upper_a = 'A';
1130     /// let lower_a = 'a';
1131     /// let lower_z = 'z';
1132     ///
1133     /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1134     /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1135     /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1136     /// ```
1137     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1138     #[inline]
1139     pub fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1140         self.to_ascii_lowercase() == other.to_ascii_lowercase()
1141     }
1142
1143     /// Converts this type to its ASCII upper case equivalent in-place.
1144     ///
1145     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1146     /// but non-ASCII letters are unchanged.
1147     ///
1148     /// To return a new uppercased value without modifying the existing one, use
1149     /// [`to_ascii_uppercase()`].
1150     ///
1151     /// # Examples
1152     ///
1153     /// ```
1154     /// let mut ascii = 'a';
1155     ///
1156     /// ascii.make_ascii_uppercase();
1157     ///
1158     /// assert_eq!('A', ascii);
1159     /// ```
1160     ///
1161     /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1162     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1163     #[inline]
1164     pub fn make_ascii_uppercase(&mut self) {
1165         *self = self.to_ascii_uppercase();
1166     }
1167
1168     /// Converts this type to its ASCII lower case equivalent in-place.
1169     ///
1170     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1171     /// but non-ASCII letters are unchanged.
1172     ///
1173     /// To return a new lowercased value without modifying the existing one, use
1174     /// [`to_ascii_lowercase()`].
1175     ///
1176     /// # Examples
1177     ///
1178     /// ```
1179     /// let mut ascii = 'A';
1180     ///
1181     /// ascii.make_ascii_lowercase();
1182     ///
1183     /// assert_eq!('a', ascii);
1184     /// ```
1185     ///
1186     /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1187     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1188     #[inline]
1189     pub fn make_ascii_lowercase(&mut self) {
1190         *self = self.to_ascii_lowercase();
1191     }
1192
1193     /// Checks if the value is an ASCII alphabetic character:
1194     ///
1195     /// - U+0041 'A' ..= U+005A 'Z', or
1196     /// - U+0061 'a' ..= U+007A 'z'.
1197     ///
1198     /// # Examples
1199     ///
1200     /// ```
1201     /// let uppercase_a = 'A';
1202     /// let uppercase_g = 'G';
1203     /// let a = 'a';
1204     /// let g = 'g';
1205     /// let zero = '0';
1206     /// let percent = '%';
1207     /// let space = ' ';
1208     /// let lf = '\n';
1209     /// let esc: char = 0x1b_u8.into();
1210     ///
1211     /// assert!(uppercase_a.is_ascii_alphabetic());
1212     /// assert!(uppercase_g.is_ascii_alphabetic());
1213     /// assert!(a.is_ascii_alphabetic());
1214     /// assert!(g.is_ascii_alphabetic());
1215     /// assert!(!zero.is_ascii_alphabetic());
1216     /// assert!(!percent.is_ascii_alphabetic());
1217     /// assert!(!space.is_ascii_alphabetic());
1218     /// assert!(!lf.is_ascii_alphabetic());
1219     /// assert!(!esc.is_ascii_alphabetic());
1220     /// ```
1221     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1222     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1223     #[inline]
1224     pub const fn is_ascii_alphabetic(&self) -> bool {
1225         matches!(*self, 'A'..='Z' | 'a'..='z')
1226     }
1227
1228     /// Checks if the value is an ASCII uppercase character:
1229     /// U+0041 'A' ..= U+005A 'Z'.
1230     ///
1231     /// # Examples
1232     ///
1233     /// ```
1234     /// let uppercase_a = 'A';
1235     /// let uppercase_g = 'G';
1236     /// let a = 'a';
1237     /// let g = 'g';
1238     /// let zero = '0';
1239     /// let percent = '%';
1240     /// let space = ' ';
1241     /// let lf = '\n';
1242     /// let esc: char = 0x1b_u8.into();
1243     ///
1244     /// assert!(uppercase_a.is_ascii_uppercase());
1245     /// assert!(uppercase_g.is_ascii_uppercase());
1246     /// assert!(!a.is_ascii_uppercase());
1247     /// assert!(!g.is_ascii_uppercase());
1248     /// assert!(!zero.is_ascii_uppercase());
1249     /// assert!(!percent.is_ascii_uppercase());
1250     /// assert!(!space.is_ascii_uppercase());
1251     /// assert!(!lf.is_ascii_uppercase());
1252     /// assert!(!esc.is_ascii_uppercase());
1253     /// ```
1254     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1255     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1256     #[inline]
1257     pub const fn is_ascii_uppercase(&self) -> bool {
1258         matches!(*self, 'A'..='Z')
1259     }
1260
1261     /// Checks if the value is an ASCII lowercase character:
1262     /// U+0061 'a' ..= U+007A 'z'.
1263     ///
1264     /// # Examples
1265     ///
1266     /// ```
1267     /// let uppercase_a = 'A';
1268     /// let uppercase_g = 'G';
1269     /// let a = 'a';
1270     /// let g = 'g';
1271     /// let zero = '0';
1272     /// let percent = '%';
1273     /// let space = ' ';
1274     /// let lf = '\n';
1275     /// let esc: char = 0x1b_u8.into();
1276     ///
1277     /// assert!(!uppercase_a.is_ascii_lowercase());
1278     /// assert!(!uppercase_g.is_ascii_lowercase());
1279     /// assert!(a.is_ascii_lowercase());
1280     /// assert!(g.is_ascii_lowercase());
1281     /// assert!(!zero.is_ascii_lowercase());
1282     /// assert!(!percent.is_ascii_lowercase());
1283     /// assert!(!space.is_ascii_lowercase());
1284     /// assert!(!lf.is_ascii_lowercase());
1285     /// assert!(!esc.is_ascii_lowercase());
1286     /// ```
1287     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1288     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1289     #[inline]
1290     pub const fn is_ascii_lowercase(&self) -> bool {
1291         matches!(*self, 'a'..='z')
1292     }
1293
1294     /// Checks if the value is an ASCII alphanumeric character:
1295     ///
1296     /// - U+0041 'A' ..= U+005A 'Z', or
1297     /// - U+0061 'a' ..= U+007A 'z', or
1298     /// - U+0030 '0' ..= U+0039 '9'.
1299     ///
1300     /// # Examples
1301     ///
1302     /// ```
1303     /// let uppercase_a = 'A';
1304     /// let uppercase_g = 'G';
1305     /// let a = 'a';
1306     /// let g = 'g';
1307     /// let zero = '0';
1308     /// let percent = '%';
1309     /// let space = ' ';
1310     /// let lf = '\n';
1311     /// let esc: char = 0x1b_u8.into();
1312     ///
1313     /// assert!(uppercase_a.is_ascii_alphanumeric());
1314     /// assert!(uppercase_g.is_ascii_alphanumeric());
1315     /// assert!(a.is_ascii_alphanumeric());
1316     /// assert!(g.is_ascii_alphanumeric());
1317     /// assert!(zero.is_ascii_alphanumeric());
1318     /// assert!(!percent.is_ascii_alphanumeric());
1319     /// assert!(!space.is_ascii_alphanumeric());
1320     /// assert!(!lf.is_ascii_alphanumeric());
1321     /// assert!(!esc.is_ascii_alphanumeric());
1322     /// ```
1323     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1324     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1325     #[inline]
1326     pub const fn is_ascii_alphanumeric(&self) -> bool {
1327         matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
1328     }
1329
1330     /// Checks if the value is an ASCII decimal digit:
1331     /// U+0030 '0' ..= U+0039 '9'.
1332     ///
1333     /// # Examples
1334     ///
1335     /// ```
1336     /// let uppercase_a = 'A';
1337     /// let uppercase_g = 'G';
1338     /// let a = 'a';
1339     /// let g = 'g';
1340     /// let zero = '0';
1341     /// let percent = '%';
1342     /// let space = ' ';
1343     /// let lf = '\n';
1344     /// let esc: char = 0x1b_u8.into();
1345     ///
1346     /// assert!(!uppercase_a.is_ascii_digit());
1347     /// assert!(!uppercase_g.is_ascii_digit());
1348     /// assert!(!a.is_ascii_digit());
1349     /// assert!(!g.is_ascii_digit());
1350     /// assert!(zero.is_ascii_digit());
1351     /// assert!(!percent.is_ascii_digit());
1352     /// assert!(!space.is_ascii_digit());
1353     /// assert!(!lf.is_ascii_digit());
1354     /// assert!(!esc.is_ascii_digit());
1355     /// ```
1356     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1357     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1358     #[inline]
1359     pub const fn is_ascii_digit(&self) -> bool {
1360         matches!(*self, '0'..='9')
1361     }
1362
1363     /// Checks if the value is an ASCII hexadecimal digit:
1364     ///
1365     /// - U+0030 '0' ..= U+0039 '9', or
1366     /// - U+0041 'A' ..= U+0046 'F', or
1367     /// - U+0061 'a' ..= U+0066 'f'.
1368     ///
1369     /// # Examples
1370     ///
1371     /// ```
1372     /// let uppercase_a = 'A';
1373     /// let uppercase_g = 'G';
1374     /// let a = 'a';
1375     /// let g = 'g';
1376     /// let zero = '0';
1377     /// let percent = '%';
1378     /// let space = ' ';
1379     /// let lf = '\n';
1380     /// let esc: char = 0x1b_u8.into();
1381     ///
1382     /// assert!(uppercase_a.is_ascii_hexdigit());
1383     /// assert!(!uppercase_g.is_ascii_hexdigit());
1384     /// assert!(a.is_ascii_hexdigit());
1385     /// assert!(!g.is_ascii_hexdigit());
1386     /// assert!(zero.is_ascii_hexdigit());
1387     /// assert!(!percent.is_ascii_hexdigit());
1388     /// assert!(!space.is_ascii_hexdigit());
1389     /// assert!(!lf.is_ascii_hexdigit());
1390     /// assert!(!esc.is_ascii_hexdigit());
1391     /// ```
1392     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1393     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1394     #[inline]
1395     pub const fn is_ascii_hexdigit(&self) -> bool {
1396         matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
1397     }
1398
1399     /// Checks if the value is an ASCII punctuation character:
1400     ///
1401     /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1402     /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1403     /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1404     /// - U+007B ..= U+007E `{ | } ~`
1405     ///
1406     /// # Examples
1407     ///
1408     /// ```
1409     /// let uppercase_a = 'A';
1410     /// let uppercase_g = 'G';
1411     /// let a = 'a';
1412     /// let g = 'g';
1413     /// let zero = '0';
1414     /// let percent = '%';
1415     /// let space = ' ';
1416     /// let lf = '\n';
1417     /// let esc: char = 0x1b_u8.into();
1418     ///
1419     /// assert!(!uppercase_a.is_ascii_punctuation());
1420     /// assert!(!uppercase_g.is_ascii_punctuation());
1421     /// assert!(!a.is_ascii_punctuation());
1422     /// assert!(!g.is_ascii_punctuation());
1423     /// assert!(!zero.is_ascii_punctuation());
1424     /// assert!(percent.is_ascii_punctuation());
1425     /// assert!(!space.is_ascii_punctuation());
1426     /// assert!(!lf.is_ascii_punctuation());
1427     /// assert!(!esc.is_ascii_punctuation());
1428     /// ```
1429     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1430     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1431     #[inline]
1432     pub const fn is_ascii_punctuation(&self) -> bool {
1433         matches!(*self, '!'..='/' | ':'..='@' | '['..='`' | '{'..='~')
1434     }
1435
1436     /// Checks if the value is an ASCII graphic character:
1437     /// U+0021 '!' ..= U+007E '~'.
1438     ///
1439     /// # Examples
1440     ///
1441     /// ```
1442     /// let uppercase_a = 'A';
1443     /// let uppercase_g = 'G';
1444     /// let a = 'a';
1445     /// let g = 'g';
1446     /// let zero = '0';
1447     /// let percent = '%';
1448     /// let space = ' ';
1449     /// let lf = '\n';
1450     /// let esc: char = 0x1b_u8.into();
1451     ///
1452     /// assert!(uppercase_a.is_ascii_graphic());
1453     /// assert!(uppercase_g.is_ascii_graphic());
1454     /// assert!(a.is_ascii_graphic());
1455     /// assert!(g.is_ascii_graphic());
1456     /// assert!(zero.is_ascii_graphic());
1457     /// assert!(percent.is_ascii_graphic());
1458     /// assert!(!space.is_ascii_graphic());
1459     /// assert!(!lf.is_ascii_graphic());
1460     /// assert!(!esc.is_ascii_graphic());
1461     /// ```
1462     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1463     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1464     #[inline]
1465     pub const fn is_ascii_graphic(&self) -> bool {
1466         matches!(*self, '!'..='~')
1467     }
1468
1469     /// Checks if the value is an ASCII whitespace character:
1470     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1471     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1472     ///
1473     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1474     /// whitespace][infra-aw]. There are several other definitions in
1475     /// wide use. For instance, [the POSIX locale][pct] includes
1476     /// U+000B VERTICAL TAB as well as all the above characters,
1477     /// but—from the very same specification—[the default rule for
1478     /// "field splitting" in the Bourne shell][bfs] considers *only*
1479     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1480     ///
1481     /// If you are writing a program that will process an existing
1482     /// file format, check what that format's definition of whitespace is
1483     /// before using this function.
1484     ///
1485     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1486     /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1487     /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1488     ///
1489     /// # Examples
1490     ///
1491     /// ```
1492     /// let uppercase_a = 'A';
1493     /// let uppercase_g = 'G';
1494     /// let a = 'a';
1495     /// let g = 'g';
1496     /// let zero = '0';
1497     /// let percent = '%';
1498     /// let space = ' ';
1499     /// let lf = '\n';
1500     /// let esc: char = 0x1b_u8.into();
1501     ///
1502     /// assert!(!uppercase_a.is_ascii_whitespace());
1503     /// assert!(!uppercase_g.is_ascii_whitespace());
1504     /// assert!(!a.is_ascii_whitespace());
1505     /// assert!(!g.is_ascii_whitespace());
1506     /// assert!(!zero.is_ascii_whitespace());
1507     /// assert!(!percent.is_ascii_whitespace());
1508     /// assert!(space.is_ascii_whitespace());
1509     /// assert!(lf.is_ascii_whitespace());
1510     /// assert!(!esc.is_ascii_whitespace());
1511     /// ```
1512     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1513     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1514     #[inline]
1515     pub const fn is_ascii_whitespace(&self) -> bool {
1516         matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1517     }
1518
1519     /// Checks if the value is an ASCII control character:
1520     /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1521     /// Note that most ASCII whitespace characters are control
1522     /// characters, but SPACE is not.
1523     ///
1524     /// # Examples
1525     ///
1526     /// ```
1527     /// let uppercase_a = 'A';
1528     /// let uppercase_g = 'G';
1529     /// let a = 'a';
1530     /// let g = 'g';
1531     /// let zero = '0';
1532     /// let percent = '%';
1533     /// let space = ' ';
1534     /// let lf = '\n';
1535     /// let esc: char = 0x1b_u8.into();
1536     ///
1537     /// assert!(!uppercase_a.is_ascii_control());
1538     /// assert!(!uppercase_g.is_ascii_control());
1539     /// assert!(!a.is_ascii_control());
1540     /// assert!(!g.is_ascii_control());
1541     /// assert!(!zero.is_ascii_control());
1542     /// assert!(!percent.is_ascii_control());
1543     /// assert!(!space.is_ascii_control());
1544     /// assert!(lf.is_ascii_control());
1545     /// assert!(esc.is_ascii_control());
1546     /// ```
1547     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1548     #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1549     #[inline]
1550     pub const fn is_ascii_control(&self) -> bool {
1551         matches!(*self, '\0'..='\x1F' | '\x7F')
1552     }
1553 }
1554
1555 #[inline]
1556 fn len_utf8(code: u32) -> usize {
1557     if code < MAX_ONE_B {
1558         1
1559     } else if code < MAX_TWO_B {
1560         2
1561     } else if code < MAX_THREE_B {
1562         3
1563     } else {
1564         4
1565     }
1566 }
1567
1568 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1569 /// and then returns the subslice of the buffer that contains the encoded character.
1570 ///
1571 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1572 /// (Creating a `char` in the surrogate range is UB.)
1573 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1574 ///
1575 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1576 ///
1577 /// # Panics
1578 ///
1579 /// Panics if the buffer is not large enough.
1580 /// A buffer of length four is large enough to encode any `char`.
1581 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1582 #[doc(hidden)]
1583 #[inline]
1584 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1585     let len = len_utf8(code);
1586     match (len, &mut dst[..]) {
1587         (1, [a, ..]) => {
1588             *a = code as u8;
1589         }
1590         (2, [a, b, ..]) => {
1591             *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
1592             *b = (code & 0x3F) as u8 | TAG_CONT;
1593         }
1594         (3, [a, b, c, ..]) => {
1595             *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
1596             *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1597             *c = (code & 0x3F) as u8 | TAG_CONT;
1598         }
1599         (4, [a, b, c, d, ..]) => {
1600             *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
1601             *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1602             *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1603             *d = (code & 0x3F) as u8 | TAG_CONT;
1604         }
1605         _ => panic!(
1606             "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1607             len,
1608             code,
1609             dst.len(),
1610         ),
1611     };
1612     &mut dst[..len]
1613 }
1614
1615 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1616 /// and then returns the subslice of the buffer that contains the encoded character.
1617 ///
1618 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1619 /// (Creating a `char` in the surrogate range is UB.)
1620 ///
1621 /// # Panics
1622 ///
1623 /// Panics if the buffer is not large enough.
1624 /// A buffer of length 2 is large enough to encode any `char`.
1625 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1626 #[doc(hidden)]
1627 #[inline]
1628 pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1629     // SAFETY: each arm checks whether there are enough bits to write into
1630     unsafe {
1631         if (code & 0xFFFF) == code && !dst.is_empty() {
1632             // The BMP falls through
1633             *dst.get_unchecked_mut(0) = code as u16;
1634             slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
1635         } else if dst.len() >= 2 {
1636             // Supplementary planes break into surrogates.
1637             code -= 0x1_0000;
1638             *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
1639             *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
1640             slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
1641         } else {
1642             panic!(
1643                 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1644                 from_u32_unchecked(code).len_utf16(),
1645                 code,
1646                 dst.len(),
1647             )
1648         }
1649     }
1650 }