]> git.lizzy.rs Git - rust.git/blob - src/libstd/char.rs
Find the cratemap at runtime on windows.
[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 //! Utilities for manipulating the 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, 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 General Category 'Ll'
93 ///
94 #[inline]
95 pub fn is_lowercase(c: char) -> bool { general_category::Ll(c) }
96
97 ///
98 /// Indicates whether a character is in upper case, defined
99 /// in terms of the Unicode General Category 'Lu'.
100 ///
101 #[inline]
102 pub fn is_uppercase(c: char) -> bool { general_category::Lu(c) }
103
104 ///
105 /// Indicates whether a character is whitespace. Whitespace is defined in
106 /// terms of the Unicode General Categories 'Zs', 'Zl', 'Zp'
107 /// additional 'Cc'-category control codes in the range [0x09, 0x0d]
108 ///
109 #[inline]
110 pub fn is_whitespace(c: char) -> bool {
111     c == ' '
112         || ('\x09' <= c && c <= '\x0d')
113         || general_category::Zs(c)
114         || general_category::Zl(c)
115         || general_category::Zp(c)
116 }
117
118 ///
119 /// Indicates whether a character is alphanumeric. Alphanumericness is
120 /// defined in terms of the Unicode General Categories 'Nd', 'Nl', 'No'
121 /// and the Derived Core Property 'Alphabetic'.
122 ///
123 #[inline]
124 pub fn is_alphanumeric(c: char) -> bool {
125     derived_property::Alphabetic(c)
126         || general_category::Nd(c)
127         || general_category::Nl(c)
128         || general_category::No(c)
129 }
130
131 /// Indicates whether the character is numeric (Nd, Nl, or No)
132 #[inline]
133 pub fn is_digit(c: char) -> bool {
134     general_category::Nd(c)
135         || general_category::Nl(c)
136         || general_category::No(c)
137 }
138
139 ///
140 /// Checks if a character parses as a numeric digit in the given radix.
141 /// Compared to `is_digit()`, this function only recognizes the
142 /// characters `0-9`, `a-z` and `A-Z`.
143 ///
144 /// # Return value
145 ///
146 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
147 /// otherwise.
148 ///
149 /// # Failure
150 ///
151 /// Fails if given a `radix` > 36.
152 ///
153 /// # Note
154 ///
155 /// This just wraps `to_digit()`.
156 ///
157 #[inline]
158 pub fn is_digit_radix(c: char, radix: uint) -> bool {
159     match to_digit(c, radix) {
160         Some(_) => true,
161         None    => false,
162     }
163 }
164
165 ///
166 /// Convert a char to the corresponding digit.
167 ///
168 /// # Return value
169 ///
170 /// If `c` is between '0' and '9', the corresponding value
171 /// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
172 /// 'b' or 'B', 11, etc. Returns none if the char does not
173 /// refer to a digit in the given radix.
174 ///
175 /// # Failure
176 ///
177 /// Fails if given a `radix` outside the range `[0..36]`.
178 ///
179 #[inline]
180 pub fn to_digit(c: char, radix: uint) -> Option<uint> {
181     if radix > 36 {
182         fail!("to_digit: radix %? is to high (maximum 36)", radix);
183     }
184     let val = match c {
185       '0' .. '9' => c as uint - ('0' as uint),
186       'a' .. 'z' => c as uint + 10u - ('a' as uint),
187       'A' .. 'Z' => c as uint + 10u - ('A' as uint),
188       _ => return None,
189     };
190     if val < radix { Some(val) }
191     else { None }
192 }
193
194 ///
195 /// Converts a number to the character representing it.
196 ///
197 /// # Return value
198 ///
199 /// Returns `Some(char)` if `num` represents one digit under `radix`,
200 /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
201 ///
202 /// # Failure
203 ///
204 /// Fails if given an `radix` > 36.
205 ///
206 #[inline]
207 pub fn from_digit(num: uint, radix: uint) -> Option<char> {
208     if radix > 36 {
209         fail!("from_digit: radix %? is to high (maximum 36)", num);
210     }
211     if num < radix {
212         unsafe {
213             if num < 10 {
214                 Some(transmute(('0' as uint + num) as u32))
215             } else {
216                 Some(transmute(('a' as uint + num - 10u) as u32))
217             }
218         }
219     } else {
220         None
221     }
222 }
223
224 // Constants from Unicode 6.2.0 Section 3.12 Conjoining Jamo Behavior
225 static S_BASE: uint = 0xAC00;
226 static L_BASE: uint = 0x1100;
227 static V_BASE: uint = 0x1161;
228 static T_BASE: uint = 0x11A7;
229 static L_COUNT: uint = 19;
230 static V_COUNT: uint = 21;
231 static T_COUNT: uint = 28;
232 static N_COUNT: uint = (V_COUNT * T_COUNT);
233 static S_COUNT: uint = (L_COUNT * N_COUNT);
234
235 // Decompose a precomposed Hangul syllable
236 fn decompose_hangul(s: char, f: &fn(char)) {
237     let si = s as uint - S_BASE;
238
239     let li = si / N_COUNT;
240     unsafe {
241         f(transmute((L_BASE + li) as u32));
242
243         let vi = (si % N_COUNT) / T_COUNT;
244         f(transmute((V_BASE + vi) as u32));
245
246         let ti = si % T_COUNT;
247         if ti > 0 {
248             f(transmute((T_BASE + ti) as u32));
249         }
250     }
251 }
252
253 /// Returns the canonical decompostion of a character
254 pub fn decompose_canonical(c: char, f: &fn(char)) {
255     if (c as uint) < S_BASE || (c as uint) >= (S_BASE + S_COUNT) {
256         decompose::canonical(c, f);
257     } else {
258         decompose_hangul(c, f);
259     }
260 }
261
262 /// Returns the compatibility decompostion of a character
263 pub fn decompose_compatible(c: char, f: &fn(char)) {
264     if (c as uint) < S_BASE || (c as uint) >= (S_BASE + S_COUNT) {
265         decompose::compatibility(c, f);
266     } else {
267         decompose_hangul(c, f);
268     }
269 }
270
271 ///
272 /// Return the hexadecimal unicode escape of a char.
273 ///
274 /// The rules are as follows:
275 ///
276 /// - chars in [0,0xff] get 2-digit escapes: `\\xNN`
277 /// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`
278 /// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`
279 ///
280 pub fn escape_unicode(c: char, f: &fn(char)) {
281     // avoid calling str::to_str_radix because we don't really need to allocate
282     // here.
283     f('\\');
284     let pad = cond!(
285         (c <= '\xff')   { f('x'); 2 }
286         (c <= '\uffff') { f('u'); 4 }
287         _               { f('U'); 8 }
288     );
289     for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
290         unsafe {
291             match ((c as i32) >> offset) & 0xf {
292                 i @ 0 .. 9 => { f(transmute('0' as i32 + i)); }
293                 i => { f(transmute('a' as i32 + (i - 10))); }
294             }
295         }
296     }
297 }
298
299 ///
300 /// Return a 'default' ASCII and C++11-like char-literal escape of a char.
301 ///
302 /// The default is chosen with a bias toward producing literals that are
303 /// legal in a variety of languages, including C++11 and similar C-family
304 /// languages. The exact rules are:
305 ///
306 /// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
307 /// - Single-quote, double-quote and backslash chars are backslash-escaped.
308 /// - Any other chars in the range [0x20,0x7e] are not escaped.
309 /// - Any other chars are given hex unicode escapes; see `escape_unicode`.
310 ///
311 pub fn escape_default(c: char, f: &fn(char)) {
312     match c {
313         '\t' => { f('\\'); f('t'); }
314         '\r' => { f('\\'); f('r'); }
315         '\n' => { f('\\'); f('n'); }
316         '\\' => { f('\\'); f('\\'); }
317         '\'' => { f('\\'); f('\''); }
318         '"'  => { f('\\'); f('"'); }
319         '\x20' .. '\x7e' => { f(c); }
320         _ => c.escape_unicode(f),
321     }
322 }
323
324 /// Returns the amount of bytes this character would need if encoded in utf8
325 pub fn len_utf8_bytes(c: char) -> uint {
326     static MAX_ONE_B:   uint = 128u;
327     static MAX_TWO_B:   uint = 2048u;
328     static MAX_THREE_B: uint = 65536u;
329     static MAX_FOUR_B:  uint = 2097152u;
330
331     let code = c as uint;
332     cond!(
333         (code < MAX_ONE_B)   { 1u }
334         (code < MAX_TWO_B)   { 2u }
335         (code < MAX_THREE_B) { 3u }
336         (code < MAX_FOUR_B)  { 4u }
337         _ { fail!("invalid character!") }
338     )
339 }
340
341 impl ToStr for char {
342     #[inline]
343     fn to_str(&self) -> ~str {
344         str::from_char(*self)
345     }
346 }
347
348 #[allow(missing_doc)]
349 pub trait Char {
350     fn is_alphabetic(&self) -> bool;
351     fn is_XID_start(&self) -> bool;
352     fn is_XID_continue(&self) -> bool;
353     fn is_lowercase(&self) -> bool;
354     fn is_uppercase(&self) -> bool;
355     fn is_whitespace(&self) -> bool;
356     fn is_alphanumeric(&self) -> bool;
357     fn is_digit(&self) -> bool;
358     fn is_digit_radix(&self, radix: uint) -> bool;
359     fn to_digit(&self, radix: uint) -> Option<uint>;
360     fn from_digit(num: uint, radix: uint) -> Option<char>;
361     fn escape_unicode(&self, f: &fn(char));
362     fn escape_default(&self, f: &fn(char));
363     fn len_utf8_bytes(&self) -> uint;
364
365     /// Encodes this character as utf-8 into the provided byte-buffer. The
366     /// buffer must be at least 4 bytes long or a runtime failure will occur.
367     ///
368     /// This will then return the number of characters written to the slice.
369     fn encode_utf8(&self, dst: &mut [u8]) -> uint;
370 }
371
372 impl Char for char {
373     fn is_alphabetic(&self) -> bool { is_alphabetic(*self) }
374
375     fn is_XID_start(&self) -> bool { is_XID_start(*self) }
376
377     fn is_XID_continue(&self) -> bool { is_XID_continue(*self) }
378
379     fn is_lowercase(&self) -> bool { is_lowercase(*self) }
380
381     fn is_uppercase(&self) -> bool { is_uppercase(*self) }
382
383     fn is_whitespace(&self) -> bool { is_whitespace(*self) }
384
385     fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
386
387     fn is_digit(&self) -> bool { is_digit(*self) }
388
389     fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
390
391     fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
392
393     fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
394
395     fn escape_unicode(&self, f: &fn(char)) { escape_unicode(*self, f) }
396
397     fn escape_default(&self, f: &fn(char)) { escape_default(*self, f) }
398
399     fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
400
401     fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> uint {
402         let code = *self as uint;
403         if code < MAX_ONE_B {
404             dst[0] = code as u8;
405             return 1;
406         } else if code < MAX_TWO_B {
407             dst[0] = (code >> 6u & 31u | TAG_TWO_B) as u8;
408             dst[1] = (code & 63u | TAG_CONT) as u8;
409             return 2;
410         } else if code < MAX_THREE_B {
411             dst[0] = (code >> 12u & 15u | TAG_THREE_B) as u8;
412             dst[1] = (code >> 6u & 63u | TAG_CONT) as u8;
413             dst[2] = (code & 63u | TAG_CONT) as u8;
414             return 3;
415         } else {
416             dst[0] = (code >> 18u & 7u | TAG_FOUR_B) as u8;
417             dst[1] = (code >> 12u & 63u | TAG_CONT) as u8;
418             dst[2] = (code >> 6u & 63u | TAG_CONT) as u8;
419             dst[3] = (code & 63u | TAG_CONT) as u8;
420             return 4;
421         }
422     }
423 }
424
425 #[cfg(not(test))]
426 impl Eq for char {
427     #[inline]
428     fn eq(&self, other: &char) -> bool { (*self) == (*other) }
429 }
430
431 #[cfg(not(test))]
432 impl Ord for char {
433     #[inline]
434     fn lt(&self, other: &char) -> bool { *self < *other }
435 }
436
437 #[cfg(not(test))]
438 impl Default for char {
439     #[inline]
440     fn default() -> char { '\x00' }
441 }
442
443 #[cfg(not(test))]
444 impl Zero for char {
445     #[inline]
446     fn zero() -> char { '\x00' }
447
448     #[inline]
449     fn is_zero(&self) -> bool { *self == '\x00' }
450 }
451
452 #[test]
453 fn test_is_lowercase() {
454     assert!('a'.is_lowercase());
455     assert!('ö'.is_lowercase());
456     assert!('ß'.is_lowercase());
457     assert!(!'Ü'.is_lowercase());
458     assert!(!'P'.is_lowercase());
459 }
460
461 #[test]
462 fn test_is_uppercase() {
463     assert!(!'h'.is_uppercase());
464     assert!(!'ä'.is_uppercase());
465     assert!(!'ß'.is_uppercase());
466     assert!('Ö'.is_uppercase());
467     assert!('T'.is_uppercase());
468 }
469
470 #[test]
471 fn test_is_whitespace() {
472     assert!(' '.is_whitespace());
473     assert!('\u2007'.is_whitespace());
474     assert!('\t'.is_whitespace());
475     assert!('\n'.is_whitespace());
476     assert!(!'a'.is_whitespace());
477     assert!(!'_'.is_whitespace());
478     assert!(!'\u0000'.is_whitespace());
479 }
480
481 #[test]
482 fn test_to_digit() {
483     assert_eq!('0'.to_digit(10u), Some(0u));
484     assert_eq!('1'.to_digit(2u), Some(1u));
485     assert_eq!('2'.to_digit(3u), Some(2u));
486     assert_eq!('9'.to_digit(10u), Some(9u));
487     assert_eq!('a'.to_digit(16u), Some(10u));
488     assert_eq!('A'.to_digit(16u), Some(10u));
489     assert_eq!('b'.to_digit(16u), Some(11u));
490     assert_eq!('B'.to_digit(16u), Some(11u));
491     assert_eq!('z'.to_digit(36u), Some(35u));
492     assert_eq!('Z'.to_digit(36u), Some(35u));
493     assert_eq!(' '.to_digit(10u), None);
494     assert_eq!('$'.to_digit(36u), None);
495 }
496
497 #[test]
498 fn test_is_digit() {
499    assert!('2'.is_digit());
500    assert!('7'.is_digit());
501    assert!(!'c'.is_digit());
502    assert!(!'i'.is_digit());
503    assert!(!'z'.is_digit());
504    assert!(!'Q'.is_digit());
505 }
506
507 #[test]
508 fn test_escape_default() {
509     fn string(c: char) -> ~str {
510         let mut result = ~"";
511         do escape_default(c) |c| { result.push_char(c); }
512         return result;
513     }
514     assert_eq!(string('\n'), ~"\\n");
515     assert_eq!(string('\r'), ~"\\r");
516     assert_eq!(string('\''), ~"\\'");
517     assert_eq!(string('"'), ~"\\\"");
518     assert_eq!(string(' '), ~" ");
519     assert_eq!(string('a'), ~"a");
520     assert_eq!(string('~'), ~"~");
521     assert_eq!(string('\x00'), ~"\\x00");
522     assert_eq!(string('\x1f'), ~"\\x1f");
523     assert_eq!(string('\x7f'), ~"\\x7f");
524     assert_eq!(string('\xff'), ~"\\xff");
525     assert_eq!(string('\u011b'), ~"\\u011b");
526     assert_eq!(string('\U0001d4b6'), ~"\\U0001d4b6");
527 }
528
529 #[test]
530 fn test_escape_unicode() {
531     fn string(c: char) -> ~str {
532         let mut result = ~"";
533         do escape_unicode(c) |c| { result.push_char(c); }
534         return result;
535     }
536     assert_eq!(string('\x00'), ~"\\x00");
537     assert_eq!(string('\n'), ~"\\x0a");
538     assert_eq!(string(' '), ~"\\x20");
539     assert_eq!(string('a'), ~"\\x61");
540     assert_eq!(string('\u011b'), ~"\\u011b");
541     assert_eq!(string('\U0001d4b6'), ~"\\U0001d4b6");
542 }
543
544 #[test]
545 fn test_to_str() {
546     let s = 't'.to_str();
547     assert_eq!(s, ~"t");
548 }