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