]> git.lizzy.rs Git - rust.git/blob - src/libcore/char.rs
librustc: Remove the fallback to `int` from typechecking.
[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         let offset = offset as uint;
312         unsafe {
313             match ((c as i32) >> offset) & 0xf {
314                 i @ 0 .. 9 => { f(transmute('0' as i32 + i)); }
315                 i => { f(transmute('a' as i32 + (i - 10))); }
316             }
317         }
318     }
319 }
320
321 ///
322 /// Returns a 'default' ASCII and C++11-like literal escape of a `char`
323 ///
324 /// The default is chosen with a bias toward producing literals that are
325 /// legal in a variety of languages, including C++11 and similar C-family
326 /// languages. The exact rules are:
327 ///
328 /// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
329 /// - Single-quote, double-quote and backslash chars are backslash-escaped.
330 /// - Any other chars in the range [0x20,0x7e] are not escaped.
331 /// - Any other chars are given hex unicode escapes; see `escape_unicode`.
332 ///
333 pub fn escape_default(c: char, f: |char|) {
334     match c {
335         '\t' => { f('\\'); f('t'); }
336         '\r' => { f('\\'); f('r'); }
337         '\n' => { f('\\'); f('n'); }
338         '\\' => { f('\\'); f('\\'); }
339         '\'' => { f('\\'); f('\''); }
340         '"'  => { f('\\'); f('"'); }
341         '\x20' .. '\x7e' => { f(c); }
342         _ => c.escape_unicode(f),
343     }
344 }
345
346 /// Returns the amount of bytes this `char` would need if encoded in UTF-8
347 pub fn len_utf8_bytes(c: char) -> uint {
348     let code = c as u32;
349     match () {
350         _ if code < MAX_ONE_B   => 1u,
351         _ if code < MAX_TWO_B   => 2u,
352         _ if code < MAX_THREE_B => 3u,
353         _ if code < MAX_FOUR_B  => 4u,
354         _                       => fail!("invalid character!"),
355     }
356 }
357
358 /// Useful functions for Unicode characters.
359 pub trait Char {
360     /// Returns whether the specified character is considered a Unicode
361     /// alphabetic code point.
362     fn is_alphabetic(&self) -> bool;
363
364     /// Returns whether the specified character satisfies the 'XID_Start'
365     /// Unicode property.
366     ///
367     /// 'XID_Start' is a Unicode Derived Property specified in
368     /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
369     /// mostly similar to ID_Start but modified for closure under NFKx.
370     fn is_XID_start(&self) -> bool;
371
372     /// Returns whether the specified `char` satisfies the 'XID_Continue'
373     /// Unicode property.
374     ///
375     /// 'XID_Continue' is a Unicode Derived Property specified in
376     /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
377     /// mostly similar to 'ID_Continue' but modified for closure under NFKx.
378     fn is_XID_continue(&self) -> bool;
379
380
381     /// Indicates whether a character is in lowercase.
382     ///
383     /// This is defined according to the terms of the Unicode Derived Core
384     /// Property `Lowercase`.
385     fn is_lowercase(&self) -> bool;
386
387     /// Indicates whether a character is in uppercase.
388     ///
389     /// This is defined according to the terms of the Unicode Derived Core
390     /// Property `Uppercase`.
391     fn is_uppercase(&self) -> bool;
392
393     /// Indicates whether a character is whitespace.
394     ///
395     /// Whitespace is defined in terms of the Unicode Property `White_Space`.
396     fn is_whitespace(&self) -> bool;
397
398     /// Indicates whether a character is alphanumeric.
399     ///
400     /// Alphanumericness is defined in terms of the Unicode General Categories
401     /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
402     fn is_alphanumeric(&self) -> bool;
403
404     /// Indicates whether a character is a control code point.
405     ///
406     /// Control code points are defined in terms of the Unicode General
407     /// Category `Cc`.
408     fn is_control(&self) -> bool;
409
410     /// Indicates whether the character is numeric (Nd, Nl, or No).
411     fn is_digit(&self) -> bool;
412
413     /// Checks if a `char` parses as a numeric digit in the given radix.
414     ///
415     /// Compared to `is_digit()`, this function only recognizes the characters
416     /// `0-9`, `a-z` and `A-Z`.
417     ///
418     /// # Return value
419     ///
420     /// Returns `true` if `c` is a valid digit under `radix`, and `false`
421     /// otherwise.
422     ///
423     /// # Failure
424     ///
425     /// Fails if given a radix > 36.
426     fn is_digit_radix(&self, radix: uint) -> bool;
427
428     /// Converts a character to the corresponding digit.
429     ///
430     /// # Return value
431     ///
432     /// If `c` is between '0' and '9', the corresponding value between 0 and
433     /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
434     /// none if the character does not refer to a digit in the given radix.
435     ///
436     /// # Failure
437     ///
438     /// Fails if given a radix outside the range [0..36].
439     fn to_digit(&self, radix: uint) -> Option<uint>;
440
441     /// Converts a character to its lowercase equivalent.
442     ///
443     /// The case-folding performed is the common or simple mapping. See
444     /// `to_uppercase()` for references and more information.
445     ///
446     /// # Return value
447     ///
448     /// Returns the lowercase equivalent of the character, or the character
449     /// itself if no conversion is possible.
450     fn to_lowercase(&self) -> char;
451
452     /// Converts a character to its uppercase equivalent.
453     ///
454     /// The case-folding performed is the common or simple mapping: it maps
455     /// one unicode codepoint (one character in Rust) to its uppercase
456     /// equivalent according to the Unicode database [1]. The additional
457     /// `SpecialCasing.txt` is not considered here, as it expands to multiple
458     /// codepoints in some cases.
459     ///
460     /// A full reference can be found here [2].
461     ///
462     /// # Return value
463     ///
464     /// Returns the uppercase equivalent of the character, or the character
465     /// itself if no conversion was made.
466     ///
467     /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
468     ///
469     /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
470     fn to_uppercase(&self) -> char;
471
472     /// Converts a number to the character representing it.
473     ///
474     /// # Return value
475     ///
476     /// Returns `Some(char)` if `num` represents one digit under `radix`,
477     /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
478     ///
479     /// # Failure
480     ///
481     /// Fails if given a radix > 36.
482     fn from_digit(num: uint, radix: uint) -> Option<char>;
483
484     /// Returns the hexadecimal Unicode escape of a character.
485     ///
486     /// The rules are as follows:
487     ///
488     /// * Characters in [0,0xff] get 2-digit escapes: `\\xNN`
489     /// * Characters in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`.
490     /// * Characters above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`.
491     fn escape_unicode(&self, f: |char|);
492
493     /// Returns a 'default' ASCII and C++11-like literal escape of a
494     /// character.
495     ///
496     /// The default is chosen with a bias toward producing literals that are
497     /// legal in a variety of languages, including C++11 and similar C-family
498     /// languages. The exact rules are:
499     ///
500     /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
501     /// * Single-quote, double-quote and backslash chars are backslash-
502     ///   escaped.
503     /// * Any other chars in the range [0x20,0x7e] are not escaped.
504     /// * Any other chars are given hex unicode escapes; see `escape_unicode`.
505     fn escape_default(&self, f: |char|);
506
507     /// Returns the amount of bytes this character would need if encoded in
508     /// UTF-8.
509     fn len_utf8_bytes(&self) -> uint;
510
511     /// Encodes this character as UTF-8 into the provided byte buffer.
512     ///
513     /// The buffer must be at least 4 bytes long or a runtime failure may
514     /// occur.
515     ///
516     /// This will then return the number of bytes written to the slice.
517     fn encode_utf8(&self, dst: &mut [u8]) -> uint;
518
519     /// Encodes this character as UTF-16 into the provided `u16` buffer.
520     ///
521     /// The buffer must be at least 2 elements long or a runtime failure may
522     /// occur.
523     ///
524     /// This will then return the number of `u16`s written to the slice.
525     fn encode_utf16(&self, dst: &mut [u16]) -> uint;
526 }
527
528 impl Char for char {
529     fn is_alphabetic(&self) -> bool { is_alphabetic(*self) }
530
531     fn is_XID_start(&self) -> bool { is_XID_start(*self) }
532
533     fn is_XID_continue(&self) -> bool { is_XID_continue(*self) }
534
535     fn is_lowercase(&self) -> bool { is_lowercase(*self) }
536
537     fn is_uppercase(&self) -> bool { is_uppercase(*self) }
538
539     fn is_whitespace(&self) -> bool { is_whitespace(*self) }
540
541     fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
542
543     fn is_control(&self) -> bool { is_control(*self) }
544
545     fn is_digit(&self) -> bool { is_digit(*self) }
546
547     fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
548
549     fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
550
551     fn to_lowercase(&self) -> char { to_lowercase(*self) }
552
553     fn to_uppercase(&self) -> char { to_uppercase(*self) }
554
555     fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
556
557     fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
558
559     fn escape_default(&self, f: |char|) { escape_default(*self, f) }
560
561     fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
562
563     fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> uint {
564         let code = *self as u32;
565         if code < MAX_ONE_B {
566             dst[0] = code as u8;
567             1
568         } else if code < MAX_TWO_B {
569             dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
570             dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
571             2
572         } else if code < MAX_THREE_B {
573             dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
574             dst[1] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
575             dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
576             3
577         } else {
578             dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
579             dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
580             dst[2] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
581             dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
582             4
583         }
584     }
585
586     fn encode_utf16(&self, dst: &mut [u16]) -> uint {
587         let mut ch = *self as u32;
588         if (ch & 0xFFFF_u32) == ch {
589             // The BMP falls through (assuming non-surrogate, as it should)
590             assert!(ch <= 0xD7FF_u32 || ch >= 0xE000_u32);
591             dst[0] = ch as u16;
592             1
593         } else {
594             // Supplementary planes break into surrogates.
595             assert!(ch >= 0x1_0000_u32 && ch <= 0x10_FFFF_u32);
596             ch -= 0x1_0000_u32;
597             dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
598             dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
599             2
600         }
601     }
602 }
603
604
605 #[cfg(test)]
606 mod test {
607     use super::{escape_unicode, escape_default};
608
609     use char::Char;
610     use slice::ImmutableVector;
611     use option::{Some, None};
612     use realstd::string::String;
613     use realstd::str::Str;
614
615     #[test]
616     fn test_is_lowercase() {
617         assert!('a'.is_lowercase());
618         assert!('ö'.is_lowercase());
619         assert!('ß'.is_lowercase());
620         assert!(!'Ü'.is_lowercase());
621         assert!(!'P'.is_lowercase());
622     }
623
624     #[test]
625     fn test_is_uppercase() {
626         assert!(!'h'.is_uppercase());
627         assert!(!'ä'.is_uppercase());
628         assert!(!'ß'.is_uppercase());
629         assert!('Ö'.is_uppercase());
630         assert!('T'.is_uppercase());
631     }
632
633     #[test]
634     fn test_is_whitespace() {
635         assert!(' '.is_whitespace());
636         assert!('\u2007'.is_whitespace());
637         assert!('\t'.is_whitespace());
638         assert!('\n'.is_whitespace());
639         assert!(!'a'.is_whitespace());
640         assert!(!'_'.is_whitespace());
641         assert!(!'\u0000'.is_whitespace());
642     }
643
644     #[test]
645     fn test_to_digit() {
646         assert_eq!('0'.to_digit(10u), Some(0u));
647         assert_eq!('1'.to_digit(2u), Some(1u));
648         assert_eq!('2'.to_digit(3u), Some(2u));
649         assert_eq!('9'.to_digit(10u), Some(9u));
650         assert_eq!('a'.to_digit(16u), Some(10u));
651         assert_eq!('A'.to_digit(16u), Some(10u));
652         assert_eq!('b'.to_digit(16u), Some(11u));
653         assert_eq!('B'.to_digit(16u), Some(11u));
654         assert_eq!('z'.to_digit(36u), Some(35u));
655         assert_eq!('Z'.to_digit(36u), Some(35u));
656         assert_eq!(' '.to_digit(10u), None);
657         assert_eq!('$'.to_digit(36u), None);
658     }
659
660     #[test]
661     fn test_to_lowercase() {
662         assert_eq!('A'.to_lowercase(), 'a');
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         assert_eq!('Σ'.to_lowercase(), 'σ');
674     }
675
676     #[test]
677     fn test_to_uppercase() {
678         assert_eq!('a'.to_uppercase(), 'A');
679         assert_eq!('ö'.to_uppercase(), 'Ö');
680         assert_eq!('ß'.to_uppercase(), 'ß'); // not ẞ: Latin capital letter sharp s
681         assert_eq!('ü'.to_uppercase(), 'Ü');
682         assert_eq!('💩'.to_uppercase(), '💩');
683
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         assert_eq!('ς'.to_uppercase(), 'Σ');
691     }
692
693     #[test]
694     fn test_is_control() {
695         assert!('\u0000'.is_control());
696         assert!('\u0003'.is_control());
697         assert!('\u0006'.is_control());
698         assert!('\u0009'.is_control());
699         assert!('\u007f'.is_control());
700         assert!('\u0092'.is_control());
701         assert!(!'\u0020'.is_control());
702         assert!(!'\u0055'.is_control());
703         assert!(!'\u0068'.is_control());
704     }
705
706     #[test]
707     fn test_is_digit() {
708        assert!('2'.is_digit());
709        assert!('7'.is_digit());
710        assert!(!'c'.is_digit());
711        assert!(!'i'.is_digit());
712        assert!(!'z'.is_digit());
713        assert!(!'Q'.is_digit());
714     }
715
716     #[test]
717     fn test_escape_default() {
718         fn string(c: char) -> String {
719             let mut result = String::new();
720             escape_default(c, |c| { result.push_char(c); });
721             return result;
722         }
723         let s = string('\n');
724         assert_eq!(s.as_slice(), "\\n");
725         let s = string('\r');
726         assert_eq!(s.as_slice(), "\\r");
727         let s = string('\'');
728         assert_eq!(s.as_slice(), "\\'");
729         let s = string('"');
730         assert_eq!(s.as_slice(), "\\\"");
731         let s = string(' ');
732         assert_eq!(s.as_slice(), " ");
733         let s = string('a');
734         assert_eq!(s.as_slice(), "a");
735         let s = string('~');
736         assert_eq!(s.as_slice(), "~");
737         let s = string('\x00');
738         assert_eq!(s.as_slice(), "\\x00");
739         let s = string('\x1f');
740         assert_eq!(s.as_slice(), "\\x1f");
741         let s = string('\x7f');
742         assert_eq!(s.as_slice(), "\\x7f");
743         let s = string('\xff');
744         assert_eq!(s.as_slice(), "\\xff");
745         let s = string('\u011b');
746         assert_eq!(s.as_slice(), "\\u011b");
747         let s = string('\U0001d4b6');
748         assert_eq!(s.as_slice(), "\\U0001d4b6");
749     }
750
751     #[test]
752     fn test_escape_unicode() {
753         fn string(c: char) -> String {
754             let mut result = String::new();
755             escape_unicode(c, |c| { result.push_char(c); });
756             return result;
757         }
758         let s = string('\x00');
759         assert_eq!(s.as_slice(), "\\x00");
760         let s = string('\n');
761         assert_eq!(s.as_slice(), "\\x0a");
762         let s = string(' ');
763         assert_eq!(s.as_slice(), "\\x20");
764         let s = string('a');
765         assert_eq!(s.as_slice(), "\\x61");
766         let s = string('\u011b');
767         assert_eq!(s.as_slice(), "\\u011b");
768         let s = string('\U0001d4b6');
769         assert_eq!(s.as_slice(), "\\U0001d4b6");
770     }
771
772     #[test]
773     fn test_to_str() {
774         use realstd::to_str::ToStr;
775         let s = 't'.to_str();
776         assert_eq!(s.as_slice(), "t");
777     }
778
779     #[test]
780     fn test_encode_utf8() {
781         fn check(input: char, expect: &[u8]) {
782             let mut buf = [0u8, ..4];
783             let n = input.encode_utf8(buf /* as mut slice! */);
784             assert_eq!(buf.slice_to(n), expect);
785         }
786
787         check('x', [0x78]);
788         check('\u00e9', [0xc3, 0xa9]);
789         check('\ua66e', [0xea, 0x99, 0xae]);
790         check('\U0001f4a9', [0xf0, 0x9f, 0x92, 0xa9]);
791     }
792
793     #[test]
794     fn test_encode_utf16() {
795         fn check(input: char, expect: &[u16]) {
796             let mut buf = [0u16, ..2];
797             let n = input.encode_utf16(buf /* as mut slice! */);
798             assert_eq!(buf.slice_to(n), expect);
799         }
800
801         check('x', [0x0078]);
802         check('\u00e9', [0x00e9]);
803         check('\ua66e', [0xa66e]);
804         check('\U0001f4a9', [0xd83d, 0xdca9]);
805     }
806 }