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