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 //! Utilities for manipulating the char type
14 use option::{None, Option, Some};
15 use iter::{Iterator, range_step};
17 use unicode::{derived_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 General Category 'Ll'
95 pub fn is_lowercase(c: char) -> bool { general_category::Ll(c) }
98 /// Indicates whether a character is in upper case, defined
99 /// in terms of the Unicode General Category 'Lu'.
102 pub fn is_uppercase(c: char) -> bool { general_category::Lu(c) }
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]
110 pub fn is_whitespace(c: char) -> bool {
112 || ('\x09' <= c && c <= '\x0d')
113 || general_category::Zs(c)
114 || general_category::Zl(c)
115 || general_category::Zp(c)
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'.
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)
131 /// Indicates whether the character is numeric (Nd, Nl, or No)
133 pub fn is_digit(c: char) -> bool {
134 general_category::Nd(c)
135 || general_category::Nl(c)
136 || general_category::No(c)
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`.
146 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
151 /// Fails if given a `radix` > 36.
155 /// This just wraps `to_digit()`.
158 pub fn is_digit_radix(c: char, radix: uint) -> bool {
159 match to_digit(c, radix) {
166 /// Convert a char to the corresponding digit.
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.
177 /// Fails if given a `radix` outside the range `[0..36]`.
180 pub fn to_digit(c: char, radix: uint) -> Option<uint> {
182 fail!("to_digit: radix %? is to high (maximum 36)", radix);
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),
190 if val < radix { Some(val) }
195 /// Converts a number to the character representing it.
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.
204 /// Fails if given an `radix` > 36.
207 pub fn from_digit(num: uint, radix: uint) -> Option<char> {
209 fail!("from_digit: radix %? is to high (maximum 36)", num);
214 Some(transmute(('0' as uint + num) as u32))
216 Some(transmute(('a' as uint + num - 10u) as u32))
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);
235 // Decompose a precomposed Hangul syllable
236 fn decompose_hangul(s: char, f: &fn(char)) {
237 let si = s as uint - S_BASE;
239 let li = si / N_COUNT;
241 f(transmute((L_BASE + li) as u32));
243 let vi = (si % N_COUNT) / T_COUNT;
244 f(transmute((V_BASE + vi) as u32));
246 let ti = si % T_COUNT;
248 f(transmute((T_BASE + ti) as u32));
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);
258 decompose_hangul(c, f);
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);
267 decompose_hangul(c, f);
272 /// Return the hexadecimal unicode escape of a char.
274 /// The rules are as follows:
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`
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
285 (c <= '\xff') { f('x'); 2 }
286 (c <= '\uffff') { f('u'); 4 }
289 for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
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))); }
300 /// Return a 'default' ASCII and C++11-like char-literal escape of a char.
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:
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`.
311 pub fn escape_default(c: char, f: &fn(char)) {
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),
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;
331 let code = c as uint;
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!") }
341 impl ToStr for char {
343 fn to_str(&self) -> ~str {
344 str::from_char(*self)
348 #[allow(missing_doc)]
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;
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.
368 /// This will then return the number of characters written to the slice.
369 fn encode_utf8(&self, dst: &mut [u8]) -> uint;
373 fn is_alphabetic(&self) -> bool { is_alphabetic(*self) }
375 fn is_XID_start(&self) -> bool { is_XID_start(*self) }
377 fn is_XID_continue(&self) -> bool { is_XID_continue(*self) }
379 fn is_lowercase(&self) -> bool { is_lowercase(*self) }
381 fn is_uppercase(&self) -> bool { is_uppercase(*self) }
383 fn is_whitespace(&self) -> bool { is_whitespace(*self) }
385 fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
387 fn is_digit(&self) -> bool { is_digit(*self) }
389 fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
391 fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
393 fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
395 fn escape_unicode(&self, f: &fn(char)) { escape_unicode(*self, f) }
397 fn escape_default(&self, f: &fn(char)) { escape_default(*self, f) }
399 fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
401 fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> uint {
402 let code = *self as uint;
403 if code < MAX_ONE_B {
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;
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;
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;
428 fn eq(&self, other: &char) -> bool { (*self) == (*other) }
434 fn lt(&self, other: &char) -> bool { *self < *other }
438 impl Default for char {
440 fn default() -> char { '\x00' }
446 fn zero() -> char { '\x00' }
449 fn is_zero(&self) -> bool { *self == '\x00' }
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());
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());
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());
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);
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());
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); }
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");
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); }
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");
546 let s = 't'.to_str();