]> git.lizzy.rs Git - rust.git/blob - src/libcore/char.rs
df371752b8651c9680f59ae6ee32d277ef06c29d
[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 #![doc(primitive = "char")]
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 { transmute(i) })
88     }
89 }
90
91 /// Converts a number to the character representing it.
92 ///
93 /// # Return value
94 ///
95 /// Returns `Some(char)` if `num` represents one digit under `radix`,
96 /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
97 ///
98 /// # Panics
99 ///
100 /// Panics if given an `radix` > 36.
101 ///
102 /// # Examples
103 ///
104 /// ```
105 /// use std::char;
106 ///
107 /// let c = char::from_digit(4, 10);
108 ///
109 /// assert_eq!(c, Some('4'));
110 /// ```
111 #[inline]
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub fn from_digit(num: u32, radix: u32) -> Option<char> {
114     if radix > 36 {
115         panic!("from_digit: radix is too high (maximum 36)");
116     }
117     if num < radix {
118         unsafe {
119             if num < 10 {
120                 Some(transmute('0' as u32 + num))
121             } else {
122                 Some(transmute('a' as u32 + num - 10))
123             }
124         }
125     } else {
126         None
127     }
128 }
129
130 // NB: the stabilization and documentation for this trait is in
131 // unicode/char.rs, not here
132 #[allow(missing_docs)] // docs in libunicode/u_char.rs
133 #[doc(hidden)]
134 pub trait CharExt {
135     fn is_digit(self, radix: u32) -> bool;
136     fn to_digit(self, radix: u32) -> Option<u32>;
137     fn escape_unicode(self) -> EscapeUnicode;
138     fn escape_default(self) -> EscapeDefault;
139     fn len_utf8(self) -> usize;
140     fn len_utf16(self) -> usize;
141     fn encode_utf8(self, dst: &mut [u8]) -> Option<usize>;
142     fn encode_utf16(self, dst: &mut [u16]) -> Option<usize>;
143 }
144
145 impl CharExt for char {
146     #[inline]
147     fn is_digit(self, radix: u32) -> bool {
148         self.to_digit(radix).is_some()
149     }
150
151     #[inline]
152     fn to_digit(self, radix: u32) -> Option<u32> {
153         if radix > 36 {
154             panic!("to_digit: radix is too high (maximum 36)");
155         }
156         let val = match self {
157           '0' ... '9' => self as u32 - '0' as u32,
158           'a' ... 'z' => self as u32 - 'a' as u32 + 10,
159           'A' ... 'Z' => self as u32 - 'A' as u32 + 10,
160           _ => return None,
161         };
162         if val < radix { Some(val) }
163         else { None }
164     }
165
166     #[inline]
167     fn escape_unicode(self) -> EscapeUnicode {
168         EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
169     }
170
171     #[inline]
172     fn escape_default(self) -> EscapeDefault {
173         let init_state = match self {
174             '\t' => EscapeDefaultState::Backslash('t'),
175             '\r' => EscapeDefaultState::Backslash('r'),
176             '\n' => EscapeDefaultState::Backslash('n'),
177             '\\' => EscapeDefaultState::Backslash('\\'),
178             '\'' => EscapeDefaultState::Backslash('\''),
179             '"'  => EscapeDefaultState::Backslash('"'),
180             '\x20' ... '\x7e' => EscapeDefaultState::Char(self),
181             _ => EscapeDefaultState::Unicode(self.escape_unicode())
182         };
183         EscapeDefault { state: init_state }
184     }
185
186     #[inline]
187     fn len_utf8(self) -> usize {
188         let code = self as u32;
189         if code < MAX_ONE_B {
190             1
191         } else if code < MAX_TWO_B {
192             2
193         } else if code < MAX_THREE_B {
194             3
195         } else {
196             4
197         }
198     }
199
200     #[inline]
201     fn len_utf16(self) -> usize {
202         let ch = self as u32;
203         if (ch & 0xFFFF) == ch { 1 } else { 2 }
204     }
205
206     #[inline]
207     fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> {
208         encode_utf8_raw(self as u32, dst)
209     }
210
211     #[inline]
212     fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> {
213         encode_utf16_raw(self as u32, dst)
214     }
215 }
216
217 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
218 /// and then returns the number of bytes written.
219 ///
220 /// If the buffer is not large enough, nothing will be written into it
221 /// and a `None` will be returned.
222 #[inline]
223 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> {
224     // Marked #[inline] to allow llvm optimizing it away
225     if code < MAX_ONE_B && !dst.is_empty() {
226         dst[0] = code as u8;
227         Some(1)
228     } else if code < MAX_TWO_B && dst.len() >= 2 {
229         dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
230         dst[1] = (code & 0x3F) as u8 | TAG_CONT;
231         Some(2)
232     } else if code < MAX_THREE_B && dst.len() >= 3  {
233         dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
234         dst[1] = (code >>  6 & 0x3F) as u8 | TAG_CONT;
235         dst[2] = (code & 0x3F) as u8 | TAG_CONT;
236         Some(3)
237     } else if dst.len() >= 4 {
238         dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
239         dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
240         dst[2] = (code >>  6 & 0x3F) as u8 | TAG_CONT;
241         dst[3] = (code & 0x3F) as u8 | TAG_CONT;
242         Some(4)
243     } else {
244         None
245     }
246 }
247
248 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
249 /// and then returns the number of `u16`s written.
250 ///
251 /// If the buffer is not large enough, nothing will be written into it
252 /// and a `None` will be returned.
253 #[inline]
254 pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> {
255     // Marked #[inline] to allow llvm optimizing it away
256     if (ch & 0xFFFF) == ch && !dst.is_empty() {
257         // The BMP falls through (assuming non-surrogate, as it should)
258         dst[0] = ch as u16;
259         Some(1)
260     } else if dst.len() >= 2 {
261         // Supplementary planes break into surrogates.
262         ch -= 0x1_0000;
263         dst[0] = 0xD800 | ((ch >> 10) as u16);
264         dst[1] = 0xDC00 | ((ch as u16) & 0x3FF);
265         Some(2)
266     } else {
267         None
268     }
269 }
270
271 /// An iterator over the characters that represent a `char`, as escaped by
272 /// Rust's unicode escaping rules.
273 #[derive(Clone)]
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub struct EscapeUnicode {
276     c: char,
277     state: EscapeUnicodeState
278 }
279
280 #[derive(Clone)]
281 enum EscapeUnicodeState {
282     Backslash,
283     Type,
284     LeftBrace,
285     Value(usize),
286     RightBrace,
287     Done,
288 }
289
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl Iterator for EscapeUnicode {
292     type Item = char;
293
294     fn next(&mut self) -> Option<char> {
295         match self.state {
296             EscapeUnicodeState::Backslash => {
297                 self.state = EscapeUnicodeState::Type;
298                 Some('\\')
299             }
300             EscapeUnicodeState::Type => {
301                 self.state = EscapeUnicodeState::LeftBrace;
302                 Some('u')
303             }
304             EscapeUnicodeState::LeftBrace => {
305                 let mut n = 0;
306                 while (self.c as u32) >> (4 * (n + 1)) != 0 {
307                     n += 1;
308                 }
309                 self.state = EscapeUnicodeState::Value(n);
310                 Some('{')
311             }
312             EscapeUnicodeState::Value(offset) => {
313                 let v = match ((self.c as i32) >> (offset * 4)) & 0xf {
314                     i @ 0 ... 9 => '0' as i32 + i,
315                     i => 'a' as i32 + (i - 10)
316                 };
317                 if offset == 0 {
318                     self.state = EscapeUnicodeState::RightBrace;
319                 } else {
320                     self.state = EscapeUnicodeState::Value(offset - 1);
321                 }
322                 Some(unsafe { transmute(v) })
323             }
324             EscapeUnicodeState::RightBrace => {
325                 self.state = EscapeUnicodeState::Done;
326                 Some('}')
327             }
328             EscapeUnicodeState::Done => None,
329         }
330     }
331 }
332
333 /// An iterator over the characters that represent a `char`, escaped
334 /// for maximum portability.
335 #[derive(Clone)]
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub struct EscapeDefault {
338     state: EscapeDefaultState
339 }
340
341 #[derive(Clone)]
342 enum EscapeDefaultState {
343     Backslash(char),
344     Char(char),
345     Done,
346     Unicode(EscapeUnicode),
347 }
348
349 #[stable(feature = "rust1", since = "1.0.0")]
350 impl Iterator for EscapeDefault {
351     type Item = char;
352
353     fn next(&mut self) -> Option<char> {
354         match self.state {
355             EscapeDefaultState::Backslash(c) => {
356                 self.state = EscapeDefaultState::Char(c);
357                 Some('\\')
358             }
359             EscapeDefaultState::Char(c) => {
360                 self.state = EscapeDefaultState::Done;
361                 Some(c)
362             }
363             EscapeDefaultState::Done => None,
364             EscapeDefaultState::Unicode(ref mut iter) => iter.next()
365         }
366     }
367 }