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 #[ferrocene::prevalidated]
468 pub fn escape_unicode(self) -> EscapeUnicode {
469 EscapeUnicode::new(self)
470 }
471
472 /// An extended version of `escape_debug` that optionally permits escaping
473 /// Extended Grapheme codepoints, single quotes, and double quotes. This
474 /// allows us to format characters like nonspacing marks better when they're
475 /// at the start of a string, and allows escaping single quotes in
476 /// characters, and double quotes in strings.
477 #[inline]
478 #[ferrocene::prevalidated]
479 pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
480 match self {
481 '\0' => EscapeDebug::backslash(ascii::Char::Digit0),
482 '\t' => EscapeDebug::backslash(ascii::Char::SmallT),
483 '\r' => EscapeDebug::backslash(ascii::Char::SmallR),
484 '\n' => EscapeDebug::backslash(ascii::Char::SmallN),
485 '\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus),
486 '\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark),
487 '\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe),
488 _ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
489 EscapeDebug::unicode(self)
490 }
491 _ if is_printable(self) => EscapeDebug::printable(self),
492 _ => EscapeDebug::unicode(self),
493 }
494 }
495
496 /// Returns an iterator that yields the literal escape code of a character
497 /// as `char`s.
498 ///
499 /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
500 /// of `str` or `char`.
501 ///
502 /// # Examples
503 ///
504 /// As an iterator:
505 ///
506 /// ```
507 /// for c in '\n'.escape_debug() {
508 /// print!("{c}");
509 /// }
510 /// println!();
511 /// ```
512 ///
513 /// Using `println!` directly:
514 ///
515 /// ```
516 /// println!("{}", '\n'.escape_debug());
517 /// ```
518 ///
519 /// Both are equivalent to:
520 ///
521 /// ```
522 /// println!("\\n");
523 /// ```
524 ///
525 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
526 ///
527 /// ```
528 /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
529 /// ```
530 #[must_use = "this returns the escaped char as an iterator, \
531 without modifying the original"]
532 #[stable(feature = "char_escape_debug", since = "1.20.0")]
533 #[inline]
534 #[ferrocene::prevalidated]
535 pub fn escape_debug(self) -> EscapeDebug {
536 self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
537 }
538
539 /// Returns an iterator that yields the literal escape code of a character
540 /// as `char`s.
541 ///
542 /// The default is chosen with a bias toward producing literals that are
543 /// legal in a variety of languages, including C++11 and similar C-family
544 /// languages. The exact rules are:
545 ///
546 /// * Tab is escaped as `\t`.
547 /// * Carriage return is escaped as `\r`.
548 /// * Line feed is escaped as `\n`.
549 /// * Single quote is escaped as `\'`.
550 /// * Double quote is escaped as `\"`.
551 /// * Backslash is escaped as `\\`.
552 /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
553 /// inclusive is not escaped.
554 /// * All other characters are given hexadecimal Unicode escapes; see
555 /// [`escape_unicode`].
556 ///
557 /// [`escape_unicode`]: #method.escape_unicode
558 ///
559 /// # Examples
560 ///
561 /// As an iterator:
562 ///
563 /// ```
564 /// for c in '"'.escape_default() {
565 /// print!("{c}");
566 /// }
567 /// println!();
568 /// ```
569 ///
570 /// Using `println!` directly:
571 ///
572 /// ```
573 /// println!("{}", '"'.escape_default());
574 /// ```
575 ///
576 /// Both are equivalent to:
577 ///
578 /// ```
579 /// println!("\\\"");
580 /// ```
581 ///
582 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
583 ///
584 /// ```
585 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
586 /// ```
587 #[must_use = "this returns the escaped char as an iterator, \
588 without modifying the original"]
589 #[stable(feature = "rust1", since = "1.0.0")]
590 #[inline]
591 #[ferrocene::prevalidated]
592 pub fn escape_default(self) -> EscapeDefault {
593 match self {
594 '\t' => EscapeDefault::backslash(ascii::Char::SmallT),
595 '\r' => EscapeDefault::backslash(ascii::Char::SmallR),
596 '\n' => EscapeDefault::backslash(ascii::Char::SmallN),
597 '\\' | '\'' | '\"' => EscapeDefault::backslash(self.as_ascii().unwrap()),
598 '\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()),
599 _ => EscapeDefault::unicode(self),
600 }
601 }
602
603 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
604 ///
605 /// That number of bytes is always between 1 and 4, inclusive.
606 ///
607 /// # Examples
608 ///
609 /// Basic usage:
610 ///
611 /// ```
612 /// let len = 'A'.len_utf8();
613 /// assert_eq!(len, 1);
614 ///
615 /// let len = 'ß'.len_utf8();
616 /// assert_eq!(len, 2);
617 ///
618 /// let len = 'ℝ'.len_utf8();
619 /// assert_eq!(len, 3);
620 ///
621 /// let len = '💣'.len_utf8();
622 /// assert_eq!(len, 4);
623 /// ```
624 ///
625 /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
626 /// would take if each code point was represented as a `char` vs in the `&str` itself:
627 ///
628 /// ```
629 /// // as chars
630 /// let eastern = '東';
631 /// let capital = '京';
632 ///
633 /// // both can be represented as three bytes
634 /// assert_eq!(3, eastern.len_utf8());
635 /// assert_eq!(3, capital.len_utf8());
636 ///
637 /// // as a &str, these two are encoded in UTF-8
638 /// let tokyo = "東京";
639 ///
640 /// let len = eastern.len_utf8() + capital.len_utf8();
641 ///
642 /// // we can see that they take six bytes total...
643 /// assert_eq!(6, tokyo.len());
644 ///
645 /// // ... just like the &str
646 /// assert_eq!(len, tokyo.len());
647 /// ```
648 #[stable(feature = "rust1", since = "1.0.0")]
649 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
650 #[inline]
651 #[must_use]
652 #[ferrocene::prevalidated]
653 pub const fn len_utf8(self) -> usize {
654 len_utf8(self as u32)
655 }
656
657 /// Returns the number of 16-bit code units this `char` would need if
658 /// encoded in UTF-16.
659 ///
660 /// That number of code units is always either 1 or 2, for unicode scalar values in
661 /// the [basic multilingual plane] or [supplementary planes] respectively.
662 ///
663 /// See the documentation for [`len_utf8()`] for more explanation of this
664 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
665 ///
666 /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
667 /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
668 /// [`len_utf8()`]: #method.len_utf8
669 ///
670 /// # Examples
671 ///
672 /// Basic usage:
673 ///
674 /// ```
675 /// let n = 'ß'.len_utf16();
676 /// assert_eq!(n, 1);
677 ///
678 /// let len = '💣'.len_utf16();
679 /// assert_eq!(len, 2);
680 /// ```
681 #[stable(feature = "rust1", since = "1.0.0")]
682 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
683 #[inline]
684 #[must_use]
685 pub const fn len_utf16(self) -> usize {
686 len_utf16(self as u32)
687 }
688
689 /// Encodes this character as UTF-8 into the provided byte buffer,
690 /// and then returns the subslice of the buffer that contains the encoded character.
691 ///
692 /// # Panics
693 ///
694 /// Panics if the buffer is not large enough.
695 /// A buffer of length four is large enough to encode any `char`.
696 ///
697 /// # Examples
698 ///
699 /// In both of these examples, 'ß' takes two bytes to encode.
700 ///
701 /// ```
702 /// let mut b = [0; 2];
703 ///
704 /// let result = 'ß'.encode_utf8(&mut b);
705 ///
706 /// assert_eq!(result, "ß");
707 ///
708 /// assert_eq!(result.len(), 2);
709 /// ```
710 ///
711 /// A buffer that's too small:
712 ///
713 /// ```should_panic
714 /// let mut b = [0; 1];
715 ///
716 /// // this panics
717 /// 'ß'.encode_utf8(&mut b);
718 /// ```
719 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
720 #[rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0")]
721 #[inline]
722 #[ferrocene::prevalidated]
723 pub const fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
724 // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
725 unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
726 }
727
728 /// Encodes this character as native endian UTF-16 into the provided `u16` buffer,
729 /// and then returns the subslice of the buffer that contains the encoded character.
730 ///
731 /// # Panics
732 ///
733 /// Panics if the buffer is not large enough.
734 /// A buffer of length 2 is large enough to encode any `char`.
735 ///
736 /// # Examples
737 ///
738 /// In both of these examples, '𝕊' takes two `u16`s to encode.
739 ///
740 /// ```
741 /// let mut b = [0; 2];
742 ///
743 /// let result = '𝕊'.encode_utf16(&mut b);
744 ///
745 /// assert_eq!(result.len(), 2);
746 /// ```
747 ///
748 /// A buffer that's too small:
749 ///
750 /// ```should_panic
751 /// let mut b = [0; 1];
752 ///
753 /// // this panics
754 /// '𝕊'.encode_utf16(&mut b);
755 /// ```
756 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
757 #[rustc_const_stable(feature = "const_char_encode_utf16", since = "1.84.0")]
758 #[inline]
759 pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
760 encode_utf16_raw(self as u32, dst)
761 }
762
763 /// Returns `true` if this `char` has the `Alphabetic` property.
764 ///
765 /// `Alphabetic` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
766 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
767 ///
768 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
769 /// [ucd]: https://www.unicode.org/reports/tr44/
770 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
771 ///
772 /// # Examples
773 ///
774 /// Basic usage:
775 ///
776 /// ```
777 /// assert!('a'.is_alphabetic());
778 /// assert!('京'.is_alphabetic());
779 ///
780 /// let c = '💝';
781 /// // love is many things, but it is not alphabetic
782 /// assert!(!c.is_alphabetic());
783 /// ```
784 #[must_use]
785 #[stable(feature = "rust1", since = "1.0.0")]
786 #[inline]
787 pub fn is_alphabetic(self) -> bool {
788 match self {
789 'a'..='z' | 'A'..='Z' => true,
790 '\0'..='\u{A9}' => false,
791 _ => unicode::Alphabetic(self),
792 }
793 }
794
795 /// Returns `true` if this `char` has the `Cased` property.
796 /// A character is cased if and only if it is uppercase, lowercase, or titlecase.
797 ///
798 /// `Cased` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
799 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
800 ///
801 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
802 /// [ucd]: https://www.unicode.org/reports/tr44/
803 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
804 ///
805 /// # Examples
806 ///
807 /// Basic usage:
808 ///
809 /// ```
810 /// #![feature(titlecase)]
811 /// assert!('A'.is_cased());
812 /// assert!('a'.is_cased());
813 /// assert!(!'京'.is_cased());
814 /// ```
815 #[must_use]
816 #[unstable(feature = "titlecase", issue = "153892")]
817 #[inline]
818 pub fn is_cased(self) -> bool {
819 match self {
820 'a'..='z' | 'A'..='Z' => true,
821 '\0'..='\u{A9}' => false,
822 _ => unicode::Lowercase(self) || unicode::Uppercase(self) || unicode::Lt(self),
823 }
824 }
825
826 /// Returns the case of this character:
827 /// [`Some(CharCase::Upper)`][`CharCase::Upper`] if [`self.is_uppercase()`][`char::is_uppercase`],
828 /// [`Some(CharCase::Lower)`][`CharCase::Lower`] if [`self.is_lowercase()`][`char::is_lowercase`],
829 /// [`Some(CharCase::Title)`][`CharCase::Title`] if [`self.is_titlecase()`][`char::is_titlecase`], and
830 /// `None` if [`!self.is_cased()`][`char::is_cased`].
831 ///
832 /// # Examples
833 ///
834 /// ```
835 /// #![feature(titlecase)]
836 /// use core::char::CharCase;
837 /// assert_eq!('a'.case(), Some(CharCase::Lower));
838 /// assert_eq!('δ'.case(), Some(CharCase::Lower));
839 /// assert_eq!('A'.case(), Some(CharCase::Upper));
840 /// assert_eq!('Δ'.case(), Some(CharCase::Upper));
841 /// assert_eq!('Dž'.case(), Some(CharCase::Title));
842 /// assert_eq!('中'.case(), None);
843 /// ```
844 #[must_use]
845 #[unstable(feature = "titlecase", issue = "153892")]
846 #[inline]
847 pub fn case(self) -> Option<CharCase> {
848 match self {
849 'a'..='z' => Some(CharCase::Lower),
850 'A'..='Z' => Some(CharCase::Upper),
851 '\0'..='\u{A9}' => None,
852 _ if unicode::Lowercase(self) => Some(CharCase::Lower),
853 _ if unicode::Uppercase(self) => Some(CharCase::Upper),
854 _ if unicode::Lt(self) => Some(CharCase::Title),
855 _ => None,
856 }
857 }
858
859 /// Returns `true` if this `char` has the `Lowercase` property.
860 ///
861 /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
862 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
863 ///
864 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
865 /// [ucd]: https://www.unicode.org/reports/tr44/
866 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
867 ///
868 /// # Examples
869 ///
870 /// Basic usage:
871 ///
872 /// ```
873 /// assert!('a'.is_lowercase());
874 /// assert!('δ'.is_lowercase());
875 /// assert!(!'A'.is_lowercase());
876 /// assert!(!'Δ'.is_lowercase());
877 ///
878 /// // The various Chinese scripts and punctuation do not have case, and so:
879 /// assert!(!'中'.is_lowercase());
880 /// assert!(!' '.is_lowercase());
881 /// ```
882 ///
883 /// In a const context:
884 ///
885 /// ```
886 /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
887 /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
888 /// ```
889 #[must_use]
890 #[stable(feature = "rust1", since = "1.0.0")]
891 #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
892 #[inline]
893 pub const fn is_lowercase(self) -> bool {
894 match self {
895 'a'..='z' => true,
896 '\0'..='\u{A9}' => false,
897 _ => unicode::Lowercase(self),
898 }
899 }
900
901 /// Returns `true` if this `char` has the general category for titlecase letters.
902 /// Conceptually, these characters consist of an uppercase portion followed by a lowercase portion.
903 ///
904 /// Titlecase letters (code points with the general category of `Lt`) are described in Chapter 4
905 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
906 /// Database][ucd] [`UnicodeData.txt`].
907 ///
908 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
909 /// [ucd]: https://www.unicode.org/reports/tr44/
910 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
911 ///
912 /// # Examples
913 ///
914 /// Basic usage:
915 ///
916 /// ```
917 /// #![feature(titlecase)]
918 /// assert!('Dž'.is_titlecase());
919 /// assert!('ῼ'.is_titlecase());
920 /// assert!(!'D'.is_titlecase());
921 /// assert!(!'z'.is_titlecase());
922 /// assert!(!'中'.is_titlecase());
923 /// assert!(!' '.is_titlecase());
924 /// ```
925 #[must_use]
926 #[unstable(feature = "titlecase", issue = "153892")]
927 #[inline]
928 pub fn is_titlecase(self) -> bool {
929 match self {
930 '\0'..='\u{01C4}' => false,
931 _ => unicode::Lt(self),
932 }
933 }
934
935 /// Returns `true` if this `char` has the `Uppercase` property.
936 ///
937 /// `Uppercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and
938 /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`].
939 ///
940 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
941 /// [ucd]: https://www.unicode.org/reports/tr44/
942 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
943 ///
944 /// # Examples
945 ///
946 /// Basic usage:
947 ///
948 /// ```
949 /// assert!(!'a'.is_uppercase());
950 /// assert!(!'δ'.is_uppercase());
951 /// assert!('A'.is_uppercase());
952 /// assert!('Δ'.is_uppercase());
953 ///
954 /// // The various Chinese scripts and punctuation do not have case, and so:
955 /// assert!(!'中'.is_uppercase());
956 /// assert!(!' '.is_uppercase());
957 /// ```
958 ///
959 /// In a const context:
960 ///
961 /// ```
962 /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
963 /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
964 /// ```
965 #[must_use]
966 #[stable(feature = "rust1", since = "1.0.0")]
967 #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
968 #[inline]
969 pub const fn is_uppercase(self) -> bool {
970 match self {
971 'A'..='Z' => true,
972 '\0'..='\u{BF}' => false,
973 _ => unicode::Uppercase(self),
974 }
975 }
976
977 /// Returns `true` if this `char` has the `White_Space` property.
978 ///
979 /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`].
980 ///
981 /// [ucd]: https://www.unicode.org/reports/tr44/
982 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
983 ///
984 /// # Examples
985 ///
986 /// Basic usage:
987 ///
988 /// ```
989 /// assert!(' '.is_whitespace());
990 ///
991 /// // line break
992 /// assert!('\n'.is_whitespace());
993 ///
994 /// // a non-breaking space
995 /// assert!('\u{A0}'.is_whitespace());
996 ///
997 /// assert!(!'越'.is_whitespace());
998 /// ```
999 #[must_use]
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
1002 #[inline]
1003 #[ferrocene::prevalidated]
1004 pub const fn is_whitespace(self) -> bool {
1005 match self {
1006 ' ' | '\x09'..='\x0d' => true,
1007 '\0'..='\u{84}' => false,
1008 _ => unicode::White_Space(self),
1009 }
1010 }
1011
1012 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
1013 ///
1014 /// [`is_alphabetic()`]: #method.is_alphabetic
1015 /// [`is_numeric()`]: #method.is_numeric
1016 ///
1017 /// # Examples
1018 ///
1019 /// Basic usage:
1020 ///
1021 /// ```
1022 /// assert!('٣'.is_alphanumeric());
1023 /// assert!('7'.is_alphanumeric());
1024 /// assert!('৬'.is_alphanumeric());
1025 /// assert!('¾'.is_alphanumeric());
1026 /// assert!('①'.is_alphanumeric());
1027 /// assert!('K'.is_alphanumeric());
1028 /// assert!('و'.is_alphanumeric());
1029 /// assert!('藏'.is_alphanumeric());
1030 /// ```
1031 #[must_use]
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 #[inline]
1034 pub fn is_alphanumeric(self) -> bool {
1035 match self {
1036 'a'..='z' | 'A'..='Z' | '0'..='9' => true,
1037 '\0'..='\u{A9}' => false,
1038 _ => unicode::Alphabetic(self) || unicode::N(self),
1039 }
1040 }
1041
1042 /// Returns `true` if this `char` has the general category for control codes.
1043 ///
1044 /// Control codes (code points with the general category of `Cc`) are described in Chapter 4
1045 /// (Character Properties) of the [Unicode Standard] and specified in the [Unicode Character
1046 /// Database][ucd] [`UnicodeData.txt`].
1047 ///
1048 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1049 /// [ucd]: https://www.unicode.org/reports/tr44/
1050 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1051 ///
1052 /// # Examples
1053 ///
1054 /// Basic usage:
1055 ///
1056 /// ```
1057 /// // U+009C, STRING TERMINATOR
1058 /// assert!(''.is_control());
1059 /// assert!(!'q'.is_control());
1060 /// ```
1061 #[must_use]
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 #[inline]
1064 pub fn is_control(self) -> bool {
1065 // According to
1066 // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1067 // the set of codepoints in `Cc` will never change.
1068 // So we can just hard-code the patterns to match against instead of using a table.
1069 matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}')
1070 }
1071
1072 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
1073 ///
1074 /// `Grapheme_Extend` is described in [Unicode Standard Annex #29 (Unicode Text
1075 /// Segmentation)][uax29] and specified in the [Unicode Character Database][ucd]
1076 /// [`DerivedCoreProperties.txt`].
1077 ///
1078 /// [uax29]: https://www.unicode.org/reports/tr29/
1079 /// [ucd]: https://www.unicode.org/reports/tr44/
1080 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1081 #[must_use]
1082 #[inline]
1083 #[ferrocene::prevalidated]
1084 pub(crate) fn is_grapheme_extended(self) -> bool {
1085 self > '\u{02FF}' && unicode::Grapheme_Extend(self)
1086 }
1087
1088 /// Returns `true` if this `char` has the `Case_Ignorable` property. This narrow-use property
1089 /// is used to implement context-dependent casing for the Greek letter sigma (uppercase Σ),
1090 /// which has two lowercase forms.
1091 ///
1092 /// `Case_Ignorable` is [described][D136] in Chapter 3 (Conformance) of the Unicode Core Specification,
1093 /// and specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`];
1094 /// see those resources for more information.
1095 ///
1096 /// [D136]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G63116
1097 /// [ucd]: https://www.unicode.org/reports/tr44/
1098 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1099 #[must_use]
1100 #[inline]
1101 #[unstable(feature = "case_ignorable", issue = "154848")]
1102 pub fn is_case_ignorable(self) -> bool {
1103 if self.is_ascii() {
1104 matches!(self, '\'' | '.' | ':' | '^' | '`')
1105 } else {
1106 unicode::Case_Ignorable(self)
1107 }
1108 }
1109
1110 /// Returns `true` if this `char` has one of the general categories for numbers.
1111 ///
1112 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
1113 /// characters, and `No` for other numeric characters) are specified in the [Unicode Character
1114 /// Database][ucd] [`UnicodeData.txt`].
1115 ///
1116 /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
1117 /// If you want everything including characters with overlapping purposes then you might want to use
1118 /// a unicode or language-processing library that exposes the appropriate character properties instead
1119 /// of looking at the unicode categories.
1120 ///
1121 /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
1122 /// `is_ascii_digit` or `is_digit` instead.
1123 ///
1124 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1125 /// [ucd]: https://www.unicode.org/reports/tr44/
1126 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1127 ///
1128 /// # Examples
1129 ///
1130 /// Basic usage:
1131 ///
1132 /// ```
1133 /// assert!('٣'.is_numeric());
1134 /// assert!('7'.is_numeric());
1135 /// assert!('৬'.is_numeric());
1136 /// assert!('¾'.is_numeric());
1137 /// assert!('①'.is_numeric());
1138 /// assert!(!'K'.is_numeric());
1139 /// assert!(!'و'.is_numeric());
1140 /// assert!(!'藏'.is_numeric());
1141 /// assert!(!'三'.is_numeric());
1142 /// ```
1143 #[must_use]
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 #[inline]
1146 pub fn is_numeric(self) -> bool {
1147 match self {
1148 '0'..='9' => true,
1149 '\0'..='\u{B1}' => false,
1150 _ => unicode::N(self),
1151 }
1152 }
1153
1154 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
1155 /// `char`s.
1156 ///
1157 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
1158 ///
1159 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
1160 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1161 ///
1162 /// [ucd]: https://www.unicode.org/reports/tr44/
1163 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1164 ///
1165 /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1166 /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1167 ///
1168 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1169 ///
1170 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1171 /// is independent of context and language. See [below](#notes-on-context-and-locale)
1172 /// for more information.
1173 ///
1174 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1175 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1176 ///
1177 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1178 ///
1179 /// # Examples
1180 ///
1181 /// As an iterator:
1182 ///
1183 /// ```
1184 /// for c in 'İ'.to_lowercase() {
1185 /// print!("{c}");
1186 /// }
1187 /// println!();
1188 /// ```
1189 ///
1190 /// Using `println!` directly:
1191 ///
1192 /// ```
1193 /// println!("{}", 'İ'.to_lowercase());
1194 /// ```
1195 ///
1196 /// Both are equivalent to:
1197 ///
1198 /// ```
1199 /// println!("i\u{307}");
1200 /// ```
1201 ///
1202 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1203 ///
1204 /// ```
1205 /// assert_eq!('C'.to_lowercase().to_string(), "c");
1206 ///
1207 /// // Sometimes the result is more than one character:
1208 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1209 ///
1210 /// // Characters that do not have both uppercase and lowercase
1211 /// // convert into themselves.
1212 /// assert_eq!('山'.to_lowercase().to_string(), "山");
1213 /// ```
1214 /// # Notes on context and locale
1215 ///
1216 /// As stated earlier, this method does not take into account language or context.
1217 /// Below is a non-exhaustive list of situations where this can be relevant.
1218 /// If you need to handle locale-depedendent casing in your code, consider using
1219 /// an external crate, like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1220 /// which is developed by Unicode.
1221 ///
1222 /// ## Greek sigma
1223 ///
1224 /// In Greek, the letter simga (uppercase Σ) has two lowercase forms:
1225 /// ς which is used only at the end of a word, and σ which is used everywhere else.
1226 /// `to_lowercase()` always uses the second form:
1227 ///
1228 /// ```
1229 /// assert_eq!('Σ'.to_lowercase().to_string(), "σ");
1230 /// ```
1231 ///
1232 /// ## Turkish and Azeri I/ı/İ/i
1233 ///
1234 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1235 ///
1236 /// * 'Dotless': I / ı, sometimes written ï
1237 /// * 'Dotted': İ / i
1238 ///
1239 /// Note that the uppercase undotted 'I' is the same as the Latin. Therefore:
1240 ///
1241 /// ```
1242 /// let lower_i = 'I'.to_lowercase().to_string();
1243 /// ```
1244 ///
1245 /// The value of `lower_i` here relies on the language of the text: if we're
1246 /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should
1247 /// be `"ı"`. `to_lowercase()` does not take this into account, and so:
1248 ///
1249 /// ```
1250 /// let lower_i = 'I'.to_lowercase().to_string();
1251 ///
1252 /// assert_eq!(lower_i, "i");
1253 /// ```
1254 ///
1255 /// holds across languages.
1256 #[must_use = "this returns the lowercased character as a new iterator, \
1257 without modifying the original"]
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 #[inline]
1260 pub fn to_lowercase(self) -> ToLowercase {
1261 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1262 }
1263
1264 /// Returns an iterator that yields the titlecase mapping of this `char` as one or more
1265 /// `char`s.
1266 ///
1267 /// This is usually, but not always, equivalent to the uppercase mapping
1268 /// returned by [`to_uppercase()`]. Prefer this method when seeking to capitalize
1269 /// Only The First Letter of a word, but use [`to_uppercase()`] for ALL CAPS.
1270 /// See [below](#difference-from-uppercase) for a thorough explanation
1271 /// of the difference between the two methods.
1272 ///
1273 /// If this `char` does not have a titlecase mapping, the iterator yields the same `char`.
1274 ///
1275 /// If this `char` has a one-to-one titlecase mapping given by the [Unicode Character
1276 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1277 ///
1278 /// [ucd]: https://www.unicode.org/reports/tr44/
1279 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1280 ///
1281 /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1282 /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1283 ///
1284 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1285 ///
1286 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1287 /// is independent of context and language. See [below](#note-on-locale)
1288 /// for more information.
1289 ///
1290 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1291 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1292 ///
1293 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1294 ///
1295 /// # Examples
1296 ///
1297 /// As an iterator:
1298 ///
1299 /// ```
1300 /// #![feature(titlecase)]
1301 /// for c in 'ß'.to_titlecase() {
1302 /// print!("{c}");
1303 /// }
1304 /// println!();
1305 /// ```
1306 ///
1307 /// Using `println!` directly:
1308 ///
1309 /// ```
1310 /// #![feature(titlecase)]
1311 /// println!("{}", 'ß'.to_titlecase());
1312 /// ```
1313 ///
1314 /// Both are equivalent to:
1315 ///
1316 /// ```
1317 /// println!("Ss");
1318 /// ```
1319 ///
1320 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1321 ///
1322 /// ```
1323 /// #![feature(titlecase)]
1324 /// assert_eq!('c'.to_titlecase().to_string(), "C");
1325 /// assert_eq!('ა'.to_titlecase().to_string(), "ა");
1326 /// assert_eq!('dž'.to_titlecase().to_string(), "Dž");
1327 /// assert_eq!('ᾨ'.to_titlecase().to_string(), "ᾨ");
1328 ///
1329 /// // Sometimes the result is more than one character:
1330 /// assert_eq!('ß'.to_titlecase().to_string(), "Ss");
1331 ///
1332 /// // Characters that do not have separate cased forms
1333 /// // convert into themselves.
1334 /// assert_eq!('山'.to_titlecase().to_string(), "山");
1335 /// ```
1336 ///
1337 /// # Difference from uppercase
1338 ///
1339 /// Currently, there are three classes of characters where [`to_uppercase()`]
1340 /// and `to_titlecase()` give different results:
1341 ///
1342 /// ## Georgian script
1343 ///
1344 /// Each letter in the modern Georgian alphabet can be written in one of two forms:
1345 /// the typical lowercase-like "mkhedruli" form, and a variant uppercase-like "mtavruli"
1346 /// form. However, unlike uppercase in most cased scripts, mtavruli is not typically used
1347 /// to start sentences, denote proper nouns, or for any other purpose
1348 /// in running text. It is instead confined to titles and headings, which are written entirely
1349 /// in mtavruli. For this reason, [`to_uppercase()`] applied to a Georgian letter
1350 /// will return the mtavruli form, but `to_titlecase()` will return the mkhedruli form.
1351 ///
1352 /// ```
1353 /// #![feature(titlecase)]
1354 /// let ani = 'ა'; // First letter of the Georgian alphabet, in mkhedruli form
1355 ///
1356 /// // Titlecasing mkhedruli maps it to itself...
1357 /// assert_eq!(ani.to_titlecase().to_string(), ani.to_string());
1358 ///
1359 /// // but uppercasing it maps it to mtavruli
1360 /// assert_eq!(ani.to_uppercase().to_string(), "Ა");
1361 /// ```
1362 ///
1363 /// ## Compatibility digraphs for Latin-alphabet Serbo-Croatian
1364 ///
1365 /// The standard Latin alphabet for the Serbo-Croatian language
1366 /// (Bosnian, Croatian, Montenegrin, and Serbian) contains
1367 /// three digraphs: Dž, Lj, and Nj. These are usually represented as
1368 /// two characters. However, for compatibility with older character sets,
1369 /// Unicode includes single-character versions of these digraphs.
1370 /// Each has a uppercase, titlecase, and lowercase version:
1371 ///
1372 /// - `'DŽ'`, `'Dž'`, `'dž'`
1373 /// - `'LJ'`, `'Lj'`, `'lj'`
1374 /// - `'NJ'`, `'Nj'`, `'nj'`
1375 ///
1376 /// Unicode additionally encodes a casing triad for the Dz digraph
1377 /// without the caron: `'DZ'`, `'Dz'`, `'dz'`.
1378 ///
1379 /// ## Iota-subscritped Greek vowels
1380 ///
1381 /// In ancient Greek, the long vowels alpha (α), eta (η), and omega (ω)
1382 /// were sometimes followed by an iota (ι), forming a diphthong. Over time,
1383 /// the diphthong pronunciation was slowly lost, with the iota becoming mute.
1384 /// Eventually, the ι disappeared from the spelling as well.
1385 /// However, there remains a need to represent ancient texts faithfully.
1386 ///
1387 /// Modern editions of ancient Greek texts commonly use a reduced-sized
1388 /// ι symbol to denote mute iotas, while distinguishing them from ιs
1389 /// which continued to affect pronunciation. The exact standard differs
1390 /// between different publications. Some render the mute ι below its associated
1391 /// vowel (subscript), while others place it to the right of said vowel (adscript).
1392 /// The interaction of mute ι symbols with casing also varies.
1393 ///
1394 /// The Unicode Standard, for its default casing rules, chose to make lowercase
1395 /// Greek vowels with iota subscipt (e.g. `'ᾠ'`) titlecase to the uppercase vowel
1396 /// with iota subscript (`'ᾨ'`) but uppercase to the uppercase vowel followed by
1397 /// full-size uppercase iota (`"ὨΙ"`). This is just one convention among many
1398 /// in common use, but it is the one Unicode settled on,
1399 /// so it is what this method does also.
1400 ///
1401 /// # Note on locale
1402 ///
1403 /// As stated above, this method is locale-insensitive.
1404 /// If you need locale support, consider using an external crate,
1405 /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1406 /// which is developed by Unicode. A description of a common
1407 /// locale-dependent casing issue follows:
1408 ///
1409 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1410 ///
1411 /// * 'Dotless': I / ı, sometimes written ï
1412 /// * 'Dotted': İ / i
1413 ///
1414 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1415 ///
1416 /// ```
1417 /// #![feature(titlecase)]
1418 /// let upper_i = 'i'.to_titlecase().to_string();
1419 /// ```
1420 ///
1421 /// The value of `upper_i` here relies on the language of the text: if we're
1422 /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1423 /// be `"İ"`. `to_titlecase()` does not take this into account, and so:
1424 ///
1425 /// ```
1426 /// #![feature(titlecase)]
1427 /// let upper_i = 'i'.to_titlecase().to_string();
1428 ///
1429 /// assert_eq!(upper_i, "I");
1430 /// ```
1431 ///
1432 /// holds across languages.
1433 ///
1434 /// [`to_uppercase()`]: Self::to_uppercase()
1435 #[must_use = "this returns the titlecased character as a new iterator, \
1436 without modifying the original"]
1437 #[unstable(feature = "titlecase", issue = "153892")]
1438 #[inline]
1439 pub fn to_titlecase(self) -> ToTitlecase {
1440 ToTitlecase(CaseMappingIter::new(conversions::to_title(self)))
1441 }
1442
1443 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1444 /// `char`s.
1445 ///
1446 /// Prefer this method when converting a word into ALL CAPS, but consider [`to_titlecase()`]
1447 /// instead if you seek to capitalize Only The First Letter. See that method's documentation
1448 /// for more information on the difference between the two.
1449 ///
1450 /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1451 ///
1452 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1453 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1454 ///
1455 /// [ucd]: https://www.unicode.org/reports/tr44/
1456 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1457 ///
1458 /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1459 /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1460 ///
1461 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1462 ///
1463 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1464 /// is independent of context and language. See [below](#note-on-locale)
1465 /// for more information.
1466 ///
1467 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1468 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1469 ///
1470 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1471 ///
1472 /// # Examples
1473 ///
1474 /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase.
1475 ///
1476 /// As an iterator:
1477 ///
1478 /// ```
1479 /// for c in 'ſt'.to_uppercase() {
1480 /// print!("{c}");
1481 /// }
1482 /// println!();
1483 /// ```
1484 ///
1485 /// Using `println!` directly:
1486 ///
1487 /// ```
1488 /// println!("{}", 'ſt'.to_uppercase());
1489 /// ```
1490 ///
1491 /// Both are equivalent to:
1492 ///
1493 /// ```
1494 /// println!("ST");
1495 /// ```
1496 ///
1497 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1498 ///
1499 /// ```
1500 /// assert_eq!('c'.to_uppercase().to_string(), "C");
1501 /// assert_eq!('ა'.to_uppercase().to_string(), "Ა");
1502 /// assert_eq!('dž'.to_uppercase().to_string(), "DŽ");
1503 ///
1504 /// // Sometimes the result is more than one character:
1505 /// assert_eq!('ſt'.to_uppercase().to_string(), "ST");
1506 /// assert_eq!('ᾨ'.to_uppercase().to_string(), "ὨΙ");
1507 ///
1508 /// // Characters that do not have both uppercase and lowercase
1509 /// // convert into themselves.
1510 /// assert_eq!('山'.to_uppercase().to_string(), "山");
1511 /// ```
1512 ///
1513 /// # Note on locale
1514 ///
1515 /// As stated above, this method is locale-insensitive.
1516 /// If you need locale support, consider using an external crate,
1517 /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1518 /// which is developed by Unicode. A description of a common
1519 /// locale-dependent casing issue follows:
1520 ///
1521 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1522 ///
1523 /// * 'Dotless': I / ı, sometimes written ï
1524 /// * 'Dotted': İ / i
1525 ///
1526 /// Note that the lowercase dotted 'i' is the same as the Latin. Therefore:
1527 ///
1528 /// ```
1529 /// let upper_i = 'i'.to_uppercase().to_string();
1530 /// ```
1531 ///
1532 /// The value of `upper_i` here relies on the language of the text: if we're
1533 /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1534 /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1535 ///
1536 /// ```
1537 /// let upper_i = 'i'.to_uppercase().to_string();
1538 ///
1539 /// assert_eq!(upper_i, "I");
1540 /// ```
1541 ///
1542 /// holds across languages.
1543 ///
1544 /// [`to_titlecase()`]: Self::to_titlecase()
1545 #[must_use = "this returns the uppercased character as a new iterator, \
1546 without modifying the original"]
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 #[inline]
1549 pub fn to_uppercase(self) -> ToUppercase {
1550 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1551 }
1552
1553 /// Checks if the value is within the ASCII range.
1554 ///
1555 /// # Examples
1556 ///
1557 /// ```
1558 /// let ascii = 'a';
1559 /// let non_ascii = '❤';
1560 ///
1561 /// assert!(ascii.is_ascii());
1562 /// assert!(!non_ascii.is_ascii());
1563 /// ```
1564 #[must_use]
1565 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1566 #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1567 #[rustc_diagnostic_item = "char_is_ascii"]
1568 #[inline]
1569 #[ferrocene::prevalidated]
1570 pub const fn is_ascii(&self) -> bool {
1571 *self as u32 <= 0x7F
1572 }
1573
1574 /// Returns `Some` if the value is within the ASCII range,
1575 /// or `None` if it's not.
1576 ///
1577 /// This is preferred to [`Self::is_ascii`] when you're passing the value
1578 /// along to something else that can take [`ascii::Char`] rather than
1579 /// needing to check again for itself whether the value is in ASCII.
1580 #[must_use]
1581 #[unstable(feature = "ascii_char", issue = "110998")]
1582 #[inline]
1583 #[ferrocene::prevalidated]
1584 pub const fn as_ascii(&self) -> Option<ascii::Char> {
1585 if self.is_ascii() {
1586 // SAFETY: Just checked that this is ASCII.
1587 Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
1588 } else {
1589 None
1590 }
1591 }
1592
1593 /// Converts this char into an [ASCII character](`ascii::Char`), without
1594 /// checking whether it is valid.
1595 ///
1596 /// # Safety
1597 ///
1598 /// This char must be within the ASCII range, or else this is UB.
1599 #[must_use]
1600 #[unstable(feature = "ascii_char", issue = "110998")]
1601 #[inline]
1602 pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1603 assert_unsafe_precondition!(
1604 check_library_ub,
1605 "as_ascii_unchecked requires that the char is valid ASCII",
1606 (it: &char = self) => it.is_ascii()
1607 );
1608
1609 // SAFETY: the caller promised that this char is ASCII.
1610 unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1611 }
1612
1613 /// Makes a copy of the value in its ASCII upper case equivalent.
1614 ///
1615 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1616 /// but non-ASCII letters are unchanged.
1617 ///
1618 /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
1619 ///
1620 /// To uppercase ASCII characters in addition to non-ASCII characters, use
1621 /// [`to_uppercase()`].
1622 ///
1623 /// # Examples
1624 ///
1625 /// ```
1626 /// let ascii = 'a';
1627 /// let non_ascii = '❤';
1628 ///
1629 /// assert_eq!('A', ascii.to_ascii_uppercase());
1630 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
1631 /// ```
1632 ///
1633 /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
1634 /// [`to_uppercase()`]: #method.to_uppercase
1635 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
1636 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1637 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1638 #[inline]
1639 pub const fn to_ascii_uppercase(&self) -> char {
1640 if self.is_ascii_lowercase() {
1641 (*self as u8).ascii_change_case_unchecked() as char
1642 } else {
1643 *self
1644 }
1645 }
1646
1647 /// Makes a copy of the value in its ASCII lower case equivalent.
1648 ///
1649 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1650 /// but non-ASCII letters are unchanged.
1651 ///
1652 /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
1653 ///
1654 /// To lowercase ASCII characters in addition to non-ASCII characters, use
1655 /// [`to_lowercase()`].
1656 ///
1657 /// # Examples
1658 ///
1659 /// ```
1660 /// let ascii = 'A';
1661 /// let non_ascii = '❤';
1662 ///
1663 /// assert_eq!('a', ascii.to_ascii_lowercase());
1664 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
1665 /// ```
1666 ///
1667 /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
1668 /// [`to_lowercase()`]: #method.to_lowercase
1669 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
1670 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1671 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1672 #[inline]
1673 pub const fn to_ascii_lowercase(&self) -> char {
1674 if self.is_ascii_uppercase() {
1675 (*self as u8).ascii_change_case_unchecked() as char
1676 } else {
1677 *self
1678 }
1679 }
1680
1681 /// Checks that two values are an ASCII case-insensitive match.
1682 ///
1683 /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
1684 ///
1685 /// # Examples
1686 ///
1687 /// ```
1688 /// let upper_a = 'A';
1689 /// let lower_a = 'a';
1690 /// let lower_z = 'z';
1691 ///
1692 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
1693 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
1694 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
1695 /// ```
1696 ///
1697 /// [to_ascii_lowercase]: #method.to_ascii_lowercase
1698 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1699 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
1700 #[inline]
1701 pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
1702 self.to_ascii_lowercase() == other.to_ascii_lowercase()
1703 }
1704
1705 /// Converts this type to its ASCII upper case equivalent in-place.
1706 ///
1707 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1708 /// but non-ASCII letters are unchanged.
1709 ///
1710 /// To return a new uppercased value without modifying the existing one, use
1711 /// [`to_ascii_uppercase()`].
1712 ///
1713 /// # Examples
1714 ///
1715 /// ```
1716 /// let mut ascii = 'a';
1717 ///
1718 /// ascii.make_ascii_uppercase();
1719 ///
1720 /// assert_eq!('A', ascii);
1721 /// ```
1722 ///
1723 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
1724 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1725 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1726 #[inline]
1727 pub const fn make_ascii_uppercase(&mut self) {
1728 *self = self.to_ascii_uppercase();
1729 }
1730
1731 /// Converts this type to its ASCII lower case equivalent in-place.
1732 ///
1733 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1734 /// but non-ASCII letters are unchanged.
1735 ///
1736 /// To return a new lowercased value without modifying the existing one, use
1737 /// [`to_ascii_lowercase()`].
1738 ///
1739 /// # Examples
1740 ///
1741 /// ```
1742 /// let mut ascii = 'A';
1743 ///
1744 /// ascii.make_ascii_lowercase();
1745 ///
1746 /// assert_eq!('a', ascii);
1747 /// ```
1748 ///
1749 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
1750 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1751 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
1752 #[inline]
1753 pub const fn make_ascii_lowercase(&mut self) {
1754 *self = self.to_ascii_lowercase();
1755 }
1756
1757 /// Checks if the value is an ASCII alphabetic character:
1758 ///
1759 /// - U+0041 'A' ..= U+005A 'Z', or
1760 /// - U+0061 'a' ..= U+007A 'z'.
1761 ///
1762 /// # Examples
1763 ///
1764 /// ```
1765 /// let uppercase_a = 'A';
1766 /// let uppercase_g = 'G';
1767 /// let a = 'a';
1768 /// let g = 'g';
1769 /// let zero = '0';
1770 /// let percent = '%';
1771 /// let space = ' ';
1772 /// let lf = '\n';
1773 /// let esc = '\x1b';
1774 ///
1775 /// assert!(uppercase_a.is_ascii_alphabetic());
1776 /// assert!(uppercase_g.is_ascii_alphabetic());
1777 /// assert!(a.is_ascii_alphabetic());
1778 /// assert!(g.is_ascii_alphabetic());
1779 /// assert!(!zero.is_ascii_alphabetic());
1780 /// assert!(!percent.is_ascii_alphabetic());
1781 /// assert!(!space.is_ascii_alphabetic());
1782 /// assert!(!lf.is_ascii_alphabetic());
1783 /// assert!(!esc.is_ascii_alphabetic());
1784 /// ```
1785 #[must_use]
1786 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1787 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1788 #[inline]
1789 pub const fn is_ascii_alphabetic(&self) -> bool {
1790 matches!(*self, 'a'..='z' | 'A'..='Z')
1791 }
1792
1793 /// Checks if the value is an ASCII uppercase character:
1794 /// U+0041 'A' ..= U+005A 'Z'.
1795 ///
1796 /// # Examples
1797 ///
1798 /// ```
1799 /// let uppercase_a = 'A';
1800 /// let uppercase_g = 'G';
1801 /// let a = 'a';
1802 /// let g = 'g';
1803 /// let zero = '0';
1804 /// let percent = '%';
1805 /// let space = ' ';
1806 /// let lf = '\n';
1807 /// let esc = '\x1b';
1808 ///
1809 /// assert!(uppercase_a.is_ascii_uppercase());
1810 /// assert!(uppercase_g.is_ascii_uppercase());
1811 /// assert!(!a.is_ascii_uppercase());
1812 /// assert!(!g.is_ascii_uppercase());
1813 /// assert!(!zero.is_ascii_uppercase());
1814 /// assert!(!percent.is_ascii_uppercase());
1815 /// assert!(!space.is_ascii_uppercase());
1816 /// assert!(!lf.is_ascii_uppercase());
1817 /// assert!(!esc.is_ascii_uppercase());
1818 /// ```
1819 #[must_use]
1820 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1821 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1822 #[inline]
1823 pub const fn is_ascii_uppercase(&self) -> bool {
1824 matches!(*self, 'A'..='Z')
1825 }
1826
1827 /// Checks if the value is an ASCII lowercase character:
1828 /// U+0061 'a' ..= U+007A 'z'.
1829 ///
1830 /// # Examples
1831 ///
1832 /// ```
1833 /// let uppercase_a = 'A';
1834 /// let uppercase_g = 'G';
1835 /// let a = 'a';
1836 /// let g = 'g';
1837 /// let zero = '0';
1838 /// let percent = '%';
1839 /// let space = ' ';
1840 /// let lf = '\n';
1841 /// let esc = '\x1b';
1842 ///
1843 /// assert!(!uppercase_a.is_ascii_lowercase());
1844 /// assert!(!uppercase_g.is_ascii_lowercase());
1845 /// assert!(a.is_ascii_lowercase());
1846 /// assert!(g.is_ascii_lowercase());
1847 /// assert!(!zero.is_ascii_lowercase());
1848 /// assert!(!percent.is_ascii_lowercase());
1849 /// assert!(!space.is_ascii_lowercase());
1850 /// assert!(!lf.is_ascii_lowercase());
1851 /// assert!(!esc.is_ascii_lowercase());
1852 /// ```
1853 #[must_use]
1854 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1855 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1856 #[inline]
1857 pub const fn is_ascii_lowercase(&self) -> bool {
1858 matches!(*self, 'a'..='z')
1859 }
1860
1861 /// Checks if the value is an ASCII alphanumeric character:
1862 ///
1863 /// - U+0041 'A' ..= U+005A 'Z', or
1864 /// - U+0061 'a' ..= U+007A 'z', or
1865 /// - U+0030 '0' ..= U+0039 '9'.
1866 ///
1867 /// # Examples
1868 ///
1869 /// ```
1870 /// let uppercase_a = 'A';
1871 /// let uppercase_g = 'G';
1872 /// let a = 'a';
1873 /// let g = 'g';
1874 /// let zero = '0';
1875 /// let percent = '%';
1876 /// let space = ' ';
1877 /// let lf = '\n';
1878 /// let esc = '\x1b';
1879 ///
1880 /// assert!(uppercase_a.is_ascii_alphanumeric());
1881 /// assert!(uppercase_g.is_ascii_alphanumeric());
1882 /// assert!(a.is_ascii_alphanumeric());
1883 /// assert!(g.is_ascii_alphanumeric());
1884 /// assert!(zero.is_ascii_alphanumeric());
1885 /// assert!(!percent.is_ascii_alphanumeric());
1886 /// assert!(!space.is_ascii_alphanumeric());
1887 /// assert!(!lf.is_ascii_alphanumeric());
1888 /// assert!(!esc.is_ascii_alphanumeric());
1889 /// ```
1890 #[must_use]
1891 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1892 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1893 #[inline]
1894 pub const fn is_ascii_alphanumeric(&self) -> bool {
1895 matches!(*self, '0'..='9') | matches!(*self, 'A'..='Z') | matches!(*self, 'a'..='z')
1896 }
1897
1898 /// Checks if the value is an ASCII decimal digit:
1899 /// U+0030 '0' ..= U+0039 '9'.
1900 ///
1901 /// # Examples
1902 ///
1903 /// ```
1904 /// let uppercase_a = 'A';
1905 /// let uppercase_g = 'G';
1906 /// let a = 'a';
1907 /// let g = 'g';
1908 /// let zero = '0';
1909 /// let percent = '%';
1910 /// let space = ' ';
1911 /// let lf = '\n';
1912 /// let esc = '\x1b';
1913 ///
1914 /// assert!(!uppercase_a.is_ascii_digit());
1915 /// assert!(!uppercase_g.is_ascii_digit());
1916 /// assert!(!a.is_ascii_digit());
1917 /// assert!(!g.is_ascii_digit());
1918 /// assert!(zero.is_ascii_digit());
1919 /// assert!(!percent.is_ascii_digit());
1920 /// assert!(!space.is_ascii_digit());
1921 /// assert!(!lf.is_ascii_digit());
1922 /// assert!(!esc.is_ascii_digit());
1923 /// ```
1924 #[must_use]
1925 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1926 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1927 #[inline]
1928 pub const fn is_ascii_digit(&self) -> bool {
1929 matches!(*self, '0'..='9')
1930 }
1931
1932 /// Checks if the value is an ASCII octal digit:
1933 /// U+0030 '0' ..= U+0037 '7'.
1934 ///
1935 /// # Examples
1936 ///
1937 /// ```
1938 /// #![feature(is_ascii_octdigit)]
1939 ///
1940 /// let uppercase_a = 'A';
1941 /// let a = 'a';
1942 /// let zero = '0';
1943 /// let seven = '7';
1944 /// let nine = '9';
1945 /// let percent = '%';
1946 /// let lf = '\n';
1947 ///
1948 /// assert!(!uppercase_a.is_ascii_octdigit());
1949 /// assert!(!a.is_ascii_octdigit());
1950 /// assert!(zero.is_ascii_octdigit());
1951 /// assert!(seven.is_ascii_octdigit());
1952 /// assert!(!nine.is_ascii_octdigit());
1953 /// assert!(!percent.is_ascii_octdigit());
1954 /// assert!(!lf.is_ascii_octdigit());
1955 /// ```
1956 #[must_use]
1957 #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
1958 #[inline]
1959 pub const fn is_ascii_octdigit(&self) -> bool {
1960 matches!(*self, '0'..='7')
1961 }
1962
1963 /// Checks if the value is an ASCII hexadecimal digit:
1964 ///
1965 /// - U+0030 '0' ..= U+0039 '9', or
1966 /// - U+0041 'A' ..= U+0046 'F', or
1967 /// - U+0061 'a' ..= U+0066 'f'.
1968 ///
1969 /// # Examples
1970 ///
1971 /// ```
1972 /// let uppercase_a = 'A';
1973 /// let uppercase_g = 'G';
1974 /// let a = 'a';
1975 /// let g = 'g';
1976 /// let zero = '0';
1977 /// let percent = '%';
1978 /// let space = ' ';
1979 /// let lf = '\n';
1980 /// let esc = '\x1b';
1981 ///
1982 /// assert!(uppercase_a.is_ascii_hexdigit());
1983 /// assert!(!uppercase_g.is_ascii_hexdigit());
1984 /// assert!(a.is_ascii_hexdigit());
1985 /// assert!(!g.is_ascii_hexdigit());
1986 /// assert!(zero.is_ascii_hexdigit());
1987 /// assert!(!percent.is_ascii_hexdigit());
1988 /// assert!(!space.is_ascii_hexdigit());
1989 /// assert!(!lf.is_ascii_hexdigit());
1990 /// assert!(!esc.is_ascii_hexdigit());
1991 /// ```
1992 #[must_use]
1993 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1994 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1995 #[inline]
1996 pub const fn is_ascii_hexdigit(&self) -> bool {
1997 matches!(*self, '0'..='9') | matches!(*self, 'A'..='F') | matches!(*self, 'a'..='f')
1998 }
1999
2000 /// Checks if the value is an ASCII punctuation or symbol character
2001 /// (i.e. not alphanumeric, whitespace, or control):
2002 ///
2003 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
2004 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
2005 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
2006 /// - U+007B ..= U+007E `{ | } ~`
2007 ///
2008 /// # Examples
2009 ///
2010 /// ```
2011 /// let uppercase_a = 'A';
2012 /// let uppercase_g = 'G';
2013 /// let a = 'a';
2014 /// let g = 'g';
2015 /// let zero = '0';
2016 /// let percent = '%';
2017 /// let space = ' ';
2018 /// let lf = '\n';
2019 /// let esc = '\x1b';
2020 ///
2021 /// assert!(!uppercase_a.is_ascii_punctuation());
2022 /// assert!(!uppercase_g.is_ascii_punctuation());
2023 /// assert!(!a.is_ascii_punctuation());
2024 /// assert!(!g.is_ascii_punctuation());
2025 /// assert!(!zero.is_ascii_punctuation());
2026 /// assert!(percent.is_ascii_punctuation());
2027 /// assert!(!space.is_ascii_punctuation());
2028 /// assert!(!lf.is_ascii_punctuation());
2029 /// assert!(!esc.is_ascii_punctuation());
2030 /// ```
2031 #[must_use]
2032 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2033 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2034 #[inline]
2035 pub const fn is_ascii_punctuation(&self) -> bool {
2036 matches!(*self, '!'..='/')
2037 | matches!(*self, ':'..='@')
2038 | matches!(*self, '['..='`')
2039 | matches!(*self, '{'..='~')
2040 }
2041
2042 /// Checks if the value is an ASCII graphic character
2043 /// (i.e. not whitespace or control):
2044 /// U+0021 '!' ..= U+007E '~'.
2045 ///
2046 /// # Examples
2047 ///
2048 /// ```
2049 /// let uppercase_a = 'A';
2050 /// let uppercase_g = 'G';
2051 /// let a = 'a';
2052 /// let g = 'g';
2053 /// let zero = '0';
2054 /// let percent = '%';
2055 /// let space = ' ';
2056 /// let lf = '\n';
2057 /// let esc = '\x1b';
2058 ///
2059 /// assert!(uppercase_a.is_ascii_graphic());
2060 /// assert!(uppercase_g.is_ascii_graphic());
2061 /// assert!(a.is_ascii_graphic());
2062 /// assert!(g.is_ascii_graphic());
2063 /// assert!(zero.is_ascii_graphic());
2064 /// assert!(percent.is_ascii_graphic());
2065 /// assert!(!space.is_ascii_graphic());
2066 /// assert!(!lf.is_ascii_graphic());
2067 /// assert!(!esc.is_ascii_graphic());
2068 /// ```
2069 #[must_use]
2070 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2071 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2072 #[inline]
2073 pub const fn is_ascii_graphic(&self) -> bool {
2074 matches!(*self, '!'..='~')
2075 }
2076
2077 /// Checks if the value is an ASCII whitespace character:
2078 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2079 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2080 ///
2081 /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
2082 /// `c.is_ascii_whitespace()` is **not** equivalent to `c.is_ascii() && c.is_whitespace()`.
2083 ///
2084 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2085 /// whitespace][infra-aw]. There are several other definitions in
2086 /// wide use. For instance, [the POSIX locale][pct] includes
2087 /// U+000B VERTICAL TAB as well as all the above characters,
2088 /// but—from the very same specification—[the default rule for
2089 /// "field splitting" in the Bourne shell][bfs] considers *only*
2090 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2091 ///
2092 /// If you are writing a program that will process an existing
2093 /// file format, check what that format's definition of whitespace is
2094 /// before using this function.
2095 ///
2096 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2097 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
2098 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
2099 ///
2100 /// # Examples
2101 ///
2102 /// ```
2103 /// let uppercase_a = 'A';
2104 /// let uppercase_g = 'G';
2105 /// let a = 'a';
2106 /// let g = 'g';
2107 /// let zero = '0';
2108 /// let percent = '%';
2109 /// let space = ' ';
2110 /// let lf = '\n';
2111 /// let esc = '\x1b';
2112 ///
2113 /// assert!(!uppercase_a.is_ascii_whitespace());
2114 /// assert!(!uppercase_g.is_ascii_whitespace());
2115 /// assert!(!a.is_ascii_whitespace());
2116 /// assert!(!g.is_ascii_whitespace());
2117 /// assert!(!zero.is_ascii_whitespace());
2118 /// assert!(!percent.is_ascii_whitespace());
2119 /// assert!(space.is_ascii_whitespace());
2120 /// assert!(lf.is_ascii_whitespace());
2121 /// assert!(!esc.is_ascii_whitespace());
2122 /// ```
2123 #[must_use]
2124 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2125 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2126 #[inline]
2127 #[ferrocene::prevalidated]
2128 pub const fn is_ascii_whitespace(&self) -> bool {
2129 matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
2130 }
2131
2132 /// Checks if the value is an ASCII control character:
2133 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
2134 /// Note that most ASCII whitespace characters are control
2135 /// characters, but SPACE is not.
2136 ///
2137 /// # Examples
2138 ///
2139 /// ```
2140 /// let uppercase_a = 'A';
2141 /// let uppercase_g = 'G';
2142 /// let a = 'a';
2143 /// let g = 'g';
2144 /// let zero = '0';
2145 /// let percent = '%';
2146 /// let space = ' ';
2147 /// let lf = '\n';
2148 /// let esc = '\x1b';
2149 ///
2150 /// assert!(!uppercase_a.is_ascii_control());
2151 /// assert!(!uppercase_g.is_ascii_control());
2152 /// assert!(!a.is_ascii_control());
2153 /// assert!(!g.is_ascii_control());
2154 /// assert!(!zero.is_ascii_control());
2155 /// assert!(!percent.is_ascii_control());
2156 /// assert!(!space.is_ascii_control());
2157 /// assert!(lf.is_ascii_control());
2158 /// assert!(esc.is_ascii_control());
2159 /// ```
2160 #[must_use]
2161 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2162 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2163 #[inline]
2164 pub const fn is_ascii_control(&self) -> bool {
2165 matches!(*self, '\0'..='\x1F' | '\x7F')
2166 }
2167}
2168
2169#[ferrocene::prevalidated]
2170pub(crate) struct EscapeDebugExtArgs {
2171 /// Escape Extended Grapheme codepoints?
2172 pub(crate) escape_grapheme_extended: bool,
2173
2174 /// Escape single quotes?
2175 pub(crate) escape_single_quote: bool,
2176
2177 /// Escape double quotes?
2178 pub(crate) escape_double_quote: bool,
2179}
2180
2181impl EscapeDebugExtArgs {
2182 pub(crate) const ESCAPE_ALL: Self = Self {
2183 escape_grapheme_extended: true,
2184 escape_single_quote: true,
2185 escape_double_quote: true,
2186 };
2187}
2188
2189#[inline]
2190#[must_use]
2191#[ferrocene::prevalidated]
2192const fn len_utf8(code: u32) -> usize {
2193 match code {
2194 ..MAX_ONE_B => 1,
2195 ..MAX_TWO_B => 2,
2196 ..MAX_THREE_B => 3,
2197 _ => 4,
2198 }
2199}
2200
2201#[inline]
2202#[must_use]
2203const fn len_utf16(code: u32) -> usize {
2204 if (code & 0xFFFF) == code { 1 } else { 2 }
2205}
2206
2207/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
2208/// and then returns the subslice of the buffer that contains the encoded character.
2209///
2210/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2211/// (Creating a `char` in the surrogate range is UB.)
2212/// The result is valid [generalized UTF-8] but not valid UTF-8.
2213///
2214/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2215///
2216/// # Panics
2217///
2218/// Panics if the buffer is not large enough.
2219/// A buffer of length four is large enough to encode any `char`.
2220#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2221#[doc(hidden)]
2222#[inline]
2223#[ferrocene::prevalidated]
2224pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
2225 let len = len_utf8(code);
2226 if dst.len() < len {
2227 const_panic!(
2228 "encode_utf8: buffer does not have enough bytes to encode code point",
2229 "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2230 code: u32 = code,
2231 len: usize = len,
2232 dst_len: usize = dst.len(),
2233 );
2234 }
2235
2236 // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint.
2237 unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) };
2238
2239 // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2240 unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2241}
2242
2243/// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`.
2244///
2245/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2246/// (Creating a `char` in the surrogate range is UB.)
2247/// The result is valid [generalized UTF-8] but not valid UTF-8.
2248///
2249/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2250///
2251/// # Safety
2252///
2253/// The behavior is undefined if the buffer pointed to by `dst` is not
2254/// large enough to hold the encoded codepoint. A buffer of length four
2255/// is large enough to encode any `char`.
2256///
2257/// For a safe version of this function, see the [`encode_utf8_raw`] function.
2258#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2259#[doc(hidden)]
2260#[inline]
2261#[ferrocene::prevalidated]
2262pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
2263 let len = len_utf8(code);
2264 // SAFETY: The caller must guarantee that the buffer pointed to by `dst`
2265 // is at least `len` bytes long.
2266 unsafe {
2267 if len == 1 {
2268 *dst = code as u8;
2269 return;
2270 }
2271
2272 let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
2273 let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
2274 let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
2275 let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
2276
2277 if len == 2 {
2278 *dst = last2 | TAG_TWO_B;
2279 *dst.add(1) = last1;
2280 return;
2281 }
2282
2283 if len == 3 {
2284 *dst = last3 | TAG_THREE_B;
2285 *dst.add(1) = last2;
2286 *dst.add(2) = last1;
2287 return;
2288 }
2289
2290 *dst = last4;
2291 *dst.add(1) = last3;
2292 *dst.add(2) = last2;
2293 *dst.add(3) = last1;
2294 }
2295}
2296
2297/// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer,
2298/// and then returns the subslice of the buffer that contains the encoded character.
2299///
2300/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
2301/// (Creating a `char` in the surrogate range is UB.)
2302///
2303/// # Panics
2304///
2305/// Panics if the buffer is not large enough.
2306/// A buffer of length 2 is large enough to encode any `char`.
2307#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2308#[doc(hidden)]
2309#[inline]
2310pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
2311 let len = len_utf16(code);
2312 match (len, &mut *dst) {
2313 (1, [a, ..]) => {
2314 *a = code as u16;
2315 }
2316 (2, [a, b, ..]) => {
2317 code -= 0x1_0000;
2318 *a = (code >> 10) as u16 | 0xD800;
2319 *b = (code & 0x3FF) as u16 | 0xDC00;
2320 }
2321 _ => {
2322 const_panic!(
2323 "encode_utf16: buffer does not have enough bytes to encode code point",
2324 "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2325 code: u32 = code,
2326 len: usize = len,
2327 dst_len: usize = dst.len(),
2328 )
2329 }
2330 };
2331 // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2332 unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2333}