]> git.lizzy.rs Git - rust.git/blob - src/libcore/char.rs
9c12b3f68d3de71603f732bdb14a3448d88c554c
[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 ::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 ops::FnMut;
21 use option::Option::{None, Some};
22 use option::Option;
23 use slice::SliceExt;
24
25 // UTF-8 ranges and tags for encoding characters
26 static TAG_CONT: u8    = 0b1000_0000u8;
27 static TAG_TWO_B: u8   = 0b1100_0000u8;
28 static TAG_THREE_B: u8 = 0b1110_0000u8;
29 static TAG_FOUR_B: u8  = 0b1111_0000u8;
30 static MAX_ONE_B: u32   =     0x80u32;
31 static MAX_TWO_B: u32   =    0x800u32;
32 static MAX_THREE_B: u32 =  0x10000u32;
33
34 /*
35     Lu  Uppercase_Letter        an uppercase letter
36     Ll  Lowercase_Letter        a lowercase letter
37     Lt  Titlecase_Letter        a digraphic character, with first part uppercase
38     Lm  Modifier_Letter         a modifier letter
39     Lo  Other_Letter            other letters, including syllables and ideographs
40     Mn  Nonspacing_Mark         a nonspacing combining mark (zero advance width)
41     Mc  Spacing_Mark            a spacing combining mark (positive advance width)
42     Me  Enclosing_Mark          an enclosing combining mark
43     Nd  Decimal_Number          a decimal digit
44     Nl  Letter_Number           a letterlike numeric character
45     No  Other_Number            a numeric character of other type
46     Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
47     Pd  Dash_Punctuation        a dash or hyphen punctuation mark
48     Ps  Open_Punctuation        an opening punctuation mark (of a pair)
49     Pe  Close_Punctuation       a closing punctuation mark (of a pair)
50     Pi  Initial_Punctuation     an initial quotation mark
51     Pf  Final_Punctuation       a final quotation mark
52     Po  Other_Punctuation       a punctuation mark of other type
53     Sm  Math_Symbol             a symbol of primarily mathematical use
54     Sc  Currency_Symbol         a currency sign
55     Sk  Modifier_Symbol         a non-letterlike modifier symbol
56     So  Other_Symbol            a symbol of other type
57     Zs  Space_Separator         a space character (of various non-zero widths)
58     Zl  Line_Separator          U+2028 LINE SEPARATOR only
59     Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
60     Cc  Control                 a C0 or C1 control code
61     Cf  Format                  a format control character
62     Cs  Surrogate               a surrogate code point
63     Co  Private_Use             a private-use character
64     Cn  Unassigned              a reserved unassigned code point or a noncharacter
65 */
66
67 /// The highest valid code point
68 #[stable]
69 pub const MAX: char = '\u{10ffff}';
70
71 /// Converts from `u32` to a `char`
72 #[inline]
73 #[unstable = "pending decisions about costructors for primitives"]
74 pub fn from_u32(i: u32) -> Option<char> {
75     // catch out-of-bounds and surrogates
76     if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
77         None
78     } else {
79         Some(unsafe { transmute(i) })
80     }
81 }
82
83 ///
84 /// Checks if a `char` parses as a numeric digit in the given radix
85 ///
86 /// Compared to `is_numeric()`, this function only recognizes the
87 /// characters `0-9`, `a-z` and `A-Z`.
88 ///
89 /// # Return value
90 ///
91 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
92 /// otherwise.
93 ///
94 /// # Panics
95 ///
96 /// Panics if given a `radix` > 36.
97 ///
98 /// # Note
99 ///
100 /// This just wraps `to_digit()`.
101 ///
102 #[inline]
103 #[deprecated = "use the Char::is_digit method"]
104 pub fn is_digit_radix(c: char, radix: uint) -> bool {
105     c.is_digit(radix)
106 }
107
108 ///
109 /// Converts a `char` to the corresponding digit
110 ///
111 /// # Return value
112 ///
113 /// If `c` is between '0' and '9', the corresponding value
114 /// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
115 /// 'b' or 'B', 11, etc. Returns none if the `char` does not
116 /// refer to a digit in the given radix.
117 ///
118 /// # Panics
119 ///
120 /// Panics if given a `radix` outside the range `[0..36]`.
121 ///
122 #[inline]
123 #[deprecated = "use the Char::to_digit method"]
124 pub fn to_digit(c: char, radix: uint) -> Option<uint> {
125     c.to_digit(radix)
126 }
127
128 ///
129 /// Converts a number to the character representing it
130 ///
131 /// # Return value
132 ///
133 /// Returns `Some(char)` if `num` represents one digit under `radix`,
134 /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
135 ///
136 /// # Panics
137 ///
138 /// Panics if given an `radix` > 36.
139 ///
140 #[inline]
141 #[unstable = "pending decisions about costructors for primitives"]
142 pub fn from_digit(num: uint, radix: uint) -> Option<char> {
143     if radix > 36 {
144         panic!("from_digit: radix is too high (maximum 36)");
145     }
146     if num < radix {
147         unsafe {
148             if num < 10 {
149                 Some(transmute(('0' as uint + num) as u32))
150             } else {
151                 Some(transmute(('a' as uint + num - 10u) as u32))
152             }
153         }
154     } else {
155         None
156     }
157 }
158
159 /// Deprecated, call the escape_unicode method instead.
160 #[deprecated = "use the Char::escape_unicode method"]
161 pub fn escape_unicode<F>(c: char, mut f: F) where F: FnMut(char) {
162     for char in c.escape_unicode() {
163         f(char);
164     }
165 }
166
167 /// Deprecated, call the escape_default method instead.
168 #[deprecated = "use the Char::escape_default method"]
169 pub fn escape_default<F>(c: char, mut f: F) where F: FnMut(char) {
170     for c in c.escape_default() {
171         f(c);
172     }
173 }
174
175 /// Returns the amount of bytes this `char` would need if encoded in UTF-8
176 #[inline]
177 #[deprecated = "use the Char::len_utf8 method"]
178 pub fn len_utf8_bytes(c: char) -> uint {
179     c.len_utf8()
180 }
181
182 /// Basic `char` manipulations.
183 #[experimental = "trait organization may change"]
184 pub trait Char {
185     /// Checks if a `char` parses as a numeric digit in the given radix.
186     ///
187     /// Compared to `is_numeric()`, this function only recognizes the characters
188     /// `0-9`, `a-z` and `A-Z`.
189     ///
190     /// # Return value
191     ///
192     /// Returns `true` if `c` is a valid digit under `radix`, and `false`
193     /// otherwise.
194     ///
195     /// # Panics
196     ///
197     /// Panics if given a radix > 36.
198     #[deprecated = "use is_digit"]
199     fn is_digit_radix(self, radix: uint) -> bool;
200
201     /// Checks if a `char` parses as a numeric digit in the given radix.
202     ///
203     /// Compared to `is_numeric()`, this function only recognizes the characters
204     /// `0-9`, `a-z` and `A-Z`.
205     ///
206     /// # Return value
207     ///
208     /// Returns `true` if `c` is a valid digit under `radix`, and `false`
209     /// otherwise.
210     ///
211     /// # Panics
212     ///
213     /// Panics if given a radix > 36.
214     #[unstable = "pending error conventions"]
215     fn is_digit(self, radix: uint) -> bool;
216
217     /// Converts a character to the corresponding digit.
218     ///
219     /// # Return value
220     ///
221     /// If `c` is between '0' and '9', the corresponding value between 0 and
222     /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
223     /// none if the character does not refer to a digit in the given radix.
224     ///
225     /// # Panics
226     ///
227     /// Panics if given a radix outside the range [0..36].
228     #[unstable = "pending error conventions, trait organization"]
229     fn to_digit(self, radix: uint) -> Option<uint>;
230
231     /// Converts a number to the character representing it.
232     ///
233     /// # Return value
234     ///
235     /// Returns `Some(char)` if `num` represents one digit under `radix`,
236     /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
237     ///
238     /// # Panics
239     ///
240     /// Panics if given a radix > 36.
241     #[deprecated = "use the char::from_digit free function"]
242     fn from_digit(num: uint, radix: uint) -> Option<Self>;
243
244     /// Converts from `u32` to a `char`
245     #[deprecated = "use the char::from_u32 free function"]
246     fn from_u32(i: u32) -> Option<char>;
247
248     /// Returns an iterator that yields the hexadecimal Unicode escape
249     /// of a character, as `char`s.
250     ///
251     /// All characters are escaped with Rust syntax of the form `\\u{NNNN}`
252     /// where `NNNN` is the shortest hexadecimal representation of the code
253     /// point.
254     #[unstable = "pending error conventions, trait organization"]
255     fn escape_unicode(self) -> EscapeUnicode;
256
257     /// Returns an iterator that yields the 'default' ASCII and
258     /// C++11-like literal escape of a character, as `char`s.
259     ///
260     /// The default is chosen with a bias toward producing literals that are
261     /// legal in a variety of languages, including C++11 and similar C-family
262     /// languages. The exact rules are:
263     ///
264     /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
265     /// * Single-quote, double-quote and backslash chars are backslash-
266     ///   escaped.
267     /// * Any other chars in the range [0x20,0x7e] are not escaped.
268     /// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
269     #[unstable = "pending error conventions, trait organization"]
270     fn escape_default(self) -> EscapeDefault;
271
272     /// Returns the amount of bytes this character would need if encoded in
273     /// UTF-8.
274     #[deprecated = "use len_utf8"]
275     fn len_utf8_bytes(self) -> uint;
276
277     /// Returns the amount of bytes this character would need if encoded in
278     /// UTF-8.
279     #[unstable = "pending trait organization"]
280     fn len_utf8(self) -> uint;
281
282     /// Returns the amount of bytes this character would need if encoded in
283     /// UTF-16.
284     #[unstable = "pending trait organization"]
285     fn len_utf16(self) -> uint;
286
287     /// Encodes this character as UTF-8 into the provided byte buffer,
288     /// and then returns the number of bytes written.
289     ///
290     /// If the buffer is not large enough, nothing will be written into it
291     /// and a `None` will be returned.
292     #[unstable = "pending trait organization"]
293     fn encode_utf8(&self, dst: &mut [u8]) -> Option<uint>;
294
295     /// Encodes this character as UTF-16 into the provided `u16` buffer,
296     /// and then returns the number of `u16`s written.
297     ///
298     /// If the buffer is not large enough, nothing will be written into it
299     /// and a `None` will be returned.
300     #[unstable = "pending trait organization"]
301     fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint>;
302 }
303
304 #[experimental = "trait is experimental"]
305 impl Char for char {
306     #[deprecated = "use is_digit"]
307     fn is_digit_radix(self, radix: uint) -> bool { self.is_digit(radix) }
308
309     #[unstable = "pending trait organization"]
310     fn is_digit(self, radix: uint) -> bool {
311         match self.to_digit(radix) {
312             Some(_) => true,
313             None    => false,
314         }
315     }
316
317     #[unstable = "pending trait organization"]
318     fn to_digit(self, radix: uint) -> Option<uint> {
319         if radix > 36 {
320             panic!("to_digit: radix is too high (maximum 36)");
321         }
322         let val = match self {
323           '0' ... '9' => self as uint - ('0' as uint),
324           'a' ... 'z' => self as uint + 10u - ('a' as uint),
325           'A' ... 'Z' => self as uint + 10u - ('A' as uint),
326           _ => return None,
327         };
328         if val < radix { Some(val) }
329         else { None }
330     }
331
332     #[deprecated = "use the char::from_digit free function"]
333     fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
334
335     #[inline]
336     #[deprecated = "use the char::from_u32 free function"]
337     fn from_u32(i: u32) -> Option<char> { from_u32(i) }
338
339     #[unstable = "pending error conventions, trait organization"]
340     fn escape_unicode(self) -> EscapeUnicode {
341         EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
342     }
343
344     #[unstable = "pending error conventions, trait organization"]
345     fn escape_default(self) -> EscapeDefault {
346         let init_state = match self {
347             '\t' => EscapeDefaultState::Backslash('t'),
348             '\r' => EscapeDefaultState::Backslash('r'),
349             '\n' => EscapeDefaultState::Backslash('n'),
350             '\\' => EscapeDefaultState::Backslash('\\'),
351             '\'' => EscapeDefaultState::Backslash('\''),
352             '"'  => EscapeDefaultState::Backslash('"'),
353             '\x20' ... '\x7e' => EscapeDefaultState::Char(self),
354             _ => EscapeDefaultState::Unicode(self.escape_unicode())
355         };
356         EscapeDefault { state: init_state }
357     }
358
359     #[inline]
360     #[deprecated = "use len_utf8"]
361     fn len_utf8_bytes(self) -> uint { self.len_utf8() }
362
363     #[inline]
364     #[unstable = "pending trait organization"]
365     fn len_utf8(self) -> uint {
366         let code = self as u32;
367         match () {
368             _ if code < MAX_ONE_B   => 1u,
369             _ if code < MAX_TWO_B   => 2u,
370             _ if code < MAX_THREE_B => 3u,
371             _  => 4u,
372         }
373     }
374
375     #[inline]
376     #[unstable = "pending trait organization"]
377     fn len_utf16(self) -> uint {
378         let ch = self as u32;
379         if (ch & 0xFFFF_u32) == ch { 1 } else { 2 }
380     }
381
382     #[inline]
383     #[unstable = "pending error conventions, trait organization"]
384     fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
385         // Marked #[inline] to allow llvm optimizing it away
386         let code = *self as u32;
387         if code < MAX_ONE_B && dst.len() >= 1 {
388             dst[0] = code as u8;
389             Some(1)
390         } else if code < MAX_TWO_B && dst.len() >= 2 {
391             dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
392             dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
393             Some(2)
394         } else if code < MAX_THREE_B && dst.len() >= 3  {
395             dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
396             dst[1] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
397             dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
398             Some(3)
399         } else if dst.len() >= 4 {
400             dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
401             dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
402             dst[2] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
403             dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
404             Some(4)
405         } else {
406             None
407         }
408     }
409
410     #[inline]
411     #[unstable = "pending error conventions, trait organization"]
412     fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint> {
413         // Marked #[inline] to allow llvm optimizing it away
414         let mut ch = *self as u32;
415         if (ch & 0xFFFF_u32) == ch  && dst.len() >= 1 {
416             // The BMP falls through (assuming non-surrogate, as it should)
417             dst[0] = ch as u16;
418             Some(1)
419         } else if dst.len() >= 2 {
420             // Supplementary planes break into surrogates.
421             ch -= 0x1_0000_u32;
422             dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
423             dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
424             Some(2)
425         } else {
426             None
427         }
428     }
429 }
430
431 /// An iterator over the characters that represent a `char`, as escaped by
432 /// Rust's unicode escaping rules.
433 pub struct EscapeUnicode {
434     c: char,
435     state: EscapeUnicodeState
436 }
437
438 enum EscapeUnicodeState {
439     Backslash,
440     Type,
441     LeftBrace,
442     Value(uint),
443     RightBrace,
444     Done,
445 }
446
447 impl Iterator<char> for EscapeUnicode {
448     fn next(&mut self) -> Option<char> {
449         match self.state {
450             EscapeUnicodeState::Backslash => {
451                 self.state = EscapeUnicodeState::Type;
452                 Some('\\')
453             }
454             EscapeUnicodeState::Type => {
455                 self.state = EscapeUnicodeState::LeftBrace;
456                 Some('u')
457             }
458             EscapeUnicodeState::LeftBrace => {
459                 let mut n = 0u;
460                 while (self.c as u32) >> (4 * (n + 1)) != 0 {
461                     n += 1;
462                 }
463                 self.state = EscapeUnicodeState::Value(n);
464                 Some('{')
465             }
466             EscapeUnicodeState::Value(offset) => {
467                 let v = match ((self.c as i32) >> (offset * 4)) & 0xf {
468                     i @ 0 ... 9 => '0' as i32 + i,
469                     i => 'a' as i32 + (i - 10)
470                 };
471                 if offset == 0 {
472                     self.state = EscapeUnicodeState::RightBrace;
473                 } else {
474                     self.state = EscapeUnicodeState::Value(offset - 1);
475                 }
476                 Some(unsafe { transmute(v) })
477             }
478             EscapeUnicodeState::RightBrace => {
479                 self.state = EscapeUnicodeState::Done;
480                 Some('}')
481             }
482             EscapeUnicodeState::Done => None,
483         }
484     }
485 }
486
487 /// An iterator over the characters that represent a `char`, escaped
488 /// for maximum portability.
489 pub struct EscapeDefault {
490     state: EscapeDefaultState
491 }
492
493 enum EscapeDefaultState {
494     Backslash(char),
495     Char(char),
496     Done,
497     Unicode(EscapeUnicode),
498 }
499
500 impl Iterator<char> for EscapeDefault {
501     fn next(&mut self) -> Option<char> {
502         match self.state {
503             EscapeDefaultState::Backslash(c) => {
504                 self.state = EscapeDefaultState::Char(c);
505                 Some('\\')
506             }
507             EscapeDefaultState::Char(c) => {
508                 self.state = EscapeDefaultState::Done;
509                 Some(c)
510             }
511             EscapeDefaultState::Done => None,
512             EscapeDefaultState::Unicode(ref mut iter) => iter.next()
513         }
514     }
515 }
516