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