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