]> git.proxmox.com Git - rustc.git/blob - src/libcore/char/methods.rs
New upstream version 1.46.0~beta.2+dfsg1
[rustc.git] / src / libcore / 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_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1230 #[inline]
1231 pub const fn is_ascii_alphabetic(&self) -> bool {
1232 match *self {
1233 'A'..='Z' | 'a'..='z' => true,
1234 _ => false,
1235 }
1236 }
1237
1238 /// Checks if the value is an ASCII uppercase character:
1239 /// U+0041 'A' ..= U+005A 'Z'.
1240 ///
1241 /// # Examples
1242 ///
1243 /// ```
1244 /// let uppercase_a = 'A';
1245 /// let uppercase_g = 'G';
1246 /// let a = 'a';
1247 /// let g = 'g';
1248 /// let zero = '0';
1249 /// let percent = '%';
1250 /// let space = ' ';
1251 /// let lf = '\n';
1252 /// let esc: char = 0x1b_u8.into();
1253 ///
1254 /// assert!(uppercase_a.is_ascii_uppercase());
1255 /// assert!(uppercase_g.is_ascii_uppercase());
1256 /// assert!(!a.is_ascii_uppercase());
1257 /// assert!(!g.is_ascii_uppercase());
1258 /// assert!(!zero.is_ascii_uppercase());
1259 /// assert!(!percent.is_ascii_uppercase());
1260 /// assert!(!space.is_ascii_uppercase());
1261 /// assert!(!lf.is_ascii_uppercase());
1262 /// assert!(!esc.is_ascii_uppercase());
1263 /// ```
1264 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1265 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1266 #[inline]
1267 pub const fn is_ascii_uppercase(&self) -> bool {
1268 match *self {
1269 'A'..='Z' => true,
1270 _ => false,
1271 }
1272 }
1273
1274 /// Checks if the value is an ASCII lowercase character:
1275 /// U+0061 'a' ..= U+007A 'z'.
1276 ///
1277 /// # Examples
1278 ///
1279 /// ```
1280 /// let uppercase_a = 'A';
1281 /// let uppercase_g = 'G';
1282 /// let a = 'a';
1283 /// let g = 'g';
1284 /// let zero = '0';
1285 /// let percent = '%';
1286 /// let space = ' ';
1287 /// let lf = '\n';
1288 /// let esc: char = 0x1b_u8.into();
1289 ///
1290 /// assert!(!uppercase_a.is_ascii_lowercase());
1291 /// assert!(!uppercase_g.is_ascii_lowercase());
1292 /// assert!(a.is_ascii_lowercase());
1293 /// assert!(g.is_ascii_lowercase());
1294 /// assert!(!zero.is_ascii_lowercase());
1295 /// assert!(!percent.is_ascii_lowercase());
1296 /// assert!(!space.is_ascii_lowercase());
1297 /// assert!(!lf.is_ascii_lowercase());
1298 /// assert!(!esc.is_ascii_lowercase());
1299 /// ```
1300 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1301 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1302 #[inline]
1303 pub const fn is_ascii_lowercase(&self) -> bool {
1304 match *self {
1305 'a'..='z' => true,
1306 _ => false,
1307 }
1308 }
1309
1310 /// Checks if the value is an ASCII alphanumeric character:
1311 ///
1312 /// - U+0041 'A' ..= U+005A 'Z', or
1313 /// - U+0061 'a' ..= U+007A 'z', or
1314 /// - U+0030 '0' ..= U+0039 '9'.
1315 ///
1316 /// # Examples
1317 ///
1318 /// ```
1319 /// let uppercase_a = 'A';
1320 /// let uppercase_g = 'G';
1321 /// let a = 'a';
1322 /// let g = 'g';
1323 /// let zero = '0';
1324 /// let percent = '%';
1325 /// let space = ' ';
1326 /// let lf = '\n';
1327 /// let esc: char = 0x1b_u8.into();
1328 ///
1329 /// assert!(uppercase_a.is_ascii_alphanumeric());
1330 /// assert!(uppercase_g.is_ascii_alphanumeric());
1331 /// assert!(a.is_ascii_alphanumeric());
1332 /// assert!(g.is_ascii_alphanumeric());
1333 /// assert!(zero.is_ascii_alphanumeric());
1334 /// assert!(!percent.is_ascii_alphanumeric());
1335 /// assert!(!space.is_ascii_alphanumeric());
1336 /// assert!(!lf.is_ascii_alphanumeric());
1337 /// assert!(!esc.is_ascii_alphanumeric());
1338 /// ```
1339 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1340 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1341 #[inline]
1342 pub const fn is_ascii_alphanumeric(&self) -> bool {
1343 match *self {
1344 '0'..='9' | 'A'..='Z' | 'a'..='z' => true,
1345 _ => false,
1346 }
1347 }
1348
1349 /// Checks if the value is an ASCII decimal digit:
1350 /// U+0030 '0' ..= U+0039 '9'.
1351 ///
1352 /// # Examples
1353 ///
1354 /// ```
1355 /// let uppercase_a = 'A';
1356 /// let uppercase_g = 'G';
1357 /// let a = 'a';
1358 /// let g = 'g';
1359 /// let zero = '0';
1360 /// let percent = '%';
1361 /// let space = ' ';
1362 /// let lf = '\n';
1363 /// let esc: char = 0x1b_u8.into();
1364 ///
1365 /// assert!(!uppercase_a.is_ascii_digit());
1366 /// assert!(!uppercase_g.is_ascii_digit());
1367 /// assert!(!a.is_ascii_digit());
1368 /// assert!(!g.is_ascii_digit());
1369 /// assert!(zero.is_ascii_digit());
1370 /// assert!(!percent.is_ascii_digit());
1371 /// assert!(!space.is_ascii_digit());
1372 /// assert!(!lf.is_ascii_digit());
1373 /// assert!(!esc.is_ascii_digit());
1374 /// ```
1375 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1376 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1377 #[inline]
1378 pub const fn is_ascii_digit(&self) -> bool {
1379 match *self {
1380 '0'..='9' => true,
1381 _ => false,
1382 }
1383 }
1384
1385 /// Checks if the value is an ASCII hexadecimal digit:
1386 ///
1387 /// - U+0030 '0' ..= U+0039 '9', or
1388 /// - U+0041 'A' ..= U+0046 'F', or
1389 /// - U+0061 'a' ..= U+0066 'f'.
1390 ///
1391 /// # Examples
1392 ///
1393 /// ```
1394 /// let uppercase_a = 'A';
1395 /// let uppercase_g = 'G';
1396 /// let a = 'a';
1397 /// let g = 'g';
1398 /// let zero = '0';
1399 /// let percent = '%';
1400 /// let space = ' ';
1401 /// let lf = '\n';
1402 /// let esc: char = 0x1b_u8.into();
1403 ///
1404 /// assert!(uppercase_a.is_ascii_hexdigit());
1405 /// assert!(!uppercase_g.is_ascii_hexdigit());
1406 /// assert!(a.is_ascii_hexdigit());
1407 /// assert!(!g.is_ascii_hexdigit());
1408 /// assert!(zero.is_ascii_hexdigit());
1409 /// assert!(!percent.is_ascii_hexdigit());
1410 /// assert!(!space.is_ascii_hexdigit());
1411 /// assert!(!lf.is_ascii_hexdigit());
1412 /// assert!(!esc.is_ascii_hexdigit());
1413 /// ```
1414 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1415 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1416 #[inline]
1417 pub const fn is_ascii_hexdigit(&self) -> bool {
1418 match *self {
1419 '0'..='9' | 'A'..='F' | 'a'..='f' => true,
1420 _ => false,
1421 }
1422 }
1423
1424 /// Checks if the value is an ASCII punctuation character:
1425 ///
1426 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1427 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1428 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1429 /// - U+007B ..= U+007E `{ | } ~`
1430 ///
1431 /// # Examples
1432 ///
1433 /// ```
1434 /// let uppercase_a = 'A';
1435 /// let uppercase_g = 'G';
1436 /// let a = 'a';
1437 /// let g = 'g';
1438 /// let zero = '0';
1439 /// let percent = '%';
1440 /// let space = ' ';
1441 /// let lf = '\n';
1442 /// let esc: char = 0x1b_u8.into();
1443 ///
1444 /// assert!(!uppercase_a.is_ascii_punctuation());
1445 /// assert!(!uppercase_g.is_ascii_punctuation());
1446 /// assert!(!a.is_ascii_punctuation());
1447 /// assert!(!g.is_ascii_punctuation());
1448 /// assert!(!zero.is_ascii_punctuation());
1449 /// assert!(percent.is_ascii_punctuation());
1450 /// assert!(!space.is_ascii_punctuation());
1451 /// assert!(!lf.is_ascii_punctuation());
1452 /// assert!(!esc.is_ascii_punctuation());
1453 /// ```
1454 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1455 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1456 #[inline]
1457 pub const fn is_ascii_punctuation(&self) -> bool {
1458 match *self {
1459 '!'..='/' | ':'..='@' | '['..='`' | '{'..='~' => true,
1460 _ => false,
1461 }
1462 }
1463
1464 /// Checks if the value is an ASCII graphic character:
1465 /// U+0021 '!' ..= U+007E '~'.
1466 ///
1467 /// # Examples
1468 ///
1469 /// ```
1470 /// let uppercase_a = 'A';
1471 /// let uppercase_g = 'G';
1472 /// let a = 'a';
1473 /// let g = 'g';
1474 /// let zero = '0';
1475 /// let percent = '%';
1476 /// let space = ' ';
1477 /// let lf = '\n';
1478 /// let esc: char = 0x1b_u8.into();
1479 ///
1480 /// assert!(uppercase_a.is_ascii_graphic());
1481 /// assert!(uppercase_g.is_ascii_graphic());
1482 /// assert!(a.is_ascii_graphic());
1483 /// assert!(g.is_ascii_graphic());
1484 /// assert!(zero.is_ascii_graphic());
1485 /// assert!(percent.is_ascii_graphic());
1486 /// assert!(!space.is_ascii_graphic());
1487 /// assert!(!lf.is_ascii_graphic());
1488 /// assert!(!esc.is_ascii_graphic());
1489 /// ```
1490 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1491 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1492 #[inline]
1493 pub const fn is_ascii_graphic(&self) -> bool {
1494 match *self {
1495 '!'..='~' => true,
1496 _ => false,
1497 }
1498 }
1499
1500 /// Checks if the value is an ASCII whitespace character:
1501 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1502 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1503 ///
1504 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1505 /// whitespace][infra-aw]. There are several other definitions in
1506 /// wide use. For instance, [the POSIX locale][pct] includes
1507 /// U+000B VERTICAL TAB as well as all the above characters,
1508 /// but—from the very same specification—[the default rule for
1509 /// "field splitting" in the Bourne shell][bfs] considers *only*
1510 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1511 ///
1512 /// If you are writing a program that will process an existing
1513 /// file format, check what that format's definition of whitespace is
1514 /// before using this function.
1515 ///
1516 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1517 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1518 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1519 ///
1520 /// # Examples
1521 ///
1522 /// ```
1523 /// let uppercase_a = 'A';
1524 /// let uppercase_g = 'G';
1525 /// let a = 'a';
1526 /// let g = 'g';
1527 /// let zero = '0';
1528 /// let percent = '%';
1529 /// let space = ' ';
1530 /// let lf = '\n';
1531 /// let esc: char = 0x1b_u8.into();
1532 ///
1533 /// assert!(!uppercase_a.is_ascii_whitespace());
1534 /// assert!(!uppercase_g.is_ascii_whitespace());
1535 /// assert!(!a.is_ascii_whitespace());
1536 /// assert!(!g.is_ascii_whitespace());
1537 /// assert!(!zero.is_ascii_whitespace());
1538 /// assert!(!percent.is_ascii_whitespace());
1539 /// assert!(space.is_ascii_whitespace());
1540 /// assert!(lf.is_ascii_whitespace());
1541 /// assert!(!esc.is_ascii_whitespace());
1542 /// ```
1543 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1544 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1545 #[inline]
1546 pub const fn is_ascii_whitespace(&self) -> bool {
1547 match *self {
1548 '\t' | '\n' | '\x0C' | '\r' | ' ' => true,
1549 _ => false,
1550 }
1551 }
1552
1553 /// Checks if the value is an ASCII control character:
1554 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1555 /// Note that most ASCII whitespace characters are control
1556 /// characters, but SPACE is not.
1557 ///
1558 /// # Examples
1559 ///
1560 /// ```
1561 /// let uppercase_a = 'A';
1562 /// let uppercase_g = 'G';
1563 /// let a = 'a';
1564 /// let g = 'g';
1565 /// let zero = '0';
1566 /// let percent = '%';
1567 /// let space = ' ';
1568 /// let lf = '\n';
1569 /// let esc: char = 0x1b_u8.into();
1570 ///
1571 /// assert!(!uppercase_a.is_ascii_control());
1572 /// assert!(!uppercase_g.is_ascii_control());
1573 /// assert!(!a.is_ascii_control());
1574 /// assert!(!g.is_ascii_control());
1575 /// assert!(!zero.is_ascii_control());
1576 /// assert!(!percent.is_ascii_control());
1577 /// assert!(!space.is_ascii_control());
1578 /// assert!(lf.is_ascii_control());
1579 /// assert!(esc.is_ascii_control());
1580 /// ```
1581 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1582 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
1583 #[inline]
1584 pub const fn is_ascii_control(&self) -> bool {
1585 match *self {
1586 '\0'..='\x1F' | '\x7F' => true,
1587 _ => false,
1588 }
1589 }
1590 }
1591
1592 #[inline]
1593 fn len_utf8(code: u32) -> usize {
1594 if code < MAX_ONE_B {
1595 1
1596 } else if code < MAX_TWO_B {
1597 2
1598 } else if code < MAX_THREE_B {
1599 3
1600 } else {
1601 4
1602 }
1603 }
1604
1605 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
1606 /// and then returns the subslice of the buffer that contains the encoded character.
1607 ///
1608 /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
1609 /// (Creating a `char` in the surrogate range is UB.)
1610 /// The result is valid [generalized UTF-8] but not valid UTF-8.
1611 ///
1612 /// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
1613 ///
1614 /// # Panics
1615 ///
1616 /// Panics if the buffer is not large enough.
1617 /// A buffer of length four is large enough to encode any `char`.
1618 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1619 #[doc(hidden)]
1620 #[inline]
1621 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
1622 let len = len_utf8(code);
1623 match (len, &mut dst[..]) {
1624 (1, [a, ..]) => {
1625 *a = code as u8;
1626 }
1627 (2, [a, b, ..]) => {
1628 *a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
1629 *b = (code & 0x3F) as u8 | TAG_CONT;
1630 }
1631 (3, [a, b, c, ..]) => {
1632 *a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
1633 *b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1634 *c = (code & 0x3F) as u8 | TAG_CONT;
1635 }
1636 (4, [a, b, c, d, ..]) => {
1637 *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
1638 *b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
1639 *c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
1640 *d = (code & 0x3F) as u8 | TAG_CONT;
1641 }
1642 _ => panic!(
1643 "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
1644 len,
1645 code,
1646 dst.len(),
1647 ),
1648 };
1649 &mut dst[..len]
1650 }
1651
1652 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
1653 /// and then returns the subslice of the buffer that contains the encoded character.
1654 ///
1655 /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
1656 /// (Creating a `char` in the surrogate range is UB.)
1657 ///
1658 /// # Panics
1659 ///
1660 /// Panics if the buffer is not large enough.
1661 /// A buffer of length 2 is large enough to encode any `char`.
1662 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1663 #[doc(hidden)]
1664 #[inline]
1665 pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
1666 // SAFETY: each arm checks whether there are enough bits to write into
1667 unsafe {
1668 if (code & 0xFFFF) == code && !dst.is_empty() {
1669 // The BMP falls through
1670 *dst.get_unchecked_mut(0) = code as u16;
1671 slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
1672 } else if dst.len() >= 2 {
1673 // Supplementary planes break into surrogates.
1674 code -= 0x1_0000;
1675 *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
1676 *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
1677 slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
1678 } else {
1679 panic!(
1680 "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
1681 from_u32_unchecked(code).len_utf16(),
1682 code,
1683 dst.len(),
1684 )
1685 }
1686 }
1687 }