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