]> git.lizzy.rs Git - rust.git/blob - src/libcore/char/mod.rs
Rollup merge of #68438 - Aaron1011:fix/tait-non-defining, r=estebank
[rust.git] / src / libcore / char / mod.rs
1 //! A character type.
2 //!
3 //! The `char` type represents a single character. More specifically, since
4 //! 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
5 //! scalar value]', which is similar to, but not the same as, a '[Unicode code
6 //! point]'.
7 //!
8 //! [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
9 //! [Unicode code point]: http://www.unicode.org/glossary/#code_point
10 //!
11 //! This module exists for technical reasons, the primary documentation for
12 //! `char` is directly on [the `char` primitive type](../../std/primitive.char.html)
13 //! itself.
14 //!
15 //! This module is the home of the iterator implementations for the iterators
16 //! implemented on `char`, as well as some useful constants and conversion
17 //! functions that convert various types to `char`.
18
19 #![allow(non_snake_case)]
20 #![stable(feature = "core_char", since = "1.2.0")]
21
22 mod convert;
23 mod decode;
24 mod methods;
25
26 // stable re-exports
27 #[stable(feature = "char_from_unchecked", since = "1.5.0")]
28 pub use self::convert::from_u32_unchecked;
29 #[stable(feature = "try_from", since = "1.34.0")]
30 pub use self::convert::CharTryFromError;
31 #[stable(feature = "char_from_str", since = "1.20.0")]
32 pub use self::convert::ParseCharError;
33 #[stable(feature = "rust1", since = "1.0.0")]
34 pub use self::convert::{from_digit, from_u32};
35 #[stable(feature = "decode_utf16", since = "1.9.0")]
36 pub use self::decode::{decode_utf16, DecodeUtf16, DecodeUtf16Error};
37
38 // unstable re-exports
39 #[unstable(feature = "unicode_version", issue = "49726")]
40 pub use crate::unicode::version::UnicodeVersion;
41 #[unstable(feature = "unicode_version", issue = "49726")]
42 pub use crate::unicode::UNICODE_VERSION;
43
44 use crate::fmt::{self, Write};
45 use crate::iter::FusedIterator;
46
47 // UTF-8 ranges and tags for encoding characters
48 const TAG_CONT: u8 = 0b1000_0000;
49 const TAG_TWO_B: u8 = 0b1100_0000;
50 const TAG_THREE_B: u8 = 0b1110_0000;
51 const TAG_FOUR_B: u8 = 0b1111_0000;
52 const MAX_ONE_B: u32 = 0x80;
53 const MAX_TWO_B: u32 = 0x800;
54 const MAX_THREE_B: u32 = 0x10000;
55
56 /*
57     Lu  Uppercase_Letter        an uppercase letter
58     Ll  Lowercase_Letter        a lowercase letter
59     Lt  Titlecase_Letter        a digraphic character, with first part uppercase
60     Lm  Modifier_Letter         a modifier letter
61     Lo  Other_Letter            other letters, including syllables and ideographs
62     Mn  Nonspacing_Mark         a nonspacing combining mark (zero advance width)
63     Mc  Spacing_Mark            a spacing combining mark (positive advance width)
64     Me  Enclosing_Mark          an enclosing combining mark
65     Nd  Decimal_Number          a decimal digit
66     Nl  Letter_Number           a letterlike numeric character
67     No  Other_Number            a numeric character of other type
68     Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
69     Pd  Dash_Punctuation        a dash or hyphen punctuation mark
70     Ps  Open_Punctuation        an opening punctuation mark (of a pair)
71     Pe  Close_Punctuation       a closing punctuation mark (of a pair)
72     Pi  Initial_Punctuation     an initial quotation mark
73     Pf  Final_Punctuation       a final quotation mark
74     Po  Other_Punctuation       a punctuation mark of other type
75     Sm  Math_Symbol             a symbol of primarily mathematical use
76     Sc  Currency_Symbol         a currency sign
77     Sk  Modifier_Symbol         a non-letterlike modifier symbol
78     So  Other_Symbol            a symbol of other type
79     Zs  Space_Separator         a space character (of various non-zero widths)
80     Zl  Line_Separator          U+2028 LINE SEPARATOR only
81     Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
82     Cc  Control                 a C0 or C1 control code
83     Cf  Format                  a format control character
84     Cs  Surrogate               a surrogate code point
85     Co  Private_Use             a private-use character
86     Cn  Unassigned              a reserved unassigned code point or a noncharacter
87 */
88
89 /// The highest valid code point a `char` can have.
90 ///
91 /// A [`char`] is a [Unicode Scalar Value], which means that it is a [Code
92 /// Point], but only ones within a certain range. `MAX` is the highest valid
93 /// code point that's a valid [Unicode Scalar Value].
94 ///
95 /// [`char`]: ../../std/primitive.char.html
96 /// [Unicode Scalar Value]: http://www.unicode.org/glossary/#unicode_scalar_value
97 /// [Code Point]: http://www.unicode.org/glossary/#code_point
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub const MAX: char = '\u{10ffff}';
100
101 /// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
102 /// decoding error.
103 ///
104 /// It can occur, for example, when giving ill-formed UTF-8 bytes to
105 /// [`String::from_utf8_lossy`](../../std/string/struct.String.html#method.from_utf8_lossy).
106 #[stable(feature = "decode_utf16", since = "1.9.0")]
107 pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
108
109 /// Returns an iterator that yields the hexadecimal Unicode escape of a
110 /// character, as `char`s.
111 ///
112 /// This `struct` is created by the [`escape_unicode`] method on [`char`]. See
113 /// its documentation for more.
114 ///
115 /// [`escape_unicode`]: ../../std/primitive.char.html#method.escape_unicode
116 /// [`char`]: ../../std/primitive.char.html
117 #[derive(Clone, Debug)]
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub struct EscapeUnicode {
120     c: char,
121     state: EscapeUnicodeState,
122
123     // The index of the next hex digit to be printed (0 if none),
124     // i.e., the number of remaining hex digits to be printed;
125     // increasing from the least significant digit: 0x543210
126     hex_digit_idx: usize,
127 }
128
129 // The enum values are ordered so that their representation is the
130 // same as the remaining length (besides the hexadecimal digits). This
131 // likely makes `len()` a single load from memory) and inline-worth.
132 #[derive(Clone, Debug)]
133 enum EscapeUnicodeState {
134     Done,
135     RightBrace,
136     Value,
137     LeftBrace,
138     Type,
139     Backslash,
140 }
141
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl Iterator for EscapeUnicode {
144     type Item = char;
145
146     fn next(&mut self) -> Option<char> {
147         match self.state {
148             EscapeUnicodeState::Backslash => {
149                 self.state = EscapeUnicodeState::Type;
150                 Some('\\')
151             }
152             EscapeUnicodeState::Type => {
153                 self.state = EscapeUnicodeState::LeftBrace;
154                 Some('u')
155             }
156             EscapeUnicodeState::LeftBrace => {
157                 self.state = EscapeUnicodeState::Value;
158                 Some('{')
159             }
160             EscapeUnicodeState::Value => {
161                 let hex_digit = ((self.c as u32) >> (self.hex_digit_idx * 4)) & 0xf;
162                 let c = from_digit(hex_digit, 16).unwrap();
163                 if self.hex_digit_idx == 0 {
164                     self.state = EscapeUnicodeState::RightBrace;
165                 } else {
166                     self.hex_digit_idx -= 1;
167                 }
168                 Some(c)
169             }
170             EscapeUnicodeState::RightBrace => {
171                 self.state = EscapeUnicodeState::Done;
172                 Some('}')
173             }
174             EscapeUnicodeState::Done => None,
175         }
176     }
177
178     #[inline]
179     fn size_hint(&self) -> (usize, Option<usize>) {
180         let n = self.len();
181         (n, Some(n))
182     }
183
184     #[inline]
185     fn count(self) -> usize {
186         self.len()
187     }
188
189     fn last(self) -> Option<char> {
190         match self.state {
191             EscapeUnicodeState::Done => None,
192
193             EscapeUnicodeState::RightBrace
194             | EscapeUnicodeState::Value
195             | EscapeUnicodeState::LeftBrace
196             | EscapeUnicodeState::Type
197             | EscapeUnicodeState::Backslash => Some('}'),
198         }
199     }
200 }
201
202 #[stable(feature = "exact_size_escape", since = "1.11.0")]
203 impl ExactSizeIterator for EscapeUnicode {
204     #[inline]
205     fn len(&self) -> usize {
206         // The match is a single memory access with no branching
207         self.hex_digit_idx
208             + match self.state {
209                 EscapeUnicodeState::Done => 0,
210                 EscapeUnicodeState::RightBrace => 1,
211                 EscapeUnicodeState::Value => 2,
212                 EscapeUnicodeState::LeftBrace => 3,
213                 EscapeUnicodeState::Type => 4,
214                 EscapeUnicodeState::Backslash => 5,
215             }
216     }
217 }
218
219 #[stable(feature = "fused", since = "1.26.0")]
220 impl FusedIterator for EscapeUnicode {}
221
222 #[stable(feature = "char_struct_display", since = "1.16.0")]
223 impl fmt::Display for EscapeUnicode {
224     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225         for c in self.clone() {
226             f.write_char(c)?;
227         }
228         Ok(())
229     }
230 }
231
232 /// An iterator that yields the literal escape code of a `char`.
233 ///
234 /// This `struct` is created by the [`escape_default`] method on [`char`]. See
235 /// its documentation for more.
236 ///
237 /// [`escape_default`]: ../../std/primitive.char.html#method.escape_default
238 /// [`char`]: ../../std/primitive.char.html
239 #[derive(Clone, Debug)]
240 #[stable(feature = "rust1", since = "1.0.0")]
241 pub struct EscapeDefault {
242     state: EscapeDefaultState,
243 }
244
245 #[derive(Clone, Debug)]
246 enum EscapeDefaultState {
247     Done,
248     Char(char),
249     Backslash(char),
250     Unicode(EscapeUnicode),
251 }
252
253 #[stable(feature = "rust1", since = "1.0.0")]
254 impl Iterator for EscapeDefault {
255     type Item = char;
256
257     fn next(&mut self) -> Option<char> {
258         match self.state {
259             EscapeDefaultState::Backslash(c) => {
260                 self.state = EscapeDefaultState::Char(c);
261                 Some('\\')
262             }
263             EscapeDefaultState::Char(c) => {
264                 self.state = EscapeDefaultState::Done;
265                 Some(c)
266             }
267             EscapeDefaultState::Done => None,
268             EscapeDefaultState::Unicode(ref mut iter) => iter.next(),
269         }
270     }
271
272     #[inline]
273     fn size_hint(&self) -> (usize, Option<usize>) {
274         let n = self.len();
275         (n, Some(n))
276     }
277
278     #[inline]
279     fn count(self) -> usize {
280         self.len()
281     }
282
283     fn nth(&mut self, n: usize) -> Option<char> {
284         match self.state {
285             EscapeDefaultState::Backslash(c) if n == 0 => {
286                 self.state = EscapeDefaultState::Char(c);
287                 Some('\\')
288             }
289             EscapeDefaultState::Backslash(c) if n == 1 => {
290                 self.state = EscapeDefaultState::Done;
291                 Some(c)
292             }
293             EscapeDefaultState::Backslash(_) => {
294                 self.state = EscapeDefaultState::Done;
295                 None
296             }
297             EscapeDefaultState::Char(c) => {
298                 self.state = EscapeDefaultState::Done;
299
300                 if n == 0 { Some(c) } else { None }
301             }
302             EscapeDefaultState::Done => None,
303             EscapeDefaultState::Unicode(ref mut i) => i.nth(n),
304         }
305     }
306
307     fn last(self) -> Option<char> {
308         match self.state {
309             EscapeDefaultState::Unicode(iter) => iter.last(),
310             EscapeDefaultState::Done => None,
311             EscapeDefaultState::Backslash(c) | EscapeDefaultState::Char(c) => Some(c),
312         }
313     }
314 }
315
316 #[stable(feature = "exact_size_escape", since = "1.11.0")]
317 impl ExactSizeIterator for EscapeDefault {
318     fn len(&self) -> usize {
319         match self.state {
320             EscapeDefaultState::Done => 0,
321             EscapeDefaultState::Char(_) => 1,
322             EscapeDefaultState::Backslash(_) => 2,
323             EscapeDefaultState::Unicode(ref iter) => iter.len(),
324         }
325     }
326 }
327
328 #[stable(feature = "fused", since = "1.26.0")]
329 impl FusedIterator for EscapeDefault {}
330
331 #[stable(feature = "char_struct_display", since = "1.16.0")]
332 impl fmt::Display for EscapeDefault {
333     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334         for c in self.clone() {
335             f.write_char(c)?;
336         }
337         Ok(())
338     }
339 }
340
341 /// An iterator that yields the literal escape code of a `char`.
342 ///
343 /// This `struct` is created by the [`escape_debug`] method on [`char`]. See its
344 /// documentation for more.
345 ///
346 /// [`escape_debug`]: ../../std/primitive.char.html#method.escape_debug
347 /// [`char`]: ../../std/primitive.char.html
348 #[stable(feature = "char_escape_debug", since = "1.20.0")]
349 #[derive(Clone, Debug)]
350 pub struct EscapeDebug(EscapeDefault);
351
352 #[stable(feature = "char_escape_debug", since = "1.20.0")]
353 impl Iterator for EscapeDebug {
354     type Item = char;
355     fn next(&mut self) -> Option<char> {
356         self.0.next()
357     }
358     fn size_hint(&self) -> (usize, Option<usize>) {
359         self.0.size_hint()
360     }
361 }
362
363 #[stable(feature = "char_escape_debug", since = "1.20.0")]
364 impl ExactSizeIterator for EscapeDebug {}
365
366 #[stable(feature = "fused", since = "1.26.0")]
367 impl FusedIterator for EscapeDebug {}
368
369 #[stable(feature = "char_escape_debug", since = "1.20.0")]
370 impl fmt::Display for EscapeDebug {
371     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372         fmt::Display::fmt(&self.0, f)
373     }
374 }
375
376 /// Returns an iterator that yields the lowercase equivalent of a `char`.
377 ///
378 /// This `struct` is created by the [`to_lowercase`] method on [`char`]. See
379 /// its documentation for more.
380 ///
381 /// [`to_lowercase`]: ../../std/primitive.char.html#method.to_lowercase
382 /// [`char`]: ../../std/primitive.char.html
383 #[stable(feature = "rust1", since = "1.0.0")]
384 #[derive(Debug, Clone)]
385 pub struct ToLowercase(CaseMappingIter);
386
387 #[stable(feature = "rust1", since = "1.0.0")]
388 impl Iterator for ToLowercase {
389     type Item = char;
390     fn next(&mut self) -> Option<char> {
391         self.0.next()
392     }
393     fn size_hint(&self) -> (usize, Option<usize>) {
394         self.0.size_hint()
395     }
396 }
397
398 #[stable(feature = "fused", since = "1.26.0")]
399 impl FusedIterator for ToLowercase {}
400
401 #[stable(feature = "exact_size_case_mapping_iter", since = "1.35.0")]
402 impl ExactSizeIterator for ToLowercase {}
403
404 /// Returns an iterator that yields the uppercase equivalent of a `char`.
405 ///
406 /// This `struct` is created by the [`to_uppercase`] method on [`char`]. See
407 /// its documentation for more.
408 ///
409 /// [`to_uppercase`]: ../../std/primitive.char.html#method.to_uppercase
410 /// [`char`]: ../../std/primitive.char.html
411 #[stable(feature = "rust1", since = "1.0.0")]
412 #[derive(Debug, Clone)]
413 pub struct ToUppercase(CaseMappingIter);
414
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl Iterator for ToUppercase {
417     type Item = char;
418     fn next(&mut self) -> Option<char> {
419         self.0.next()
420     }
421     fn size_hint(&self) -> (usize, Option<usize>) {
422         self.0.size_hint()
423     }
424 }
425
426 #[stable(feature = "fused", since = "1.26.0")]
427 impl FusedIterator for ToUppercase {}
428
429 #[stable(feature = "exact_size_case_mapping_iter", since = "1.35.0")]
430 impl ExactSizeIterator for ToUppercase {}
431
432 #[derive(Debug, Clone)]
433 enum CaseMappingIter {
434     Three(char, char, char),
435     Two(char, char),
436     One(char),
437     Zero,
438 }
439
440 impl CaseMappingIter {
441     fn new(chars: [char; 3]) -> CaseMappingIter {
442         if chars[2] == '\0' {
443             if chars[1] == '\0' {
444                 CaseMappingIter::One(chars[0]) // Including if chars[0] == '\0'
445             } else {
446                 CaseMappingIter::Two(chars[0], chars[1])
447             }
448         } else {
449             CaseMappingIter::Three(chars[0], chars[1], chars[2])
450         }
451     }
452 }
453
454 impl Iterator for CaseMappingIter {
455     type Item = char;
456     fn next(&mut self) -> Option<char> {
457         match *self {
458             CaseMappingIter::Three(a, b, c) => {
459                 *self = CaseMappingIter::Two(b, c);
460                 Some(a)
461             }
462             CaseMappingIter::Two(b, c) => {
463                 *self = CaseMappingIter::One(c);
464                 Some(b)
465             }
466             CaseMappingIter::One(c) => {
467                 *self = CaseMappingIter::Zero;
468                 Some(c)
469             }
470             CaseMappingIter::Zero => None,
471         }
472     }
473
474     fn size_hint(&self) -> (usize, Option<usize>) {
475         let size = match self {
476             CaseMappingIter::Three(..) => 3,
477             CaseMappingIter::Two(..) => 2,
478             CaseMappingIter::One(_) => 1,
479             CaseMappingIter::Zero => 0,
480         };
481         (size, Some(size))
482     }
483 }
484
485 impl fmt::Display for CaseMappingIter {
486     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487         match *self {
488             CaseMappingIter::Three(a, b, c) => {
489                 f.write_char(a)?;
490                 f.write_char(b)?;
491                 f.write_char(c)
492             }
493             CaseMappingIter::Two(b, c) => {
494                 f.write_char(b)?;
495                 f.write_char(c)
496             }
497             CaseMappingIter::One(c) => f.write_char(c),
498             CaseMappingIter::Zero => Ok(()),
499         }
500     }
501 }
502
503 #[stable(feature = "char_struct_display", since = "1.16.0")]
504 impl fmt::Display for ToLowercase {
505     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506         fmt::Display::fmt(&self.0, f)
507     }
508 }
509
510 #[stable(feature = "char_struct_display", since = "1.16.0")]
511 impl fmt::Display for ToUppercase {
512     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513         fmt::Display::fmt(&self.0, f)
514     }
515 }