]> git.lizzy.rs Git - rust.git/blob - src/libcore/char.rs
76ff56a77a48d67a4bee6b92d23b149da8601158
[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 (`char` type, Unicode Scalar Value)
12 //!
13 //! This module  provides the `Char` trait, as well as its implementation
14 //! for the primitive `char` type, in order to allow basic character manipulation.
15 //!
16 //! A `char` actually represents a
17 //! *[Unicode Scalar Value](http://www.unicode.org/glossary/#unicode_scalar_value)*,
18 //! as it can contain any Unicode code point except high-surrogate and
19 //! low-surrogate code points.
20 //!
21 //! As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\]
22 //! (inclusive) are allowed. A `char` can always be safely cast to a `u32`;
23 //! however the converse is not always true due to the above range limits
24 //! and, as such, should be performed via the `from_u32` function..
25
26 #![allow(non_snake_case_functions)]
27 #![doc(primitive = "char")]
28
29 use mem::transmute;
30 use option::{None, Option, Some};
31 use iter::{Iterator, range_step};
32 use unicode::{derived_property, property, general_category, conversions};
33
34 /// Returns the canonical decomposition of a character.
35 pub use unicode::normalization::decompose_canonical;
36 /// Returns the compatibility decomposition of a character.
37 pub use unicode::normalization::decompose_compatible;
38
39 // UTF-8 ranges and tags for encoding characters
40 static TAG_CONT: u8    = 0b1000_0000u8;
41 static TAG_TWO_B: u8   = 0b1100_0000u8;
42 static TAG_THREE_B: u8 = 0b1110_0000u8;
43 static TAG_FOUR_B: u8  = 0b1111_0000u8;
44 static MAX_ONE_B: u32   =     0x80u32;
45 static MAX_TWO_B: u32   =    0x800u32;
46 static MAX_THREE_B: u32 =  0x10000u32;
47 static MAX_FOUR_B:  u32 = 0x200000u32;
48
49 /*
50     Lu  Uppercase_Letter        an uppercase letter
51     Ll  Lowercase_Letter        a lowercase letter
52     Lt  Titlecase_Letter        a digraphic character, with first part uppercase
53     Lm  Modifier_Letter         a modifier letter
54     Lo  Other_Letter            other letters, including syllables and ideographs
55     Mn  Nonspacing_Mark         a nonspacing combining mark (zero advance width)
56     Mc  Spacing_Mark            a spacing combining mark (positive advance width)
57     Me  Enclosing_Mark          an enclosing combining mark
58     Nd  Decimal_Number          a decimal digit
59     Nl  Letter_Number           a letterlike numeric character
60     No  Other_Number            a numeric character of other type
61     Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
62     Pd  Dash_Punctuation        a dash or hyphen punctuation mark
63     Ps  Open_Punctuation        an opening punctuation mark (of a pair)
64     Pe  Close_Punctuation       a closing punctuation mark (of a pair)
65     Pi  Initial_Punctuation     an initial quotation mark
66     Pf  Final_Punctuation       a final quotation mark
67     Po  Other_Punctuation       a punctuation mark of other type
68     Sm  Math_Symbol             a symbol of primarily mathematical use
69     Sc  Currency_Symbol         a currency sign
70     Sk  Modifier_Symbol         a non-letterlike modifier symbol
71     So  Other_Symbol            a symbol of other type
72     Zs  Space_Separator         a space character (of various non-zero widths)
73     Zl  Line_Separator          U+2028 LINE SEPARATOR only
74     Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
75     Cc  Control                 a C0 or C1 control code
76     Cf  Format                  a format control character
77     Cs  Surrogate               a surrogate code point
78     Co  Private_Use             a private-use character
79     Cn  Unassigned              a reserved unassigned code point or a noncharacter
80 */
81
82 /// The highest valid code point
83 pub static MAX: char = '\U0010ffff';
84
85 /// Converts from `u32` to a `char`
86 #[inline]
87 pub fn from_u32(i: u32) -> Option<char> {
88     // catch out-of-bounds and surrogates
89     if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
90         None
91     } else {
92         Some(unsafe { transmute(i) })
93     }
94 }
95
96 /// Returns whether the specified `char` is considered a Unicode alphabetic
97 /// code point
98 pub fn is_alphabetic(c: char) -> bool   { derived_property::Alphabetic(c) }
99
100 /// Returns whether the specified `char` satisfies the 'XID_Start' Unicode property
101 ///
102 /// 'XID_Start' is a Unicode Derived Property specified in
103 /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
104 /// mostly similar to ID_Start but modified for closure under NFKx.
105 pub fn is_XID_start(c: char) -> bool    { derived_property::XID_Start(c) }
106
107 /// Returns whether the specified `char` satisfies the 'XID_Continue' Unicode property
108 ///
109 /// 'XID_Continue' is a Unicode Derived Property specified in
110 /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
111 /// mostly similar to 'ID_Continue' but modified for closure under NFKx.
112 pub fn is_XID_continue(c: char) -> bool { derived_property::XID_Continue(c) }
113
114 ///
115 /// Indicates whether a `char` is in lower case
116 ///
117 /// This is defined according to the terms of the Unicode Derived Core Property 'Lowercase'.
118 ///
119 #[inline]
120 pub fn is_lowercase(c: char) -> bool { derived_property::Lowercase(c) }
121
122 ///
123 /// Indicates whether a `char` is in upper case
124 ///
125 /// This is defined according to the terms of the Unicode Derived Core Property 'Uppercase'.
126 ///
127 #[inline]
128 pub fn is_uppercase(c: char) -> bool { derived_property::Uppercase(c) }
129
130 ///
131 /// Indicates whether a `char` is whitespace
132 ///
133 /// Whitespace is defined in terms of the Unicode Property 'White_Space'.
134 ///
135 #[inline]
136 pub fn is_whitespace(c: char) -> bool {
137     // As an optimization ASCII whitespace characters are checked separately
138     c == ' '
139         || ('\x09' <= c && c <= '\x0d')
140         || property::White_Space(c)
141 }
142
143 ///
144 /// Indicates whether a `char` is alphanumeric
145 ///
146 /// Alphanumericness is defined in terms of the Unicode General Categories
147 /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
148 ///
149 #[inline]
150 pub fn is_alphanumeric(c: char) -> bool {
151     derived_property::Alphabetic(c)
152         || general_category::Nd(c)
153         || general_category::Nl(c)
154         || general_category::No(c)
155 }
156
157 ///
158 /// Indicates whether a `char` is a control code point
159 ///
160 /// Control code points are defined in terms of the Unicode General Category
161 /// 'Cc'.
162 ///
163 #[inline]
164 pub fn is_control(c: char) -> bool { general_category::Cc(c) }
165
166 /// Indicates whether the `char` is numeric (Nd, Nl, or No)
167 #[inline]
168 pub fn is_digit(c: char) -> bool {
169     general_category::Nd(c)
170         || general_category::Nl(c)
171         || general_category::No(c)
172 }
173
174 ///
175 /// Checks if a `char` parses as a numeric digit in the given radix
176 ///
177 /// Compared to `is_digit()`, this function only recognizes the
178 /// characters `0-9`, `a-z` and `A-Z`.
179 ///
180 /// # Return value
181 ///
182 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
183 /// otherwise.
184 ///
185 /// # Failure
186 ///
187 /// Fails if given a `radix` > 36.
188 ///
189 /// # Note
190 ///
191 /// This just wraps `to_digit()`.
192 ///
193 #[inline]
194 pub fn is_digit_radix(c: char, radix: uint) -> bool {
195     match to_digit(c, radix) {
196         Some(_) => true,
197         None    => false,
198     }
199 }
200
201 ///
202 /// Converts a `char` to the corresponding digit
203 ///
204 /// # Return value
205 ///
206 /// If `c` is between '0' and '9', the corresponding value
207 /// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
208 /// 'b' or 'B', 11, etc. Returns none if the `char` does not
209 /// refer to a digit in the given radix.
210 ///
211 /// # Failure
212 ///
213 /// Fails if given a `radix` outside the range `[0..36]`.
214 ///
215 #[inline]
216 pub fn to_digit(c: char, radix: uint) -> Option<uint> {
217     if radix > 36 {
218         fail!("to_digit: radix is too high (maximum 36)");
219     }
220     let val = match c {
221       '0' .. '9' => c as uint - ('0' as uint),
222       'a' .. 'z' => c as uint + 10u - ('a' as uint),
223       'A' .. 'Z' => c as uint + 10u - ('A' as uint),
224       _ => return None,
225     };
226     if val < radix { Some(val) }
227     else { None }
228 }
229
230 /// Convert a char to its uppercase equivalent
231 ///
232 /// The case-folding performed is the common or simple mapping:
233 /// it maps one unicode codepoint (one char in Rust) to its uppercase equivalent according
234 /// to the Unicode database at ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
235 /// The additional SpecialCasing.txt is not considered here, as it expands to multiple
236 /// codepoints in some cases.
237 ///
238 /// A full reference can be found here
239 /// http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
240 ///
241 /// # Return value
242 ///
243 /// Returns the char itself if no conversion was made
244 #[inline]
245 pub fn to_uppercase(c: char) -> char {
246     conversions::to_upper(c)
247 }
248
249 /// Convert a char to its lowercase equivalent
250 ///
251 /// The case-folding performed is the common or simple mapping
252 /// see `to_uppercase` for references and more information
253 ///
254 /// # Return value
255 ///
256 /// Returns the char itself if no conversion if possible
257 #[inline]
258 pub fn to_lowercase(c: char) -> char {
259     conversions::to_lower(c)
260 }
261
262 ///
263 /// Converts a number to the character representing it
264 ///
265 /// # Return value
266 ///
267 /// Returns `Some(char)` if `num` represents one digit under `radix`,
268 /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
269 ///
270 /// # Failure
271 ///
272 /// Fails if given an `radix` > 36.
273 ///
274 #[inline]
275 pub fn from_digit(num: uint, radix: uint) -> Option<char> {
276     if radix > 36 {
277         fail!("from_digit: radix is to high (maximum 36)");
278     }
279     if num < radix {
280         unsafe {
281             if num < 10 {
282                 Some(transmute(('0' as uint + num) as u32))
283             } else {
284                 Some(transmute(('a' as uint + num - 10u) as u32))
285             }
286         }
287     } else {
288         None
289     }
290 }
291
292 ///
293 /// Returns the hexadecimal Unicode escape of a `char`
294 ///
295 /// The rules are as follows:
296 ///
297 /// - chars in [0,0xff] get 2-digit escapes: `\\xNN`
298 /// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`
299 /// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`
300 ///
301 pub fn escape_unicode(c: char, f: |char|) {
302     // avoid calling str::to_str_radix because we don't really need to allocate
303     // here.
304     f('\\');
305     let pad = match () {
306         _ if c <= '\xff'    => { f('x'); 2 }
307         _ if c <= '\uffff'  => { f('u'); 4 }
308         _                   => { f('U'); 8 }
309     };
310     for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
311         unsafe {
312             match ((c as i32) >> offset) & 0xf {
313                 i @ 0 .. 9 => { f(transmute('0' as i32 + i)); }
314                 i => { f(transmute('a' as i32 + (i - 10))); }
315             }
316         }
317     }
318 }
319
320 ///
321 /// Returns a 'default' ASCII and C++11-like literal escape of a `char`
322 ///
323 /// The default is chosen with a bias toward producing literals that are
324 /// legal in a variety of languages, including C++11 and similar C-family
325 /// languages. The exact rules are:
326 ///
327 /// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
328 /// - Single-quote, double-quote and backslash chars are backslash-escaped.
329 /// - Any other chars in the range [0x20,0x7e] are not escaped.
330 /// - Any other chars are given hex unicode escapes; see `escape_unicode`.
331 ///
332 pub fn escape_default(c: char, f: |char|) {
333     match c {
334         '\t' => { f('\\'); f('t'); }
335         '\r' => { f('\\'); f('r'); }
336         '\n' => { f('\\'); f('n'); }
337         '\\' => { f('\\'); f('\\'); }
338         '\'' => { f('\\'); f('\''); }
339         '"'  => { f('\\'); f('"'); }
340         '\x20' .. '\x7e' => { f(c); }
341         _ => c.escape_unicode(f),
342     }
343 }
344
345 /// Returns the amount of bytes this `char` would need if encoded in UTF-8
346 pub fn len_utf8_bytes(c: char) -> uint {
347     let code = c as u32;
348     match () {
349         _ if code < MAX_ONE_B   => 1u,
350         _ if code < MAX_TWO_B   => 2u,
351         _ if code < MAX_THREE_B => 3u,
352         _ if code < MAX_FOUR_B  => 4u,
353         _                       => fail!("invalid character!"),
354     }
355 }
356
357 /// Useful functions for Unicode characters.
358 pub trait Char {
359     /// Returns whether the specified character is considered a Unicode
360     /// alphabetic code point.
361     fn is_alphabetic(&self) -> bool;
362
363     /// Returns whether the specified character satisfies the 'XID_Start'
364     /// Unicode property.
365     ///
366     /// 'XID_Start' is a Unicode Derived Property specified in
367     /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
368     /// mostly similar to ID_Start but modified for closure under NFKx.
369     fn is_XID_start(&self) -> bool;
370
371     /// Returns whether the specified `char` satisfies the 'XID_Continue'
372     /// Unicode property.
373     ///
374     /// 'XID_Continue' is a Unicode Derived Property specified in
375     /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
376     /// mostly similar to 'ID_Continue' but modified for closure under NFKx.
377     fn is_XID_continue(&self) -> bool;
378
379
380     /// Indicates whether a character is in lowercase.
381     ///
382     /// This is defined according to the terms of the Unicode Derived Core
383     /// Property `Lowercase`.
384     fn is_lowercase(&self) -> bool;
385
386     /// Indicates whether a character is in uppercase.
387     ///
388     /// This is defined according to the terms of the Unicode Derived Core
389     /// Property `Uppercase`.
390     fn is_uppercase(&self) -> bool;
391
392     /// Indicates whether a character is whitespace.
393     ///
394     /// Whitespace is defined in terms of the Unicode Property `White_Space`.
395     fn is_whitespace(&self) -> bool;
396
397     /// Indicates whether a character is alphanumeric.
398     ///
399     /// Alphanumericness is defined in terms of the Unicode General Categories
400     /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
401     fn is_alphanumeric(&self) -> bool;
402
403     /// Indicates whether a character is a control code point.
404     ///
405     /// Control code points are defined in terms of the Unicode General
406     /// Category `Cc`.
407     fn is_control(&self) -> bool;
408
409     /// Indicates whether the character is numeric (Nd, Nl, or No).
410     fn is_digit(&self) -> bool;
411
412     /// Checks if a `char` parses as a numeric digit in the given radix.
413     ///
414     /// Compared to `is_digit()`, this function only recognizes the characters
415     /// `0-9`, `a-z` and `A-Z`.
416     ///
417     /// # Return value
418     ///
419     /// Returns `true` if `c` is a valid digit under `radix`, and `false`
420     /// otherwise.
421     ///
422     /// # Failure
423     ///
424     /// Fails if given a radix > 36.
425     fn is_digit_radix(&self, radix: uint) -> bool;
426
427     /// Converts a character to the corresponding digit.
428     ///
429     /// # Return value
430     ///
431     /// If `c` is between '0' and '9', the corresponding value between 0 and
432     /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
433     /// none if the character does not refer to a digit in the given radix.
434     ///
435     /// # Failure
436     ///
437     /// Fails if given a radix outside the range [0..36].
438     fn to_digit(&self, radix: uint) -> Option<uint>;
439
440     /// Converts a character to its lowercase equivalent.
441     ///
442     /// The case-folding performed is the common or simple mapping. See
443     /// `to_uppercase()` for references and more information.
444     ///
445     /// # Return value
446     ///
447     /// Returns the lowercase equivalent of the character, or the character
448     /// itself if no conversion is possible.
449     fn to_lowercase(&self) -> char;
450
451     /// Converts a character to its uppercase equivalent.
452     ///
453     /// The case-folding performed is the common or simple mapping: it maps
454     /// one unicode codepoint (one character in Rust) to its uppercase
455     /// equivalent according to the Unicode database [1]. The additional
456     /// `SpecialCasing.txt` is not considered here, as it expands to multiple
457     /// codepoints in some cases.
458     ///
459     /// A full reference can be found here [2].
460     ///
461     /// # Return value
462     ///
463     /// Returns the uppercase equivalent of the character, or the character
464     /// itself if no conversion was made.
465     ///
466     /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
467     ///
468     /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
469     fn to_uppercase(&self) -> char;
470
471     /// Converts a number to the character representing it.
472     ///
473     /// # Return value
474     ///
475     /// Returns `Some(char)` if `num` represents one digit under `radix`,
476     /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
477     ///
478     /// # Failure
479     ///
480     /// Fails if given a radix > 36.
481     fn from_digit(num: uint, radix: uint) -> Option<char>;
482
483     /// Returns the hexadecimal Unicode escape of a character.
484     ///
485     /// The rules are as follows:
486     ///
487     /// * Characters in [0,0xff] get 2-digit escapes: `\\xNN`
488     /// * Characters in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`.
489     /// * Characters above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`.
490     fn escape_unicode(&self, f: |char|);
491
492     /// Returns a 'default' ASCII and C++11-like literal escape of a
493     /// character.
494     ///
495     /// The default is chosen with a bias toward producing literals that are
496     /// legal in a variety of languages, including C++11 and similar C-family
497     /// languages. The exact rules are:
498     ///
499     /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
500     /// * Single-quote, double-quote and backslash chars are backslash-
501     ///   escaped.
502     /// * Any other chars in the range [0x20,0x7e] are not escaped.
503     /// * Any other chars are given hex unicode escapes; see `escape_unicode`.
504     fn escape_default(&self, f: |char|);
505
506     /// Returns the amount of bytes this character would need if encoded in
507     /// UTF-8.
508     fn len_utf8_bytes(&self) -> uint;
509
510     /// Encodes this character as UTF-8 into the provided byte buffer.
511     ///
512     /// The buffer must be at least 4 bytes long or a runtime failure may
513     /// occur.
514     ///
515     /// This will then return the number of bytes written to the slice.
516     fn encode_utf8(&self, dst: &mut [u8]) -> uint;
517
518     /// Encodes this character as UTF-16 into the provided `u16` buffer.
519     ///
520     /// The buffer must be at least 2 elements long or a runtime failure may
521     /// occur.
522     ///
523     /// This will then return the number of `u16`s written to the slice.
524     fn encode_utf16(&self, dst: &mut [u16]) -> uint;
525 }
526
527 impl Char for char {
528     fn is_alphabetic(&self) -> bool { is_alphabetic(*self) }
529
530     fn is_XID_start(&self) -> bool { is_XID_start(*self) }
531
532     fn is_XID_continue(&self) -> bool { is_XID_continue(*self) }
533
534     fn is_lowercase(&self) -> bool { is_lowercase(*self) }
535
536     fn is_uppercase(&self) -> bool { is_uppercase(*self) }
537
538     fn is_whitespace(&self) -> bool { is_whitespace(*self) }
539
540     fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
541
542     fn is_control(&self) -> bool { is_control(*self) }
543
544     fn is_digit(&self) -> bool { is_digit(*self) }
545
546     fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
547
548     fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
549
550     fn to_lowercase(&self) -> char { to_lowercase(*self) }
551
552     fn to_uppercase(&self) -> char { to_uppercase(*self) }
553
554     fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
555
556     fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
557
558     fn escape_default(&self, f: |char|) { escape_default(*self, f) }
559
560     fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
561
562     fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> uint {
563         let code = *self as u32;
564         if code < MAX_ONE_B {
565             dst[0] = code as u8;
566             1
567         } else if code < MAX_TWO_B {
568             dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
569             dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
570             2
571         } else if code < MAX_THREE_B {
572             dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
573             dst[1] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
574             dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
575             3
576         } else {
577             dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
578             dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
579             dst[2] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
580             dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
581             4
582         }
583     }
584
585     fn encode_utf16(&self, dst: &mut [u16]) -> uint {
586         let mut ch = *self as u32;
587         if (ch & 0xFFFF_u32) == ch {
588             // The BMP falls through (assuming non-surrogate, as it should)
589             assert!(ch <= 0xD7FF_u32 || ch >= 0xE000_u32);
590             dst[0] = ch as u16;
591             1
592         } else {
593             // Supplementary planes break into surrogates.
594             assert!(ch >= 0x1_0000_u32 && ch <= 0x10_FFFF_u32);
595             ch -= 0x1_0000_u32;
596             dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
597             dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
598             2
599         }
600     }
601 }
602
603
604 #[cfg(test)]
605 mod test {
606     use super::{escape_unicode, escape_default};
607
608     use char::Char;
609     use slice::ImmutableVector;
610     use option::{Some, None};
611     use realstd::string::String;
612     use realstd::str::Str;
613
614     #[test]
615     fn test_is_lowercase() {
616         assert!('a'.is_lowercase());
617         assert!('ö'.is_lowercase());
618         assert!('ß'.is_lowercase());
619         assert!(!'Ü'.is_lowercase());
620         assert!(!'P'.is_lowercase());
621     }
622
623     #[test]
624     fn test_is_uppercase() {
625         assert!(!'h'.is_uppercase());
626         assert!(!'ä'.is_uppercase());
627         assert!(!'ß'.is_uppercase());
628         assert!('Ö'.is_uppercase());
629         assert!('T'.is_uppercase());
630     }
631
632     #[test]
633     fn test_is_whitespace() {
634         assert!(' '.is_whitespace());
635         assert!('\u2007'.is_whitespace());
636         assert!('\t'.is_whitespace());
637         assert!('\n'.is_whitespace());
638         assert!(!'a'.is_whitespace());
639         assert!(!'_'.is_whitespace());
640         assert!(!'\u0000'.is_whitespace());
641     }
642
643     #[test]
644     fn test_to_digit() {
645         assert_eq!('0'.to_digit(10u), Some(0u));
646         assert_eq!('1'.to_digit(2u), Some(1u));
647         assert_eq!('2'.to_digit(3u), Some(2u));
648         assert_eq!('9'.to_digit(10u), Some(9u));
649         assert_eq!('a'.to_digit(16u), Some(10u));
650         assert_eq!('A'.to_digit(16u), Some(10u));
651         assert_eq!('b'.to_digit(16u), Some(11u));
652         assert_eq!('B'.to_digit(16u), Some(11u));
653         assert_eq!('z'.to_digit(36u), Some(35u));
654         assert_eq!('Z'.to_digit(36u), Some(35u));
655         assert_eq!(' '.to_digit(10u), None);
656         assert_eq!('$'.to_digit(36u), None);
657     }
658
659     #[test]
660     fn test_to_lowercase() {
661         assert_eq!('A'.to_lowercase(), 'a');
662         assert_eq!('Ö'.to_lowercase(), 'ö');
663         assert_eq!('ß'.to_lowercase(), 'ß');
664         assert_eq!('Ü'.to_lowercase(), 'ü');
665         assert_eq!('💩'.to_lowercase(), '💩');
666         assert_eq!('Σ'.to_lowercase(), 'σ');
667         assert_eq!('Τ'.to_lowercase(), 'τ');
668         assert_eq!('Ι'.to_lowercase(), 'ι');
669         assert_eq!('Γ'.to_lowercase(), 'γ');
670         assert_eq!('Μ'.to_lowercase(), 'μ');
671         assert_eq!('Α'.to_lowercase(), 'α');
672         assert_eq!('Σ'.to_lowercase(), 'σ');
673     }
674
675     #[test]
676     fn test_to_uppercase() {
677         assert_eq!('a'.to_uppercase(), 'A');
678         assert_eq!('ö'.to_uppercase(), 'Ö');
679         assert_eq!('ß'.to_uppercase(), 'ß'); // not ẞ: Latin capital letter sharp s
680         assert_eq!('ü'.to_uppercase(), 'Ü');
681         assert_eq!('💩'.to_uppercase(), '💩');
682
683         assert_eq!('σ'.to_uppercase(), 'Σ');
684         assert_eq!('τ'.to_uppercase(), 'Τ');
685         assert_eq!('ι'.to_uppercase(), 'Ι');
686         assert_eq!('γ'.to_uppercase(), 'Γ');
687         assert_eq!('μ'.to_uppercase(), 'Μ');
688         assert_eq!('α'.to_uppercase(), 'Α');
689         assert_eq!('ς'.to_uppercase(), 'Σ');
690     }
691
692     #[test]
693     fn test_is_control() {
694         assert!('\u0000'.is_control());
695         assert!('\u0003'.is_control());
696         assert!('\u0006'.is_control());
697         assert!('\u0009'.is_control());
698         assert!('\u007f'.is_control());
699         assert!('\u0092'.is_control());
700         assert!(!'\u0020'.is_control());
701         assert!(!'\u0055'.is_control());
702         assert!(!'\u0068'.is_control());
703     }
704
705     #[test]
706     fn test_is_digit() {
707        assert!('2'.is_digit());
708        assert!('7'.is_digit());
709        assert!(!'c'.is_digit());
710        assert!(!'i'.is_digit());
711        assert!(!'z'.is_digit());
712        assert!(!'Q'.is_digit());
713     }
714
715     #[test]
716     fn test_escape_default() {
717         fn string(c: char) -> String {
718             let mut result = String::new();
719             escape_default(c, |c| { result.push_char(c); });
720             return result;
721         }
722         let s = string('\n');
723         assert_eq!(s.as_slice(), "\\n");
724         let s = string('\r');
725         assert_eq!(s.as_slice(), "\\r");
726         let s = string('\'');
727         assert_eq!(s.as_slice(), "\\'");
728         let s = string('"');
729         assert_eq!(s.as_slice(), "\\\"");
730         let s = string(' ');
731         assert_eq!(s.as_slice(), " ");
732         let s = string('a');
733         assert_eq!(s.as_slice(), "a");
734         let s = string('~');
735         assert_eq!(s.as_slice(), "~");
736         let s = string('\x00');
737         assert_eq!(s.as_slice(), "\\x00");
738         let s = string('\x1f');
739         assert_eq!(s.as_slice(), "\\x1f");
740         let s = string('\x7f');
741         assert_eq!(s.as_slice(), "\\x7f");
742         let s = string('\xff');
743         assert_eq!(s.as_slice(), "\\xff");
744         let s = string('\u011b');
745         assert_eq!(s.as_slice(), "\\u011b");
746         let s = string('\U0001d4b6');
747         assert_eq!(s.as_slice(), "\\U0001d4b6");
748     }
749
750     #[test]
751     fn test_escape_unicode() {
752         fn string(c: char) -> String {
753             let mut result = String::new();
754             escape_unicode(c, |c| { result.push_char(c); });
755             return result;
756         }
757         let s = string('\x00');
758         assert_eq!(s.as_slice(), "\\x00");
759         let s = string('\n');
760         assert_eq!(s.as_slice(), "\\x0a");
761         let s = string(' ');
762         assert_eq!(s.as_slice(), "\\x20");
763         let s = string('a');
764         assert_eq!(s.as_slice(), "\\x61");
765         let s = string('\u011b');
766         assert_eq!(s.as_slice(), "\\u011b");
767         let s = string('\U0001d4b6');
768         assert_eq!(s.as_slice(), "\\U0001d4b6");
769     }
770
771     #[test]
772     fn test_to_str() {
773         use realstd::to_str::ToStr;
774         let s = 't'.to_str();
775         assert_eq!(s.as_slice(), "t");
776     }
777
778     #[test]
779     fn test_encode_utf8() {
780         fn check(input: char, expect: &[u8]) {
781             let mut buf = [0u8, ..4];
782             let n = input.encode_utf8(buf /* as mut slice! */);
783             assert_eq!(buf.slice_to(n), expect);
784         }
785
786         check('x', [0x78]);
787         check('\u00e9', [0xc3, 0xa9]);
788         check('\ua66e', [0xea, 0x99, 0xae]);
789         check('\U0001f4a9', [0xf0, 0x9f, 0x92, 0xa9]);
790     }
791
792     #[test]
793     fn test_encode_utf16() {
794         fn check(input: char, expect: &[u16]) {
795             let mut buf = [0u16, ..2];
796             let n = input.encode_utf16(buf /* as mut slice! */);
797             assert_eq!(buf.slice_to(n), expect);
798         }
799
800         check('x', [0x0078]);
801         check('\u00e9', [0x00e9]);
802         check('\ua66e', [0xa66e]);
803         check('\U0001f4a9', [0xd83d, 0xdca9]);
804     }
805 }