core/char/methods.rs
1//! impl char {}
2
3use super::*;
4use crate::panic::const_panic;
5use crate::slice;
6use crate::str::from_utf8_unchecked_mut;
7use crate::ub_checks::assert_unsafe_precondition;
8use crate::unicode::printable::is_printable;
9use crate::unicode::{self, conversions};
10
11impl char {
12 /// The lowest valid code point a `char` can have, `'\0'`.
13 ///
14 /// Unlike integer types, `char` actually has a gap in the middle,
15 /// meaning that the range of possible `char`s is smaller than you
16 /// might expect. Ranges of `char` will automatically hop this gap
17 /// for you:
18 ///
19 /// ```
20 /// let dist = u32::from(char::MAX) - u32::from(char::MIN);
21 /// let size = (char::MIN..=char::MAX).count() as u32;
22 /// assert!(size < dist);
23 /// ```
24 ///
25 /// Despite this gap, the `MIN` and [`MAX`] values can be used as bounds for
26 /// all `char` values.
27 ///
28 /// [`MAX`]: char::MAX
29 ///
30 /// # Examples
31 ///
32 /// ```
33 /// # fn something_which_returns_char() -> char { 'a' }
34 /// let c: char = something_which_returns_char();
35 /// assert!(char::MIN <= c);
36 ///
37 /// let value_at_min = u32::from(char::MIN);
38 /// assert_eq!(char::from_u32(value_at_min), Some('\0'));
39 /// ```
40 #[stable(feature = "char_min", since = "1.83.0")]
41 pub const MIN: char = '\0';
42
43 /// The highest valid code point a `char` can have, `'\u{10FFFF}'`.
44 ///
45 /// Unlike integer types, `char` actually has a gap in the middle,
46 /// meaning that the range of possible `char`s is smaller than you
47 /// might expect. Ranges of `char` will automatically hop this gap
48 /// for you:
49 ///
50 /// ```
51 /// let dist = u32::from(char::MAX) - u32::from(char::MIN);
52 /// let size = (char::MIN..=char::MAX).count() as u32;
53 /// assert!(size < dist);
54 /// ```
55 ///
56 /// Despite this gap, the [`MIN`] and `MAX` values can be used as bounds for
57 /// all `char` values.
58 ///
59 /// [`MIN`]: char::MIN
60 ///
61 /// # Examples
62 ///
63 /// ```
64 /// # fn something_which_returns_char() -> char { 'a' }
65 /// let c: char = something_which_returns_char();
66 /// assert!(c <= char::MAX);
67 ///
68 /// let value_at_max = u32::from(char::MAX);
69 /// assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
70 /// assert_eq!(char::from_u32(value_at_max + 1), None);
71 /// ```
72 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
73 pub const MAX: char = '\u{10FFFF}';
74
75 /// The maximum number of bytes required to [encode](char::encode_utf8) a `char` to
76 /// UTF-8 encoding.
77 #[stable(feature = "char_max_len_assoc", since = "1.93.0")]
78 pub const MAX_LEN_UTF8: usize = 4;
79
80 /// The maximum number of two-byte units required to [encode](char::encode_utf16) a `char`
81 /// to UTF-16 encoding.
82 #[stable(feature = "char_max_len_assoc", since = "1.93.0")]
83 pub const MAX_LEN_UTF16: usize = 2;
84
85 /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
86 /// decoding error.
87 ///
88 /// It can occur, for example, when giving ill-formed UTF-8 bytes to
89 /// [`String::from_utf8_lossy`](../std/string/struct.String.html#method.from_utf8_lossy).
90 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
91 pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
92
93 /// The version of [Unicode](https://www.unicode.org/) that the Unicode parts of
94 /// `char` and `str` methods are based on.
95 ///
96 /// New versions of Unicode are released regularly and subsequently all methods
97 /// in the standard library depending on Unicode are updated. Therefore the
98 /// behavior of some `char` and `str` methods and the value of this constant
99 /// changes over time. This is *not* considered to be a breaking change.
100 ///
101 /// The version numbering scheme is explained in
102 /// [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).
103 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
104 pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION;
105
106 /// Creates an iterator over the native endian UTF-16 encoded code points in `iter`,
107 /// returning unpaired surrogates as `Err`s.
108 ///
109 /// # Examples
110 ///
111 /// Basic usage:
112 ///
113 /// ```
114 /// // 𝄞mus<invalid>ic<invalid>
115 /// let v = [
116 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
117 /// ];
118 ///
119 /// assert_eq!(
120 /// char::decode_utf16(v)
121 /// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
122 /// .collect::<Vec<_>>(),
123 /// vec![
124 /// Ok('𝄞'),
125 /// Ok('m'), Ok('u'), Ok('s'),
126 /// Err(0xDD1E),
127 /// Ok('i'), Ok('c'),
128 /// Err(0xD834)
129 /// ]
130 /// );
131 /// ```
132 ///
133 /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
134 ///
135 /// ```
136 /// // 𝄞mus<invalid>ic<invalid>
137 /// let v = [
138 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
139 /// ];
140 ///
141 /// assert_eq!(
142 /// char::decode_utf16(v)
143 /// .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
144 /// .collect::<String>(),
145 /// "𝄞mus�ic�"
146 /// );
147 /// ```
148 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
149 #[inline]
150 #[ferrocene::prevalidated]
151 pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
152 super::decode::decode_utf16(iter)
153 }
154
155 /// Converts a `u32` to a `char`.
156 ///
157 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
158 /// [`as`](../std/keyword.as.html):
159 ///
160 /// ```
161 /// let c = '💯';
162 /// let i = c as u32;
163 ///
164 /// assert_eq!(128175, i);
165 /// ```
166 ///
167 /// However, the reverse is not true: not all valid [`u32`]s are valid
168 /// `char`s. `from_u32()` will return `None` if the input is not a valid value
169 /// for a `char`.
170 ///
171 /// For an unsafe version of this function which ignores these checks, see
172 /// [`from_u32_unchecked`].
173 ///
174 /// [`from_u32_unchecked`]: #method.from_u32_unchecked
175 ///
176 /// # Examples
177 ///
178 /// Basic usage:
179 ///
180 /// ```
181 /// let c = char::from_u32(0x2764);
182 ///
183 /// assert_eq!(Some('❤'), c);
184 /// ```
185 ///
186 /// Returning `None` when the input is not a valid `char`:
187 ///
188 /// ```
189 /// let c = char::from_u32(0x110000);
190 ///
191 /// assert_eq!(None, c);
192 /// ```
193 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
194 #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
195 #[must_use]
196 #[inline]
197 pub const fn from_u32(i: u32) -> Option<char> {
198 super::convert::from_u32(i)
199 }
200
201 /// Converts a `u32` to a `char`, ignoring validity.
202 ///
203 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
204 /// `as`:
205 ///
206 /// ```
207 /// let c = '💯';
208 /// let i = c as u32;
209 ///
210 /// assert_eq!(128175, i);
211 /// ```
212 ///
213 /// However, the reverse is not true: not all valid [`u32`]s are valid
214 /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to
215 /// `char`, possibly creating an invalid one.
216 ///
217 /// # Safety
218 ///
219 /// This function is unsafe, as it may construct invalid `char` values.
220 ///
221 /// For a safe version of this function, see the [`from_u32`] function.
222 ///
223 /// [`from_u32`]: #method.from_u32
224 ///
225 /// # Examples
226 ///
227 /// Basic usage:
228 ///
229 /// ```
230 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
231 ///
232 /// assert_eq!('❤', c);
233 /// ```
234 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
235 #[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")]
236 #[must_use]
237 #[inline]
238 #[ferrocene::prevalidated]
239 pub const unsafe fn from_u32_unchecked(i: u32) -> char {
240 // SAFETY: the safety contract must be upheld by the caller.
241 unsafe { super::convert::from_u32_unchecked(i) }
242 }
243
244 /// Converts a digit in the given radix to a `char`.
245 ///
246 /// A 'radix' here is sometimes also called a 'base'. A radix of two
247 /// indicates a binary number, a radix of ten, decimal, and a radix of
248 /// sixteen, hexadecimal, to give some common values. Arbitrary
249 /// radices are supported.
250 ///
251 /// `from_digit()` will return `None` if the input is not a digit in
252 /// the given radix.
253 ///
254 /// # Panics
255 ///
256 /// Panics if given a radix larger than 36.
257 ///
258 /// # Examples
259 ///
260 /// Basic usage:
261 ///
262 /// ```
263 /// let c = char::from_digit(4, 10);
264 ///
265 /// assert_eq!(Some('4'), c);
266 ///
267 /// // Decimal 11 is a single digit in base 16
268 /// let c = char::from_digit(11, 16);
269 ///
270 /// assert_eq!(Some('b'), c);
271 /// ```
272 ///
273 /// Returning `None` when the input is not a digit:
274 ///
275 /// ```
276 /// let c = char::from_digit(20, 10);
277 ///
278 /// assert_eq!(None, c);
279 /// ```
280 ///
281 /// Passing a large radix, causing a panic:
282 ///
283 /// ```should_panic
284 /// // this panics
285 /// let _c = char::from_digit(1, 37);
286 /// ```
287 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
288 #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
289 #[must_use]
290 #[inline]
291 pub const fn from_digit(num: u32, radix: u32) -> Option<char> {
292 super::convert::from_digit(num, radix)
293 }
294
295 /// Checks if a `char` is a digit in the given radix.
296 ///
297 /// A 'radix' here is sometimes also called a 'base'. A radix of two
298 /// indicates a binary number, a radix of ten, decimal, and a radix of
299 /// sixteen, hexadecimal, to give some common values. Arbitrary
300 /// radices are supported.
301 ///
302 /// Compared to [`is_numeric()`], this function only recognizes the characters
303 /// `0-9`, `a-z` and `A-Z`.
304 ///
305 /// 'Digit' is defined to be only the following characters:
306 ///
307 /// * `0-9`
308 /// * `a-z`
309 /// * `A-Z`
310 ///
311 /// For a more comprehensive understanding of 'digit', see [`is_numeric()`].
312 ///
313 /// [`is_numeric()`]: #method.is_numeric
314 ///
315 /// # Panics
316 ///
317 /// Panics if given a radix smaller than 2 or larger than 36.
318 ///
319 /// # Examples
320 ///
321 /// Basic usage:
322 ///
323 /// ```
324 /// assert!('1'.is_digit(10));
325 /// assert!('f'.is_digit(16));
326 /// assert!(!'f'.is_digit(10));
327 /// ```
328 ///
329 /// Passing a large radix, causing a panic:
330 ///
331 /// ```should_panic
332 /// // this panics
333 /// '1'.is_digit(37);
334 /// ```
335 ///
336 /// Passing a small radix, causing a panic:
337 ///
338 /// ```should_panic
339 /// // this panics
340 /// '1'.is_digit(1);
341 /// ```
342 #[stable(feature = "rust1", since = "1.0.0")]
343 #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
344 #[inline]
345 pub const fn is_digit(self, radix: u32) -> bool {
346 self.to_digit(radix).is_some()
347 }
348
349 /// Converts a `char` to a digit in the given radix.
350 ///
351 /// A 'radix' here is sometimes also called a 'base'. A radix of two
352 /// indicates a binary number, a radix of ten, decimal, and a radix of
353 /// sixteen, hexadecimal, to give some common values. Arbitrary
354 /// radices are supported.
355 ///
356 /// 'Digit' is defined to be only the following characters:
357 ///
358 /// * `0-9`
359 /// * `a-z`
360 /// * `A-Z`
361 ///
362 /// # Errors
363 ///
364 /// Returns `None` if the `char` does not refer to a digit in the given radix.
365 ///
366 /// # Panics
367 ///
368 /// Panics if given a radix smaller than 2 or larger than 36.
369 ///
370 /// # Examples
371 ///
372 /// Basic usage:
373 ///
374 /// ```
375 /// assert_eq!('1'.to_digit(10), Some(1));
376 /// assert_eq!('f'.to_digit(16), Some(15));
377 /// ```
378 ///
379 /// Passing a non-digit results in failure:
380 ///
381 /// ```
382 /// assert_eq!('f'.to_digit(10), None);
383 /// assert_eq!('z'.to_digit(16), None);
384 /// ```
385 ///
386 /// Passing a large radix, causing a panic:
387 ///
388 /// ```should_panic
389 /// // this panics
390 /// let _ = '1'.to_digit(37);
391 /// ```
392 /// Passing a small radix, causing a panic:
393 ///
394 /// ```should_panic
395 /// // this panics
396 /// let _ = '1'.to_digit(1);
397 /// ```
398 #[stable(feature = "rust1", since = "1.0.0")]
399 #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
400 #[rustc_diagnostic_item = "char_to_digit"]
401 #[must_use = "this returns the result of the operation, \
402 without modifying the original"]
403 #[inline]
404 #[ferrocene::prevalidated]
405 pub const fn to_digit(self, radix: u32) -> Option<u32> {
406 assert!(
407 radix >= 2 && radix <= 36,
408 "to_digit: invalid radix -- radix must be in the range 2 to 36 inclusive"
409 );
410 // check radix to remove letter handling code when radix is a known constant
411 let value = if self > '9' && radix > 10 {
412 // mask to convert ASCII letters to uppercase
413 const TO_UPPERCASE_MASK: u32 = !0b0010_0000;
414 // Converts an ASCII letter to its corresponding integer value:
415 // A-Z => 10-35, a-z => 10-35. Other characters produce values >= 36.
416 //
417 // Add Overflow Safety:
418 // By applying the mask after the subtraction, the first addendum is
419 // constrained such that it never exceeds u32::MAX - 0x20.
420 ((self as u32).wrapping_sub('A' as u32) & TO_UPPERCASE_MASK) + 10
421 } else {
422 // convert digit to value, non-digits wrap to values > 36
423 (self as u32).wrapping_sub('0' as u32)
424 };
425 // FIXME(const-hack): once then_some is const fn, use it here
426 if value < radix { Some(value) } else { None }
427 }
428
429 /// Returns an iterator that yields the hexadecimal Unicode escape of a
430 /// character as `char`s.
431 ///
432 /// This will escape characters with the Rust syntax of the form
433 /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
434 ///
435 /// # Examples
436 ///
437 /// As an iterator:
438 ///
439 /// ```
440 /// for c in '❤'.escape_unicode() {
441 /// print!("{c}");
442 /// }
443 /// println!();
444 /// ```
445 ///
446 /// Using `println!` directly:
447 ///
448 /// ```
449 /// println!("{}", '❤'.escape_unicode());
450 /// ```
451 ///
452 /// Both are equivalent to:
453 ///
454 /// ```
455 /// println!("\\u{{2764}}");
456 /// ```
457 ///
458 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
459 ///
460 /// ```
461 /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
462 /// ```
463 #[must_use = "this returns the escaped char as an iterator, \
464 without modifying the original"]
465 #[stable(feature = "rust1", since = "1.0.0")]
466 #[inline]
467 pub fn escape_unicode(self) -> EscapeUnicode {
468 EscapeUnicode::new(self)
469 }
470
471 /// An extended version of `escape_debug` that optionally permits escaping
472 /// Extended Grapheme codepoints, single quotes, and double quotes. This
473 /// allows us to format characters like nonspacing marks better when they're
474 /// at the start of a string, and allows escaping single quotes in
475 /// characters, and double quotes in strings.
476 #[inline]
477 #[ferrocene::prevalidated]
478 pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
479 match self {
480 '\0' => EscapeDebug::backslash(ascii::Char::Digit0),
481 '\t' => EscapeDebug::backslash(ascii::Char::SmallT),
482 '\r' => EscapeDebug::backslash(ascii::Char::SmallR),
483 '\n' => EscapeDebug::backslash(ascii::Char::SmallN),
484 '\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus),
485 '\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark),
486 '\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe),
487 _ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
488 EscapeDebug::unicode(self)
489 }
490 _ if is_printable(self) => EscapeDebug::printable(self),
491 _ => EscapeDebug::unicode(self),
492 }
493 }
494
495 /// Returns an iterator that yields the literal escape code of a character
496 /// as `char`s.
497 ///
498 /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
499 /// of `str` or `char`.
500 ///
501 /// # Examples
502 ///
503 /// As an iterator:
504 ///
505 /// ```
506 /// for c in '\n'.escape_debug() {
507 /// print!("{c}");
508 /// }
509 /// println!();
510 /// ```
511 ///
512 /// Using `println!` directly:
513 ///
514 /// ```
515 /// println!("{}", '\n'.escape_debug());
516 /// ```
517 ///
518 /// Both are equivalent to:
519 ///
520 /// ```
521 /// println!("\\n");
522 /// ```
523 ///
524 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
525 ///
526 /// ```
527 /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
528 /// ```
529 #[must_use = "this returns the escaped char as an iterator, \
530 without modifying the original"]
531 #[stable(feature = "char_escape_debug", since = "1.20.0")]
532 #[inline]
533 #[ferrocene::prevalidated]
534 pub fn escape_debug(self) -> EscapeDebug {
535 self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
536 }
537
538 /// Returns an iterator that yields the literal escape code of a character
539 /// as `char`s.
540 ///
541 /// The default is chosen with a bias toward producing literals that are
542 /// legal in a variety of languages, including C++11 and similar C-family
543 /// languages. The exact rules are:
544 ///
545 /// * Tab is escaped as `\t`.
546 /// * Carriage return is escaped as `\r`.
547 /// * Line feed is escaped as `\n`.
548 /// * Single quote is escaped as `\'`.
549 /// * Double quote is escaped as `\"`.
550 /// * Backslash is escaped as `\\`.
551 /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
552 /// inclusive is not escaped.
553 /// * All other characters are given hexadecimal Unicode escapes; see
554 /// [`escape_unicode`].
555 ///
556 /// [`escape_unicode`]: #method.escape_unicode
557 ///
558 /// # Examples
559 ///
560 /// As an iterator:
561 ///
562 /// ```
563 /// for c in '"'.escape_default() {
564 /// print!("{c}");
565 /// }
566 /// println!();
567 /// ```
568 ///
569 /// Using `println!` directly:
570 ///
571 /// ```
572 /// println!("{}", '"'.escape_default());
573 /// ```
574 ///
575 /// Both are equivalent to:
576 ///
577 /// ```
578 /// println!("\\\"");
579 /// ```
580 ///
581 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
582 ///
583 /// ```
584 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
585 /// ```
586 #[must_use = "this returns the escaped char as an iterator, \
587 without modifying the original"]
588 #[stable(feature = "rust1", since = "1.0.0")]
589 #[inline]
590 pub fn escape_default(self) -> EscapeDefault {
591 match self {
592 '\t' => EscapeDefault::backslash(ascii::Char::SmallT),
593 '\r' => EscapeDefault::backslash(ascii::Char::SmallR),
594 '\n' => EscapeDefault::backslash(ascii::Char::SmallN),
595 '\\' | '\'' | '\"' => EscapeDefault::backslash(self.as_ascii().unwrap()),
596 '\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()),
597 _ => EscapeDefault::unicode(self),
598 }
599 }
600
601 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
602 ///
603 /// That number of bytes is always between 1 and 4, inclusive.
604 ///
605 /// # Examples
606 ///
607 /// Basic usage:
608 ///
609 /// ```
610 /// let len = 'A'.len_utf8();
611 /// assert_eq!(len, 1);
612 ///
613 /// let len = 'ß'.len_utf8();
614 /// assert_eq!(len, 2);
615 ///
616 /// let len = 'ℝ'.len_utf8();
617 /// assert_eq!(len, 3);
618 ///
619 /// let len = '💣'.len_utf8();
620 /// assert_eq!(len, 4);
621 /// ```
622 ///
623 /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
624 /// would take if each code point was represented as a `char` vs in the `&str` itself:
625 ///
626 /// ```
627 /// // as chars
628 /// let eastern = '東';
629 /// let capital = '京';
630 ///
631 /// // both can be represented as three bytes
632 /// assert_eq!(3, eastern.len_utf8());
633 /// assert_eq!(3, capital.len_utf8());
634 ///
635 /// // as a &str, these two are encoded in UTF-8
636 /// let tokyo = "東京";
637 ///
638 /// let len = eastern.len_utf8() + capital.len_utf8();
639 ///
640 /// // we can see that they take six bytes total...
641 /// assert_eq!(6, tokyo.len());
642 ///
643 /// // ... just like the &str
644 /// assert_eq!(len, tokyo.len());
645 /// ```
646 #[stable(feature = "rust1", since = "1.0.0")]
647 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
648 #[inline]
649 #[must_use]
650 #[ferrocene::prevalidated]
651 pub const fn len_utf8(self) -> usize {
652 len_utf8(self as u32)
653 }
654
655 /// Returns the number of 16-bit code units this `char` would need if
656 /// encoded in UTF-16.
657 ///
658 /// That number of code units is always either 1 or 2, for unicode scalar values in
659 /// the [basic multilingual plane] or [supplementary planes] respectively.
660 ///
661 /// See the documentation for [`len_utf8()`] for more explanation of this
662 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
663 ///
664 /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
665 /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
666 /// [`len_utf8()`]: #method.len_utf8
667 ///
668 /// # Examples
669 ///
670 /// Basic usage:
671 ///
672 /// ```
673 /// let n = 'ß'.len_utf16();
674 /// assert_eq!(n, 1);
675 ///
676 /// let len = '💣'.len_utf16();
677 /// assert_eq!(len, 2);
678 /// ```
679 #[stable(feature = "rust1", since = "1.0.0")]
680 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
681 #[inline]
682 #[must_use]
683 pub const fn len_utf16(self) -> usize {
684 len_utf16(self as u32)
685 }
686
687 /// Encodes this character as UTF-8 into the provided byte buffer,
688 /// and then returns the subslice of the buffer that contains the encoded character.
689 ///
690 /// # Panics
691 ///
692 /// Panics if the buffer is not large enough.
693 /// A buffer of length four is large enough to encode any `char`.
694 ///
695 /// # Examples
696 ///
697 /// In both of these examples, 'ß' takes two bytes to encode.
698 ///
699 /// ```
700 /// let mut b = [0; 2];
701 ///
702 /// let result = 'ß'.encode_utf8(&mut b);
703 ///
704 /// assert_eq!(result, "ß");
705 ///
706 /// assert_eq!(result.len(), 2);
707 /// ```
708 ///
709 /// A buffer that's too small:
710 ///
711 /// ```should_panic
712 /// let mut b = [0; 1];
713 ///
714 /// // this panics
715 /// 'ß'.encode_utf8(&mut b);
716 /// ```
717 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
718 #[rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0")]
719 #[inline]
720 #[ferrocene::prevalidated]
721 pub const fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
722 // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
723 unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
724 }
725
726 /// Encodes this character as native endian UTF-16 into the provided `u16` buffer,
727 /// and then returns the subslice of the buffer that contains the encoded character.
728 ///
729 /// # Panics
730 ///
731 /// Panics if the buffer is not large enough.
732 /// A buffer of length 2 is large enough to encode any `char`.
733 ///
734 /// # Examples
735 ///
736 /// In both of these examples, '𝕊' takes two `u16`s to encode.
737 ///
738 /// ```
739 /// let mut b = [0; 2];
740 ///
741 /// let result = '𝕊'.encode_utf16(&mut b);
742 ///
743 /// assert_eq!(result.len(), 2);
744 /// ```
745 ///
746 /// A buffer that's too small:
747 ///
748 /// ```should_panic
749 /// let mut b = [0; 1];
750 ///
751 /// // this panics
752 /// '𝕊'.encode_utf16(&mut b);
753 /// ```
754 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
755 #[rustc_const_stable(feature = "const_char_encode_utf16", since = "1.84.0")]
756 #[inline]
757 pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
758 encode_utf16_raw(self as u32, dst)
759 }
760
761 /// Returns `true` if this `char` has the `Alphabetic` property.
762 ///
763 /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
764 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
765 ///
766 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
767 /// [ucd]: https://www.unicode.org/reports/tr44/
768 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
769 ///
770 /// # Examples
771 ///
772 /// Basic usage:
773 ///
774 /// ```
775 /// assert!('a'.is_alphabetic());
776 /// assert!('京'.is_alphabetic());
777 ///
778 /// let c = '💝';
779 /// // love is many things, but it is not alphabetic
780 /// assert!(!c.is_alphabetic());
781 /// ```
782 #[must_use]
783 #[stable(feature = "rust1", since = "1.0.0")]
784 #[inline]
785 pub fn is_alphabetic(self) -> bool {
786 match self {
787 'a'..='z' | 'A'..='Z' => true,
788 '\0'..='\u{A9}' => false,
789 _ => unicode::Alphabetic(self),
790 }
791 }
792
793 /// Returns `true` if this `char` has the `Cased` property.
794 /// A character is cased if and only if it is uppercase, lowercase, or titlecase.
795 ///
796 /// `Cased` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
797 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
798 ///
799 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
800 /// [ucd]: https://www.unicode.org/reports/tr44/
801 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
802 ///
803 /// # Examples
804 ///
805 /// Basic usage:
806 ///
807 /// ```
808 /// #![feature(titlecase)]
809 /// assert!('A'.is_cased());
810 /// assert!('a'.is_cased());
811 /// assert!(!'京'.is_cased());
812 /// ```
813 #[must_use]
814 #[unstable(feature = "titlecase", issue = "153892")]
815 #[inline]
816 pub fn is_cased(self) -> bool {
817 match self {
818 'a'..='z' | 'A'..='Z' => true,
819 '\0'..='\u{A9}' => false,
820 _ => unicode::Cased(self),
821 }
822 }
823
824 /// Returns the case of this character:
825 /// [`Some(CharCase::Upper)`][`CharCase::Upper`] if [`self.is_uppercase()`][`char::is_uppercase`],
826 /// [`Some(CharCase::Lower)`][`CharCase::Lower`] if [`self.is_lowercase()`][`char::is_lowercase`],
827 /// [`Some(CharCase::Title)`][`CharCase::Title`] if [`self.is_titlecase()`][`char::is_titlecase`], and
828 /// `None` if [`!self.is_cased()`][`char::is_cased`].
829 ///
830 /// # Examples
831 ///
832 /// ```
833 /// #![feature(titlecase)]
834 /// use core::char::CharCase;
835 /// assert_eq!('a'.case(), Some(CharCase::Lower));
836 /// assert_eq!('δ'.case(), Some(CharCase::Lower));
837 /// assert_eq!('A'.case(), Some(CharCase::Upper));
838 /// assert_eq!('Δ'.case(), Some(CharCase::Upper));
839 /// assert_eq!('Dž'.case(), Some(CharCase::Title));
840 /// assert_eq!('中'.case(), None);
841 /// ```
842 #[must_use]
843 #[unstable(feature = "titlecase", issue = "153892")]
844 #[inline]
845 pub fn case(self) -> Option<CharCase> {
846 match self {
847 'a'..='z' => Some(CharCase::Lower),
848 'A'..='Z' => Some(CharCase::Upper),
849 '\0'..='\u{A9}' => None,
850 _ if !unicode::Cased(self) => None,
851 _ if unicode::Lowercase(self) => Some(CharCase::Lower),
852 _ if unicode::Uppercase(self) => Some(CharCase::Upper),
853 _ => Some(CharCase::Title),
854 }
855 }
856
857 /// Returns `true` if this `char` has the `Lowercase` property.
858 ///
859 /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
860 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
861 ///
862 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
863 /// [ucd]: https://www.unicode.org/reports/tr44/
864 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
865 ///
866 /// # Examples
867 ///
868 /// Basic usage:
869 ///
870 /// ```
871 /// assert!('a'.is_lowercase());
872 /// assert!('δ'.is_lowercase());
873 /// assert!(!'A'.is_lowercase());
874 /// assert!(!'Δ'.is_lowercase());
875 ///
876 /// // The various Chinese scripts and punctuation do not have case, and so:
877 /// assert!(!'中'.is_lowercase());
878 /// assert!(!' '.is_lowercase());
879 /// ```
880 ///
881 /// In a const context:
882 ///
883 /// ```
884 /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
885 /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
886 /// ```
887 #[must_use]
888 #[stable(feature = "rust1", since = "1.0.0")]
889 #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
890 #[inline]
891 pub const fn is_lowercase(self) -> bool {
892 match self {
893 'a'..='z' => true,
894 '\0'..='\u{A9}' => false,
895 _ => unicode::Lowercase(self),
896 }
897 }
898
899 /// Returns `true` if this `char` has the general category for titlecase letters.
900 /// Conceptually, these characters consist of an uppercase portion followed by a lowercase portion.
901 ///
902 /// Titlecase letters (code points with the general category of `Lt`) are described in Chapter 4
903 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
904 /// Database][ucd] [`UnicodeData.txt`].
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 /// #![feature(titlecase)]
916 /// assert!('Dž'.is_titlecase());
917 /// assert!('ῼ'.is_titlecase());
918 /// assert!(!'D'.is_titlecase());
919 /// assert!(!'z'.is_titlecase());
920 /// assert!(!'中'.is_titlecase());
921 /// assert!(!' '.is_titlecase());
922 /// ```
923 #[must_use]
924 #[unstable(feature = "titlecase", issue = "153892")]
925 #[inline]
926 pub fn is_titlecase(self) -> bool {
927 match self {
928 '\0'..='\u{01C4}' => false,
929 _ => self.is_cased() && !self.is_lowercase() && !self.is_uppercase(),
930 }
931 }
932
933 /// Returns `true` if this `char` has the `Uppercase` property.
934 ///
935 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
936 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
937 ///
938 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
939 /// [ucd]: https://www.unicode.org/reports/tr44/
940 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
941 ///
942 /// # Examples
943 ///
944 /// Basic usage:
945 ///
946 /// ```
947 /// assert!(!'a'.is_uppercase());
948 /// assert!(!'δ'.is_uppercase());
949 /// assert!('A'.is_uppercase());
950 /// assert!('Δ'.is_uppercase());
951 ///
952 /// // The various Chinese scripts and punctuation do not have case, and so:
953 /// assert!(!'中'.is_uppercase());
954 /// assert!(!' '.is_uppercase());
955 /// ```
956 ///
957 /// In a const context:
958 ///
959 /// ```
960 /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
961 /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
962 /// ```
963 #[must_use]
964 #[stable(feature = "rust1", since = "1.0.0")]
965 #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
966 #[inline]
967 pub const fn is_uppercase(self) -> bool {
968 match self {
969 'A'..='Z' => true,
970 '\0'..='\u{BF}' => false,
971 _ => unicode::Uppercase(self),
972 }
973 }
974
975 /// Returns `true` if this `char` has the `White_Space` property.
976 ///
977 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
978 ///
979 /// [ucd]: https://www.unicode.org/reports/tr44/
980 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
981 ///
982 /// # Examples
983 ///
984 /// Basic usage:
985 ///
986 /// ```
987 /// assert!(' '.is_whitespace());
988 ///
989 /// // line break
990 /// assert!('\n'.is_whitespace());
991 ///
992 /// // a non-breaking space
993 /// assert!('\u{A0}'.is_whitespace());
994 ///
995 /// assert!(!'越'.is_whitespace());
996 /// ```
997 #[must_use]
998 #[stable(feature = "rust1", since = "1.0.0")]
999 #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
1000 #[inline]
1001 pub const fn is_whitespace(self) -> bool {
1002 match self {
1003 ' ' | '\x09'..='\x0d' => true,
1004 '\0'..='\u{84}' => false,
1005 _ => unicode::White_Space(self),
1006 }
1007 }
1008
1009 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
1010 ///
1011 /// [`is_alphabetic()`]: #method.is_alphabetic
1012 /// [`is_numeric()`]: #method.is_numeric
1013 ///
1014 /// # Examples
1015 ///
1016 /// Basic usage:
1017 ///
1018 /// ```
1019 /// assert!('٣'.is_alphanumeric());
1020 /// assert!('7'.is_alphanumeric());
1021 /// assert!('৬'.is_alphanumeric());
1022 /// assert!('¾'.is_alphanumeric());
1023 /// assert!('①'.is_alphanumeric());
1024 /// assert!('K'.is_alphanumeric());
1025 /// assert!('و'.is_alphanumeric());
1026 /// assert!('藏'.is_alphanumeric());
1027 /// ```
1028 #[must_use]
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 #[inline]
1031 pub fn is_alphanumeric(self) -> bool {
1032 match self {
1033 'a'..='z' | 'A'..='Z' | '0'..='9' => true,
1034 '\0'..='\u{A9}' => false,
1035 _ => unicode::Alphabetic(self) || unicode::N(self),
1036 }
1037 }
1038
1039 /// Returns `true` if this `char` has the general category for control codes.
1040 ///
1041 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
1042 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
1043 /// Database][ucd] [`UnicodeData.txt`].
1044 ///
1045 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1046 /// [ucd]: https://www.unicode.org/reports/tr44/
1047 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1048 ///
1049 /// # Examples
1050 ///
1051 /// Basic usage:
1052 ///
1053 /// ```
1054 /// // U+009C, STRING TERMINATOR
1055 /// assert!(''.is_control());
1056 /// assert!(!'q'.is_control());
1057 /// ```
1058 #[must_use]
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 #[inline]
1061 pub fn is_control(self) -> bool {
1062 // According to
1063 // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1064 // the set of codepoints in `Cc` will never change.
1065 // So we can just hard-code the patterns to match against instead of using a table.
1066 matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}')
1067 }
1068
1069 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
1070 ///
1071 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
1072 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
1073 /// [`DerivedCoreProperties.txt`].
1074 ///
1075 /// [uax29]: https://www.unicode.org/reports/tr29/
1076 /// [ucd]: https://www.unicode.org/reports/tr44/
1077 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1078 #[must_use]
1079 #[inline]
1080 #[ferrocene::prevalidated]
1081 pub(crate) fn is_grapheme_extended(self) -> bool {
1082 self > '\u{02FF}' && unicode::Grapheme_Extend(self)
1083 }
1084
1085 /// Returns `true` if this `char` has the `Case_Ignorable` property.
1086 ///
1087 /// `Case_Ignorable` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
1088 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
1089 ///
1090 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1091 /// [ucd]: https://www.unicode.org/reports/tr44/
1092 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1093 #[must_use]
1094 #[inline]
1095 #[doc(hidden)]
1096 #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
1097 pub fn is_case_ignorable(self) -> bool {
1098 if self.is_ascii() {
1099 matches!(self, '\'' | '.' | ':' | '^' | '`')
1100 } else {
1101 unicode::Case_Ignorable(self)
1102 }
1103 }
1104
1105 /// Returns `true` if this `char` has one of the general categories for numbers.
1106 ///
1107 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
1108 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
1109 /// Database][ucd] [`UnicodeData.txt`].
1110 ///
1111 /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
1112 /// If you want everything including characters with overlapping purposes then you might want to use
1113 /// a unicode or language-processing library that exposes the appropriate character properties instead
1114 /// of looking at the unicode categories.
1115 ///
1116 /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
1117 /// `is_ascii_digit` or `is_digit` instead.
1118 ///
1119 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1120 /// [ucd]: https://www.unicode.org/reports/tr44/
1121 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1122 ///
1123 /// # Examples
1124 ///
1125 /// Basic usage:
1126 ///
1127 /// ```
1128 /// assert!('٣'.is_numeric());
1129 /// assert!('7'.is_numeric());
1130 /// assert!('৬'.is_numeric());
1131 /// assert!('¾'.is_numeric());
1132 /// assert!('①'.is_numeric());
1133 /// assert!(!'K'.is_numeric());
1134 /// assert!(!'و'.is_numeric());
1135 /// assert!(!'藏'.is_numeric());
1136 /// assert!(!'三'.is_numeric());
1137 /// ```
1138 #[must_use]
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 #[inline]
1141 pub fn is_numeric(self) -> bool {
1142 match self {
1143 '0'..='9' => true,
1144 '\0'..='\u{B1}' => false,
1145 _ => unicode::N(self),
1146 }
1147 }
1148
1149 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
1150 /// `char`s.
1151 ///
1152 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
1153 ///
1154 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
1155 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1156 ///
1157 /// [ucd]: https://www.unicode.org/reports/tr44/
1158 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1159 ///
1160 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1161 /// the `char`(s) given by [`SpecialCasing.txt`].
1162 ///
1163 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1164 ///
1165 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1166 /// is independent of context and language.
1167 ///
1168 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1169 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1170 ///
1171 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1172 ///
1173 /// # Examples
1174 ///
1175 /// As an iterator:
1176 ///
1177 /// ```
1178 /// for c in 'İ'.to_lowercase() {
1179 /// print!("{c}");
1180 /// }
1181 /// println!();
1182 /// ```
1183 ///
1184 /// Using `println!` directly:
1185 ///
1186 /// ```
1187 /// println!("{}", 'İ'.to_lowercase());
1188 /// ```
1189 ///
1190 /// Both are equivalent to:
1191 ///
1192 /// ```
1193 /// println!("i\u{307}");
1194 /// ```
1195 ///
1196 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1197 ///
1198 /// ```
1199 /// assert_eq!('C'.to_lowercase().to_string(), "c");
1200 ///
1201 /// // Sometimes the result is more than one character:
1202 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1203 ///
1204 /// // Characters that do not have both uppercase and lowercase
1205 /// // convert into themselves.
1206 /// assert_eq!('山'.to_lowercase().to_string(), "山");
1207 /// ```
1208 #[must_use = "this returns the lowercased character as a new iterator, \
1209 without modifying the original"]
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 #[inline]
1212 pub fn to_lowercase(self) -> ToLowercase {
1213 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1214 }
1215
1216 /// Returns an iterator that yields the titlecase mapping of this `char` as one or more
1217 /// `char`s.
1218 ///
1219 /// This is usually, but not always, equivalent to the uppercase mapping
1220 /// returned by [`Self::to_uppercase`]. Prefer this method when seeking to capitalize
1221 /// Only The First Letter of a word, but use [`Self::to_uppercase`] for ALL CAPS.
1222 ///
1223 /// If this `char` does not have a titlecase mapping, the iterator yields the same `char`.
1224 ///
1225 /// If this `char` has a one-to-one titlecase mapping given by the [Unicode Character
1226 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1227 ///
1228 /// [ucd]: https://www.unicode.org/reports/tr44/
1229 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1230 ///
1231 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1232 /// the `char`(s) given by [`SpecialCasing.txt`].
1233 ///
1234 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1235 ///
1236 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1237 /// is independent of context and language.
1238 ///
1239 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1240 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1241 ///
1242 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1243 ///
1244 /// # Examples
1245 ///
1246 /// As an iterator:
1247 ///
1248 /// ```
1249 /// #![feature(titlecase)]
1250 /// for c in 'ß'.to_titlecase() {
1251 /// print!("{c}");
1252 /// }
1253 /// println!();
1254 /// ```
1255 ///
1256 /// Using `println!` directly:
1257 ///
1258 /// ```
1259 /// #![feature(titlecase)]
1260 /// println!("{}", 'ß'.to_titlecase());
1261 /// ```
1262 ///
1263 /// Both are equivalent to:
1264 ///
1265 /// ```
1266 /// println!("Ss");
1267 /// ```
1268 ///
1269 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1270 ///
1271 /// ```
1272 /// #![feature(titlecase)]
1273 /// assert_eq!('c'.to_titlecase().to_string(), "C");
1274 /// assert_eq!('dž'.to_titlecase().to_string(), "Dž");
1275 /// assert_eq!('ῼ'.to_titlecase().to_string(), "ῼ");
1276 ///
1277 /// // Sometimes the result is more than one character:
1278 /// assert_eq!('ß'.to_titlecase().to_string(), "Ss");
1279 ///
1280 /// // Characters that do not have separate cased forms
1281 /// // convert into themselves.
1282 /// assert_eq!('山'.to_titlecase().to_string(), "山");
1283 /// ```
1284 ///
1285 /// # Note on locale
1286 ///
1287 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1288 ///
1289 /// * 'Dotless': I / ı, sometimes written ï
1290 /// * 'Dotted': İ / i
1291 ///
1292 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1293 ///
1294 /// ```
1295 /// #![feature(titlecase)]
1296 /// let upper_i = 'i'.to_titlecase().to_string();
1297 /// ```
1298 ///
1299 /// The value of `upper_i` here relies on the language of the text: if we're
1300 /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1301 /// be `"İ"`. `to_titlecase()` does not take this into account, and so:
1302 ///
1303 /// ```
1304 /// #![feature(titlecase)]
1305 /// let upper_i = 'i'.to_titlecase().to_string();
1306 ///
1307 /// assert_eq!(upper_i, "I");
1308 /// ```
1309 ///
1310 /// holds across languages.
1311 #[must_use = "this returns the titlecased character as a new iterator, \
1312 without modifying the original"]
1313 #[unstable(feature = "titlecase", issue = "153892")]
1314 #[inline]
1315 pub fn to_titlecase(self) -> ToTitlecase {
1316 ToTitlecase(CaseMappingIter::new(conversions::to_title(self)))
1317 }
1318
1319 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1320 /// `char`s.
1321 ///
1322 /// Prefer this method when converting a word into ALL CAPS, but consider [`Self::to_titlecase`]
1323 /// instead if you seek to capitalize Only The First Letter.
1324 ///
1325 /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1326 ///
1327 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1328 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1329 ///
1330 /// [ucd]: https://www.unicode.org/reports/tr44/
1331 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1332 ///
1333 /// If this `char` requires special considerations (e.g. multiple `char`s) the iterator yields
1334 /// the `char`(s) given by [`SpecialCasing.txt`].
1335 ///
1336 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1337 ///
1338 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1339 /// is independent of context and language.
1340 ///
1341 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1342 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1343 ///
1344 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1345 ///
1346 /// # Examples
1347 /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase.
1348 ///
1349 /// As an iterator:
1350 ///
1351 /// ```
1352 /// for c in 'ſt'.to_uppercase() {
1353 /// print!("{c}");
1354 /// }
1355 /// println!();
1356 /// ```
1357 ///
1358 /// Using `println!` directly:
1359 ///
1360 /// ```
1361 /// println!("{}", 'ſt'.to_uppercase());
1362 /// ```
1363 ///
1364 /// Both are equivalent to:
1365 ///
1366 /// ```
1367 /// println!("ST");
1368 /// ```
1369 ///
1370 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1371 ///
1372 /// ```
1373 /// assert_eq!('c'.to_uppercase().to_string(), "C");
1374 /// assert_eq!('dž'.to_uppercase().to_string(), "DŽ");
1375 ///
1376 /// // Sometimes the result is more than one character:
1377 /// assert_eq!('ſt'.to_uppercase().to_string(), "ST");
1378 /// assert_eq!('ῼ'.to_uppercase().to_string(), "ΩΙ");
1379 ///
1380 /// // Characters that do not have both uppercase and lowercase
1381 /// // convert into themselves.
1382 /// assert_eq!('山'.to_uppercase().to_string(), "山");
1383 /// ```
1384 ///
1385 /// # Note on locale
1386 ///
1387 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1388 ///
1389 /// * 'Dotless': I / ı, sometimes written ï
1390 /// * 'Dotted': İ / i
1391 ///
1392 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1393 ///
1394 /// ```
1395 /// let upper_i = 'i'.to_uppercase().to_string();
1396 /// ```
1397 ///
1398 /// The value of `upper_i` here relies on the language of the text: if we're
1399 /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1400 /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1401 ///
1402 /// ```
1403 /// let upper_i = 'i'.to_uppercase().to_string();
1404 ///
1405 /// assert_eq!(upper_i, "I");
1406 /// ```
1407 ///
1408 /// holds across languages.
1409 #[must_use = "this returns the uppercased character as a new iterator, \
1410 without modifying the original"]
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 #[inline]
1413 pub fn to_uppercase(self) -> ToUppercase {
1414 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1415 }
1416
1417 /// Checks if the value is within the ASCII range.
1418 ///
1419 /// # Examples
1420 ///
1421 /// ```
1422 /// let ascii = 'a';
1423 /// let non_ascii = '❤';
1424 ///
1425 /// assert!(ascii.is_ascii());
1426 /// assert!(!non_ascii.is_ascii());
1427 /// ```
1428 #[must_use]
1429 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1430 #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1431 #[rustc_diagnostic_item = "char_is_ascii"]
1432 #[inline]
1433 #[ferrocene::prevalidated]
1434 pub const fn is_ascii(&self) -> bool {
1435 *self as u32 <= 0x7F
1436 }
1437
1438 /// Returns `Some` if the value is within the ASCII range,
1439 /// or `None` if it's not.
1440 ///
1441 /// This is preferred to [`Self::is_ascii`] when you're passing the value
1442 /// along to something else that can take [`ascii::Char`] rather than
1443 /// needing to check again for itself whether the value is in ASCII.
1444 #[must_use]
1445 #[unstable(feature = "ascii_char", issue = "110998")]
1446 #[inline]
1447 pub const fn as_ascii(&self) -> Option<ascii::Char> {
1448 if self.is_ascii() {
1449 // SAFETY: Just checked that this is ASCII.
1450 Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
1451 } else {
1452 None
1453 }
1454 }
1455
1456 /// Converts this char into an [ASCII character](`ascii::Char`), without
1457 /// checking whether it is valid.
1458 ///
1459 /// # Safety
1460 ///
1461 /// This char must be within the ASCII range, or else this is UB.
1462 #[must_use]
1463 #[unstable(feature = "ascii_char", issue = "110998")]
1464 #[inline]
1465 pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1466 assert_unsafe_precondition!(
1467 check_library_ub,
1468 "as_ascii_unchecked requires that the char is valid ASCII",
1469 (it: &char = self) => it.is_ascii()
1470 );
1471
1472 // SAFETY: the caller promised that this char is ASCII.
1473 unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1474 }
1475
1476 /// Makes a copy of the value in its ASCII upper case equivalent.
1477 ///
1478 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1479 /// but non-ASCII letters are unchanged.
1480 ///
1481 /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1482 ///
1483 /// To uppercase ASCII characters in addition to non-ASCII characters, use
1484 /// [`to_uppercase()`].
1485 ///
1486 /// # Examples
1487 ///
1488 /// ```
1489 /// let ascii = 'a';
1490 /// let non_ascii = '❤';
1491 ///
1492 /// assert_eq!('A', ascii.to_ascii_uppercase());
1493 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1494 /// ```
1495 ///
1496 /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1497 /// [`to_uppercase()`]: #method.to_uppercase
1498 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1499 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1500 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1501 #[inline]
1502 pub const fn to_ascii_uppercase(&self) -> char {
1503 if self.is_ascii_lowercase() {
1504 (*self as u8).ascii_change_case_unchecked() as char
1505 } else {
1506 *self
1507 }
1508 }
1509
1510 /// Makes a copy of the value in its ASCII lower case equivalent.
1511 ///
1512 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1513 /// but non-ASCII letters are unchanged.
1514 ///
1515 /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1516 ///
1517 /// To lowercase ASCII characters in addition to non-ASCII characters, use
1518 /// [`to_lowercase()`].
1519 ///
1520 /// # Examples
1521 ///
1522 /// ```
1523 /// let ascii = 'A';
1524 /// let non_ascii = '❤';
1525 ///
1526 /// assert_eq!('a', ascii.to_ascii_lowercase());
1527 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1528 /// ```
1529 ///
1530 /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1531 /// [`to_lowercase()`]: #method.to_lowercase
1532 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1533 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1534 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1535 #[inline]
1536 pub const fn to_ascii_lowercase(&self) -> char {
1537 if self.is_ascii_uppercase() {
1538 (*self as u8).ascii_change_case_unchecked() as char
1539 } else {
1540 *self
1541 }
1542 }
1543
1544 /// Checks that two values are an ASCII case-insensitive match.
1545 ///
1546 /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1547 ///
1548 /// # Examples
1549 ///
1550 /// ```
1551 /// let upper_a = 'A';
1552 /// let lower_a = 'a';
1553 /// let lower_z = 'z';
1554 ///
1555 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1556 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1557 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1558 /// ```
1559 ///
1560 /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1561 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1562 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1563 #[inline]
1564 pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1565 self.to_ascii_lowercase() == other.to_ascii_lowercase()
1566 }
1567
1568 /// Converts this type to its ASCII upper case equivalent in-place.
1569 ///
1570 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1571 /// but non-ASCII letters are unchanged.
1572 ///
1573 /// To return a new uppercased value without modifying the existing one, use
1574 /// [`to_ascii_uppercase()`].
1575 ///
1576 /// # Examples
1577 ///
1578 /// ```
1579 /// let mut ascii = 'a';
1580 ///
1581 /// ascii.make_ascii_uppercase();
1582 ///
1583 /// assert_eq!('A', ascii);
1584 /// ```
1585 ///
1586 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1587 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1588 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1589 #[inline]
1590 pub const fn make_ascii_uppercase(&mut self) {
1591 *self = self.to_ascii_uppercase();
1592 }
1593
1594 /// Converts this type to its ASCII lower case equivalent in-place.
1595 ///
1596 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1597 /// but non-ASCII letters are unchanged.
1598 ///
1599 /// To return a new lowercased value without modifying the existing one, use
1600 /// [`to_ascii_lowercase()`].
1601 ///
1602 /// # Examples
1603 ///
1604 /// ```
1605 /// let mut ascii = 'A';
1606 ///
1607 /// ascii.make_ascii_lowercase();
1608 ///
1609 /// assert_eq!('a', ascii);
1610 /// ```
1611 ///
1612 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1613 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1614 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1615 #[inline]
1616 pub const fn make_ascii_lowercase(&mut self) {
1617 *self = self.to_ascii_lowercase();
1618 }
1619
1620 /// Checks if the value is an ASCII alphabetic character:
1621 ///
1622 /// - U+0041 'A' ..= U+005A 'Z', or
1623 /// - U+0061 'a' ..= U+007A 'z'.
1624 ///
1625 /// # Examples
1626 ///
1627 /// ```
1628 /// let uppercase_a = 'A';
1629 /// let uppercase_g = 'G';
1630 /// let a = 'a';
1631 /// let g = 'g';
1632 /// let zero = '0';
1633 /// let percent = '%';
1634 /// let space = ' ';
1635 /// let lf = '\n';
1636 /// let esc = '\x1b';
1637 ///
1638 /// assert!(uppercase_a.is_ascii_alphabetic());
1639 /// assert!(uppercase_g.is_ascii_alphabetic());
1640 /// assert!(a.is_ascii_alphabetic());
1641 /// assert!(g.is_ascii_alphabetic());
1642 /// assert!(!zero.is_ascii_alphabetic());
1643 /// assert!(!percent.is_ascii_alphabetic());
1644 /// assert!(!space.is_ascii_alphabetic());
1645 /// assert!(!lf.is_ascii_alphabetic());
1646 /// assert!(!esc.is_ascii_alphabetic());
1647 /// ```
1648 #[must_use]
1649 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1650 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1651 #[inline]
1652 pub const fn is_ascii_alphabetic(&self) -> bool {
1653 matches!(*self, 'a'..='z' | 'A'..='Z')
1654 }
1655
1656 /// Checks if the value is an ASCII uppercase character:
1657 /// U+0041 'A' ..= U+005A 'Z'.
1658 ///
1659 /// # Examples
1660 ///
1661 /// ```
1662 /// let uppercase_a = 'A';
1663 /// let uppercase_g = 'G';
1664 /// let a = 'a';
1665 /// let g = 'g';
1666 /// let zero = '0';
1667 /// let percent = '%';
1668 /// let space = ' ';
1669 /// let lf = '\n';
1670 /// let esc = '\x1b';
1671 ///
1672 /// assert!(uppercase_a.is_ascii_uppercase());
1673 /// assert!(uppercase_g.is_ascii_uppercase());
1674 /// assert!(!a.is_ascii_uppercase());
1675 /// assert!(!g.is_ascii_uppercase());
1676 /// assert!(!zero.is_ascii_uppercase());
1677 /// assert!(!percent.is_ascii_uppercase());
1678 /// assert!(!space.is_ascii_uppercase());
1679 /// assert!(!lf.is_ascii_uppercase());
1680 /// assert!(!esc.is_ascii_uppercase());
1681 /// ```
1682 #[must_use]
1683 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1684 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1685 #[inline]
1686 pub const fn is_ascii_uppercase(&self) -> bool {
1687 matches!(*self, 'A'..='Z')
1688 }
1689
1690 /// Checks if the value is an ASCII lowercase character:
1691 /// U+0061 'a' ..= U+007A 'z'.
1692 ///
1693 /// # Examples
1694 ///
1695 /// ```
1696 /// let uppercase_a = 'A';
1697 /// let uppercase_g = 'G';
1698 /// let a = 'a';
1699 /// let g = 'g';
1700 /// let zero = '0';
1701 /// let percent = '%';
1702 /// let space = ' ';
1703 /// let lf = '\n';
1704 /// let esc = '\x1b';
1705 ///
1706 /// assert!(!uppercase_a.is_ascii_lowercase());
1707 /// assert!(!uppercase_g.is_ascii_lowercase());
1708 /// assert!(a.is_ascii_lowercase());
1709 /// assert!(g.is_ascii_lowercase());
1710 /// assert!(!zero.is_ascii_lowercase());
1711 /// assert!(!percent.is_ascii_lowercase());
1712 /// assert!(!space.is_ascii_lowercase());
1713 /// assert!(!lf.is_ascii_lowercase());
1714 /// assert!(!esc.is_ascii_lowercase());
1715 /// ```
1716 #[must_use]
1717 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1718 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1719 #[inline]
1720 pub const fn is_ascii_lowercase(&self) -> bool {
1721 matches!(*self, 'a'..='z')
1722 }
1723
1724 /// Checks if the value is an ASCII alphanumeric character:
1725 ///
1726 /// - U+0041 'A' ..= U+005A 'Z', or
1727 /// - U+0061 'a' ..= U+007A 'z', or
1728 /// - U+0030 '0' ..= U+0039 '9'.
1729 ///
1730 /// # Examples
1731 ///
1732 /// ```
1733 /// let uppercase_a = 'A';
1734 /// let uppercase_g = 'G';
1735 /// let a = 'a';
1736 /// let g = 'g';
1737 /// let zero = '0';
1738 /// let percent = '%';
1739 /// let space = ' ';
1740 /// let lf = '\n';
1741 /// let esc = '\x1b';
1742 ///
1743 /// assert!(uppercase_a.is_ascii_alphanumeric());
1744 /// assert!(uppercase_g.is_ascii_alphanumeric());
1745 /// assert!(a.is_ascii_alphanumeric());
1746 /// assert!(g.is_ascii_alphanumeric());
1747 /// assert!(zero.is_ascii_alphanumeric());
1748 /// assert!(!percent.is_ascii_alphanumeric());
1749 /// assert!(!space.is_ascii_alphanumeric());
1750 /// assert!(!lf.is_ascii_alphanumeric());
1751 /// assert!(!esc.is_ascii_alphanumeric());
1752 /// ```
1753 #[must_use]
1754 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1755 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1756 #[inline]
1757 pub const fn is_ascii_alphanumeric(&self) -> bool {
1758 matches!(*self, '0'..='9') | matches!(*self, 'A'..='Z') | matches!(*self, 'a'..='z')
1759 }
1760
1761 /// Checks if the value is an ASCII decimal digit:
1762 /// U+0030 '0' ..= U+0039 '9'.
1763 ///
1764 /// # Examples
1765 ///
1766 /// ```
1767 /// let uppercase_a = 'A';
1768 /// let uppercase_g = 'G';
1769 /// let a = 'a';
1770 /// let g = 'g';
1771 /// let zero = '0';
1772 /// let percent = '%';
1773 /// let space = ' ';
1774 /// let lf = '\n';
1775 /// let esc = '\x1b';
1776 ///
1777 /// assert!(!uppercase_a.is_ascii_digit());
1778 /// assert!(!uppercase_g.is_ascii_digit());
1779 /// assert!(!a.is_ascii_digit());
1780 /// assert!(!g.is_ascii_digit());
1781 /// assert!(zero.is_ascii_digit());
1782 /// assert!(!percent.is_ascii_digit());
1783 /// assert!(!space.is_ascii_digit());
1784 /// assert!(!lf.is_ascii_digit());
1785 /// assert!(!esc.is_ascii_digit());
1786 /// ```
1787 #[must_use]
1788 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1789 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1790 #[inline]
1791 pub const fn is_ascii_digit(&self) -> bool {
1792 matches!(*self, '0'..='9')
1793 }
1794
1795 /// Checks if the value is an ASCII octal digit:
1796 /// U+0030 '0' ..= U+0037 '7'.
1797 ///
1798 /// # Examples
1799 ///
1800 /// ```
1801 /// #![feature(is_ascii_octdigit)]
1802 ///
1803 /// let uppercase_a = 'A';
1804 /// let a = 'a';
1805 /// let zero = '0';
1806 /// let seven = '7';
1807 /// let nine = '9';
1808 /// let percent = '%';
1809 /// let lf = '\n';
1810 ///
1811 /// assert!(!uppercase_a.is_ascii_octdigit());
1812 /// assert!(!a.is_ascii_octdigit());
1813 /// assert!(zero.is_ascii_octdigit());
1814 /// assert!(seven.is_ascii_octdigit());
1815 /// assert!(!nine.is_ascii_octdigit());
1816 /// assert!(!percent.is_ascii_octdigit());
1817 /// assert!(!lf.is_ascii_octdigit());
1818 /// ```
1819 #[must_use]
1820 #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
1821 #[inline]
1822 pub const fn is_ascii_octdigit(&self) -> bool {
1823 matches!(*self, '0'..='7')
1824 }
1825
1826 /// Checks if the value is an ASCII hexadecimal digit:
1827 ///
1828 /// - U+0030 '0' ..= U+0039 '9', or
1829 /// - U+0041 'A' ..= U+0046 'F', or
1830 /// - U+0061 'a' ..= U+0066 'f'.
1831 ///
1832 /// # Examples
1833 ///
1834 /// ```
1835 /// let uppercase_a = 'A';
1836 /// let uppercase_g = 'G';
1837 /// let a = 'a';
1838 /// let g = 'g';
1839 /// let zero = '0';
1840 /// let percent = '%';
1841 /// let space = ' ';
1842 /// let lf = '\n';
1843 /// let esc = '\x1b';
1844 ///
1845 /// assert!(uppercase_a.is_ascii_hexdigit());
1846 /// assert!(!uppercase_g.is_ascii_hexdigit());
1847 /// assert!(a.is_ascii_hexdigit());
1848 /// assert!(!g.is_ascii_hexdigit());
1849 /// assert!(zero.is_ascii_hexdigit());
1850 /// assert!(!percent.is_ascii_hexdigit());
1851 /// assert!(!space.is_ascii_hexdigit());
1852 /// assert!(!lf.is_ascii_hexdigit());
1853 /// assert!(!esc.is_ascii_hexdigit());
1854 /// ```
1855 #[must_use]
1856 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1857 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1858 #[inline]
1859 pub const fn is_ascii_hexdigit(&self) -> bool {
1860 matches!(*self, '0'..='9') | matches!(*self, 'A'..='F') | matches!(*self, 'a'..='f')
1861 }
1862
1863 /// Checks if the value is an ASCII punctuation character:
1864 ///
1865 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1866 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1867 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
1868 /// - U+007B ..= U+007E `{ | } ~`
1869 ///
1870 /// # Examples
1871 ///
1872 /// ```
1873 /// let uppercase_a = 'A';
1874 /// let uppercase_g = 'G';
1875 /// let a = 'a';
1876 /// let g = 'g';
1877 /// let zero = '0';
1878 /// let percent = '%';
1879 /// let space = ' ';
1880 /// let lf = '\n';
1881 /// let esc = '\x1b';
1882 ///
1883 /// assert!(!uppercase_a.is_ascii_punctuation());
1884 /// assert!(!uppercase_g.is_ascii_punctuation());
1885 /// assert!(!a.is_ascii_punctuation());
1886 /// assert!(!g.is_ascii_punctuation());
1887 /// assert!(!zero.is_ascii_punctuation());
1888 /// assert!(percent.is_ascii_punctuation());
1889 /// assert!(!space.is_ascii_punctuation());
1890 /// assert!(!lf.is_ascii_punctuation());
1891 /// assert!(!esc.is_ascii_punctuation());
1892 /// ```
1893 #[must_use]
1894 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1895 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1896 #[inline]
1897 pub const fn is_ascii_punctuation(&self) -> bool {
1898 matches!(*self, '!'..='/')
1899 | matches!(*self, ':'..='@')
1900 | matches!(*self, '['..='`')
1901 | matches!(*self, '{'..='~')
1902 }
1903
1904 /// Checks if the value is an ASCII graphic character:
1905 /// U+0021 '!' ..= U+007E '~'.
1906 ///
1907 /// # Examples
1908 ///
1909 /// ```
1910 /// let uppercase_a = 'A';
1911 /// let uppercase_g = 'G';
1912 /// let a = 'a';
1913 /// let g = 'g';
1914 /// let zero = '0';
1915 /// let percent = '%';
1916 /// let space = ' ';
1917 /// let lf = '\n';
1918 /// let esc = '\x1b';
1919 ///
1920 /// assert!(uppercase_a.is_ascii_graphic());
1921 /// assert!(uppercase_g.is_ascii_graphic());
1922 /// assert!(a.is_ascii_graphic());
1923 /// assert!(g.is_ascii_graphic());
1924 /// assert!(zero.is_ascii_graphic());
1925 /// assert!(percent.is_ascii_graphic());
1926 /// assert!(!space.is_ascii_graphic());
1927 /// assert!(!lf.is_ascii_graphic());
1928 /// assert!(!esc.is_ascii_graphic());
1929 /// ```
1930 #[must_use]
1931 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1932 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1933 #[inline]
1934 pub const fn is_ascii_graphic(&self) -> bool {
1935 matches!(*self, '!'..='~')
1936 }
1937
1938 /// Checks if the value is an ASCII whitespace character:
1939 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1940 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1941 ///
1942 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1943 /// whitespace][infra-aw]. There are several other definitions in
1944 /// wide use. For instance, [the POSIX locale][pct] includes
1945 /// U+000B VERTICAL TAB as well as all the above characters,
1946 /// but—from the very same specification—[the default rule for
1947 /// "field splitting" in the Bourne shell][bfs] considers *only*
1948 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1949 ///
1950 /// If you are writing a program that will process an existing
1951 /// file format, check what that format's definition of whitespace is
1952 /// before using this function.
1953 ///
1954 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1955 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1956 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1957 ///
1958 /// # Examples
1959 ///
1960 /// ```
1961 /// let uppercase_a = 'A';
1962 /// let uppercase_g = 'G';
1963 /// let a = 'a';
1964 /// let g = 'g';
1965 /// let zero = '0';
1966 /// let percent = '%';
1967 /// let space = ' ';
1968 /// let lf = '\n';
1969 /// let esc = '\x1b';
1970 ///
1971 /// assert!(!uppercase_a.is_ascii_whitespace());
1972 /// assert!(!uppercase_g.is_ascii_whitespace());
1973 /// assert!(!a.is_ascii_whitespace());
1974 /// assert!(!g.is_ascii_whitespace());
1975 /// assert!(!zero.is_ascii_whitespace());
1976 /// assert!(!percent.is_ascii_whitespace());
1977 /// assert!(space.is_ascii_whitespace());
1978 /// assert!(lf.is_ascii_whitespace());
1979 /// assert!(!esc.is_ascii_whitespace());
1980 /// ```
1981 #[must_use]
1982 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1983 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1984 #[inline]
1985 pub const fn is_ascii_whitespace(&self) -> bool {
1986 matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
1987 }
1988
1989 /// Checks if the value is an ASCII control character:
1990 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1991 /// Note that most ASCII whitespace characters are control
1992 /// characters, but SPACE is not.
1993 ///
1994 /// # Examples
1995 ///
1996 /// ```
1997 /// let uppercase_a = 'A';
1998 /// let uppercase_g = 'G';
1999 /// let a = 'a';
2000 /// let g = 'g';
2001 /// let zero = '0';
2002 /// let percent = '%';
2003 /// let space = ' ';
2004 /// let lf = '\n';
2005 /// let esc = '\x1b';
2006 ///
2007 /// assert!(!uppercase_a.is_ascii_control());
2008 /// assert!(!uppercase_g.is_ascii_control());
2009 /// assert!(!a.is_ascii_control());
2010 /// assert!(!g.is_ascii_control());
2011 /// assert!(!zero.is_ascii_control());
2012 /// assert!(!percent.is_ascii_control());
2013 /// assert!(!space.is_ascii_control());
2014 /// assert!(lf.is_ascii_control());
2015 /// assert!(esc.is_ascii_control());
2016 /// ```
2017 #[must_use]
2018 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2019 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2020 #[inline]
2021 pub const fn is_ascii_control(&self) -> bool {
2022 matches!(*self, '\0'..='\x1F' | '\x7F')
2023 }
2024}
2025
2026#[ferrocene::prevalidated]
2027pub(crate) struct EscapeDebugExtArgs {
2028 /// Escape Extended Grapheme codepoints?
2029 pub(crate) escape_grapheme_extended: bool,
2030
2031 /// Escape single quotes?
2032 pub(crate) escape_single_quote: bool,
2033
2034 /// Escape double quotes?
2035 pub(crate) escape_double_quote: bool,
2036}
2037
2038impl EscapeDebugExtArgs {
2039 pub(crate) const ESCAPE_ALL: Self = Self {
2040 escape_grapheme_extended: true,
2041 escape_single_quote: true,
2042 escape_double_quote: true,
2043 };
2044}
2045
2046#[inline]
2047#[must_use]
2048#[ferrocene::prevalidated]
2049const fn len_utf8(code: u32) -> usize {
2050 match code {
2051 ..MAX_ONE_B => 1,
2052 ..MAX_TWO_B => 2,
2053 ..MAX_THREE_B => 3,
2054 _ => 4,
2055 }
2056}
2057
2058#[inline]
2059#[must_use]
2060const fn len_utf16(code: u32) -> usize {
2061 if (code & 0xFFFF) == code { 1 } else { 2 }
2062}
2063
2064/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
2065/// and then returns the subslice of the buffer that contains the encoded character.
2066///
2067/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2068/// (Creating a `char` in the surrogate range is UB.)
2069/// The result is valid [generalized UTF-8] but not valid UTF-8.
2070///
2071/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2072///
2073/// # Panics
2074///
2075/// Panics if the buffer is not large enough.
2076/// A buffer of length four is large enough to encode any `char`.
2077#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2078#[doc(hidden)]
2079#[inline]
2080#[ferrocene::prevalidated]
2081pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
2082 let len = len_utf8(code);
2083 if dst.len() < len {
2084 const_panic!(
2085 "encode_utf8: buffer does not have enough bytes to encode code point",
2086 "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2087 code: u32 = code,
2088 len: usize = len,
2089 dst_len: usize = dst.len(),
2090 );
2091 }
2092
2093 // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint.
2094 unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) };
2095
2096 // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2097 unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2098}
2099
2100/// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`.
2101///
2102/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2103/// (Creating a `char` in the surrogate range is UB.)
2104/// The result is valid [generalized UTF-8] but not valid UTF-8.
2105///
2106/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2107///
2108/// # Safety
2109///
2110/// The behavior is undefined if the buffer pointed to by `dst` is not
2111/// large enough to hold the encoded codepoint. A buffer of length four
2112/// is large enough to encode any `char`.
2113///
2114/// For a safe version of this function, see the [`encode_utf8_raw`] function.
2115#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2116#[doc(hidden)]
2117#[inline]
2118#[ferrocene::prevalidated]
2119pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
2120 let len = len_utf8(code);
2121 // SAFETY: The caller must guarantee that the buffer pointed to by `dst`
2122 // is at least `len` bytes long.
2123 unsafe {
2124 if len == 1 {
2125 *dst = code as u8;
2126 return;
2127 }
2128
2129 let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
2130 let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
2131 let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
2132 let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
2133
2134 if len == 2 {
2135 *dst = last2 | TAG_TWO_B;
2136 *dst.add(1) = last1;
2137 return;
2138 }
2139
2140 if len == 3 {
2141 *dst = last3 | TAG_THREE_B;
2142 *dst.add(1) = last2;
2143 *dst.add(2) = last1;
2144 return;
2145 }
2146
2147 *dst = last4;
2148 *dst.add(1) = last3;
2149 *dst.add(2) = last2;
2150 *dst.add(3) = last1;
2151 }
2152}
2153
2154/// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer,
2155/// and then returns the subslice of the buffer that contains the encoded character.
2156///
2157/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
2158/// (Creating a `char` in the surrogate range is UB.)
2159///
2160/// # Panics
2161///
2162/// Panics if the buffer is not large enough.
2163/// A buffer of length 2 is large enough to encode any `char`.
2164#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2165#[doc(hidden)]
2166#[inline]
2167pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
2168 let len = len_utf16(code);
2169 match (len, &mut *dst) {
2170 (1, [a, ..]) => {
2171 *a = code as u16;
2172 }
2173 (2, [a, b, ..]) => {
2174 code -= 0x1_0000;
2175 *a = (code >> 10) as u16 | 0xD800;
2176 *b = (code & 0x3FF) as u16 | 0xDC00;
2177 }
2178 _ => {
2179 const_panic!(
2180 "encode_utf16: buffer does not have enough bytes to encode code point",
2181 "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2182 code: u32 = code,
2183 len: usize = len,
2184 dst_len: usize = dst.len(),
2185 )
2186 }
2187 };
2188 // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2189 unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2190}