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