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.
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.
11 //! Unicode characters manipulation (`char` type)
14 use option::{None, Option, Some};
15 use iter::{Iterator, range_step};
17 use unicode::{derived_property, property, general_category, decompose};
21 #[cfg(test)] use str::OwnedStr;
23 #[cfg(not(test))] use cmp::{Eq, Ord};
24 #[cfg(not(test))] use default::Default;
25 #[cfg(not(test))] use num::Zero;
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;
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
69 /// The highest valid code point
70 pub static MAX: char = '\U0010ffff';
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) {
78 Some(unsafe { transmute(i) })
82 /// Returns whether the specified character is considered a unicode alphabetic
84 pub fn is_alphabetic(c: char) -> bool { derived_property::Alphabetic(c) }
86 pub fn is_XID_start(c: char) -> bool { derived_property::XID_Start(c) }
88 pub fn is_XID_continue(c: char) -> bool { derived_property::XID_Continue(c) }
91 /// Indicates whether a character is in lower case, defined
92 /// in terms of the Unicode Derived Core Property 'Lowercase'.
95 pub fn is_lowercase(c: char) -> bool { derived_property::Lowercase(c) }
98 /// Indicates whether a character is in upper case, defined
99 /// in terms of the Unicode Derived Core Property 'Uppercase'.
102 pub fn is_uppercase(c: char) -> bool { derived_property::Uppercase(c) }
105 /// Indicates whether a character is whitespace. Whitespace is defined in
106 /// terms of the Unicode Property 'White_Space'.
109 pub fn is_whitespace(c: char) -> bool {
110 // As an optimization ASCII whitespace characters are checked separately
112 || ('\x09' <= c && c <= '\x0d')
113 || property::White_Space(c)
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'.
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)
130 /// Indicates whether a character is a control character. Control
131 /// characters are defined in terms of the Unicode General Category
135 pub fn is_control(c: char) -> bool { general_category::Cc(c) }
137 /// Indicates whether the character is numeric (Nd, Nl, or No)
139 pub fn is_digit(c: char) -> bool {
140 general_category::Nd(c)
141 || general_category::Nl(c)
142 || general_category::No(c)
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`.
152 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
157 /// Fails if given a `radix` > 36.
161 /// This just wraps `to_digit()`.
164 pub fn is_digit_radix(c: char, radix: uint) -> bool {
165 match to_digit(c, radix) {
172 /// Convert a char to the corresponding digit.
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.
183 /// Fails if given a `radix` outside the range `[0..36]`.
186 pub fn to_digit(c: char, radix: uint) -> Option<uint> {
188 fail!("to_digit: radix {} is too high (maximum 36)", radix);
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),
196 if val < radix { Some(val) }
201 /// Converts a number to the character representing it.
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.
210 /// Fails if given an `radix` > 36.
213 pub fn from_digit(num: uint, radix: uint) -> Option<char> {
215 fail!("from_digit: radix {} is to high (maximum 36)", num);
220 Some(transmute(('0' as uint + num) as u32))
222 Some(transmute(('a' as uint + num - 10u) as u32))
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);
241 // Decompose a precomposed Hangul syllable
242 fn decompose_hangul(s: char, f: |char|) {
243 let si = s as uint - S_BASE;
245 let li = si / N_COUNT;
247 f(transmute((L_BASE + li) as u32));
249 let vi = (si % N_COUNT) / T_COUNT;
250 f(transmute((V_BASE + vi) as u32));
252 let ti = si % T_COUNT;
254 f(transmute((T_BASE + ti) as u32));
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);
264 decompose_hangul(c, f);
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);
273 decompose_hangul(c, f);
278 /// Return the hexadecimal unicode escape of a char.
280 /// The rules are as follows:
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`
286 pub fn escape_unicode(c: char, f: |char|) {
287 // avoid calling str::to_str_radix because we don't really need to allocate
291 _ if c <= '\xff' => { f('x'); 2 }
292 _ if c <= '\uffff' => { f('u'); 4 }
295 for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
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))); }
306 /// Return a 'default' ASCII and C++11-like char-literal escape of a char.
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:
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`.
317 pub fn escape_default(c: char, f: |char|) {
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),
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;
337 let code = c as uint;
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!"),
347 impl ToStr for char {
349 fn to_str(&self) -> ~str {
350 str::from_char(*self)
354 #[allow(missing_doc)]
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;
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.
375 /// This will then return the number of characters written to the slice.
376 fn encode_utf8(&self, dst: &mut [u8]) -> uint;
380 fn is_alphabetic(&self) -> bool { is_alphabetic(*self) }
382 fn is_XID_start(&self) -> bool { is_XID_start(*self) }
384 fn is_XID_continue(&self) -> bool { is_XID_continue(*self) }
386 fn is_lowercase(&self) -> bool { is_lowercase(*self) }
388 fn is_uppercase(&self) -> bool { is_uppercase(*self) }
390 fn is_whitespace(&self) -> bool { is_whitespace(*self) }
392 fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
394 fn is_control(&self) -> bool { is_control(*self) }
396 fn is_digit(&self) -> bool { is_digit(*self) }
398 fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
400 fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
402 fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
404 fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
406 fn escape_default(&self, f: |char|) { escape_default(*self, f) }
408 fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
410 fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> uint {
411 let code = *self as uint;
412 if code < MAX_ONE_B {
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;
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;
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;
437 fn eq(&self, other: &char) -> bool { (*self) == (*other) }
443 fn lt(&self, other: &char) -> bool { *self < *other }
447 impl Default for char {
449 fn default() -> char { '\x00' }
455 fn zero() -> char { '\x00' }
458 fn is_zero(&self) -> bool { *self == '\x00' }
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());
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());
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());
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);
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());
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());
530 fn test_escape_default() {
531 fn string(c: char) -> ~str {
532 let mut result = ~"";
533 escape_default(c, |c| { result.push_char(c); });
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");
552 fn test_escape_unicode() {
553 fn string(c: char) -> ~str {
554 let mut result = ~"";
555 escape_unicode(c, |c| { result.push_char(c); });
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");
568 let s = 't'.to_str();