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.
13 //! For more details, see ::unicode::char (a.k.a. std::char)
15 #![allow(non_snake_case)]
16 #![doc(primitive = "char")]
21 use option::Option::{None, Some};
25 // UTF-8 ranges and tags for encoding characters
26 static TAG_CONT: u8 = 0b1000_0000u8;
27 static TAG_TWO_B: u8 = 0b1100_0000u8;
28 static TAG_THREE_B: u8 = 0b1110_0000u8;
29 static TAG_FOUR_B: u8 = 0b1111_0000u8;
30 static MAX_ONE_B: u32 = 0x80u32;
31 static MAX_TWO_B: u32 = 0x800u32;
32 static MAX_THREE_B: u32 = 0x10000u32;
35 Lu Uppercase_Letter an uppercase letter
36 Ll Lowercase_Letter a lowercase letter
37 Lt Titlecase_Letter a digraphic character, with first part uppercase
38 Lm Modifier_Letter a modifier letter
39 Lo Other_Letter other letters, including syllables and ideographs
40 Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
41 Mc Spacing_Mark a spacing combining mark (positive advance width)
42 Me Enclosing_Mark an enclosing combining mark
43 Nd Decimal_Number a decimal digit
44 Nl Letter_Number a letterlike numeric character
45 No Other_Number a numeric character of other type
46 Pc Connector_Punctuation a connecting punctuation mark, like a tie
47 Pd Dash_Punctuation a dash or hyphen punctuation mark
48 Ps Open_Punctuation an opening punctuation mark (of a pair)
49 Pe Close_Punctuation a closing punctuation mark (of a pair)
50 Pi Initial_Punctuation an initial quotation mark
51 Pf Final_Punctuation a final quotation mark
52 Po Other_Punctuation a punctuation mark of other type
53 Sm Math_Symbol a symbol of primarily mathematical use
54 Sc Currency_Symbol a currency sign
55 Sk Modifier_Symbol a non-letterlike modifier symbol
56 So Other_Symbol a symbol of other type
57 Zs Space_Separator a space character (of various non-zero widths)
58 Zl Line_Separator U+2028 LINE SEPARATOR only
59 Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only
60 Cc Control a C0 or C1 control code
61 Cf Format a format control character
62 Cs Surrogate a surrogate code point
63 Co Private_Use a private-use character
64 Cn Unassigned a reserved unassigned code point or a noncharacter
67 /// The highest valid code point
69 pub const MAX: char = '\u{10ffff}';
71 /// Converts from `u32` to a `char`
73 #[unstable = "pending decisions about costructors for primitives"]
74 pub fn from_u32(i: u32) -> Option<char> {
75 // catch out-of-bounds and surrogates
76 if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
79 Some(unsafe { transmute(i) })
84 /// Checks if a `char` parses as a numeric digit in the given radix
86 /// Compared to `is_numeric()`, this function only recognizes the
87 /// characters `0-9`, `a-z` and `A-Z`.
91 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
96 /// Panics if given a `radix` > 36.
100 /// This just wraps `to_digit()`.
103 #[deprecated = "use the Char::is_digit method"]
104 pub fn is_digit_radix(c: char, radix: uint) -> bool {
109 /// Converts a `char` to the corresponding digit
113 /// If `c` is between '0' and '9', the corresponding value
114 /// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
115 /// 'b' or 'B', 11, etc. Returns none if the `char` does not
116 /// refer to a digit in the given radix.
120 /// Panics if given a `radix` outside the range `[0..36]`.
123 #[deprecated = "use the Char::to_digit method"]
124 pub fn to_digit(c: char, radix: uint) -> Option<uint> {
129 /// Converts a number to the character representing it
133 /// Returns `Some(char)` if `num` represents one digit under `radix`,
134 /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
138 /// Panics if given an `radix` > 36.
141 #[unstable = "pending decisions about costructors for primitives"]
142 pub fn from_digit(num: uint, radix: uint) -> Option<char> {
144 panic!("from_digit: radix is too high (maximum 36)");
149 Some(transmute(('0' as uint + num) as u32))
151 Some(transmute(('a' as uint + num - 10u) as u32))
159 /// Deprecated, call the escape_unicode method instead.
160 #[deprecated = "use the Char::escape_unicode method"]
161 pub fn escape_unicode<F>(c: char, mut f: F) where F: FnMut(char) {
162 for char in c.escape_unicode() {
167 /// Deprecated, call the escape_default method instead.
168 #[deprecated = "use the Char::escape_default method"]
169 pub fn escape_default<F>(c: char, mut f: F) where F: FnMut(char) {
170 for c in c.escape_default() {
175 /// Returns the amount of bytes this `char` would need if encoded in UTF-8
177 #[deprecated = "use the Char::len_utf8 method"]
178 pub fn len_utf8_bytes(c: char) -> uint {
182 /// Basic `char` manipulations.
183 #[experimental = "trait organization may change"]
185 /// Checks if a `char` parses as a numeric digit in the given radix.
187 /// Compared to `is_numeric()`, this function only recognizes the characters
188 /// `0-9`, `a-z` and `A-Z`.
192 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
197 /// Panics if given a radix > 36.
198 #[deprecated = "use is_digit"]
199 fn is_digit_radix(self, radix: uint) -> bool;
201 /// Checks if a `char` parses as a numeric digit in the given radix.
203 /// Compared to `is_numeric()`, this function only recognizes the characters
204 /// `0-9`, `a-z` and `A-Z`.
208 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
213 /// Panics if given a radix > 36.
214 #[unstable = "pending error conventions"]
215 fn is_digit(self, radix: uint) -> bool;
217 /// Converts a character to the corresponding digit.
221 /// If `c` is between '0' and '9', the corresponding value between 0 and
222 /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
223 /// none if the character does not refer to a digit in the given radix.
227 /// Panics if given a radix outside the range [0..36].
228 #[unstable = "pending error conventions, trait organization"]
229 fn to_digit(self, radix: uint) -> Option<uint>;
231 /// Converts a number to the character representing it.
235 /// Returns `Some(char)` if `num` represents one digit under `radix`,
236 /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
240 /// Panics if given a radix > 36.
241 #[deprecated = "use the char::from_digit free function"]
242 fn from_digit(num: uint, radix: uint) -> Option<Self>;
244 /// Converts from `u32` to a `char`
245 #[deprecated = "use the char::from_u32 free function"]
246 fn from_u32(i: u32) -> Option<char>;
248 /// Returns an iterator that yields the hexadecimal Unicode escape
249 /// of a character, as `char`s.
251 /// All characters are escaped with Rust syntax of the form `\\u{NNNN}`
252 /// where `NNNN` is the shortest hexadecimal representation of the code
254 #[unstable = "pending error conventions, trait organization"]
255 fn escape_unicode(self) -> EscapeUnicode;
257 /// Returns an iterator that yields the 'default' ASCII and
258 /// C++11-like literal escape of a character, as `char`s.
260 /// The default is chosen with a bias toward producing literals that are
261 /// legal in a variety of languages, including C++11 and similar C-family
262 /// languages. The exact rules are:
264 /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
265 /// * Single-quote, double-quote and backslash chars are backslash-
267 /// * Any other chars in the range [0x20,0x7e] are not escaped.
268 /// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
269 #[unstable = "pending error conventions, trait organization"]
270 fn escape_default(self) -> EscapeDefault;
272 /// Returns the amount of bytes this character would need if encoded in
274 #[deprecated = "use len_utf8"]
275 fn len_utf8_bytes(self) -> uint;
277 /// Returns the amount of bytes this character would need if encoded in
279 #[unstable = "pending trait organization"]
280 fn len_utf8(self) -> uint;
282 /// Returns the amount of bytes this character would need if encoded in
284 #[unstable = "pending trait organization"]
285 fn len_utf16(self) -> uint;
287 /// Encodes this character as UTF-8 into the provided byte buffer,
288 /// and then returns the number of bytes written.
290 /// If the buffer is not large enough, nothing will be written into it
291 /// and a `None` will be returned.
292 #[unstable = "pending trait organization"]
293 fn encode_utf8(&self, dst: &mut [u8]) -> Option<uint>;
295 /// Encodes this character as UTF-16 into the provided `u16` buffer,
296 /// and then returns the number of `u16`s written.
298 /// If the buffer is not large enough, nothing will be written into it
299 /// and a `None` will be returned.
300 #[unstable = "pending trait organization"]
301 fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint>;
304 #[experimental = "trait is experimental"]
306 #[deprecated = "use is_digit"]
307 fn is_digit_radix(self, radix: uint) -> bool { self.is_digit(radix) }
309 #[unstable = "pending trait organization"]
310 fn is_digit(self, radix: uint) -> bool {
311 match self.to_digit(radix) {
317 #[unstable = "pending trait organization"]
318 fn to_digit(self, radix: uint) -> Option<uint> {
320 panic!("to_digit: radix is too high (maximum 36)");
322 let val = match self {
323 '0' ... '9' => self as uint - ('0' as uint),
324 'a' ... 'z' => self as uint + 10u - ('a' as uint),
325 'A' ... 'Z' => self as uint + 10u - ('A' as uint),
328 if val < radix { Some(val) }
332 #[deprecated = "use the char::from_digit free function"]
333 fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
336 #[deprecated = "use the char::from_u32 free function"]
337 fn from_u32(i: u32) -> Option<char> { from_u32(i) }
339 #[unstable = "pending error conventions, trait organization"]
340 fn escape_unicode(self) -> EscapeUnicode {
341 EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
344 #[unstable = "pending error conventions, trait organization"]
345 fn escape_default(self) -> EscapeDefault {
346 let init_state = match self {
347 '\t' => EscapeDefaultState::Backslash('t'),
348 '\r' => EscapeDefaultState::Backslash('r'),
349 '\n' => EscapeDefaultState::Backslash('n'),
350 '\\' => EscapeDefaultState::Backslash('\\'),
351 '\'' => EscapeDefaultState::Backslash('\''),
352 '"' => EscapeDefaultState::Backslash('"'),
353 '\x20' ... '\x7e' => EscapeDefaultState::Char(self),
354 _ => EscapeDefaultState::Unicode(self.escape_unicode())
356 EscapeDefault { state: init_state }
360 #[deprecated = "use len_utf8"]
361 fn len_utf8_bytes(self) -> uint { self.len_utf8() }
364 #[unstable = "pending trait organization"]
365 fn len_utf8(self) -> uint {
366 let code = self as u32;
368 _ if code < MAX_ONE_B => 1u,
369 _ if code < MAX_TWO_B => 2u,
370 _ if code < MAX_THREE_B => 3u,
376 #[unstable = "pending trait organization"]
377 fn len_utf16(self) -> uint {
378 let ch = self as u32;
379 if (ch & 0xFFFF_u32) == ch { 1 } else { 2 }
383 #[unstable = "pending error conventions, trait organization"]
384 fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
385 // Marked #[inline] to allow llvm optimizing it away
386 let code = *self as u32;
387 if code < MAX_ONE_B && dst.len() >= 1 {
390 } else if code < MAX_TWO_B && dst.len() >= 2 {
391 dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
392 dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
394 } else if code < MAX_THREE_B && dst.len() >= 3 {
395 dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
396 dst[1] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
397 dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
399 } else if dst.len() >= 4 {
400 dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
401 dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
402 dst[2] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
403 dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
411 #[unstable = "pending error conventions, trait organization"]
412 fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint> {
413 // Marked #[inline] to allow llvm optimizing it away
414 let mut ch = *self as u32;
415 if (ch & 0xFFFF_u32) == ch && dst.len() >= 1 {
416 // The BMP falls through (assuming non-surrogate, as it should)
419 } else if dst.len() >= 2 {
420 // Supplementary planes break into surrogates.
422 dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
423 dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
431 /// An iterator over the characters that represent a `char`, as escaped by
432 /// Rust's unicode escaping rules.
434 pub struct EscapeUnicode {
436 state: EscapeUnicodeState
440 enum EscapeUnicodeState {
449 impl Iterator for EscapeUnicode {
452 fn next(&mut self) -> Option<char> {
454 EscapeUnicodeState::Backslash => {
455 self.state = EscapeUnicodeState::Type;
458 EscapeUnicodeState::Type => {
459 self.state = EscapeUnicodeState::LeftBrace;
462 EscapeUnicodeState::LeftBrace => {
464 while (self.c as u32) >> (4 * (n + 1)) != 0 {
467 self.state = EscapeUnicodeState::Value(n);
470 EscapeUnicodeState::Value(offset) => {
471 let v = match ((self.c as i32) >> (offset * 4)) & 0xf {
472 i @ 0 ... 9 => '0' as i32 + i,
473 i => 'a' as i32 + (i - 10)
476 self.state = EscapeUnicodeState::RightBrace;
478 self.state = EscapeUnicodeState::Value(offset - 1);
480 Some(unsafe { transmute(v) })
482 EscapeUnicodeState::RightBrace => {
483 self.state = EscapeUnicodeState::Done;
486 EscapeUnicodeState::Done => None,
491 /// An iterator over the characters that represent a `char`, escaped
492 /// for maximum portability.
494 pub struct EscapeDefault {
495 state: EscapeDefaultState
499 enum EscapeDefaultState {
503 Unicode(EscapeUnicode),
506 impl Iterator for EscapeDefault {
509 fn next(&mut self) -> Option<char> {
511 EscapeDefaultState::Backslash(c) => {
512 self.state = EscapeDefaultState::Char(c);
515 EscapeDefaultState::Char(c) => {
516 self.state = EscapeDefaultState::Done;
519 EscapeDefaultState::Done => None,
520 EscapeDefaultState::Unicode(ref mut iter) => iter.next()