]> git.lizzy.rs Git - rust.git/blob - src/libcore/char.rs
Rollup merge of #28588 - critiqjo:trpl-closure, r=steveklabnik
[rust.git] / src / libcore / char.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Character manipulation.
12 //!
13 //! For more details, see ::rustc_unicode::char (a.k.a. std::char)
14
15 #![allow(non_snake_case)]
16 #![stable(feature = "core_char", since = "1.2.0")]
17
18 use iter::Iterator;
19 use mem::transmute;
20 use option::Option::{None, Some};
21 use option::Option;
22 use slice::SliceExt;
23
24 // UTF-8 ranges and tags for encoding characters
25 const TAG_CONT: u8    = 0b1000_0000;
26 const TAG_TWO_B: u8   = 0b1100_0000;
27 const TAG_THREE_B: u8 = 0b1110_0000;
28 const TAG_FOUR_B: u8  = 0b1111_0000;
29 const MAX_ONE_B: u32   =     0x80;
30 const MAX_TWO_B: u32   =    0x800;
31 const MAX_THREE_B: u32 =  0x10000;
32
33 /*
34     Lu  Uppercase_Letter        an uppercase letter
35     Ll  Lowercase_Letter        a lowercase letter
36     Lt  Titlecase_Letter        a digraphic character, with first part uppercase
37     Lm  Modifier_Letter         a modifier letter
38     Lo  Other_Letter            other letters, including syllables and ideographs
39     Mn  Nonspacing_Mark         a nonspacing combining mark (zero advance width)
40     Mc  Spacing_Mark            a spacing combining mark (positive advance width)
41     Me  Enclosing_Mark          an enclosing combining mark
42     Nd  Decimal_Number          a decimal digit
43     Nl  Letter_Number           a letterlike numeric character
44     No  Other_Number            a numeric character of other type
45     Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
46     Pd  Dash_Punctuation        a dash or hyphen punctuation mark
47     Ps  Open_Punctuation        an opening punctuation mark (of a pair)
48     Pe  Close_Punctuation       a closing punctuation mark (of a pair)
49     Pi  Initial_Punctuation     an initial quotation mark
50     Pf  Final_Punctuation       a final quotation mark
51     Po  Other_Punctuation       a punctuation mark of other type
52     Sm  Math_Symbol             a symbol of primarily mathematical use
53     Sc  Currency_Symbol         a currency sign
54     Sk  Modifier_Symbol         a non-letterlike modifier symbol
55     So  Other_Symbol            a symbol of other type
56     Zs  Space_Separator         a space character (of various non-zero widths)
57     Zl  Line_Separator          U+2028 LINE SEPARATOR only
58     Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
59     Cc  Control                 a C0 or C1 control code
60     Cf  Format                  a format control character
61     Cs  Surrogate               a surrogate code point
62     Co  Private_Use             a private-use character
63     Cn  Unassigned              a reserved unassigned code point or a noncharacter
64 */
65
66 /// The highest valid code point
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub const MAX: char = '\u{10ffff}';
69
70 /// Converts a `u32` to an `Option<char>`.
71 ///
72 /// # Examples
73 ///
74 /// ```
75 /// use std::char;
76 ///
77 /// assert_eq!(char::from_u32(0x2764), Some('❤'));
78 /// assert_eq!(char::from_u32(0x110000), None); // invalid character
79 /// ```
80 #[inline]
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub fn from_u32(i: u32) -> Option<char> {
83     // catch out-of-bounds and surrogates
84     if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
85         None
86     } else {
87         Some(unsafe { from_u32_unchecked(i) })
88     }
89 }
90
91 /// Converts a `u32` to an `char`, not checking whether it is a valid unicode
92 /// codepoint.
93 #[inline]
94 #[unstable(feature = "char_from_unchecked", reason = "recently added API",
95            issue = "27781")]
96 pub unsafe fn from_u32_unchecked(i: u32) -> char {
97     transmute(i)
98 }
99
100 /// Converts a number to the character representing it.
101 ///
102 /// # Return value
103 ///
104 /// Returns `Some(char)` if `num` represents one digit under `radix`,
105 /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
106 ///
107 /// # Panics
108 ///
109 /// Panics if given an `radix` > 36.
110 ///
111 /// # Examples
112 ///
113 /// ```
114 /// use std::char;
115 ///
116 /// let c = char::from_digit(4, 10);
117 ///
118 /// assert_eq!(c, Some('4'));
119 /// ```
120 #[inline]
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub fn from_digit(num: u32, radix: u32) -> Option<char> {
123     if radix > 36 {
124         panic!("from_digit: radix is too high (maximum 36)");
125     }
126     if num < radix {
127         let num = num as u8;
128         if num < 10 {
129             Some((b'0' + num) as char)
130         } else {
131             Some((b'a' + num - 10) as char)
132         }
133     } else {
134         None
135     }
136 }
137
138 // NB: the stabilization and documentation for this trait is in
139 // unicode/char.rs, not here
140 #[allow(missing_docs)] // docs in libunicode/u_char.rs
141 #[doc(hidden)]
142 #[unstable(feature = "core_char_ext",
143            reason = "the stable interface is `impl char` in later crate",
144            issue = "27701")]
145 pub trait CharExt {
146     fn is_digit(self, radix: u32) -> bool;
147     fn to_digit(self, radix: u32) -> Option<u32>;
148     fn escape_unicode(self) -> EscapeUnicode;
149     fn escape_default(self) -> EscapeDefault;
150     fn len_utf8(self) -> usize;
151     fn len_utf16(self) -> usize;
152     fn encode_utf8(self, dst: &mut [u8]) -> Option<usize>;
153     fn encode_utf16(self, dst: &mut [u16]) -> Option<usize>;
154 }
155
156 impl CharExt for char {
157     #[inline]
158     fn is_digit(self, radix: u32) -> bool {
159         self.to_digit(radix).is_some()
160     }
161
162     #[inline]
163     fn to_digit(self, radix: u32) -> Option<u32> {
164         if radix > 36 {
165             panic!("to_digit: radix is too high (maximum 36)");
166         }
167         let val = match self {
168           '0' ... '9' => self as u32 - '0' as u32,
169           'a' ... 'z' => self as u32 - 'a' as u32 + 10,
170           'A' ... 'Z' => self as u32 - 'A' as u32 + 10,
171           _ => return None,
172         };
173         if val < radix { Some(val) }
174         else { None }
175     }
176
177     #[inline]
178     fn escape_unicode(self) -> EscapeUnicode {
179         EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
180     }
181
182     #[inline]
183     fn escape_default(self) -> EscapeDefault {
184         let init_state = match self {
185             '\t' => EscapeDefaultState::Backslash('t'),
186             '\r' => EscapeDefaultState::Backslash('r'),
187             '\n' => EscapeDefaultState::Backslash('n'),
188             '\\' => EscapeDefaultState::Backslash('\\'),
189             '\'' => EscapeDefaultState::Backslash('\''),
190             '"'  => EscapeDefaultState::Backslash('"'),
191             '\x20' ... '\x7e' => EscapeDefaultState::Char(self),
192             _ => EscapeDefaultState::Unicode(self.escape_unicode())
193         };
194         EscapeDefault { state: init_state }
195     }
196
197     #[inline]
198     fn len_utf8(self) -> usize {
199         let code = self as u32;
200         if code < MAX_ONE_B {
201             1
202         } else if code < MAX_TWO_B {
203             2
204         } else if code < MAX_THREE_B {
205             3
206         } else {
207             4
208         }
209     }
210
211     #[inline]
212     fn len_utf16(self) -> usize {
213         let ch = self as u32;
214         if (ch & 0xFFFF) == ch { 1 } else { 2 }
215     }
216
217     #[inline]
218     fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> {
219         encode_utf8_raw(self as u32, dst)
220     }
221
222     #[inline]
223     fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> {
224         encode_utf16_raw(self as u32, dst)
225     }
226 }
227
228 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
229 /// and then returns the number of bytes written.
230 ///
231 /// If the buffer is not large enough, nothing will be written into it
232 /// and a `None` will be returned.
233 #[inline]
234 #[unstable(feature = "char_internals",
235            reason = "this function should not be exposed publicly",
236            issue = "0")]
237 #[doc(hidden)]
238 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> {
239     // Marked #[inline] to allow llvm optimizing it away
240     if code < MAX_ONE_B && !dst.is_empty() {
241         dst[0] = code as u8;
242         Some(1)
243     } else if code < MAX_TWO_B && dst.len() >= 2 {
244         dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
245         dst[1] = (code & 0x3F) as u8 | TAG_CONT;
246         Some(2)
247     } else if code < MAX_THREE_B && dst.len() >= 3  {
248         dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
249         dst[1] = (code >>  6 & 0x3F) as u8 | TAG_CONT;
250         dst[2] = (code & 0x3F) as u8 | TAG_CONT;
251         Some(3)
252     } else if dst.len() >= 4 {
253         dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
254         dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
255         dst[2] = (code >>  6 & 0x3F) as u8 | TAG_CONT;
256         dst[3] = (code & 0x3F) as u8 | TAG_CONT;
257         Some(4)
258     } else {
259         None
260     }
261 }
262
263 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
264 /// and then returns the number of `u16`s written.
265 ///
266 /// If the buffer is not large enough, nothing will be written into it
267 /// and a `None` will be returned.
268 #[inline]
269 #[unstable(feature = "char_internals",
270            reason = "this function should not be exposed publicly",
271            issue = "0")]
272 #[doc(hidden)]
273 pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> {
274     // Marked #[inline] to allow llvm optimizing it away
275     if (ch & 0xFFFF) == ch && !dst.is_empty() {
276         // The BMP falls through (assuming non-surrogate, as it should)
277         dst[0] = ch as u16;
278         Some(1)
279     } else if dst.len() >= 2 {
280         // Supplementary planes break into surrogates.
281         ch -= 0x1_0000;
282         dst[0] = 0xD800 | ((ch >> 10) as u16);
283         dst[1] = 0xDC00 | ((ch as u16) & 0x3FF);
284         Some(2)
285     } else {
286         None
287     }
288 }
289
290 /// An iterator over the characters that represent a `char`, as escaped by
291 /// Rust's unicode escaping rules.
292 #[derive(Clone)]
293 #[stable(feature = "rust1", since = "1.0.0")]
294 pub struct EscapeUnicode {
295     c: char,
296     state: EscapeUnicodeState
297 }
298
299 #[derive(Clone)]
300 enum EscapeUnicodeState {
301     Backslash,
302     Type,
303     LeftBrace,
304     Value(usize),
305     RightBrace,
306     Done,
307 }
308
309 #[stable(feature = "rust1", since = "1.0.0")]
310 impl Iterator for EscapeUnicode {
311     type Item = char;
312
313     fn next(&mut self) -> Option<char> {
314         match self.state {
315             EscapeUnicodeState::Backslash => {
316                 self.state = EscapeUnicodeState::Type;
317                 Some('\\')
318             }
319             EscapeUnicodeState::Type => {
320                 self.state = EscapeUnicodeState::LeftBrace;
321                 Some('u')
322             }
323             EscapeUnicodeState::LeftBrace => {
324                 let mut n = 0;
325                 while (self.c as u32) >> (4 * (n + 1)) != 0 {
326                     n += 1;
327                 }
328                 self.state = EscapeUnicodeState::Value(n);
329                 Some('{')
330             }
331             EscapeUnicodeState::Value(offset) => {
332                 let c = from_digit(((self.c as u32) >> (offset * 4)) & 0xf, 16).unwrap();
333                 if offset == 0 {
334                     self.state = EscapeUnicodeState::RightBrace;
335                 } else {
336                     self.state = EscapeUnicodeState::Value(offset - 1);
337                 }
338                 Some(c)
339             }
340             EscapeUnicodeState::RightBrace => {
341                 self.state = EscapeUnicodeState::Done;
342                 Some('}')
343             }
344             EscapeUnicodeState::Done => None,
345         }
346     }
347 }
348
349 /// An iterator over the characters that represent a `char`, escaped
350 /// for maximum portability.
351 #[derive(Clone)]
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub struct EscapeDefault {
354     state: EscapeDefaultState
355 }
356
357 #[derive(Clone)]
358 enum EscapeDefaultState {
359     Backslash(char),
360     Char(char),
361     Done,
362     Unicode(EscapeUnicode),
363 }
364
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl Iterator for EscapeDefault {
367     type Item = char;
368
369     fn next(&mut self) -> Option<char> {
370         match self.state {
371             EscapeDefaultState::Backslash(c) => {
372                 self.state = EscapeDefaultState::Char(c);
373                 Some('\\')
374             }
375             EscapeDefaultState::Char(c) => {
376                 self.state = EscapeDefaultState::Done;
377                 Some(c)
378             }
379             EscapeDefaultState::Done => None,
380             EscapeDefaultState::Unicode(ref mut iter) => iter.next()
381         }
382     }
383 }