core/char/methods.rs
1//! impl char {}
2
3#![expect(clippy::manual_is_ascii_check, reason = "this module implements various is_ascii checks")]
4
5use super::*;
6use crate::panic::const_panic;
7use crate::slice;
8use crate::str::from_utf8_unchecked_mut;
9use crate::ub_checks::assert_unsafe_precondition;
10use crate::unicode::{self, conversions};
11
12impl char {
13 /// The lowest valid code point a `char` can have, `'\0'`.
14 ///
15 /// Unlike integer types, `char` actually has a gap in the middle,
16 /// meaning that the range of possible `char`s is smaller than you
17 /// might expect. Ranges of `char` will automatically hop this gap
18 /// for you:
19 ///
20 /// ```
21 /// let dist = u32::from(char::MAX) - u32::from(char::MIN);
22 /// let size = (char::MIN..=char::MAX).count() as u32;
23 /// assert!(size < dist);
24 /// ```
25 ///
26 /// Despite this gap, the `MIN` and [`MAX`] values can be used as bounds for
27 /// all `char` values.
28 ///
29 /// [`MAX`]: char::MAX
30 ///
31 /// # Examples
32 ///
33 /// ```
34 /// # fn something_which_returns_char() -> char { 'a' }
35 /// let c: char = something_which_returns_char();
36 /// assert!(char::MIN <= c);
37 ///
38 /// let value_at_min = u32::from(char::MIN);
39 /// assert_eq!(char::from_u32(value_at_min), Some('\0'));
40 /// ```
41 #[stable(feature = "char_min", since = "1.83.0")]
42 pub const MIN: char = '\0';
43
44 /// The highest valid code point a `char` can have, `'\u{10FFFF}'`.
45 ///
46 /// Unlike integer types, `char` actually has a gap in the middle,
47 /// meaning that the range of possible `char`s is smaller than you
48 /// might expect. Ranges of `char` will automatically hop this gap
49 /// for you:
50 ///
51 /// ```
52 /// let dist = u32::from(char::MAX) - u32::from(char::MIN);
53 /// let size = (char::MIN..=char::MAX).count() as u32;
54 /// assert!(size < dist);
55 /// ```
56 ///
57 /// Despite this gap, the [`MIN`] and `MAX` values can be used as bounds for
58 /// all `char` values.
59 ///
60 /// [`MIN`]: char::MIN
61 ///
62 /// # Examples
63 ///
64 /// ```
65 /// # fn something_which_returns_char() -> char { 'a' }
66 /// let c: char = something_which_returns_char();
67 /// assert!(c <= char::MAX);
68 ///
69 /// let value_at_max = u32::from(char::MAX);
70 /// assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
71 /// assert_eq!(char::from_u32(value_at_max + 1), None);
72 /// ```
73 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
74 pub const MAX: char = '\u{10FFFF}';
75
76 /// The maximum number of bytes required to [encode](char::encode_utf8) a `char` to
77 /// UTF-8 encoding.
78 #[stable(feature = "char_max_len_assoc", since = "1.93.0")]
79 pub const MAX_LEN_UTF8: usize = 4;
80
81 /// The maximum number of two-byte units required to [encode](char::encode_utf16) a `char`
82 /// to UTF-16 encoding.
83 #[stable(feature = "char_max_len_assoc", since = "1.93.0")]
84 pub const MAX_LEN_UTF16: usize = 2;
85
86 /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
87 /// decoding error.
88 ///
89 /// It can occur, for example, when giving ill-formed UTF-8 bytes to
90 /// [`String::from_utf8_lossy`](../std/string/struct.String.html#method.from_utf8_lossy).
91 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
92 pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
93
94 /// The version of [Unicode](https://www.unicode.org/) that the Unicode parts of
95 /// `char` and `str` methods are based on.
96 ///
97 /// New versions of Unicode are released regularly, and subsequently all methods
98 /// in the standard library depending on Unicode are updated. Therefore, the
99 /// behavior of some `char` and `str` methods, and the value of this constant,
100 /// change over time (within the boundaries of Unicode's [stability policies]).
101 /// This is *not* considered to be a breaking change.
102 ///
103 /// [stability policies]: https://www.unicode.org/policies/stability_policy.html
104 ///
105 /// The version numbering scheme is explained in
106 /// [Section 3.1 (Version Numbering)] of the Unicode Standard.
107 ///
108 /// [Section 3.1 (Version Numbering)]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G49512
109 #[stable(feature = "assoc_char_consts", since = "1.52.0")]
110 pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION;
111
112 /// Creates an iterator over the native endian UTF-16 encoded code points in `iter`,
113 /// returning unpaired surrogates as `Err`s.
114 ///
115 /// # Examples
116 ///
117 /// Basic usage:
118 ///
119 /// ```
120 /// // 𝄞mus<invalid>ic<invalid>
121 /// let v = [
122 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
123 /// ];
124 ///
125 /// assert_eq!(
126 /// char::decode_utf16(v)
127 /// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
128 /// .collect::<Vec<_>>(),
129 /// vec![
130 /// Ok('𝄞'),
131 /// Ok('m'), Ok('u'), Ok('s'),
132 /// Err(0xDD1E),
133 /// Ok('i'), Ok('c'),
134 /// Err(0xD834)
135 /// ]
136 /// );
137 /// ```
138 ///
139 /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
140 ///
141 /// ```
142 /// // 𝄞mus<invalid>ic<invalid>
143 /// let v = [
144 /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
145 /// ];
146 ///
147 /// assert_eq!(
148 /// char::decode_utf16(v)
149 /// .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
150 /// .collect::<String>(),
151 /// "𝄞mus�ic�"
152 /// );
153 /// ```
154 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
155 #[inline]
156 #[ferrocene::prevalidated]
157 pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
158 super::decode::decode_utf16(iter)
159 }
160
161 /// Converts a `u32` to a `char`.
162 ///
163 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
164 /// [`as`](../std/keyword.as.html):
165 ///
166 /// ```
167 /// let c = '💯';
168 /// let i = c as u32;
169 ///
170 /// assert_eq!(128175, i);
171 /// ```
172 ///
173 /// However, the reverse is not true: not all valid [`u32`]s are valid
174 /// `char`s. `from_u32()` will return `None` if the input is not a valid value
175 /// for a `char`.
176 ///
177 /// For an unsafe version of this function which ignores these checks, see
178 /// [`from_u32_unchecked`].
179 ///
180 /// [`from_u32_unchecked`]: #method.from_u32_unchecked
181 ///
182 /// # Examples
183 ///
184 /// Basic usage:
185 ///
186 /// ```
187 /// let c = char::from_u32(0x2764);
188 ///
189 /// assert_eq!(Some('❤'), c);
190 /// ```
191 ///
192 /// Returning `None` when the input is not a valid `char`:
193 ///
194 /// ```
195 /// let c = char::from_u32(0x110000);
196 ///
197 /// assert_eq!(None, c);
198 /// ```
199 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
200 #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
201 #[must_use]
202 #[inline]
203 pub const fn from_u32(i: u32) -> Option<char> {
204 super::convert::from_u32(i)
205 }
206
207 /// Converts a `u32` to a `char`, ignoring validity.
208 ///
209 /// Note that all `char`s are valid [`u32`]s, and can be cast to one with
210 /// `as`:
211 ///
212 /// ```
213 /// let c = '💯';
214 /// let i = c as u32;
215 ///
216 /// assert_eq!(128175, i);
217 /// ```
218 ///
219 /// However, the reverse is not true: not all valid [`u32`]s are valid
220 /// `char`s. `from_u32_unchecked()` will ignore this, and blindly cast to
221 /// `char`, possibly creating an invalid one.
222 ///
223 /// # Safety
224 ///
225 /// This function is unsafe, as it may construct invalid `char` values.
226 ///
227 /// For a safe version of this function, see the [`from_u32`] function.
228 ///
229 /// [`from_u32`]: #method.from_u32
230 ///
231 /// # Examples
232 ///
233 /// Basic usage:
234 ///
235 /// ```
236 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
237 ///
238 /// assert_eq!('❤', c);
239 /// ```
240 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
241 #[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")]
242 #[must_use]
243 #[inline]
244 #[ferrocene::prevalidated]
245 pub const unsafe fn from_u32_unchecked(i: u32) -> char {
246 // SAFETY: the safety contract must be upheld by the caller.
247 unsafe { super::convert::from_u32_unchecked(i) }
248 }
249
250 /// Converts a digit in the given radix to a `char`.
251 ///
252 /// A 'radix' here is sometimes also called a 'base'. A radix of two
253 /// indicates a binary number, a radix of ten, decimal, and a radix of
254 /// sixteen, hexadecimal, to give some common values. Arbitrary
255 /// radices are supported.
256 ///
257 /// `from_digit()` will return `None` if the input is not a digit in
258 /// the given radix.
259 ///
260 /// # Panics
261 ///
262 /// Panics if given a radix larger than 36.
263 ///
264 /// # Examples
265 ///
266 /// Basic usage:
267 ///
268 /// ```
269 /// let c = char::from_digit(4, 10);
270 ///
271 /// assert_eq!(Some('4'), c);
272 ///
273 /// // Decimal 11 is a single digit in base 16
274 /// let c = char::from_digit(11, 16);
275 ///
276 /// assert_eq!(Some('b'), c);
277 /// ```
278 ///
279 /// Returning `None` when the input is not a digit:
280 ///
281 /// ```
282 /// let c = char::from_digit(20, 10);
283 ///
284 /// assert_eq!(None, c);
285 /// ```
286 ///
287 /// Passing a large radix, causing a panic:
288 ///
289 /// ```should_panic
290 /// // this panics
291 /// let _c = char::from_digit(1, 37);
292 /// ```
293 #[stable(feature = "assoc_char_funcs", since = "1.52.0")]
294 #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
295 #[must_use]
296 #[inline]
297 pub const fn from_digit(num: u32, radix: u32) -> Option<char> {
298 super::convert::from_digit(num, radix)
299 }
300
301 /// Checks if a `char` is a digit in the given radix.
302 ///
303 /// A 'radix' here is sometimes also called a 'base'. A radix of two
304 /// indicates a binary number, a radix of ten, decimal, and a radix of
305 /// sixteen, hexadecimal, to give some common values. Arbitrary
306 /// radices are supported.
307 ///
308 /// Compared to [`is_numeric()`], this function only recognizes the characters
309 /// `0-9`, `a-z` and `A-Z`.
310 ///
311 /// 'Digit' is defined to be only the following characters:
312 ///
313 /// * `0-9`
314 /// * `a-z`
315 /// * `A-Z`
316 ///
317 /// For a more comprehensive understanding of 'digit', see [`is_numeric()`].
318 ///
319 /// [`is_numeric()`]: #method.is_numeric
320 ///
321 /// # Panics
322 ///
323 /// Panics if given a radix smaller than 2 or larger than 36.
324 ///
325 /// # Examples
326 ///
327 /// Basic usage:
328 ///
329 /// ```
330 /// assert!('1'.is_digit(10));
331 /// assert!('f'.is_digit(16));
332 /// assert!(!'f'.is_digit(10));
333 /// ```
334 ///
335 /// Passing a large radix, causing a panic:
336 ///
337 /// ```should_panic
338 /// // this panics
339 /// '1'.is_digit(37);
340 /// ```
341 ///
342 /// Passing a small radix, causing a panic:
343 ///
344 /// ```should_panic
345 /// // this panics
346 /// '1'.is_digit(1);
347 /// ```
348 #[stable(feature = "rust1", since = "1.0.0")]
349 #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
350 #[expect(clippy::to_digit_is_some, reason = "implements is_digit")]
351 #[inline]
352 pub const fn is_digit(self, radix: u32) -> bool {
353 self.to_digit(radix).is_some()
354 }
355
356 /// Converts a `char` to a digit in the given radix.
357 ///
358 /// A 'radix' here is sometimes also called a 'base'. A radix of two
359 /// indicates a binary number, a radix of ten, decimal, and a radix of
360 /// sixteen, hexadecimal, to give some common values. Arbitrary
361 /// radices are supported.
362 ///
363 /// 'Digit' is defined to be only the following characters:
364 ///
365 /// * `0-9`
366 /// * `a-z`
367 /// * `A-Z`
368 ///
369 /// # Errors
370 ///
371 /// Returns `None` if the `char` does not refer to a digit in the given radix.
372 ///
373 /// # Panics
374 ///
375 /// Panics if given a radix smaller than 2 or larger than 36.
376 ///
377 /// # Examples
378 ///
379 /// Basic usage:
380 ///
381 /// ```
382 /// assert_eq!('1'.to_digit(10), Some(1));
383 /// assert_eq!('f'.to_digit(16), Some(15));
384 /// ```
385 ///
386 /// Passing a non-digit results in failure:
387 ///
388 /// ```
389 /// assert_eq!('f'.to_digit(10), None);
390 /// assert_eq!('z'.to_digit(16), None);
391 /// ```
392 ///
393 /// Passing a large radix, causing a panic:
394 ///
395 /// ```should_panic
396 /// // this panics
397 /// let _ = '1'.to_digit(37);
398 /// ```
399 /// Passing a small radix, causing a panic:
400 ///
401 /// ```should_panic
402 /// // this panics
403 /// let _ = '1'.to_digit(1);
404 /// ```
405 #[stable(feature = "rust1", since = "1.0.0")]
406 #[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
407 #[rustc_diagnostic_item = "char_to_digit"]
408 #[must_use = "this returns the result of the operation, \
409 without modifying the original"]
410 #[inline]
411 #[ferrocene::prevalidated]
412 pub const fn to_digit(self, radix: u32) -> Option<u32> {
413 assert!(
414 radix >= 2 && radix <= 36,
415 "to_digit: invalid radix -- radix must be in the range 2 to 36 inclusive"
416 );
417 // check radix to remove letter handling code when radix is a known constant
418 let value = if self > '9' && radix > 10 {
419 // mask to convert ASCII letters to uppercase
420 const TO_UPPERCASE_MASK: u32 = !0b0010_0000;
421 // Converts an ASCII letter to its corresponding integer value:
422 // A-Z => 10-35, a-z => 10-35. Other characters produce values >= 36.
423 //
424 // Add Overflow Safety:
425 // By applying the mask after the subtraction, the first addendum is
426 // constrained such that it never exceeds u32::MAX - 0x20.
427 ((self as u32).wrapping_sub('A' as u32) & TO_UPPERCASE_MASK) + 10
428 } else {
429 // convert digit to value, non-digits wrap to values > 36
430 (self as u32).wrapping_sub('0' as u32)
431 };
432 // FIXME(const-hack): once then_some is const fn, use it here
433 if value < radix { Some(value) } else { None }
434 }
435
436 /// Returns an iterator that yields the hexadecimal Unicode escape of a
437 /// character as `char`s.
438 ///
439 /// This will escape characters with the Rust syntax of the form
440 /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation.
441 ///
442 /// # Examples
443 ///
444 /// As an iterator:
445 ///
446 /// ```
447 /// for c in '❤'.escape_unicode() {
448 /// print!("{c}");
449 /// }
450 /// println!();
451 /// ```
452 ///
453 /// Using `println!` directly:
454 ///
455 /// ```
456 /// println!("{}", '❤'.escape_unicode());
457 /// ```
458 ///
459 /// Both are equivalent to:
460 ///
461 /// ```
462 /// println!("\\u{{2764}}");
463 /// ```
464 ///
465 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
466 ///
467 /// ```
468 /// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
469 /// ```
470 #[must_use = "this returns the escaped char as an iterator, \
471 without modifying the original"]
472 #[stable(feature = "rust1", since = "1.0.0")]
473 #[inline]
474 #[ferrocene::prevalidated]
475 pub fn escape_unicode(self) -> EscapeUnicode {
476 EscapeUnicode::new(self)
477 }
478
479 /// An extended version of `escape_debug` that optionally permits escaping
480 /// single quotes and double quotes. This allows escaping single quotes in
481 /// characters, and double quotes in strings.
482 #[inline]
483 #[ferrocene::prevalidated]
484 pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
485 match self {
486 // Special escapes
487 '\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark),
488 '\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe),
489 '\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus),
490 '\n' => EscapeDebug::backslash(ascii::Char::SmallN),
491 '\t' => EscapeDebug::backslash(ascii::Char::SmallT),
492 '\r' => EscapeDebug::backslash(ascii::Char::SmallR),
493 '\0' => EscapeDebug::backslash(ascii::Char::Digit0),
494
495 // ASCII fast path,
496 // plus U+FF9E HALFWIDTH KATAKANA VOICED SOUND MARK
497 // and U+FF9F HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
498 // which should not be escaped despite being grapheme extenders.
499 '\x20'..='\x7E' | '\u{FF9E}' | '\u{FF9F}' => EscapeDebug::printable(self),
500
501 _ if self.is_control()
502 || self.is_private_use()
503 || self.is_whitespace()
504 || self.is_grapheme_extender()
505 || self.is_default_ignorable()
506 || self.is_format_control()
507 || !self.is_assigned() =>
508 {
509 EscapeDebug::unicode(self)
510 }
511
512 _ => EscapeDebug::printable(self),
513 }
514 }
515
516 /// Returns an iterator that yields the literal escape code of a character
517 /// as `char`s.
518 ///
519 /// This will escape the characters similar to the [`Debug`](core::fmt::Debug) implementations
520 /// of `str` or `char`.
521 ///
522 /// # Examples
523 ///
524 /// As an iterator:
525 ///
526 /// ```
527 /// for c in '\n'.escape_debug() {
528 /// print!("{c}");
529 /// }
530 /// println!();
531 /// ```
532 ///
533 /// Using `println!` directly:
534 ///
535 /// ```
536 /// println!("{}", '\n'.escape_debug());
537 /// ```
538 ///
539 /// Both are equivalent to:
540 ///
541 /// ```
542 /// println!("\\n");
543 /// ```
544 ///
545 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
546 ///
547 /// ```
548 /// assert_eq!('\n'.escape_debug().to_string(), "\\n");
549 /// ```
550 #[must_use = "this returns the escaped char as an iterator, \
551 without modifying the original"]
552 #[stable(feature = "char_escape_debug", since = "1.20.0")]
553 #[inline]
554 #[ferrocene::prevalidated]
555 pub fn escape_debug(self) -> EscapeDebug {
556 self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
557 }
558
559 /// Returns an iterator that yields the literal escape code of a character
560 /// as `char`s.
561 ///
562 /// The default is chosen with a bias toward producing literals that are
563 /// legal in a variety of languages, including C++11 and similar C-family
564 /// languages. The exact rules are:
565 ///
566 /// * Tab is escaped as `\t`.
567 /// * Carriage return is escaped as `\r`.
568 /// * Line feed is escaped as `\n`.
569 /// * Single quote is escaped as `\'`.
570 /// * Double quote is escaped as `\"`.
571 /// * Backslash is escaped as `\\`.
572 /// * Any character in the 'printable ASCII' range `0x20` .. `0x7e`
573 /// inclusive is not escaped.
574 /// * All other characters are given hexadecimal Unicode escapes; see
575 /// [`escape_unicode`].
576 ///
577 /// [`escape_unicode`]: #method.escape_unicode
578 ///
579 /// # Examples
580 ///
581 /// As an iterator:
582 ///
583 /// ```
584 /// for c in '"'.escape_default() {
585 /// print!("{c}");
586 /// }
587 /// println!();
588 /// ```
589 ///
590 /// Using `println!` directly:
591 ///
592 /// ```
593 /// println!("{}", '"'.escape_default());
594 /// ```
595 ///
596 /// Both are equivalent to:
597 ///
598 /// ```
599 /// println!("\\\"");
600 /// ```
601 ///
602 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
603 ///
604 /// ```
605 /// assert_eq!('"'.escape_default().to_string(), "\\\"");
606 /// ```
607 #[must_use = "this returns the escaped char as an iterator, \
608 without modifying the original"]
609 #[stable(feature = "rust1", since = "1.0.0")]
610 #[inline]
611 #[ferrocene::prevalidated]
612 pub fn escape_default(self) -> EscapeDefault {
613 match self {
614 '\t' => EscapeDefault::backslash(ascii::Char::SmallT),
615 '\r' => EscapeDefault::backslash(ascii::Char::SmallR),
616 '\n' => EscapeDefault::backslash(ascii::Char::SmallN),
617 '\\' | '\'' | '\"' => EscapeDefault::backslash(self.as_ascii().unwrap()),
618 '\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()),
619 _ => EscapeDefault::unicode(self),
620 }
621 }
622
623 /// Returns the number of bytes this `char` would need if encoded in UTF-8.
624 ///
625 /// That number of bytes is always between 1 and 4, inclusive.
626 ///
627 /// # Examples
628 ///
629 /// Basic usage:
630 ///
631 /// ```
632 /// let len = 'A'.len_utf8();
633 /// assert_eq!(len, 1);
634 ///
635 /// let len = 'ß'.len_utf8();
636 /// assert_eq!(len, 2);
637 ///
638 /// let len = 'ℝ'.len_utf8();
639 /// assert_eq!(len, 3);
640 ///
641 /// let len = '💣'.len_utf8();
642 /// assert_eq!(len, 4);
643 /// ```
644 ///
645 /// The `&str` type guarantees that its contents are UTF-8, and so we can compare the length it
646 /// would take if each code point was represented as a `char` vs in the `&str` itself:
647 ///
648 /// ```
649 /// // as chars
650 /// let eastern = '東';
651 /// let capital = '京';
652 ///
653 /// // both can be represented as three bytes
654 /// assert_eq!(3, eastern.len_utf8());
655 /// assert_eq!(3, capital.len_utf8());
656 ///
657 /// // as a &str, these two are encoded in UTF-8
658 /// let tokyo = "東京";
659 ///
660 /// let len = eastern.len_utf8() + capital.len_utf8();
661 ///
662 /// // we can see that they take six bytes total...
663 /// assert_eq!(6, tokyo.len());
664 ///
665 /// // ... just like the &str
666 /// assert_eq!(len, tokyo.len());
667 /// ```
668 #[stable(feature = "rust1", since = "1.0.0")]
669 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
670 #[inline]
671 #[must_use]
672 #[ferrocene::prevalidated]
673 pub const fn len_utf8(self) -> usize {
674 len_utf8(self as u32)
675 }
676
677 /// Returns the number of 16-bit code units this `char` would need if
678 /// encoded in UTF-16.
679 ///
680 /// That number of code units is always either 1 or 2, for unicode scalar values in
681 /// the [basic multilingual plane] or [supplementary planes] respectively.
682 ///
683 /// See the documentation for [`len_utf8()`] for more explanation of this
684 /// concept. This function is a mirror, but for UTF-16 instead of UTF-8.
685 ///
686 /// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
687 /// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
688 /// [`len_utf8()`]: #method.len_utf8
689 ///
690 /// # Examples
691 ///
692 /// Basic usage:
693 ///
694 /// ```
695 /// let n = 'ß'.len_utf16();
696 /// assert_eq!(n, 1);
697 ///
698 /// let len = '💣'.len_utf16();
699 /// assert_eq!(len, 2);
700 /// ```
701 #[stable(feature = "rust1", since = "1.0.0")]
702 #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
703 #[inline]
704 #[must_use]
705 pub const fn len_utf16(self) -> usize {
706 len_utf16(self as u32)
707 }
708
709 /// Encodes this character as UTF-8 into the provided byte buffer,
710 /// and then returns the subslice of the buffer that contains the encoded character.
711 ///
712 /// # Panics
713 ///
714 /// Panics if the buffer is not large enough.
715 /// A buffer of length four is large enough to encode any `char`.
716 ///
717 /// # Examples
718 ///
719 /// In both of these examples, 'ß' takes two bytes to encode.
720 ///
721 /// ```
722 /// let mut b = [0; 2];
723 ///
724 /// let result = 'ß'.encode_utf8(&mut b);
725 ///
726 /// assert_eq!(result, "ß");
727 ///
728 /// assert_eq!(result.len(), 2);
729 /// ```
730 ///
731 /// A buffer that's too small:
732 ///
733 /// ```should_panic
734 /// let mut b = [0; 1];
735 ///
736 /// // this panics
737 /// 'ß'.encode_utf8(&mut b);
738 /// ```
739 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
740 #[rustc_const_stable(feature = "const_char_encode_utf8", since = "1.83.0")]
741 #[inline]
742 #[ferrocene::prevalidated]
743 pub const fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
744 // SAFETY: `char` is not a surrogate, so this is valid UTF-8.
745 unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
746 }
747
748 /// Encodes this character as native endian UTF-16 into the provided `u16` buffer,
749 /// and then returns the subslice of the buffer that contains the encoded character.
750 ///
751 /// # Panics
752 ///
753 /// Panics if the buffer is not large enough.
754 /// A buffer of length 2 is large enough to encode any `char`.
755 ///
756 /// # Examples
757 ///
758 /// In both of these examples, '𝕊' takes two `u16`s to encode.
759 ///
760 /// ```
761 /// let mut b = [0; 2];
762 ///
763 /// let result = '𝕊'.encode_utf16(&mut b);
764 ///
765 /// assert_eq!(result.len(), 2);
766 /// ```
767 ///
768 /// A buffer that's too small:
769 ///
770 /// ```should_panic
771 /// let mut b = [0; 1];
772 ///
773 /// // this panics
774 /// '𝕊'.encode_utf16(&mut b);
775 /// ```
776 #[stable(feature = "unicode_encode_char", since = "1.15.0")]
777 #[rustc_const_stable(feature = "const_char_encode_utf16", since = "1.84.0")]
778 #[inline]
779 pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
780 encode_utf16_raw(self as u32, dst)
781 }
782
783 /// Returns `true` if this `char` has the `Alphabetic` property.
784 ///
785 /// `Alphabetic` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and
786 /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
787 ///
788 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G32524
789 /// [specified]: https://www.unicode.org/reports/tr44/#Alphabetic
790 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
791 ///
792 /// # Examples
793 ///
794 /// Basic usage:
795 ///
796 /// ```
797 /// assert!('a'.is_alphabetic());
798 /// assert!('京'.is_alphabetic());
799 ///
800 /// let c = '💝';
801 /// // love is many things, but it is not alphabetic
802 /// assert!(!c.is_alphabetic());
803 /// ```
804 #[must_use]
805 #[stable(feature = "rust1", since = "1.0.0")]
806 #[inline]
807 pub fn is_alphabetic(self) -> bool {
808 match self {
809 'a'..='z' | 'A'..='Z' => true,
810 '\0'..='\u{A9}' => false,
811 _ => unicode::Alphabetic(self),
812 }
813 }
814
815 /// Returns `true` if this `char` has the `Cased` property.
816 /// A character is cased if and only if it is uppercase, lowercase, or titlecase.
817 ///
818 /// `Cased` is [described] in Chapter 3 (Character Properties) of the Unicode Standard and
819 /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
820 ///
821 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G44595
822 /// [specified]: https://www.unicode.org/reports/tr44/#Cased
823 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
824 ///
825 /// # Examples
826 ///
827 /// Basic usage:
828 ///
829 /// ```
830 /// #![feature(titlecase)]
831 /// assert!('A'.is_cased());
832 /// assert!('a'.is_cased());
833 /// assert!(!'京'.is_cased());
834 /// ```
835 #[must_use]
836 #[unstable(feature = "titlecase", issue = "153892")]
837 #[inline]
838 pub fn is_cased(self) -> bool {
839 match self {
840 'a'..='z' | 'A'..='Z' => true,
841 '\0'..='\u{A9}' => false,
842 _ => unicode::Lowercase(self) || unicode::Uppercase(self) || unicode::Lt(self),
843 }
844 }
845
846 /// Returns the case of this character:
847 /// [`Some(CharCase::Upper)`][`CharCase::Upper`] if [`self.is_uppercase()`][`char::is_uppercase`],
848 /// [`Some(CharCase::Lower)`][`CharCase::Lower`] if [`self.is_lowercase()`][`char::is_lowercase`],
849 /// [`Some(CharCase::Title)`][`CharCase::Title`] if [`self.is_titlecase()`][`char::is_titlecase`], and
850 /// `None` if [`!self.is_cased()`][`char::is_cased`].
851 ///
852 /// # Examples
853 ///
854 /// ```
855 /// #![feature(titlecase)]
856 /// use core::char::CharCase;
857 /// assert_eq!('a'.case(), Some(CharCase::Lower));
858 /// assert_eq!('δ'.case(), Some(CharCase::Lower));
859 /// assert_eq!('A'.case(), Some(CharCase::Upper));
860 /// assert_eq!('Δ'.case(), Some(CharCase::Upper));
861 /// assert_eq!('Dž'.case(), Some(CharCase::Title));
862 /// assert_eq!('中'.case(), None);
863 /// ```
864 #[must_use]
865 #[unstable(feature = "titlecase", issue = "153892")]
866 #[inline]
867 pub fn case(self) -> Option<CharCase> {
868 match self {
869 'a'..='z' => Some(CharCase::Lower),
870 'A'..='Z' => Some(CharCase::Upper),
871 '\0'..='\u{A9}' => None,
872 _ if unicode::Lowercase(self) => Some(CharCase::Lower),
873 _ if unicode::Uppercase(self) => Some(CharCase::Upper),
874 _ if unicode::Lt(self) => Some(CharCase::Title),
875 _ => None,
876 }
877 }
878
879 /// Returns `true` if this `char` has the `Lowercase` property.
880 ///
881 /// `Lowercase` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and
882 /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
883 ///
884 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G136255
885 /// [specified]: https://www.unicode.org/reports/tr44/#Lowercase
886 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
887 ///
888 /// # Examples
889 ///
890 /// Basic usage:
891 ///
892 /// ```
893 /// assert!('a'.is_lowercase());
894 /// assert!('δ'.is_lowercase());
895 /// assert!(!'A'.is_lowercase());
896 /// assert!(!'Δ'.is_lowercase());
897 ///
898 /// // The various Chinese scripts and punctuation do not have case, and so:
899 /// assert!(!'中'.is_lowercase());
900 /// assert!(!' '.is_lowercase());
901 /// ```
902 ///
903 /// In a const context:
904 ///
905 /// ```
906 /// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
907 /// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
908 /// ```
909 #[must_use]
910 #[stable(feature = "rust1", since = "1.0.0")]
911 #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
912 #[inline]
913 pub const fn is_lowercase(self) -> bool {
914 match self {
915 'a'..='z' => true,
916 '\0'..='\u{A9}' => false,
917 _ => unicode::Lowercase(self),
918 }
919 }
920
921 /// Returns `true` if this `char` is in the general category for titlecase letters.
922 /// Conceptually, these characters consist of an uppercase portion followed by a lowercase portion.
923 ///
924 /// Titlecase letters (code points with the general category of `Lt`) are [described] in Chapter 4
925 /// (Character Properties) of the Unicode Standard, and [specified] in the Unicode Character
926 /// Database [`UnicodeData.txt`].
927 ///
928 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G124722
929 /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
930 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
931 ///
932 /// # Examples
933 ///
934 /// Basic usage:
935 ///
936 /// ```
937 /// #![feature(titlecase)]
938 /// assert!('Dž'.is_titlecase());
939 /// assert!('ῼ'.is_titlecase());
940 /// assert!(!'D'.is_titlecase());
941 /// assert!(!'z'.is_titlecase());
942 /// assert!(!'中'.is_titlecase());
943 /// assert!(!' '.is_titlecase());
944 /// ```
945 #[must_use]
946 #[unstable(feature = "titlecase", issue = "153892")]
947 #[inline]
948 pub fn is_titlecase(self) -> bool {
949 match self {
950 '\0'..='\u{01C4}' => false,
951 _ => unicode::Lt(self),
952 }
953 }
954
955 /// Returns `true` if this `char` has the `Uppercase` property.
956 ///
957 /// `Uppercase` is [described] in Chapter 4 (Character Properties) of the Unicode Standard, and
958 /// [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
959 ///
960 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G136255
961 /// [specified]: https://www.unicode.org/reports/tr44/#Uppercase
962 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
963 ///
964 /// # Examples
965 ///
966 /// Basic usage:
967 ///
968 /// ```
969 /// assert!(!'a'.is_uppercase());
970 /// assert!(!'δ'.is_uppercase());
971 /// assert!('A'.is_uppercase());
972 /// assert!('Δ'.is_uppercase());
973 ///
974 /// // The various Chinese scripts and punctuation do not have case, and so:
975 /// assert!(!'中'.is_uppercase());
976 /// assert!(!' '.is_uppercase());
977 /// ```
978 ///
979 /// In a const context:
980 ///
981 /// ```
982 /// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
983 /// assert!(CAPITAL_DELTA_IS_UPPERCASE);
984 /// ```
985 #[must_use]
986 #[stable(feature = "rust1", since = "1.0.0")]
987 #[rustc_const_stable(feature = "const_unicode_case_lookup", since = "1.84.0")]
988 #[inline]
989 pub const fn is_uppercase(self) -> bool {
990 match self {
991 'A'..='Z' => true,
992 '\0'..='\u{BF}' => false,
993 _ => unicode::Uppercase(self),
994 }
995 }
996
997 /// Returns `true` if this `char` has one of the general categories for numbers.
998 ///
999 /// The general categories for numbers (`Nd` for decimal digits, `Nl` for letter-like numeric
1000 /// characters, and `No` for other numeric characters) are [specified] in the Unicode Character
1001 /// Database [`UnicodeData.txt`].
1002 ///
1003 /// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
1004 /// If you want everything including characters with overlapping purposes, then you might want to use
1005 /// a Unicode or language-processing library that exposes the appropriate character properties
1006 /// (e.g. [`Numeric_Type`]) instead of looking at the Unicode categories.
1007 ///
1008 /// If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use
1009 /// `is_ascii_digit` or `is_digit` instead.
1010 ///
1011 /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1012 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1013 /// [`Numeric_Type`]: https://www.unicode.org/reports/tr44/#Numeric_Type
1014 ///
1015 /// # Examples
1016 ///
1017 /// Basic usage:
1018 ///
1019 /// ```
1020 /// assert!('٣'.is_numeric());
1021 /// assert!('7'.is_numeric());
1022 /// assert!('৬'.is_numeric());
1023 /// assert!('¾'.is_numeric());
1024 /// assert!('①'.is_numeric());
1025 /// assert!(!'K'.is_numeric());
1026 /// assert!(!'و'.is_numeric());
1027 /// assert!(!'藏'.is_numeric());
1028 /// assert!(!'三'.is_numeric());
1029 /// ```
1030 #[must_use]
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 #[inline]
1033 pub fn is_numeric(self) -> bool {
1034 match self {
1035 '0'..='9' => true,
1036 '\0'..='\u{B1}' => false,
1037 _ => unicode::N(self),
1038 }
1039 }
1040
1041 /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`].
1042 ///
1043 /// [`is_alphabetic()`]: Self::is_alphabetic
1044 /// [`is_numeric()`]: Self::is_numeric
1045 ///
1046 /// # Examples
1047 ///
1048 /// Basic usage:
1049 ///
1050 /// ```
1051 /// assert!('٣'.is_alphanumeric());
1052 /// assert!('7'.is_alphanumeric());
1053 /// assert!('৬'.is_alphanumeric());
1054 /// assert!('¾'.is_alphanumeric());
1055 /// assert!('①'.is_alphanumeric());
1056 /// assert!('K'.is_alphanumeric());
1057 /// assert!('و'.is_alphanumeric());
1058 /// assert!('藏'.is_alphanumeric());
1059 /// ```
1060 #[must_use]
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 #[inline]
1063 pub fn is_alphanumeric(self) -> bool {
1064 match self {
1065 'a'..='z' | 'A'..='Z' | '0'..='9' => true,
1066 '\0'..='\u{A9}' => false,
1067 _ => unicode::Alphabetic(self) || unicode::N(self),
1068 }
1069 }
1070
1071 /// Returns `true` if this `char` has the `White_Space` property.
1072 ///
1073 /// `White_Space` is [specified] in the Unicode Character Database [`PropList.txt`].
1074 ///
1075 /// [specified]: https://www.unicode.org/reports/tr44/#White_Space
1076 /// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
1077 ///
1078 /// # Examples
1079 ///
1080 /// Basic usage:
1081 ///
1082 /// ```
1083 /// assert!(' '.is_whitespace());
1084 ///
1085 /// // line break
1086 /// assert!('\n'.is_whitespace());
1087 ///
1088 /// // a non-breaking space
1089 /// assert!('\u{A0}'.is_whitespace());
1090 ///
1091 /// assert!(!'越'.is_whitespace());
1092 /// ```
1093 #[must_use]
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 #[rustc_const_stable(feature = "const_char_classify", since = "1.87.0")]
1096 #[inline]
1097 #[ferrocene::prevalidated]
1098 pub const fn is_whitespace(self) -> bool {
1099 match self {
1100 ' ' | '\x09'..='\x0d' => true,
1101 '\0'..='\u{84}' => false,
1102 _ => unicode::White_Space(self),
1103 }
1104 }
1105
1106 /// Returns `true` if this `char` has the `XID_Continue` property.
1107 ///
1108 /// `XID_Continue` is [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1109 ///
1110 /// [specified]: https://www.unicode.org/reports/tr31
1111 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1112 ///
1113 /// New versions of Unicode may add new characters to this set, in accordance with its [stability policy].
1114 /// This is *not* considered a [breaking change].
1115 ///
1116 /// [stability policy]: https://www.unicode.org/policies/stability_policy.html#Identifier
1117 /// [breaking change]: char::UNICODE_VERSION
1118 ///
1119 /// # Examples
1120 ///
1121 /// Basic usage:
1122 ///
1123 /// ```
1124 /// #![feature(char_is_xid)]
1125 ///
1126 /// assert!('A'.is_xid_continue());
1127 /// assert!('9'.is_xid_continue());
1128 /// assert!('_'.is_xid_continue());
1129 ///
1130 /// assert!(!' '.is_xid_continue());
1131 /// ```
1132 #[must_use]
1133 #[unstable(feature = "char_is_xid", issue = "164841")]
1134 #[inline]
1135 pub fn is_xid_continue(self) -> bool {
1136 match self {
1137 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => true,
1138 '\0'..='\u{A9}' => false,
1139 _ => unicode::XID_Continue(self),
1140 }
1141 }
1142
1143 /// Returns `true` if this `char` has the `XID_Start` property.
1144 ///
1145 /// `XID_Start` is [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1146 ///
1147 /// [specified]: https://www.unicode.org/reports/tr31
1148 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1149 ///
1150 /// New versions of Unicode may add new characters to this set, in accordance with its [stability policy].
1151 /// This is *not* considered a [breaking change].
1152 ///
1153 /// [stability policy]: https://www.unicode.org/policies/stability_policy.html#Identifier
1154 /// [breaking change]: char::UNICODE_VERSION
1155 ///
1156 /// # Examples
1157 ///
1158 /// Basic usage:
1159 ///
1160 /// ```
1161 /// #![feature(char_is_xid)]
1162 ///
1163 /// assert!('A'.is_xid_start());
1164 ///
1165 /// assert!(!' '.is_xid_start());
1166 /// assert!(!'9'.is_xid_start());
1167 /// assert!(!'_'.is_xid_start());
1168 /// ```
1169 #[must_use]
1170 #[unstable(feature = "char_is_xid", issue = "164841")]
1171 #[inline]
1172 pub fn is_xid_start(self) -> bool {
1173 match self {
1174 'a'..='z' | 'A'..='Z' => true,
1175 '\0'..='\u{A9}' => false,
1176 _ => unicode::XID_Start(self),
1177 }
1178 }
1179
1180 /// Returns `true` if this `char` has the general category for control codes.
1181 ///
1182 /// Control codes (code points with the general category of `Cc`) are [described] in Chapter 23
1183 /// (Special Areas and Format Characters) of the Unicode Standard, and [specified] in the Unicode Character
1184 /// Database [`UnicodeData.txt`]. The full set of Unicode control codes is
1185 /// `'\0'..='\x1f' | '\x7f'..='\u{9f}'`, and will never change.
1186 ///
1187 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-23/#G20365
1188 /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1189 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1190 ///
1191 /// # Examples
1192 ///
1193 /// Basic usage:
1194 ///
1195 /// ```
1196 /// assert!('\t'.is_control());
1197 /// assert!('\n'.is_control());
1198 /// assert!('\u{9C}'.is_control()); // STRING TERMINATOR
1199 /// assert!(!'q'.is_control());
1200 /// ```
1201 #[ferrocene::prevalidated]
1202 #[must_use]
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 #[rustc_const_stable(feature = "const_is_control", since = "1.97.0")]
1205 #[inline]
1206 pub const fn is_control(self) -> bool {
1207 // According to
1208 // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1209 // the set of codepoints in `Cc` will never change.
1210 // So we can just hard-code the patterns to match against instead of using a table.
1211 matches!(self, '\0'..='\x1f' | '\x7f'..='\u{9f}')
1212 }
1213
1214 /// Returns `true` if this `char` has the general category for [private-use characters].
1215 /// These characters do not have an interpretation specified by Unicode; individual programs
1216 /// and users are free to assign them whatever meaning they like.
1217 ///
1218 /// [private-use characters]: https://www.unicode.org/faq/private_use#private_use
1219 ///
1220 /// Private-use characters (code points with the general category of `Co`) are [described] in Chapter 23
1221 /// (Special Areas and Format Characters) of the Unicode Standard, and [specified] in the
1222 /// Unicode Character Database [`UnicodeData.txt`]. The full set of private-use characters is
1223 /// `'\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}'`,
1224 /// and will never change.
1225 ///
1226 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-23/#G19184
1227 /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1228 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1229 ///
1230 #[ferrocene::prevalidated]
1231 #[must_use]
1232 #[unstable(feature = "char_unassigned_private_use", issue = "158322")]
1233 #[inline]
1234 pub const fn is_private_use(self) -> bool {
1235 // According to
1236 // https://www.unicode.org/policies/stability_policy.html#Property_Value,
1237 // the set of codepoints in `Co` will never change.
1238 // So we can just hard-code the patterns to match against instead of using a table.
1239 matches!(self, '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}')
1240 }
1241
1242 /// Returns `true` if this `char` has the general category for format control characters.
1243 ///
1244 /// Format controls (code points with the general category of `Cf`) are [described] in Chapter 4
1245 /// (Character Properties) of the Unicode Standard, and [specified] in the Unicode Character
1246 /// Database [`UnicodeData.txt`].
1247 ///
1248 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G134153
1249 /// [specified]: https://www.unicode.org/reports/tr44/#GC_Values_Table
1250 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1251 ///
1252 /// # Examples
1253 ///
1254 /// Basic usage:
1255 ///
1256 /// ```ignore(private)
1257 /// assert!('\u{AD}'.is_format_control()); // SOFT HYPHEN
1258 /// assert!('\u{200B}'.is_format_control()); // ZERO WIDTH SPACE
1259 /// assert!('\u{E0041}'.is_format_control()); // TAG LATIN CAPITAL LETTER A
1260 /// assert!(''.is_format_control()); // ARABIC END OF AYAH
1261 /// assert!(''.is_format_control()); // EGYPTIAN HIEROGLYPH INSERT AT TOP START
1262 /// assert!(!'q'.is_format_control());
1263 /// ```
1264 #[ferrocene::prevalidated]
1265 #[must_use]
1266 #[inline]
1267 fn is_format_control(self) -> bool {
1268 self > '\u{AC}' && unicode::Cf(self)
1269 }
1270
1271 /// Returns `true` if this `char` has been assigned a meaning by Unicode, as of
1272 /// [`UNICODE_VERSION`].
1273 ///
1274 /// [`UNICODE_VERSION`]: Self::UNICODE_VERSION
1275 ///
1276 /// Many of Unicode's [stability policies] apply only to assigned characters.
1277 ///
1278 /// [stability policies]: https://www.unicode.org/policies/stability_policy.html
1279 ///
1280 /// Currently unassigned characters (characters for which this method returns `false`)
1281 /// may have a meaning assigned in a future version of Unicode,
1282 /// except for the 66 [noncharacters] which will never be assigned a meaning.
1283 ///
1284 /// [noncharacters]: https://www.unicode.org/faq/private_use.html#noncharacters
1285 ///
1286 /// A character is considered assigned if it is present in [`UnicodeData.txt`].
1287 /// Unassigned characters have general category `Cn`, as [described] in Chapter 4
1288 /// (Character Properties) of the Unicode Standard.
1289 ///
1290 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1291 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-4/#G134153
1292 ///
1293 /// # Examples
1294 ///
1295 /// Basic usage:
1296 ///
1297 /// ```
1298 /// #![feature(char_unassigned_private_use)]
1299 /// assert!('γ'.is_assigned()); // once a character is assigned, it stays assigned forever
1300 /// assert!(!'\u{FFFE}'.is_assigned()); // noncharacter, will never be assigned
1301 ///
1302 /// // Not currently assigned, but may be in the future,
1303 /// // so we shouldn't rely on the current status
1304 /// /* assert!(!'\u{7AAAA}'.is_assigned()); */
1305 /// ```
1306 #[ferrocene::prevalidated]
1307 #[must_use]
1308 #[unstable(feature = "char_unassigned_private_use", issue = "158322")]
1309 #[inline]
1310 pub fn is_assigned(self) -> bool {
1311 match self {
1312 '\0'..='\u{377}' => true,
1313 '\u{378}'..='\u{3FFFD}' => !unicode::Cn_planes_0_3(self),
1314 // Assigned character ranges in planes 4 and above.
1315 // `src/tools/unicode-table-generator/src/main.rs` asserts that this is correct
1316 '\u{E0001}'
1317 | '\u{E0020}'..='\u{E007F}'
1318 | '\u{E0100}'..='\u{E01EF}'
1319 | '\u{F0000}'..='\u{FFFFD}'
1320 | '\u{100000}'..='\u{10FFFD}' => true,
1321 _ => false,
1322 }
1323 }
1324
1325 /// Returns `true` if this `char` has the `Default_Ignorable_Code_Point` property.
1326 /// These characters [should be displayed as invisible in fallback rendering](https://www.unicode.org/faq/unsup_char#3).
1327 ///
1328 /// `Default_Ignorable_Code_Point` is [described] in Chapter 5 (Implementation Guidelines) of the Unicode Standard,
1329 /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1330 ///
1331 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-5/#G40120
1332 /// [specified]: https://www.unicode.org/reports/tr44/#Default_Ignorable_Code_Point
1333 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1334 ///
1335 /// # Examples
1336 ///
1337 /// Basic usage:
1338 ///
1339 /// ```
1340 /// #![feature(default_ignorable)]
1341 /// assert!('\u{AD}'.is_default_ignorable()); // SOFT HYPHEN
1342 /// assert!('\u{115F}'.is_default_ignorable()); // HANGUL CHOSEONG FILLER
1343 /// assert!('\u{200B}'.is_default_ignorable()); // ZERO WIDTH SPACE
1344 /// assert!('\u{E0041}'.is_default_ignorable()); // TAG LATIN CAPITAL LETTER A
1345 /// assert!(!''.is_default_ignorable()); // ARABIC END OF AYAH
1346 /// assert!(!''.is_default_ignorable()); // EGYPTIAN HIEROGLYPH INSERT AT TOP START
1347 /// assert!(!' '.is_default_ignorable());
1348 /// assert!(!'\n'.is_default_ignorable());
1349 /// assert!(!'\0'.is_default_ignorable());
1350 /// assert!(!'q'.is_default_ignorable());
1351 /// ```
1352 #[ferrocene::prevalidated]
1353 #[must_use]
1354 #[unstable(feature = "default_ignorable", issue = "160583")]
1355 #[inline]
1356 pub fn is_default_ignorable(self) -> bool {
1357 self > '\u{AC}' && unicode::Default_Ignorable_Code_Point(self)
1358 }
1359
1360 /// Returns `true` if this `char` has the `Grapheme_Extend` property.
1361 ///
1362 /// `Grapheme_Extend` is [described] in Chapter 3 (Conformance) of the Unicode Standard,
1363 /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1364 ///
1365 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G41165
1366 /// [specified]: https://www.unicode.org/reports/tr44/#Grapheme_Extend
1367 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1368 #[ferrocene::prevalidated]
1369 #[must_use]
1370 #[inline]
1371 fn is_grapheme_extender(self) -> bool {
1372 self > '\u{02FF}' && unicode::Grapheme_Extend(self)
1373 }
1374
1375 /// Returns `true` if this `char` has the `Case_Ignorable` property. This narrow-use property
1376 /// is used to implement context-dependent casing for the Greek letter sigma (uppercase 'Σ'),
1377 /// which has two lowercase forms.
1378 ///
1379 /// `Case_Ignorable` is [described] in Chapter 3 (Conformance) of the Unicode Core Specification,
1380 /// and [specified] in the Unicode Character Database [`DerivedCoreProperties.txt`].
1381 /// See those resources, as well as [`to_lowercase()`]'s documentation, for more information.
1382 ///
1383 /// [described]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G63116
1384 /// [specified]: https://www.unicode.org/reports/tr44/#Case_Ignorable
1385 /// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
1386 /// [`to_lowercase()`]: Self::to_lowercase()
1387 #[must_use]
1388 #[inline]
1389 #[unstable(feature = "case_ignorable", issue = "154848")]
1390 pub fn is_case_ignorable(self) -> bool {
1391 if self.is_ascii() {
1392 matches!(self, '\'' | '.' | ':' | '^' | '`')
1393 } else {
1394 unicode::Case_Ignorable(self)
1395 }
1396 }
1397
1398 /// Returns an iterator that yields the lowercase mapping of this `char` as one or more
1399 /// `char`s.
1400 ///
1401 /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`.
1402 ///
1403 /// If this `char` has a one-to-one lowercase mapping given by the [Unicode Character
1404 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1405 ///
1406 /// [ucd]: https://www.unicode.org/reports/tr44/
1407 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1408 ///
1409 /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1410 /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1411 ///
1412 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1413 /// is independent of context and language. See [below](#notes-on-context-and-locale)
1414 /// for more information.
1415 ///
1416 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1417 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1418 ///
1419 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1420 ///
1421 /// # Examples
1422 ///
1423 /// As an iterator:
1424 ///
1425 /// ```
1426 /// for c in 'İ'.to_lowercase() {
1427 /// print!("{c}");
1428 /// }
1429 /// println!();
1430 /// ```
1431 ///
1432 /// Using `println!` directly:
1433 ///
1434 /// ```
1435 /// println!("{}", 'İ'.to_lowercase());
1436 /// ```
1437 ///
1438 /// Both are equivalent to:
1439 ///
1440 /// ```
1441 /// println!("i\u{307}");
1442 /// ```
1443 ///
1444 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1445 ///
1446 /// ```
1447 /// assert_eq!('C'.to_lowercase().to_string(), "c");
1448 ///
1449 /// // Sometimes the result is more than one character:
1450 /// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
1451 ///
1452 /// // Characters that do not have both uppercase and lowercase
1453 /// // convert into themselves.
1454 /// assert_eq!('山'.to_lowercase().to_string(), "山");
1455 /// ```
1456 /// # Notes on context and locale
1457 ///
1458 /// As stated earlier, this method does not take into account language or context.
1459 /// Below is a non-exhaustive list of situations where this can be relevant.
1460 /// If you need to handle locale-depedendent casing in your code, consider using
1461 /// an external crate, like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1462 /// which is developed by Unicode.
1463 ///
1464 /// ## Greek sigma
1465 ///
1466 /// In Greek, the letter sigma (uppercase 'Σ') has two lowercase forms:
1467 /// 'σ' which is used in most situations, and 'ς' which appears only
1468 /// at the end of a word. [`char::to_lowercase()`] always uses the first form:
1469 ///
1470 /// ```
1471 /// assert_eq!('Σ'.to_lowercase().to_string(), "σ");
1472 /// ```
1473 ///
1474 /// `str::to_lowercase()` (only available with the `alloc` crate)
1475 /// *does* properly handle this contextual mapping,
1476 /// so prefer using that method if you can. Alternatively, you can use
1477 /// [`is_cased()`] and [`is_case_ignorable()`] to implement it yourself.
1478 /// See `Final_Sigma` in [Table 3.17] of the Unicode Standard,
1479 /// along with [`SpecialCasing.txt`], for more details.
1480 ///
1481 /// [`is_cased()`]: Self::is_cased()
1482 /// [`is_case_ignorable()`]: Self::is_case_ignorable()
1483 /// [Table 3.17]: https://www.unicode.org/versions/latest/core-spec/chapter-3/#G54277
1484 ///
1485 /// ## Turkish and Azeri I/ı/İ/i
1486 ///
1487 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1488 ///
1489 /// * 'Dotless': I / ı, sometimes written ï
1490 /// * 'Dotted': İ / i
1491 ///
1492 /// Note that the uppercase undotted 'I' is the same codepoint as the Latin. Therefore:
1493 ///
1494 /// ```
1495 /// let lower_i = 'I'.to_lowercase().to_string();
1496 /// ```
1497 ///
1498 /// `'I'`'s correct lowercase relies on the language of the text: if we're
1499 /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should
1500 /// be `"ı"`. `to_lowercase()` does not take this into account, and so:
1501 ///
1502 /// ```
1503 /// let lower_i = 'I'.to_lowercase().to_string();
1504 ///
1505 /// assert_eq!(lower_i, "i");
1506 /// ```
1507 ///
1508 /// holds across languages.
1509 ///
1510 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1511 #[must_use = "this returns the lowercased character as a new iterator, \
1512 without modifying the original"]
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 #[inline]
1515 pub fn to_lowercase(self) -> ToLowercase {
1516 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
1517 }
1518
1519 /// Returns an iterator that yields the titlecase mapping of this `char` as one or more
1520 /// `char`s.
1521 ///
1522 /// This is usually, but not always, equivalent to the uppercase mapping
1523 /// returned by [`to_uppercase()`]. Prefer this method when seeking to capitalize
1524 /// Only The First Letter of a word, but use [`to_uppercase()`] for ALL CAPS.
1525 /// See [below](#difference-from-uppercase) for a thorough explanation
1526 /// of the difference between the two methods.
1527 ///
1528 /// If this `char` does not have a titlecase mapping, the iterator yields the same `char`.
1529 ///
1530 /// If this `char` has a one-to-one titlecase mapping given by the [Unicode Character
1531 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1532 ///
1533 /// [ucd]: https://www.unicode.org/reports/tr44/
1534 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1535 ///
1536 /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1537 /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1538 ///
1539 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1540 ///
1541 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1542 /// is independent of context and language. See [below](#note-on-locale)
1543 /// for more information.
1544 ///
1545 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1546 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1547 ///
1548 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1549 ///
1550 /// # Examples
1551 ///
1552 /// As an iterator:
1553 ///
1554 /// ```
1555 /// #![feature(titlecase)]
1556 /// for c in 'ß'.to_titlecase() {
1557 /// print!("{c}");
1558 /// }
1559 /// println!();
1560 /// ```
1561 ///
1562 /// Using `println!` directly:
1563 ///
1564 /// ```
1565 /// #![feature(titlecase)]
1566 /// println!("{}", 'ß'.to_titlecase());
1567 /// ```
1568 ///
1569 /// Both are equivalent to:
1570 ///
1571 /// ```
1572 /// println!("Ss");
1573 /// ```
1574 ///
1575 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1576 ///
1577 /// ```
1578 /// #![feature(titlecase)]
1579 /// assert_eq!('c'.to_titlecase().to_string(), "C");
1580 /// assert_eq!('ა'.to_titlecase().to_string(), "ა");
1581 /// assert_eq!('dž'.to_titlecase().to_string(), "Dž");
1582 /// assert_eq!('ᾨ'.to_titlecase().to_string(), "ᾨ");
1583 ///
1584 /// // Sometimes the result is more than one character:
1585 /// assert_eq!('ß'.to_titlecase().to_string(), "Ss");
1586 ///
1587 /// // Characters that do not have separate cased forms
1588 /// // convert into themselves.
1589 /// assert_eq!('山'.to_titlecase().to_string(), "山");
1590 /// ```
1591 ///
1592 /// # Difference from uppercase
1593 ///
1594 /// Currently, there are three classes of characters where [`to_uppercase()`]
1595 /// and `to_titlecase()` give different results:
1596 ///
1597 /// ## Georgian script
1598 ///
1599 /// Each letter in the modern Georgian alphabet can be written in one of two forms:
1600 /// the typical lowercase-like "mkhedruli" form, and a variant uppercase-like "mtavruli"
1601 /// form. However, unlike uppercase in most cased scripts, mtavruli is not typically used
1602 /// to start sentences, denote proper nouns, or for any other purpose
1603 /// in running text. It is instead confined to titles and headings, which are written entirely
1604 /// in mtavruli. For this reason, [`to_uppercase()`] applied to a Georgian letter
1605 /// will return the mtavruli form, but `to_titlecase()` will return the mkhedruli form.
1606 ///
1607 /// ```
1608 /// #![feature(titlecase)]
1609 /// let ani = 'ა'; // First letter of the Georgian alphabet, in mkhedruli form
1610 ///
1611 /// // Titlecasing mkhedruli maps it to itself...
1612 /// assert_eq!(ani.to_titlecase().to_string(), ani.to_string());
1613 ///
1614 /// // but uppercasing it maps it to mtavruli
1615 /// assert_eq!(ani.to_uppercase().to_string(), "Ა");
1616 /// ```
1617 ///
1618 /// ## Compatibility digraphs for Latin-alphabet Serbo-Croatian
1619 ///
1620 /// The standard Latin alphabet for the Serbo-Croatian language
1621 /// (Bosnian, Croatian, Montenegrin, and Serbian) contains
1622 /// three digraphs: Dž, Lj, and Nj. These are usually represented as
1623 /// two characters. However, for compatibility with older character sets,
1624 /// Unicode includes single-character versions of these digraphs.
1625 /// Each has a uppercase, titlecase, and lowercase version:
1626 ///
1627 /// - `'DŽ'`, `'Dž'`, `'dž'`
1628 /// - `'LJ'`, `'Lj'`, `'lj'`
1629 /// - `'NJ'`, `'Nj'`, `'nj'`
1630 ///
1631 /// Unicode additionally encodes a casing triad for the Dz digraph
1632 /// without the caron: `'DZ'`, `'Dz'`, `'dz'`.
1633 ///
1634 /// ## Iota-subscritped Greek vowels
1635 ///
1636 /// In ancient Greek, the long vowels alpha (α), eta (η), and omega (ω)
1637 /// were sometimes followed by an iota (ι), forming a diphthong. Over time,
1638 /// the diphthong pronunciation was slowly lost, with the iota becoming mute.
1639 /// Eventually, the ι disappeared from the spelling as well.
1640 /// However, there remains a need to represent ancient texts faithfully.
1641 ///
1642 /// Modern editions of ancient Greek texts commonly use a reduced-sized
1643 /// ι symbol to denote mute iotas, while distinguishing them from ιs
1644 /// which continued to affect pronunciation. The exact standard differs
1645 /// between different publications. Some render the mute ι below its associated
1646 /// vowel (subscript), while others place it to the right of said vowel (adscript).
1647 /// The interaction of mute ι symbols with casing also varies.
1648 ///
1649 /// The Unicode Standard, for its default casing rules, chose to make lowercase
1650 /// Greek vowels with iota subscipt (e.g. `'ᾠ'`) titlecase to the uppercase vowel
1651 /// with iota subscript (`'ᾨ'`) but uppercase to the uppercase vowel followed by
1652 /// full-size uppercase iota (`"ὨΙ"`). This is just one convention among many
1653 /// in common use, but it is the one Unicode settled on,
1654 /// so it is what this method does also.
1655 ///
1656 /// # Note on locale
1657 ///
1658 /// As stated above, this method is locale-insensitive.
1659 /// If you need locale support, consider using an external crate,
1660 /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1661 /// which is developed by Unicode. A description of one common
1662 /// locale-dependent casing issue follows (there are others):
1663 ///
1664 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1665 ///
1666 /// * 'Dotless': I / ı, sometimes written ï
1667 /// * 'Dotted': İ / i
1668 ///
1669 /// Note that the lowercase dotted 'i' is the same codepoint as the Latin. Therefore:
1670 ///
1671 /// ```
1672 /// #![feature(titlecase)]
1673 /// let upper_i = 'i'.to_titlecase().to_string();
1674 /// ```
1675 ///
1676 /// `'i'`'s correct titlecase relies on the language of the text: if we're
1677 /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1678 /// be `"İ"`. `to_titlecase()` does not take this into account, and so:
1679 ///
1680 /// ```
1681 /// #![feature(titlecase)]
1682 /// let upper_i = 'i'.to_titlecase().to_string();
1683 ///
1684 /// assert_eq!(upper_i, "I");
1685 /// ```
1686 ///
1687 /// holds across languages.
1688 ///
1689 /// [`to_uppercase()`]: Self::to_uppercase()
1690 #[must_use = "this returns the titlecased character as a new iterator, \
1691 without modifying the original"]
1692 #[unstable(feature = "titlecase", issue = "153892")]
1693 #[inline]
1694 pub fn to_titlecase(self) -> ToTitlecase {
1695 ToTitlecase(CaseMappingIter::new(conversions::to_title(self)))
1696 }
1697
1698 /// Returns an iterator that yields the uppercase mapping of this `char` as one or more
1699 /// `char`s.
1700 ///
1701 /// Prefer this method when converting a word into ALL CAPS, but consider [`to_titlecase()`]
1702 /// instead if you seek to capitalize Only The First Letter. See that method's documentation
1703 /// for more information on the difference between the two.
1704 ///
1705 /// If this `char` does not have an uppercase mapping, the iterator yields the same `char`.
1706 ///
1707 /// If this `char` has a one-to-one uppercase mapping given by the [Unicode Character
1708 /// Database][ucd] [`UnicodeData.txt`], the iterator yields that `char`.
1709 ///
1710 /// [ucd]: https://www.unicode.org/reports/tr44/
1711 /// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
1712 ///
1713 /// If this `char` expands to multiple `char`s, the iterator yields the `char`s given by
1714 /// [`SpecialCasing.txt`]. The maximum number of `char`s in a case mapping is 3.
1715 ///
1716 /// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1717 ///
1718 /// This operation performs an unconditional mapping without tailoring. That is, the conversion
1719 /// is independent of context and language. See [below](#note-on-locale)
1720 /// for more information.
1721 ///
1722 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case mapping in
1723 /// general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.
1724 ///
1725 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1726 ///
1727 /// # Examples
1728 ///
1729 /// `'ſt'` (U+FB05) is a single Unicode code point (a ligature) that maps to "ST" in uppercase.
1730 ///
1731 /// As an iterator:
1732 ///
1733 /// ```
1734 /// for c in 'ſt'.to_uppercase() {
1735 /// print!("{c}");
1736 /// }
1737 /// println!();
1738 /// ```
1739 ///
1740 /// Using `println!` directly:
1741 ///
1742 /// ```
1743 /// println!("{}", 'ſt'.to_uppercase());
1744 /// ```
1745 ///
1746 /// Both are equivalent to:
1747 ///
1748 /// ```
1749 /// println!("ST");
1750 /// ```
1751 ///
1752 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1753 ///
1754 /// ```
1755 /// assert_eq!('c'.to_uppercase().to_string(), "C");
1756 /// assert_eq!('ა'.to_uppercase().to_string(), "Ა");
1757 /// assert_eq!('dž'.to_uppercase().to_string(), "DŽ");
1758 ///
1759 /// // Sometimes the result is more than one character:
1760 /// assert_eq!('ſt'.to_uppercase().to_string(), "ST");
1761 /// assert_eq!('ᾨ'.to_uppercase().to_string(), "ὨΙ");
1762 ///
1763 /// // Characters that do not have both uppercase and lowercase
1764 /// // convert into themselves.
1765 /// assert_eq!('山'.to_uppercase().to_string(), "山");
1766 /// ```
1767 ///
1768 /// # Note on locale
1769 ///
1770 /// As stated above, this method is locale-insensitive.
1771 /// If you need locale support, consider using an external crate,
1772 /// like [`icu_casemap`](https://crates.io/crates/icu_casemap)
1773 /// which is developed by Unicode. A description of one common
1774 /// locale-dependent casing issue follows (there are others):
1775 ///
1776 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1777 ///
1778 /// * 'Dotless': I / ı, sometimes written ï
1779 /// * 'Dotted': İ / i
1780 ///
1781 /// Note that the lowercase dotted 'i' is the same codepoint as the Latin. Therefore:
1782 ///
1783 /// ```
1784 /// let upper_i = 'i'.to_uppercase().to_string();
1785 /// ```
1786 ///
1787 /// `'i'`'s correct uppercase relies on the language of the text: if we're
1788 /// in `en-US`, it should be `"I"`, but if we're in `tr-TR` or `az-AZ`, it should
1789 /// be `"İ"`. `to_uppercase()` does not take this into account, and so:
1790 ///
1791 /// ```
1792 /// let upper_i = 'i'.to_uppercase().to_string();
1793 ///
1794 /// assert_eq!(upper_i, "I");
1795 /// ```
1796 ///
1797 /// holds across languages.
1798 ///
1799 /// [`to_titlecase()`]: Self::to_titlecase()
1800 #[must_use = "this returns the uppercased character as a new iterator, \
1801 without modifying the original"]
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 #[inline]
1804 pub fn to_uppercase(self) -> ToUppercase {
1805 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
1806 }
1807
1808 /// Returns an iterator that yields the case folding of this `char` as one or more
1809 /// `char`s.
1810 ///
1811 /// Case folding is meant to be used when performing case-insensitive string comparisons.
1812 /// Case-folded strings should not usually be exposed directly to users. For most,
1813 /// but not all, characters, the casefold mapping is identical to the lowercase one.
1814 ///
1815 /// This iterator yields the `char`(s) in the common or full case folding for this `char`,
1816 /// as given by the [Unicode Character Database][ucd] [`CaseFolding.txt`].
1817 /// The maximum number of `char`s in a case folding is 3.
1818 ///
1819 /// [ucd]: https://www.unicode.org/reports/tr44/
1820 /// [`CaseFolding.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt
1821 ///
1822 ///
1823 /// No [normalization] (e.g. NFC) is performed, so visually and semantically identical characters
1824 /// might still casefold differently. For example, `'ά'` (U+03AC GREEK SMALL LETTER ALPHA WITH TONOS)
1825 /// is considered distinct from `'ά'` (U+1F71 GREEK SMALL LETTER ALPHA WITH OXIA),
1826 /// even though Unicode considers them canonically equivalent.
1827 ///
1828 /// In addition, this method is independent of language/locale,
1829 /// so the special behavior of I/ı/İ/i in Turkish and Azeri is not handled.
1830 ///
1831 /// In the [Unicode Standard], Chapter 4 (Character Properties) discusses case folding in
1832 /// general and Chapter 3 (Conformance) discusses the default algorithm for case folding.
1833 ///
1834 /// [Unicode Standard]: https://www.unicode.org/versions/latest/
1835 ///
1836 /// # Examples
1837 ///
1838 /// The German sharp S `'ß'` (U+DF) is a single Unicode code point
1839 /// that casefolds to `"ss"`. Its uppercase variant '`ẞ`' (U+1E9E)
1840 /// has the same case-folding.
1841 ///
1842 /// As an iterator:
1843 ///
1844 /// ```
1845 /// #![feature(casefold)]
1846 /// assert!('ß'.to_casefold_unnormalized().eq(['s', 's']));
1847 /// assert!('ẞ'.to_casefold_unnormalized().eq(['s', 's']));
1848 /// ```
1849 ///
1850 /// Using [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
1851 ///
1852 /// ```
1853 /// #![feature(casefold)]
1854 /// assert_eq!('ß'.to_casefold_unnormalized().to_string(), "ss");
1855 /// assert_eq!('ẞ'.to_casefold_unnormalized().to_string(), "ss");
1856 /// ```
1857 ///
1858 /// No [normalization] is performed:
1859 ///
1860 /// ```rust
1861 /// #![feature(casefold)]
1862 /// // These two characters are visually and semantically identical;
1863 /// // Unicode considers them to be canonically equivalent.
1864 /// let alpha_tonos = 'ά';
1865 /// let alpha_oxia = 'ά';
1866 ///
1867 /// // However, they are different codepoints:
1868 /// assert_eq!(alpha_tonos, '\u{03AC}');
1869 /// assert_eq!(alpha_oxia, '\u{1F71}');
1870 ///
1871 /// // Their case-foldings are likewise unequal:
1872 /// assert!(alpha_tonos.to_casefold_unnormalized().eq(['\u{03AC}']));
1873 /// assert!(alpha_oxia.to_casefold_unnormalized().eq(['\u{1F71}']));
1874 /// ```
1875 ///
1876 /// # Note on locale
1877 ///
1878 /// In Turkish and Azeri, the equivalent of 'i' in Latin has five forms instead of two:
1879 ///
1880 /// * 'Dotless': I / ı, sometimes written ï
1881 /// * 'Dotted': İ / i
1882 ///
1883 /// Note that the uppercase undotted 'I' is the same codepoint as the Latin. Therefore:
1884 ///
1885 /// ```
1886 /// #![feature(casefold)]
1887 /// let casefold_i = 'I'.to_casefold_unnormalized().to_string();
1888 /// ```
1889 ///
1890 /// `'I'`'s correct case folding relies on the language of the text: if we're
1891 /// in `en-US`, it should be `"i"`, but if we're in `tr-TR` or `az-AZ`, it should
1892 /// be `"ı"`. `to_casefold_unnormalized()` does not take this into account, and so:
1893 ///
1894 /// ```
1895 /// #![feature(casefold)]
1896 /// let casefold_i = 'I'.to_casefold_unnormalized().to_string();
1897 ///
1898 /// assert_eq!(casefold_i, "i");
1899 /// ```
1900 ///
1901 /// holds across languages.
1902 ///
1903 /// [normalization]: https://www.unicode.org/faq/normalization.html
1904 #[must_use = "this returns the case-folded character as a new iterator, \
1905 without modifying the original"]
1906 #[unstable(feature = "casefold", issue = "157000")]
1907 #[inline]
1908 pub fn to_casefold_unnormalized(self) -> ToCasefold {
1909 ToCasefold(CaseMappingIter::new(conversions::to_casefold(self)))
1910 }
1911
1912 /// Returns the code point value as a `u32`.
1913 ///
1914 /// # Examples
1915 ///
1916 /// ```
1917 /// #![feature(char_to_u32)]
1918 ///
1919 /// let ascii = 'a';
1920 /// let heart = '❤';
1921 ///
1922 /// assert_eq!(ascii.to_u32(), 97_u32);
1923 /// assert_eq!(heart.to_u32(), 0x2764_u32);
1924 /// ```
1925 #[must_use = "this returns the result of the operation, \
1926 without modifying the original"]
1927 #[unstable(feature = "char_to_u32", issue = "158938")]
1928 #[rustc_const_unstable(feature = "char_to_u32", issue = "158938")]
1929 #[inline(always)]
1930 pub const fn to_u32(self) -> u32 {
1931 self as u32
1932 }
1933
1934 /// Checks if the value is within the ASCII range.
1935 ///
1936 /// # Examples
1937 ///
1938 /// ```
1939 /// let ascii = 'a';
1940 /// let non_ascii = '❤';
1941 ///
1942 /// assert!(ascii.is_ascii());
1943 /// assert!(!non_ascii.is_ascii());
1944 /// ```
1945 #[must_use]
1946 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1947 #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
1948 #[rustc_diagnostic_item = "char_is_ascii"]
1949 #[inline]
1950 #[ferrocene::prevalidated]
1951 pub const fn is_ascii(&self) -> bool {
1952 *self as u32 <= 0x7F
1953 }
1954
1955 /// Returns `Some` if the value is within the ASCII range,
1956 /// or `None` if it's not.
1957 ///
1958 /// This is preferred to [`Self::is_ascii`] when you're passing the value
1959 /// along to something else that can take [`ascii::Char`] rather than
1960 /// needing to check again for itself whether the value is in ASCII.
1961 #[must_use]
1962 #[unstable(feature = "ascii_char", issue = "110998")]
1963 #[inline]
1964 #[ferrocene::prevalidated]
1965 pub const fn as_ascii(&self) -> Option<ascii::Char> {
1966 if self.is_ascii() {
1967 // SAFETY: Just checked that this is ASCII.
1968 Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
1969 } else {
1970 None
1971 }
1972 }
1973
1974 /// Converts this char into an [ASCII character](`ascii::Char`), without
1975 /// checking whether it is valid.
1976 ///
1977 /// # Safety
1978 ///
1979 /// This char must be within the ASCII range, or else this is UB.
1980 #[must_use]
1981 #[unstable(feature = "ascii_char", issue = "110998")]
1982 #[inline]
1983 pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
1984 assert_unsafe_precondition!(
1985 check_library_ub,
1986 "as_ascii_unchecked requires that the char is valid ASCII",
1987 (it: &char = self) => it.is_ascii()
1988 );
1989
1990 // SAFETY: the caller promised that this char is ASCII.
1991 unsafe { ascii::Char::from_u8_unchecked(*self as u8) }
1992 }
1993
1994 /// Makes a copy of the value in its ASCII upper case equivalent.
1995 ///
1996 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1997 /// but non-ASCII letters are unchanged.
1998 ///
1999 /// To uppercase the value in-place, use [`make_ascii_uppercase()`].
2000 ///
2001 /// To uppercase ASCII characters in addition to non-ASCII characters, use
2002 /// [`to_uppercase()`].
2003 ///
2004 /// # Examples
2005 ///
2006 /// ```
2007 /// let ascii = 'a';
2008 /// let non_ascii = '❤';
2009 ///
2010 /// assert_eq!('A', ascii.to_ascii_uppercase());
2011 /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
2012 /// ```
2013 ///
2014 /// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
2015 /// [`to_uppercase()`]: #method.to_uppercase
2016 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
2017 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2018 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
2019 #[inline]
2020 pub const fn to_ascii_uppercase(&self) -> char {
2021 if self.is_ascii_lowercase() {
2022 (*self as u8).ascii_change_case_unchecked() as char
2023 } else {
2024 *self
2025 }
2026 }
2027
2028 /// Makes a copy of the value in its ASCII lower case equivalent.
2029 ///
2030 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2031 /// but non-ASCII letters are unchanged.
2032 ///
2033 /// To lowercase the value in-place, use [`make_ascii_lowercase()`].
2034 ///
2035 /// To lowercase ASCII characters in addition to non-ASCII characters, use
2036 /// [`to_lowercase()`].
2037 ///
2038 /// # Examples
2039 ///
2040 /// ```
2041 /// let ascii = 'A';
2042 /// let non_ascii = '❤';
2043 ///
2044 /// assert_eq!('a', ascii.to_ascii_lowercase());
2045 /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
2046 /// ```
2047 ///
2048 /// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
2049 /// [`to_lowercase()`]: #method.to_lowercase
2050 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
2051 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2052 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
2053 #[inline]
2054 pub const fn to_ascii_lowercase(&self) -> char {
2055 if self.is_ascii_uppercase() {
2056 (*self as u8).ascii_change_case_unchecked() as char
2057 } else {
2058 *self
2059 }
2060 }
2061
2062 /// Checks that two values are an ASCII case-insensitive match.
2063 ///
2064 /// Equivalent to <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>.
2065 ///
2066 /// # Examples
2067 ///
2068 /// ```
2069 /// let upper_a = 'A';
2070 /// let lower_a = 'a';
2071 /// let lower_z = 'z';
2072 ///
2073 /// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
2074 /// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
2075 /// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
2076 /// ```
2077 ///
2078 /// [to_ascii_lowercase]: #method.to_ascii_lowercase
2079 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2080 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
2081 #[expect(clippy::manual_ignore_case_cmp, reason = "implements eq_ignore_ascii_case")]
2082 #[inline]
2083 pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
2084 self.to_ascii_lowercase() == other.to_ascii_lowercase()
2085 }
2086
2087 /// Converts this type to its ASCII upper case equivalent in-place.
2088 ///
2089 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2090 /// but non-ASCII letters are unchanged.
2091 ///
2092 /// To return a new uppercased value without modifying the existing one, use
2093 /// [`to_ascii_uppercase()`].
2094 ///
2095 /// # Examples
2096 ///
2097 /// ```
2098 /// let mut ascii = 'a';
2099 ///
2100 /// ascii.make_ascii_uppercase();
2101 ///
2102 /// assert_eq!('A', ascii);
2103 /// ```
2104 ///
2105 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2106 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2107 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2108 #[inline]
2109 pub const fn make_ascii_uppercase(&mut self) {
2110 *self = self.to_ascii_uppercase();
2111 }
2112
2113 /// Converts this type to its ASCII lower case equivalent in-place.
2114 ///
2115 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2116 /// but non-ASCII letters are unchanged.
2117 ///
2118 /// To return a new lowercased value without modifying the existing one, use
2119 /// [`to_ascii_lowercase()`].
2120 ///
2121 /// # Examples
2122 ///
2123 /// ```
2124 /// let mut ascii = 'A';
2125 ///
2126 /// ascii.make_ascii_lowercase();
2127 ///
2128 /// assert_eq!('a', ascii);
2129 /// ```
2130 ///
2131 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2132 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2133 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2134 #[inline]
2135 pub const fn make_ascii_lowercase(&mut self) {
2136 *self = self.to_ascii_lowercase();
2137 }
2138
2139 /// Checks if the value is an ASCII alphabetic character:
2140 ///
2141 /// - U+0041 'A' ..= U+005A 'Z', or
2142 /// - U+0061 'a' ..= U+007A 'z'.
2143 ///
2144 /// # Examples
2145 ///
2146 /// ```
2147 /// let uppercase_a = 'A';
2148 /// let uppercase_g = 'G';
2149 /// let a = 'a';
2150 /// let g = 'g';
2151 /// let zero = '0';
2152 /// let percent = '%';
2153 /// let space = ' ';
2154 /// let lf = '\n';
2155 /// let esc = '\x1b';
2156 ///
2157 /// assert!(uppercase_a.is_ascii_alphabetic());
2158 /// assert!(uppercase_g.is_ascii_alphabetic());
2159 /// assert!(a.is_ascii_alphabetic());
2160 /// assert!(g.is_ascii_alphabetic());
2161 /// assert!(!zero.is_ascii_alphabetic());
2162 /// assert!(!percent.is_ascii_alphabetic());
2163 /// assert!(!space.is_ascii_alphabetic());
2164 /// assert!(!lf.is_ascii_alphabetic());
2165 /// assert!(!esc.is_ascii_alphabetic());
2166 /// ```
2167 #[must_use]
2168 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2169 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2170 #[inline]
2171 pub const fn is_ascii_alphabetic(&self) -> bool {
2172 matches!(*self, 'a'..='z' | 'A'..='Z')
2173 }
2174
2175 /// Checks if the value is an ASCII uppercase character:
2176 /// U+0041 'A' ..= U+005A 'Z'.
2177 ///
2178 /// # Examples
2179 ///
2180 /// ```
2181 /// let uppercase_a = 'A';
2182 /// let uppercase_g = 'G';
2183 /// let a = 'a';
2184 /// let g = 'g';
2185 /// let zero = '0';
2186 /// let percent = '%';
2187 /// let space = ' ';
2188 /// let lf = '\n';
2189 /// let esc = '\x1b';
2190 ///
2191 /// assert!(uppercase_a.is_ascii_uppercase());
2192 /// assert!(uppercase_g.is_ascii_uppercase());
2193 /// assert!(!a.is_ascii_uppercase());
2194 /// assert!(!g.is_ascii_uppercase());
2195 /// assert!(!zero.is_ascii_uppercase());
2196 /// assert!(!percent.is_ascii_uppercase());
2197 /// assert!(!space.is_ascii_uppercase());
2198 /// assert!(!lf.is_ascii_uppercase());
2199 /// assert!(!esc.is_ascii_uppercase());
2200 /// ```
2201 #[must_use]
2202 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2203 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2204 #[inline]
2205 pub const fn is_ascii_uppercase(&self) -> bool {
2206 matches!(*self, 'A'..='Z')
2207 }
2208
2209 /// Checks if the value is an ASCII lowercase character:
2210 /// U+0061 'a' ..= U+007A 'z'.
2211 ///
2212 /// # Examples
2213 ///
2214 /// ```
2215 /// let uppercase_a = 'A';
2216 /// let uppercase_g = 'G';
2217 /// let a = 'a';
2218 /// let g = 'g';
2219 /// let zero = '0';
2220 /// let percent = '%';
2221 /// let space = ' ';
2222 /// let lf = '\n';
2223 /// let esc = '\x1b';
2224 ///
2225 /// assert!(!uppercase_a.is_ascii_lowercase());
2226 /// assert!(!uppercase_g.is_ascii_lowercase());
2227 /// assert!(a.is_ascii_lowercase());
2228 /// assert!(g.is_ascii_lowercase());
2229 /// assert!(!zero.is_ascii_lowercase());
2230 /// assert!(!percent.is_ascii_lowercase());
2231 /// assert!(!space.is_ascii_lowercase());
2232 /// assert!(!lf.is_ascii_lowercase());
2233 /// assert!(!esc.is_ascii_lowercase());
2234 /// ```
2235 #[must_use]
2236 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2237 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2238 #[inline]
2239 pub const fn is_ascii_lowercase(&self) -> bool {
2240 matches!(*self, 'a'..='z')
2241 }
2242
2243 /// Checks if the value is an ASCII alphanumeric character:
2244 ///
2245 /// - U+0041 'A' ..= U+005A 'Z', or
2246 /// - U+0061 'a' ..= U+007A 'z', or
2247 /// - U+0030 '0' ..= U+0039 '9'.
2248 ///
2249 /// # Examples
2250 ///
2251 /// ```
2252 /// let uppercase_a = 'A';
2253 /// let uppercase_g = 'G';
2254 /// let a = 'a';
2255 /// let g = 'g';
2256 /// let zero = '0';
2257 /// let percent = '%';
2258 /// let space = ' ';
2259 /// let lf = '\n';
2260 /// let esc = '\x1b';
2261 ///
2262 /// assert!(uppercase_a.is_ascii_alphanumeric());
2263 /// assert!(uppercase_g.is_ascii_alphanumeric());
2264 /// assert!(a.is_ascii_alphanumeric());
2265 /// assert!(g.is_ascii_alphanumeric());
2266 /// assert!(zero.is_ascii_alphanumeric());
2267 /// assert!(!percent.is_ascii_alphanumeric());
2268 /// assert!(!space.is_ascii_alphanumeric());
2269 /// assert!(!lf.is_ascii_alphanumeric());
2270 /// assert!(!esc.is_ascii_alphanumeric());
2271 /// ```
2272 #[must_use]
2273 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2274 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2275 #[inline]
2276 pub const fn is_ascii_alphanumeric(&self) -> bool {
2277 matches!(*self, '0'..='9') | matches!(*self, 'A'..='Z') | matches!(*self, 'a'..='z')
2278 }
2279
2280 /// Checks if the value is an ASCII decimal digit:
2281 /// U+0030 '0' ..= U+0039 '9'.
2282 ///
2283 /// # Examples
2284 ///
2285 /// ```
2286 /// let uppercase_a = 'A';
2287 /// let uppercase_g = 'G';
2288 /// let a = 'a';
2289 /// let g = 'g';
2290 /// let zero = '0';
2291 /// let percent = '%';
2292 /// let space = ' ';
2293 /// let lf = '\n';
2294 /// let esc = '\x1b';
2295 ///
2296 /// assert!(!uppercase_a.is_ascii_digit());
2297 /// assert!(!uppercase_g.is_ascii_digit());
2298 /// assert!(!a.is_ascii_digit());
2299 /// assert!(!g.is_ascii_digit());
2300 /// assert!(zero.is_ascii_digit());
2301 /// assert!(!percent.is_ascii_digit());
2302 /// assert!(!space.is_ascii_digit());
2303 /// assert!(!lf.is_ascii_digit());
2304 /// assert!(!esc.is_ascii_digit());
2305 /// ```
2306 #[must_use]
2307 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2308 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2309 #[inline]
2310 pub const fn is_ascii_digit(&self) -> bool {
2311 matches!(*self, '0'..='9')
2312 }
2313
2314 /// Checks if the value is an ASCII octal digit:
2315 /// U+0030 '0' ..= U+0037 '7'.
2316 ///
2317 /// # Examples
2318 ///
2319 /// ```
2320 /// #![feature(is_ascii_octdigit)]
2321 ///
2322 /// let uppercase_a = 'A';
2323 /// let a = 'a';
2324 /// let zero = '0';
2325 /// let seven = '7';
2326 /// let nine = '9';
2327 /// let percent = '%';
2328 /// let lf = '\n';
2329 ///
2330 /// assert!(!uppercase_a.is_ascii_octdigit());
2331 /// assert!(!a.is_ascii_octdigit());
2332 /// assert!(zero.is_ascii_octdigit());
2333 /// assert!(seven.is_ascii_octdigit());
2334 /// assert!(!nine.is_ascii_octdigit());
2335 /// assert!(!percent.is_ascii_octdigit());
2336 /// assert!(!lf.is_ascii_octdigit());
2337 /// ```
2338 #[must_use]
2339 #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
2340 #[inline]
2341 pub const fn is_ascii_octdigit(&self) -> bool {
2342 matches!(*self, '0'..='7')
2343 }
2344
2345 /// Checks if the value is an ASCII hexadecimal digit:
2346 ///
2347 /// - U+0030 '0' ..= U+0039 '9', or
2348 /// - U+0041 'A' ..= U+0046 'F', or
2349 /// - U+0061 'a' ..= U+0066 'f'.
2350 ///
2351 /// # Examples
2352 ///
2353 /// ```
2354 /// let uppercase_a = 'A';
2355 /// let uppercase_g = 'G';
2356 /// let a = 'a';
2357 /// let g = 'g';
2358 /// let zero = '0';
2359 /// let percent = '%';
2360 /// let space = ' ';
2361 /// let lf = '\n';
2362 /// let esc = '\x1b';
2363 ///
2364 /// assert!(uppercase_a.is_ascii_hexdigit());
2365 /// assert!(!uppercase_g.is_ascii_hexdigit());
2366 /// assert!(a.is_ascii_hexdigit());
2367 /// assert!(!g.is_ascii_hexdigit());
2368 /// assert!(zero.is_ascii_hexdigit());
2369 /// assert!(!percent.is_ascii_hexdigit());
2370 /// assert!(!space.is_ascii_hexdigit());
2371 /// assert!(!lf.is_ascii_hexdigit());
2372 /// assert!(!esc.is_ascii_hexdigit());
2373 /// ```
2374 #[must_use]
2375 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2376 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2377 #[inline]
2378 pub const fn is_ascii_hexdigit(&self) -> bool {
2379 matches!(*self, '0'..='9') | matches!(*self, 'A'..='F') | matches!(*self, 'a'..='f')
2380 }
2381
2382 /// Checks if the value is an ASCII punctuation or symbol character
2383 /// (i.e. not alphanumeric, whitespace, or control):
2384 ///
2385 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
2386 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
2387 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
2388 /// - U+007B ..= U+007E `{ | } ~`
2389 ///
2390 /// # Examples
2391 ///
2392 /// ```
2393 /// let uppercase_a = 'A';
2394 /// let uppercase_g = 'G';
2395 /// let a = 'a';
2396 /// let g = 'g';
2397 /// let zero = '0';
2398 /// let percent = '%';
2399 /// let space = ' ';
2400 /// let lf = '\n';
2401 /// let esc = '\x1b';
2402 ///
2403 /// assert!(!uppercase_a.is_ascii_punctuation());
2404 /// assert!(!uppercase_g.is_ascii_punctuation());
2405 /// assert!(!a.is_ascii_punctuation());
2406 /// assert!(!g.is_ascii_punctuation());
2407 /// assert!(!zero.is_ascii_punctuation());
2408 /// assert!(percent.is_ascii_punctuation());
2409 /// assert!(!space.is_ascii_punctuation());
2410 /// assert!(!lf.is_ascii_punctuation());
2411 /// assert!(!esc.is_ascii_punctuation());
2412 /// ```
2413 #[must_use]
2414 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2415 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2416 #[inline]
2417 pub const fn is_ascii_punctuation(&self) -> bool {
2418 matches!(*self, '!'..='/')
2419 | matches!(*self, ':'..='@')
2420 | matches!(*self, '['..='`')
2421 | matches!(*self, '{'..='~')
2422 }
2423
2424 /// Checks if the value is an ASCII graphic character
2425 /// (i.e. not whitespace or control):
2426 /// U+0021 '!' ..= U+007E '~'.
2427 ///
2428 /// # Examples
2429 ///
2430 /// ```
2431 /// let uppercase_a = 'A';
2432 /// let uppercase_g = 'G';
2433 /// let a = 'a';
2434 /// let g = 'g';
2435 /// let zero = '0';
2436 /// let percent = '%';
2437 /// let space = ' ';
2438 /// let lf = '\n';
2439 /// let esc = '\x1b';
2440 ///
2441 /// assert!(uppercase_a.is_ascii_graphic());
2442 /// assert!(uppercase_g.is_ascii_graphic());
2443 /// assert!(a.is_ascii_graphic());
2444 /// assert!(g.is_ascii_graphic());
2445 /// assert!(zero.is_ascii_graphic());
2446 /// assert!(percent.is_ascii_graphic());
2447 /// assert!(!space.is_ascii_graphic());
2448 /// assert!(!lf.is_ascii_graphic());
2449 /// assert!(!esc.is_ascii_graphic());
2450 /// ```
2451 #[must_use]
2452 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2453 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2454 #[inline]
2455 pub const fn is_ascii_graphic(&self) -> bool {
2456 matches!(*self, '!'..='~')
2457 }
2458
2459 /// Checks if the value is an ASCII whitespace character:
2460 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2461 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2462 ///
2463 /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
2464 /// `c.is_ascii_whitespace()` is **not** equivalent to `c.is_ascii() && c.is_whitespace()`.
2465 ///
2466 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2467 /// whitespace][infra-aw]. There are several other definitions in
2468 /// wide use. For instance, [the POSIX locale][pct] includes
2469 /// U+000B VERTICAL TAB as well as all the above characters,
2470 /// but—from the very same specification—[the default rule for
2471 /// "field splitting" in the Bourne shell][bfs] considers *only*
2472 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2473 ///
2474 /// If you are writing a program that will process an existing
2475 /// file format, check what that format's definition of whitespace is
2476 /// before using this function.
2477 ///
2478 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2479 /// [pct]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap07.html#tag_07_03_01
2480 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_06_05
2481 ///
2482 /// # Examples
2483 ///
2484 /// ```
2485 /// let uppercase_a = 'A';
2486 /// let uppercase_g = 'G';
2487 /// let a = 'a';
2488 /// let g = 'g';
2489 /// let zero = '0';
2490 /// let percent = '%';
2491 /// let space = ' ';
2492 /// let lf = '\n';
2493 /// let esc = '\x1b';
2494 ///
2495 /// assert!(!uppercase_a.is_ascii_whitespace());
2496 /// assert!(!uppercase_g.is_ascii_whitespace());
2497 /// assert!(!a.is_ascii_whitespace());
2498 /// assert!(!g.is_ascii_whitespace());
2499 /// assert!(!zero.is_ascii_whitespace());
2500 /// assert!(!percent.is_ascii_whitespace());
2501 /// assert!(space.is_ascii_whitespace());
2502 /// assert!(lf.is_ascii_whitespace());
2503 /// assert!(!esc.is_ascii_whitespace());
2504 /// ```
2505 #[must_use]
2506 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2507 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2508 #[inline]
2509 #[ferrocene::prevalidated]
2510 pub const fn is_ascii_whitespace(&self) -> bool {
2511 matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
2512 }
2513
2514 /// Checks if the value is an ASCII control character:
2515 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
2516 /// Note that most ASCII whitespace characters are control
2517 /// characters, but SPACE is not.
2518 ///
2519 /// # Examples
2520 ///
2521 /// ```
2522 /// let uppercase_a = 'A';
2523 /// let uppercase_g = 'G';
2524 /// let a = 'a';
2525 /// let g = 'g';
2526 /// let zero = '0';
2527 /// let percent = '%';
2528 /// let space = ' ';
2529 /// let lf = '\n';
2530 /// let esc = '\x1b';
2531 ///
2532 /// assert!(!uppercase_a.is_ascii_control());
2533 /// assert!(!uppercase_g.is_ascii_control());
2534 /// assert!(!a.is_ascii_control());
2535 /// assert!(!g.is_ascii_control());
2536 /// assert!(!zero.is_ascii_control());
2537 /// assert!(!percent.is_ascii_control());
2538 /// assert!(!space.is_ascii_control());
2539 /// assert!(lf.is_ascii_control());
2540 /// assert!(esc.is_ascii_control());
2541 /// ```
2542 #[must_use]
2543 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2544 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
2545 #[inline]
2546 pub const fn is_ascii_control(&self) -> bool {
2547 matches!(*self, '\0'..='\x1F' | '\x7F')
2548 }
2549}
2550
2551#[ferrocene::prevalidated]
2552pub(crate) struct EscapeDebugExtArgs {
2553 /// Escape single quotes?
2554 pub(crate) escape_single_quote: bool,
2555
2556 /// Escape double quotes?
2557 pub(crate) escape_double_quote: bool,
2558}
2559
2560impl EscapeDebugExtArgs {
2561 pub(crate) const ESCAPE_ALL: Self =
2562 Self { escape_single_quote: true, escape_double_quote: true };
2563}
2564
2565#[inline]
2566#[must_use]
2567#[ferrocene::prevalidated]
2568const fn len_utf8(code: u32) -> usize {
2569 match code {
2570 ..MAX_ONE_B => 1,
2571 ..MAX_TWO_B => 2,
2572 ..MAX_THREE_B => 3,
2573 _ => 4,
2574 }
2575}
2576
2577#[inline]
2578#[must_use]
2579const fn len_utf16(code: u32) -> usize {
2580 if (code & 0xFFFF) == code { 1 } else { 2 }
2581}
2582
2583/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer,
2584/// and then returns the subslice of the buffer that contains the encoded character.
2585///
2586/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2587/// (Creating a `char` in the surrogate range is UB.)
2588/// The result is valid [generalized UTF-8] but not valid UTF-8.
2589///
2590/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2591///
2592/// # Panics
2593///
2594/// Panics if the buffer is not large enough.
2595/// A buffer of length four is large enough to encode any `char`.
2596#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2597#[doc(hidden)]
2598#[inline]
2599#[ferrocene::prevalidated]
2600pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
2601 let len = len_utf8(code);
2602 if dst.len() < len {
2603 const_panic!(
2604 "encode_utf8: buffer does not have enough bytes to encode code point",
2605 "encode_utf8: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2606 code: u32 = code,
2607 len: usize = len,
2608 dst_len: usize = dst.len(),
2609 );
2610 }
2611
2612 // SAFETY: `dst` is checked to be at least the length needed to encode the codepoint.
2613 unsafe { encode_utf8_raw_unchecked(code, dst.as_mut_ptr()) };
2614
2615 // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2616 unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2617}
2618
2619/// Encodes a raw `u32` value as UTF-8 into the byte buffer pointed to by `dst`.
2620///
2621/// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range.
2622/// (Creating a `char` in the surrogate range is UB.)
2623/// The result is valid [generalized UTF-8] but not valid UTF-8.
2624///
2625/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
2626///
2627/// # Safety
2628///
2629/// The behavior is undefined if the buffer pointed to by `dst` is not
2630/// large enough to hold the encoded codepoint. A buffer of length four
2631/// is large enough to encode any `char`.
2632///
2633/// For a safe version of this function, see the [`encode_utf8_raw`] function.
2634#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2635#[doc(hidden)]
2636#[inline]
2637#[ferrocene::prevalidated]
2638pub const unsafe fn encode_utf8_raw_unchecked(code: u32, dst: *mut u8) {
2639 let len = len_utf8(code);
2640 // SAFETY: The caller must guarantee that the buffer pointed to by `dst`
2641 // is at least `len` bytes long.
2642 unsafe {
2643 if len == 1 {
2644 *dst = code as u8;
2645 return;
2646 }
2647
2648 let last1 = (code >> 0 & 0x3F) as u8 | TAG_CONT;
2649 let last2 = (code >> 6 & 0x3F) as u8 | TAG_CONT;
2650 let last3 = (code >> 12 & 0x3F) as u8 | TAG_CONT;
2651 let last4 = (code >> 18 & 0x3F) as u8 | TAG_FOUR_B;
2652
2653 if len == 2 {
2654 *dst = last2 | TAG_TWO_B;
2655 *dst.add(1) = last1;
2656 return;
2657 }
2658
2659 if len == 3 {
2660 *dst = last3 | TAG_THREE_B;
2661 *dst.add(1) = last2;
2662 *dst.add(2) = last1;
2663 return;
2664 }
2665
2666 *dst = last4;
2667 *dst.add(1) = last3;
2668 *dst.add(2) = last2;
2669 *dst.add(3) = last1;
2670 }
2671}
2672
2673/// Encodes a raw `u32` value as native endian UTF-16 into the provided `u16` buffer,
2674/// and then returns the subslice of the buffer that contains the encoded character.
2675///
2676/// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range.
2677/// (Creating a `char` in the surrogate range is UB.)
2678///
2679/// # Panics
2680///
2681/// Panics if the buffer is not large enough.
2682/// A buffer of length 2 is large enough to encode any `char`.
2683#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
2684#[doc(hidden)]
2685#[inline]
2686pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
2687 let len = len_utf16(code);
2688 match (len, &mut *dst) {
2689 (1, [a, ..]) => {
2690 *a = code as u16;
2691 }
2692 (2, [a, b, ..]) => {
2693 code -= 0x1_0000;
2694 *a = (code >> 10) as u16 | 0xD800;
2695 *b = (code & 0x3FF) as u16 | 0xDC00;
2696 }
2697 _ => {
2698 const_panic!(
2699 "encode_utf16: buffer does not have enough bytes to encode code point",
2700 "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}",
2701 code: u32 = code,
2702 len: usize = len,
2703 dst_len: usize = dst.len(),
2704 )
2705 }
2706 };
2707 // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
2708 unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) }
2709}