]> git.lizzy.rs Git - rust.git/blob - src/libstd/char.rs
auto merge of #11304 : alexcrichton/rust/eintr, r=brson
[rust.git] / src / libstd / char.rs
1 // Copyright 2012-2013 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 //! Unicode characters manipulation (`char` type)
12
13 use cast::transmute;
14 use option::{None, Option, Some};
15 use iter::{Iterator, range_step};
16 use str::StrSlice;
17 use unicode::{derived_property, property, general_category, decompose};
18 use to_str::ToStr;
19 use str;
20
21 #[cfg(test)] use str::OwnedStr;
22
23 #[cfg(not(test))] use cmp::{Eq, Ord};
24 #[cfg(not(test))] use default::Default;
25 #[cfg(not(test))] use num::Zero;
26
27 // UTF-8 ranges and tags for encoding characters
28 static TAG_CONT: uint = 128u;
29 static MAX_ONE_B: uint = 128u;
30 static TAG_TWO_B: uint = 192u;
31 static MAX_TWO_B: uint = 2048u;
32 static TAG_THREE_B: uint = 224u;
33 static MAX_THREE_B: uint = 65536u;
34 static TAG_FOUR_B: uint = 240u;
35
36 /*
37     Lu  Uppercase_Letter        an uppercase letter
38     Ll  Lowercase_Letter        a lowercase letter
39     Lt  Titlecase_Letter        a digraphic character, with first part uppercase
40     Lm  Modifier_Letter         a modifier letter
41     Lo  Other_Letter            other letters, including syllables and ideographs
42     Mn  Nonspacing_Mark         a nonspacing combining mark (zero advance width)
43     Mc  Spacing_Mark            a spacing combining mark (positive advance width)
44     Me  Enclosing_Mark          an enclosing combining mark
45     Nd  Decimal_Number          a decimal digit
46     Nl  Letter_Number           a letterlike numeric character
47     No  Other_Number            a numeric character of other type
48     Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
49     Pd  Dash_Punctuation        a dash or hyphen punctuation mark
50     Ps  Open_Punctuation        an opening punctuation mark (of a pair)
51     Pe  Close_Punctuation       a closing punctuation mark (of a pair)
52     Pi  Initial_Punctuation     an initial quotation mark
53     Pf  Final_Punctuation       a final quotation mark
54     Po  Other_Punctuation       a punctuation mark of other type
55     Sm  Math_Symbol             a symbol of primarily mathematical use
56     Sc  Currency_Symbol         a currency sign
57     Sk  Modifier_Symbol         a non-letterlike modifier symbol
58     So  Other_Symbol            a symbol of other type
59     Zs  Space_Separator         a space character (of various non-zero widths)
60     Zl  Line_Separator          U+2028 LINE SEPARATOR only
61     Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
62     Cc  Control                 a C0 or C1 control code
63     Cf  Format                  a format control character
64     Cs  Surrogate               a surrogate code point
65     Co  Private_Use             a private-use character
66     Cn  Unassigned              a reserved unassigned code point or a noncharacter
67 */
68
69 /// The highest valid code point
70 pub static MAX: char = '\U0010ffff';
71
72 /// Convert from `u32` to a character.
73 pub fn from_u32(i: u32) -> Option<char> {
74     // catch out-of-bounds and surrogates
75     if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
76         None
77     } else {
78         Some(unsafe { transmute(i) })
79     }
80 }
81
82 /// Returns whether the specified character is considered a unicode alphabetic
83 /// character
84 pub fn is_alphabetic(c: char) -> bool   { derived_property::Alphabetic(c) }
85 #[allow(missing_doc)]
86 pub fn is_XID_start(c: char) -> bool    { derived_property::XID_Start(c) }
87 #[allow(missing_doc)]
88 pub fn is_XID_continue(c: char) -> bool { derived_property::XID_Continue(c) }
89
90 ///
91 /// Indicates whether a character is in lower case, defined
92 /// in terms of the Unicode Derived Core Property 'Lowercase'.
93 ///
94 #[inline]
95 pub fn is_lowercase(c: char) -> bool { derived_property::Lowercase(c) }
96
97 ///
98 /// Indicates whether a character is in upper case, defined
99 /// in terms of the Unicode Derived Core Property 'Uppercase'.
100 ///
101 #[inline]
102 pub fn is_uppercase(c: char) -> bool { derived_property::Uppercase(c) }
103
104 ///
105 /// Indicates whether a character is whitespace. Whitespace is defined in
106 /// terms of the Unicode Property 'White_Space'.
107 ///
108 #[inline]
109 pub fn is_whitespace(c: char) -> bool {
110     // As an optimization ASCII whitespace characters are checked separately
111     c == ' '
112         || ('\x09' <= c && c <= '\x0d')
113         || property::White_Space(c)
114 }
115
116 ///
117 /// Indicates whether a character is alphanumeric. Alphanumericness is
118 /// defined in terms of the Unicode General Categories 'Nd', 'Nl', 'No'
119 /// and the Derived Core Property 'Alphabetic'.
120 ///
121 #[inline]
122 pub fn is_alphanumeric(c: char) -> bool {
123     derived_property::Alphabetic(c)
124         || general_category::Nd(c)
125         || general_category::Nl(c)
126         || general_category::No(c)
127 }
128
129 ///
130 /// Indicates whether a character is a control character. Control
131 /// characters are defined in terms of the Unicode General Category
132 /// 'Cc'.
133 ///
134 #[inline]
135 pub fn is_control(c: char) -> bool { general_category::Cc(c) }
136
137 /// Indicates whether the character is numeric (Nd, Nl, or No)
138 #[inline]
139 pub fn is_digit(c: char) -> bool {
140     general_category::Nd(c)
141         || general_category::Nl(c)
142         || general_category::No(c)
143 }
144
145 ///
146 /// Checks if a character parses as a numeric digit in the given radix.
147 /// Compared to `is_digit()`, this function only recognizes the
148 /// characters `0-9`, `a-z` and `A-Z`.
149 ///
150 /// # Return value
151 ///
152 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
153 /// otherwise.
154 ///
155 /// # Failure
156 ///
157 /// Fails if given a `radix` > 36.
158 ///
159 /// # Note
160 ///
161 /// This just wraps `to_digit()`.
162 ///
163 #[inline]
164 pub fn is_digit_radix(c: char, radix: uint) -> bool {
165     match to_digit(c, radix) {
166         Some(_) => true,
167         None    => false,
168     }
169 }
170
171 ///
172 /// Convert a char to the corresponding digit.
173 ///
174 /// # Return value
175 ///
176 /// If `c` is between '0' and '9', the corresponding value
177 /// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
178 /// 'b' or 'B', 11, etc. Returns none if the char does not
179 /// refer to a digit in the given radix.
180 ///
181 /// # Failure
182 ///
183 /// Fails if given a `radix` outside the range `[0..36]`.
184 ///
185 #[inline]
186 pub fn to_digit(c: char, radix: uint) -> Option<uint> {
187     if radix > 36 {
188         fail!("to_digit: radix {} is too high (maximum 36)", radix);
189     }
190     let val = match c {
191       '0' .. '9' => c as uint - ('0' as uint),
192       'a' .. 'z' => c as uint + 10u - ('a' as uint),
193       'A' .. 'Z' => c as uint + 10u - ('A' as uint),
194       _ => return None,
195     };
196     if val < radix { Some(val) }
197     else { None }
198 }
199
200 ///
201 /// Converts a number to the character representing it.
202 ///
203 /// # Return value
204 ///
205 /// Returns `Some(char)` if `num` represents one digit under `radix`,
206 /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
207 ///
208 /// # Failure
209 ///
210 /// Fails if given an `radix` > 36.
211 ///
212 #[inline]
213 pub fn from_digit(num: uint, radix: uint) -> Option<char> {
214     if radix > 36 {
215         fail!("from_digit: radix {} is to high (maximum 36)", num);
216     }
217     if num < radix {
218         unsafe {
219             if num < 10 {
220                 Some(transmute(('0' as uint + num) as u32))
221             } else {
222                 Some(transmute(('a' as uint + num - 10u) as u32))
223             }
224         }
225     } else {
226         None
227     }
228 }
229
230 // Constants from Unicode 6.2.0 Section 3.12 Conjoining Jamo Behavior
231 static S_BASE: uint = 0xAC00;
232 static L_BASE: uint = 0x1100;
233 static V_BASE: uint = 0x1161;
234 static T_BASE: uint = 0x11A7;
235 static L_COUNT: uint = 19;
236 static V_COUNT: uint = 21;
237 static T_COUNT: uint = 28;
238 static N_COUNT: uint = (V_COUNT * T_COUNT);
239 static S_COUNT: uint = (L_COUNT * N_COUNT);
240
241 // Decompose a precomposed Hangul syllable
242 fn decompose_hangul(s: char, f: |char|) {
243     let si = s as uint - S_BASE;
244
245     let li = si / N_COUNT;
246     unsafe {
247         f(transmute((L_BASE + li) as u32));
248
249         let vi = (si % N_COUNT) / T_COUNT;
250         f(transmute((V_BASE + vi) as u32));
251
252         let ti = si % T_COUNT;
253         if ti > 0 {
254             f(transmute((T_BASE + ti) as u32));
255         }
256     }
257 }
258
259 /// Returns the canonical decomposition of a character.
260 pub fn decompose_canonical(c: char, f: |char|) {
261     if (c as uint) < S_BASE || (c as uint) >= (S_BASE + S_COUNT) {
262         decompose::canonical(c, f);
263     } else {
264         decompose_hangul(c, f);
265     }
266 }
267
268 /// Returns the compatibility decomposition of a character.
269 pub fn decompose_compatible(c: char, f: |char|) {
270     if (c as uint) < S_BASE || (c as uint) >= (S_BASE + S_COUNT) {
271         decompose::compatibility(c, f);
272     } else {
273         decompose_hangul(c, f);
274     }
275 }
276
277 ///
278 /// Return the hexadecimal unicode escape of a char.
279 ///
280 /// The rules are as follows:
281 ///
282 /// - chars in [0,0xff] get 2-digit escapes: `\\xNN`
283 /// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`
284 /// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`
285 ///
286 pub fn escape_unicode(c: char, f: |char|) {
287     // avoid calling str::to_str_radix because we don't really need to allocate
288     // here.
289     f('\\');
290     let pad = match () {
291         _ if c <= '\xff'    => { f('x'); 2 }
292         _ if c <= '\uffff'  => { f('u'); 4 }
293         _                   => { f('U'); 8 }
294     };
295     for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
296         unsafe {
297             match ((c as i32) >> offset) & 0xf {
298                 i @ 0 .. 9 => { f(transmute('0' as i32 + i)); }
299                 i => { f(transmute('a' as i32 + (i - 10))); }
300             }
301         }
302     }
303 }
304
305 ///
306 /// Return a 'default' ASCII and C++11-like char-literal escape of a char.
307 ///
308 /// The default is chosen with a bias toward producing literals that are
309 /// legal in a variety of languages, including C++11 and similar C-family
310 /// languages. The exact rules are:
311 ///
312 /// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
313 /// - Single-quote, double-quote and backslash chars are backslash-escaped.
314 /// - Any other chars in the range [0x20,0x7e] are not escaped.
315 /// - Any other chars are given hex unicode escapes; see `escape_unicode`.
316 ///
317 pub fn escape_default(c: char, f: |char|) {
318     match c {
319         '\t' => { f('\\'); f('t'); }
320         '\r' => { f('\\'); f('r'); }
321         '\n' => { f('\\'); f('n'); }
322         '\\' => { f('\\'); f('\\'); }
323         '\'' => { f('\\'); f('\''); }
324         '"'  => { f('\\'); f('"'); }
325         '\x20' .. '\x7e' => { f(c); }
326         _ => c.escape_unicode(f),
327     }
328 }
329
330 /// Returns the amount of bytes this character would need if encoded in utf8
331 pub fn len_utf8_bytes(c: char) -> uint {
332     static MAX_ONE_B:   uint = 128u;
333     static MAX_TWO_B:   uint = 2048u;
334     static MAX_THREE_B: uint = 65536u;
335     static MAX_FOUR_B:  uint = 2097152u;
336
337     let code = c as uint;
338     match () {
339         _ if code < MAX_ONE_B   => 1u,
340         _ if code < MAX_TWO_B   => 2u,
341         _ if code < MAX_THREE_B => 3u,
342         _ if code < MAX_FOUR_B  => 4u,
343         _                       => fail!("invalid character!"),
344     }
345 }
346
347 impl ToStr for char {
348     #[inline]
349     fn to_str(&self) -> ~str {
350         str::from_char(*self)
351     }
352 }
353
354 #[allow(missing_doc)]
355 pub trait Char {
356     fn is_alphabetic(&self) -> bool;
357     fn is_XID_start(&self) -> bool;
358     fn is_XID_continue(&self) -> bool;
359     fn is_lowercase(&self) -> bool;
360     fn is_uppercase(&self) -> bool;
361     fn is_whitespace(&self) -> bool;
362     fn is_alphanumeric(&self) -> bool;
363     fn is_control(&self) -> bool;
364     fn is_digit(&self) -> bool;
365     fn is_digit_radix(&self, radix: uint) -> bool;
366     fn to_digit(&self, radix: uint) -> Option<uint>;
367     fn from_digit(num: uint, radix: uint) -> Option<char>;
368     fn escape_unicode(&self, f: |char|);
369     fn escape_default(&self, f: |char|);
370     fn len_utf8_bytes(&self) -> uint;
371
372     /// Encodes this character as utf-8 into the provided byte-buffer. The
373     /// buffer must be at least 4 bytes long or a runtime failure will occur.
374     ///
375     /// This will then return the number of characters written to the slice.
376     fn encode_utf8(&self, dst: &mut [u8]) -> uint;
377 }
378
379 impl Char for char {
380     fn is_alphabetic(&self) -> bool { is_alphabetic(*self) }
381
382     fn is_XID_start(&self) -> bool { is_XID_start(*self) }
383
384     fn is_XID_continue(&self) -> bool { is_XID_continue(*self) }
385
386     fn is_lowercase(&self) -> bool { is_lowercase(*self) }
387
388     fn is_uppercase(&self) -> bool { is_uppercase(*self) }
389
390     fn is_whitespace(&self) -> bool { is_whitespace(*self) }
391
392     fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
393
394     fn is_control(&self) -> bool { is_control(*self) }
395
396     fn is_digit(&self) -> bool { is_digit(*self) }
397
398     fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
399
400     fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
401
402     fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
403
404     fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
405
406     fn escape_default(&self, f: |char|) { escape_default(*self, f) }
407
408     fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
409
410     fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> uint {
411         let code = *self as uint;
412         if code < MAX_ONE_B {
413             dst[0] = code as u8;
414             return 1;
415         } else if code < MAX_TWO_B {
416             dst[0] = (code >> 6u & 31u | TAG_TWO_B) as u8;
417             dst[1] = (code & 63u | TAG_CONT) as u8;
418             return 2;
419         } else if code < MAX_THREE_B {
420             dst[0] = (code >> 12u & 15u | TAG_THREE_B) as u8;
421             dst[1] = (code >> 6u & 63u | TAG_CONT) as u8;
422             dst[2] = (code & 63u | TAG_CONT) as u8;
423             return 3;
424         } else {
425             dst[0] = (code >> 18u & 7u | TAG_FOUR_B) as u8;
426             dst[1] = (code >> 12u & 63u | TAG_CONT) as u8;
427             dst[2] = (code >> 6u & 63u | TAG_CONT) as u8;
428             dst[3] = (code & 63u | TAG_CONT) as u8;
429             return 4;
430         }
431     }
432 }
433
434 #[cfg(not(test))]
435 impl Eq for char {
436     #[inline]
437     fn eq(&self, other: &char) -> bool { (*self) == (*other) }
438 }
439
440 #[cfg(not(test))]
441 impl Ord for char {
442     #[inline]
443     fn lt(&self, other: &char) -> bool { *self < *other }
444 }
445
446 #[cfg(not(test))]
447 impl Default for char {
448     #[inline]
449     fn default() -> char { '\x00' }
450 }
451
452 #[cfg(not(test))]
453 impl Zero for char {
454     #[inline]
455     fn zero() -> char { '\x00' }
456
457     #[inline]
458     fn is_zero(&self) -> bool { *self == '\x00' }
459 }
460
461 #[test]
462 fn test_is_lowercase() {
463     assert!('a'.is_lowercase());
464     assert!('ö'.is_lowercase());
465     assert!('ß'.is_lowercase());
466     assert!(!'Ü'.is_lowercase());
467     assert!(!'P'.is_lowercase());
468 }
469
470 #[test]
471 fn test_is_uppercase() {
472     assert!(!'h'.is_uppercase());
473     assert!(!'ä'.is_uppercase());
474     assert!(!'ß'.is_uppercase());
475     assert!('Ö'.is_uppercase());
476     assert!('T'.is_uppercase());
477 }
478
479 #[test]
480 fn test_is_whitespace() {
481     assert!(' '.is_whitespace());
482     assert!('\u2007'.is_whitespace());
483     assert!('\t'.is_whitespace());
484     assert!('\n'.is_whitespace());
485     assert!(!'a'.is_whitespace());
486     assert!(!'_'.is_whitespace());
487     assert!(!'\u0000'.is_whitespace());
488 }
489
490 #[test]
491 fn test_to_digit() {
492     assert_eq!('0'.to_digit(10u), Some(0u));
493     assert_eq!('1'.to_digit(2u), Some(1u));
494     assert_eq!('2'.to_digit(3u), Some(2u));
495     assert_eq!('9'.to_digit(10u), Some(9u));
496     assert_eq!('a'.to_digit(16u), Some(10u));
497     assert_eq!('A'.to_digit(16u), Some(10u));
498     assert_eq!('b'.to_digit(16u), Some(11u));
499     assert_eq!('B'.to_digit(16u), Some(11u));
500     assert_eq!('z'.to_digit(36u), Some(35u));
501     assert_eq!('Z'.to_digit(36u), Some(35u));
502     assert_eq!(' '.to_digit(10u), None);
503     assert_eq!('$'.to_digit(36u), None);
504 }
505
506 #[test]
507 fn test_is_control() {
508     assert!('\u0000'.is_control());
509     assert!('\u0003'.is_control());
510     assert!('\u0006'.is_control());
511     assert!('\u0009'.is_control());
512     assert!('\u007f'.is_control());
513     assert!('\u0092'.is_control());
514     assert!(!'\u0020'.is_control());
515     assert!(!'\u0055'.is_control());
516     assert!(!'\u0068'.is_control());
517 }
518
519 #[test]
520 fn test_is_digit() {
521    assert!('2'.is_digit());
522    assert!('7'.is_digit());
523    assert!(!'c'.is_digit());
524    assert!(!'i'.is_digit());
525    assert!(!'z'.is_digit());
526    assert!(!'Q'.is_digit());
527 }
528
529 #[test]
530 fn test_escape_default() {
531     fn string(c: char) -> ~str {
532         let mut result = ~"";
533         escape_default(c, |c| { result.push_char(c); });
534         return result;
535     }
536     assert_eq!(string('\n'), ~"\\n");
537     assert_eq!(string('\r'), ~"\\r");
538     assert_eq!(string('\''), ~"\\'");
539     assert_eq!(string('"'), ~"\\\"");
540     assert_eq!(string(' '), ~" ");
541     assert_eq!(string('a'), ~"a");
542     assert_eq!(string('~'), ~"~");
543     assert_eq!(string('\x00'), ~"\\x00");
544     assert_eq!(string('\x1f'), ~"\\x1f");
545     assert_eq!(string('\x7f'), ~"\\x7f");
546     assert_eq!(string('\xff'), ~"\\xff");
547     assert_eq!(string('\u011b'), ~"\\u011b");
548     assert_eq!(string('\U0001d4b6'), ~"\\U0001d4b6");
549 }
550
551 #[test]
552 fn test_escape_unicode() {
553     fn string(c: char) -> ~str {
554         let mut result = ~"";
555         escape_unicode(c, |c| { result.push_char(c); });
556         return result;
557     }
558     assert_eq!(string('\x00'), ~"\\x00");
559     assert_eq!(string('\n'), ~"\\x0a");
560     assert_eq!(string(' '), ~"\\x20");
561     assert_eq!(string('a'), ~"\\x61");
562     assert_eq!(string('\u011b'), ~"\\u011b");
563     assert_eq!(string('\U0001d4b6'), ~"\\U0001d4b6");
564 }
565
566 #[test]
567 fn test_to_str() {
568     let s = 't'.to_str();
569     assert_eq!(s, ~"t");
570 }