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.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Character manipulation (`char` type, Unicode Scalar Value)
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.
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.
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..
26 #![allow(non_snake_case_functions)]
27 #![doc(primitive = "char")]
30 use option::{None, Option, Some};
31 use iter::{Iterator, range_step};
32 use unicode::{derived_property, property, general_category, conversions};
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;
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;
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
82 /// The highest valid code point
83 pub static MAX: char = '\U0010ffff';
85 /// Converts from `u32` to a `char`
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) {
92 Some(unsafe { transmute(i) })
96 /// Returns whether the specified `char` is considered a Unicode alphabetic
98 pub fn is_alphabetic(c: char) -> bool { derived_property::Alphabetic(c) }
100 /// Returns whether the specified `char` satisfies the 'XID_Start' Unicode property
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) }
107 /// Returns whether the specified `char` satisfies the 'XID_Continue' Unicode property
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) }
115 /// Indicates whether a `char` is in lower case
117 /// This is defined according to the terms of the Unicode Derived Core Property 'Lowercase'.
120 pub fn is_lowercase(c: char) -> bool { derived_property::Lowercase(c) }
123 /// Indicates whether a `char` is in upper case
125 /// This is defined according to the terms of the Unicode Derived Core Property 'Uppercase'.
128 pub fn is_uppercase(c: char) -> bool { derived_property::Uppercase(c) }
131 /// Indicates whether a `char` is whitespace
133 /// Whitespace is defined in terms of the Unicode Property 'White_Space'.
136 pub fn is_whitespace(c: char) -> bool {
137 // As an optimization ASCII whitespace characters are checked separately
139 || ('\x09' <= c && c <= '\x0d')
140 || property::White_Space(c)
144 /// Indicates whether a `char` is alphanumeric
146 /// Alphanumericness is defined in terms of the Unicode General Categories
147 /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
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)
158 /// Indicates whether a `char` is a control code point
160 /// Control code points are defined in terms of the Unicode General Category
164 pub fn is_control(c: char) -> bool { general_category::Cc(c) }
166 /// Indicates whether the `char` is numeric (Nd, Nl, or No)
168 pub fn is_digit(c: char) -> bool {
169 general_category::Nd(c)
170 || general_category::Nl(c)
171 || general_category::No(c)
175 /// Checks if a `char` parses as a numeric digit in the given radix
177 /// Compared to `is_digit()`, this function only recognizes the
178 /// characters `0-9`, `a-z` and `A-Z`.
182 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
187 /// Fails if given a `radix` > 36.
191 /// This just wraps `to_digit()`.
194 pub fn is_digit_radix(c: char, radix: uint) -> bool {
195 match to_digit(c, radix) {
202 /// Converts a `char` to the corresponding digit
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.
213 /// Fails if given a `radix` outside the range `[0..36]`.
216 pub fn to_digit(c: char, radix: uint) -> Option<uint> {
218 fail!("to_digit: radix is too high (maximum 36)");
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),
226 if val < radix { Some(val) }
230 /// Convert a char to its uppercase equivalent
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.
238 /// A full reference can be found here
239 /// http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
243 /// Returns the char itself if no conversion was made
245 pub fn to_uppercase(c: char) -> char {
246 conversions::to_upper(c)
249 /// Convert a char to its lowercase equivalent
251 /// The case-folding performed is the common or simple mapping
252 /// see `to_uppercase` for references and more information
256 /// Returns the char itself if no conversion if possible
258 pub fn to_lowercase(c: char) -> char {
259 conversions::to_lower(c)
263 /// Converts a number to the character representing it
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.
272 /// Fails if given an `radix` > 36.
275 pub fn from_digit(num: uint, radix: uint) -> Option<char> {
277 fail!("from_digit: radix is to high (maximum 36)");
282 Some(transmute(('0' as uint + num) as u32))
284 Some(transmute(('a' as uint + num - 10u) as u32))
293 /// Returns the hexadecimal Unicode escape of a `char`
295 /// The rules are as follows:
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`
301 pub fn escape_unicode(c: char, f: |char|) {
302 // avoid calling str::to_str_radix because we don't really need to allocate
306 _ if c <= '\xff' => { f('x'); 2 }
307 _ if c <= '\uffff' => { f('u'); 4 }
310 for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
311 let offset = offset as uint;
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))); }
322 /// Returns a 'default' ASCII and C++11-like literal escape of a `char`
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:
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`.
333 pub fn escape_default(c: char, f: |char|) {
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),
346 /// Returns the amount of bytes this `char` would need if encoded in UTF-8
347 pub fn len_utf8_bytes(c: char) -> uint {
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!"),
358 /// Useful functions for Unicode characters.
360 /// Returns whether the specified character is considered a Unicode
361 /// alphabetic code point.
362 fn is_alphabetic(&self) -> bool;
364 /// Returns whether the specified character satisfies the 'XID_Start'
365 /// Unicode property.
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;
372 /// Returns whether the specified `char` satisfies the 'XID_Continue'
373 /// Unicode property.
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;
381 /// Indicates whether a character is in lowercase.
383 /// This is defined according to the terms of the Unicode Derived Core
384 /// Property `Lowercase`.
385 fn is_lowercase(&self) -> bool;
387 /// Indicates whether a character is in uppercase.
389 /// This is defined according to the terms of the Unicode Derived Core
390 /// Property `Uppercase`.
391 fn is_uppercase(&self) -> bool;
393 /// Indicates whether a character is whitespace.
395 /// Whitespace is defined in terms of the Unicode Property `White_Space`.
396 fn is_whitespace(&self) -> bool;
398 /// Indicates whether a character is alphanumeric.
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;
404 /// Indicates whether a character is a control code point.
406 /// Control code points are defined in terms of the Unicode General
408 fn is_control(&self) -> bool;
410 /// Indicates whether the character is numeric (Nd, Nl, or No).
411 fn is_digit(&self) -> bool;
413 /// Checks if a `char` parses as a numeric digit in the given radix.
415 /// Compared to `is_digit()`, this function only recognizes the characters
416 /// `0-9`, `a-z` and `A-Z`.
420 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
425 /// Fails if given a radix > 36.
426 fn is_digit_radix(&self, radix: uint) -> bool;
428 /// Converts a character to the corresponding digit.
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.
438 /// Fails if given a radix outside the range [0..36].
439 fn to_digit(&self, radix: uint) -> Option<uint>;
441 /// Converts a character to its lowercase equivalent.
443 /// The case-folding performed is the common or simple mapping. See
444 /// `to_uppercase()` for references and more information.
448 /// Returns the lowercase equivalent of the character, or the character
449 /// itself if no conversion is possible.
450 fn to_lowercase(&self) -> char;
452 /// Converts a character to its uppercase equivalent.
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.
460 /// A full reference can be found here [2].
464 /// Returns the uppercase equivalent of the character, or the character
465 /// itself if no conversion was made.
467 /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
469 /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
470 fn to_uppercase(&self) -> char;
472 /// Converts a number to the character representing it.
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.
481 /// Fails if given a radix > 36.
482 fn from_digit(num: uint, radix: uint) -> Option<char>;
484 /// Returns the hexadecimal Unicode escape of a character.
486 /// The rules are as follows:
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|);
493 /// Returns a 'default' ASCII and C++11-like literal escape of a
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:
500 /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
501 /// * Single-quote, double-quote and backslash chars are backslash-
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|);
507 /// Returns the amount of bytes this character would need if encoded in
509 fn len_utf8_bytes(&self) -> uint;
511 /// Encodes this character as UTF-8 into the provided byte buffer.
513 /// The buffer must be at least 4 bytes long or a runtime failure may
516 /// This will then return the number of bytes written to the slice.
517 fn encode_utf8(&self, dst: &mut [u8]) -> uint;
519 /// Encodes this character as UTF-16 into the provided `u16` buffer.
521 /// The buffer must be at least 2 elements long or a runtime failure may
524 /// This will then return the number of `u16`s written to the slice.
525 fn encode_utf16(&self, dst: &mut [u16]) -> uint;
529 fn is_alphabetic(&self) -> bool { is_alphabetic(*self) }
531 fn is_XID_start(&self) -> bool { is_XID_start(*self) }
533 fn is_XID_continue(&self) -> bool { is_XID_continue(*self) }
535 fn is_lowercase(&self) -> bool { is_lowercase(*self) }
537 fn is_uppercase(&self) -> bool { is_uppercase(*self) }
539 fn is_whitespace(&self) -> bool { is_whitespace(*self) }
541 fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
543 fn is_control(&self) -> bool { is_control(*self) }
545 fn is_digit(&self) -> bool { is_digit(*self) }
547 fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
549 fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
551 fn to_lowercase(&self) -> char { to_lowercase(*self) }
553 fn to_uppercase(&self) -> char { to_uppercase(*self) }
555 fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
557 fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
559 fn escape_default(&self, f: |char|) { escape_default(*self, f) }
561 fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
563 fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> uint {
564 let code = *self as u32;
565 if code < MAX_ONE_B {
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;
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;
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;
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);
594 // Supplementary planes break into surrogates.
595 assert!(ch >= 0x1_0000_u32 && ch <= 0x10_FFFF_u32);
597 dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
598 dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
607 use super::{escape_unicode, escape_default};
610 use slice::ImmutableVector;
611 use option::{Some, None};
612 use realstd::string::String;
613 use realstd::str::Str;
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());
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());
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());
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);
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(), 'σ');
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(), '💩');
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(), 'Σ');
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());
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());
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); });
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(), "\\'");
730 assert_eq!(s.as_slice(), "\\\"");
732 assert_eq!(s.as_slice(), " ");
734 assert_eq!(s.as_slice(), "a");
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");
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); });
758 let s = string('\x00');
759 assert_eq!(s.as_slice(), "\\x00");
760 let s = string('\n');
761 assert_eq!(s.as_slice(), "\\x0a");
763 assert_eq!(s.as_slice(), "\\x20");
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");
774 use realstd::to_str::ToStr;
775 let s = 't'.to_str();
776 assert_eq!(s.as_slice(), "t");
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);
788 check('\u00e9', [0xc3, 0xa9]);
789 check('\ua66e', [0xea, 0x99, 0xae]);
790 check('\U0001f4a9', [0xf0, 0x9f, 0x92, 0xa9]);
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);
801 check('x', [0x0078]);
802 check('\u00e9', [0x00e9]);
803 check('\ua66e', [0xa66e]);
804 check('\U0001f4a9', [0xd83d, 0xdca9]);