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