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