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 ::rustc_unicode::char (a.k.a. std::char)
15 #![allow(non_snake_case)]
16 #![stable(feature = "core_char", since = "1.2.0")]
20 use option
::Option
::{None, Some}
;
24 // UTF-8 ranges and tags for encoding characters
25 const TAG_CONT
: u8 = 0b1000_0000;
26 const TAG_TWO_B
: u8 = 0b1100_0000;
27 const TAG_THREE_B
: u8 = 0b1110_0000;
28 const TAG_FOUR_B
: u8 = 0b1111_0000;
29 const MAX_ONE_B
: u32 = 0x80;
30 const MAX_TWO_B
: u32 = 0x800;
31 const MAX_THREE_B
: u32 = 0x10000;
34 Lu Uppercase_Letter an uppercase letter
35 Ll Lowercase_Letter a lowercase letter
36 Lt Titlecase_Letter a digraphic character, with first part uppercase
37 Lm Modifier_Letter a modifier letter
38 Lo Other_Letter other letters, including syllables and ideographs
39 Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
40 Mc Spacing_Mark a spacing combining mark (positive advance width)
41 Me Enclosing_Mark an enclosing combining mark
42 Nd Decimal_Number a decimal digit
43 Nl Letter_Number a letterlike numeric character
44 No Other_Number a numeric character of other type
45 Pc Connector_Punctuation a connecting punctuation mark, like a tie
46 Pd Dash_Punctuation a dash or hyphen punctuation mark
47 Ps Open_Punctuation an opening punctuation mark (of a pair)
48 Pe Close_Punctuation a closing punctuation mark (of a pair)
49 Pi Initial_Punctuation an initial quotation mark
50 Pf Final_Punctuation a final quotation mark
51 Po Other_Punctuation a punctuation mark of other type
52 Sm Math_Symbol a symbol of primarily mathematical use
53 Sc Currency_Symbol a currency sign
54 Sk Modifier_Symbol a non-letterlike modifier symbol
55 So Other_Symbol a symbol of other type
56 Zs Space_Separator a space character (of various non-zero widths)
57 Zl Line_Separator U+2028 LINE SEPARATOR only
58 Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only
59 Cc Control a C0 or C1 control code
60 Cf Format a format control character
61 Cs Surrogate a surrogate code point
62 Co Private_Use a private-use character
63 Cn Unassigned a reserved unassigned code point or a noncharacter
66 /// The highest valid code point a `char` can have.
68 /// A [`char`] is a [Unicode Scalar Value], which means that it is a [Code
69 /// Point], but only ones within a certain range. `MAX` is the highest valid
70 /// code point that's a valid [Unicode Scalar Value].
72 /// [`char`]: primitive.char.html
73 /// [Unicode Scalar Value]: http://www.unicode.org/glossary/#unicode_scalar_value
74 /// [Code Point]: http://www.unicode.org/glossary/#code_point
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub const MAX
: char = '
\u{10ffff}'
;
78 /// Converts a `u32` to a `char`.
80 /// Note that all [`char`]s are valid [`u32`]s, and can be casted to one with
87 /// assert_eq!(128175, i);
90 /// However, the reverse is not true: not all valid [`u32`]s are valid
91 /// [`char`]s. `from_u32()` will return `None` if the input is not a valid value
94 /// [`char`]: primitive.char.html
95 /// [`u32`]: primitive.u32.html
96 /// [`as`]: ../book/casting-between-types.html#as
98 /// For an unsafe version of this function which ignores these checks, see
99 /// [`from_u32_unchecked()`].
101 /// [`from_u32_unchecked()`]: fn.from_u32_unchecked.html
110 /// let c = char::from_u32(0x2764);
112 /// assert_eq!(Some('❤'), c);
115 /// Returning `None` when the input is not a valid [`char`]:
120 /// let c = char::from_u32(0x110000);
122 /// assert_eq!(None, c);
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub fn from_u32(i
: u32) -> Option
<char> {
127 // catch out-of-bounds and surrogates
128 if (i
> MAX
as u32) || (i
>= 0xD800 && i
<= 0xDFFF) {
131 Some(unsafe { from_u32_unchecked(i) }
)
135 /// Converts a `u32` to a `char`, ignoring validity.
137 /// Note that all [`char`]s are valid [`u32`]s, and can be casted to one with
142 /// let i = c as u32;
144 /// assert_eq!(128175, i);
147 /// However, the reverse is not true: not all valid [`u32`]s are valid
148 /// [`char`]s. `from_u32_unchecked()` will ignore this, and blindly cast to
149 /// [`char`], possibly creating an invalid one.
151 /// [`char`]: primitive.char.html
152 /// [`u32`]: primitive.u32.html
153 /// [`as`]: ../book/casting-between-types.html#as
157 /// This function is unsafe, as it may construct invalid `char` values.
159 /// For a safe version of this function, see the [`from_u32()`] function.
161 /// [`from_u32()`]: fn.from_u32.html
170 /// let c = unsafe { char::from_u32_unchecked(0x2764) };
172 /// assert_eq!('❤', c);
175 #[stable(feature = "char_from_unchecked", since = "1.5.0")]
176 pub unsafe fn from_u32_unchecked(i
: u32) -> char {
180 /// Converts a digit in the given radix to a `char`.
182 /// A 'radix' here is sometimes also called a 'base'. A radix of two
183 /// indicates a binary number, a radix of ten, decimal, and a radix of
184 /// sixteen, hexicdecimal, to give some common values. Arbitrary
185 /// radicum are supported.
187 /// `from_digit()` will return `None` if the input is not a digit in
192 /// Panics if given a radix larger than 36.
201 /// let c = char::from_digit(4, 10);
203 /// assert_eq!(Some('4'), c);
205 /// // Decimal 11 is a single digit in base 16
206 /// let c = char::from_digit(11, 16);
208 /// assert_eq!(Some('b'), c);
211 /// Returning `None` when the input is not a digit:
216 /// let c = char::from_digit(20, 10);
218 /// assert_eq!(None, c);
221 /// Passing a large radix, causing a panic:
227 /// let result = thread::spawn(|| {
229 /// let c = char::from_digit(1, 37);
232 /// assert!(result.is_err());
235 #[stable(feature = "rust1", since = "1.0.0")]
236 pub fn from_digit(num
: u32, radix
: u32) -> Option
<char> {
238 panic
!("from_digit: radix is too high (maximum 36)");
243 Some((b'
0'
+ num
) as char)
245 Some((b'a'
+ num
- 10) as char)
252 // NB: the stabilization and documentation for this trait is in
253 // unicode/char.rs, not here
254 #[allow(missing_docs)] // docs in libunicode/u_char.rs
256 #[unstable(feature = "core_char_ext",
257 reason
= "the stable interface is `impl char` in later crate",
260 #[stable(feature = "core", since = "1.6.0")]
261 fn is_digit(self, radix
: u32) -> bool
;
262 #[stable(feature = "core", since = "1.6.0")]
263 fn to_digit(self, radix
: u32) -> Option
<u32>;
264 #[stable(feature = "core", since = "1.6.0")]
265 fn escape_unicode(self) -> EscapeUnicode
;
266 #[stable(feature = "core", since = "1.6.0")]
267 fn escape_default(self) -> EscapeDefault
;
268 #[stable(feature = "core", since = "1.6.0")]
269 fn len_utf8(self) -> usize;
270 #[stable(feature = "core", since = "1.6.0")]
271 fn len_utf16(self) -> usize;
272 #[stable(feature = "core", since = "1.6.0")]
273 fn encode_utf8(self, dst
: &mut [u8]) -> Option
<usize>;
274 #[stable(feature = "core", since = "1.6.0")]
275 fn encode_utf16(self, dst
: &mut [u16]) -> Option
<usize>;
278 #[stable(feature = "core", since = "1.6.0")]
279 impl CharExt
for char {
281 fn is_digit(self, radix
: u32) -> bool
{
282 self.to_digit(radix
).is_some()
286 fn to_digit(self, radix
: u32) -> Option
<u32> {
288 panic
!("to_digit: radix is too high (maximum 36)");
290 let val
= match self {
291 '
0'
... '
9'
=> self as u32 - '
0'
as u32,
292 'a'
... 'z'
=> self as u32 - 'a'
as u32 + 10,
293 'A'
... 'Z'
=> self as u32 - 'A'
as u32 + 10,
296 if val
< radix { Some(val) }
301 fn escape_unicode(self) -> EscapeUnicode
{
302 EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
306 fn escape_default(self) -> EscapeDefault
{
307 let init_state
= match self {
308 '
\t'
=> EscapeDefaultState
::Backslash('t'
),
309 '
\r'
=> EscapeDefaultState
::Backslash('r'
),
310 '
\n'
=> EscapeDefaultState
::Backslash('n'
),
311 '
\\'
| '
\''
| '
"' => EscapeDefaultState::Backslash(self),
312 '\x20' ... '\x7e' => EscapeDefaultState::Char(self),
313 _ => EscapeDefaultState::Unicode(self.escape_unicode())
315 EscapeDefault { state: init_state }
319 fn len_utf8(self) -> usize {
320 let code = self as u32;
321 if code < MAX_ONE_B {
323 } else if code < MAX_TWO_B {
325 } else if code < MAX_THREE_B {
333 fn len_utf16(self) -> usize {
334 let ch = self as u32;
335 if (ch & 0xFFFF) == ch { 1 } else { 2 }
339 fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> {
340 encode_utf8_raw(self as u32, dst)
344 fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> {
345 encode_utf16_raw(self as u32, dst)
349 /// Encodes a raw u32 value as UTF-8 into the provided byte buffer,
350 /// and then returns the number of bytes written.
352 /// If the buffer is not large enough, nothing will be written into it
353 /// and a `None` will be returned.
355 #[unstable(feature = "char_internals
",
356 reason = "this function should not be exposed publicly
",
359 pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> {
360 // Marked #[inline] to allow llvm optimizing it away
361 if code < MAX_ONE_B && !dst.is_empty() {
364 } else if code < MAX_TWO_B && dst.len() >= 2 {
365 dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
366 dst[1] = (code & 0x3F) as u8 | TAG_CONT;
368 } else if code < MAX_THREE_B && dst.len() >= 3 {
369 dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
370 dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
371 dst[2] = (code & 0x3F) as u8 | TAG_CONT;
373 } else if dst.len() >= 4 {
374 dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
375 dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
376 dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
377 dst[3] = (code & 0x3F) as u8 | TAG_CONT;
384 /// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,
385 /// and then returns the number of `u16`s written.
387 /// If the buffer is not large enough, nothing will be written into it
388 /// and a `None` will be returned.
390 #[unstable(feature = "char_internals
",
391 reason = "this function should not be exposed publicly
",
394 pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> {
395 // Marked #[inline] to allow llvm optimizing it away
396 if (ch & 0xFFFF) == ch && !dst.is_empty() {
397 // The BMP falls through (assuming non-surrogate, as it should)
400 } else if dst.len() >= 2 {
401 // Supplementary planes break into surrogates.
403 dst[0] = 0xD800 | ((ch >> 10) as u16);
404 dst[1] = 0xDC00 | ((ch as u16) & 0x3FF);
411 /// Returns an iterator that yields the hexadecimal Unicode escape of a
412 /// character, as `char`s.
414 /// This `struct` is created by the [`escape_unicode()`] method on [`char`]. See
415 /// its documentation for more.
417 /// [`escape_unicode()`]: primitive.char.html#method.escape_unicode
418 /// [`char`]: primitive.char.html
420 #[stable(feature = "rust1
", since = "1.0.0")]
421 pub struct EscapeUnicode {
423 state: EscapeUnicodeState
427 enum EscapeUnicodeState {
436 #[stable(feature = "rust1
", since = "1.0.0")]
437 impl Iterator for EscapeUnicode {
440 fn next(&mut self) -> Option<char> {
442 EscapeUnicodeState::Backslash => {
443 self.state = EscapeUnicodeState::Type;
446 EscapeUnicodeState::Type => {
447 self.state = EscapeUnicodeState::LeftBrace;
450 EscapeUnicodeState::LeftBrace => {
452 while (self.c as u32) >> (4 * (n + 1)) != 0 {
455 self.state = EscapeUnicodeState::Value(n);
458 EscapeUnicodeState::Value(offset) => {
459 let c = from_digit(((self.c as u32) >> (offset * 4)) & 0xf, 16).unwrap();
461 self.state = EscapeUnicodeState::RightBrace;
463 self.state = EscapeUnicodeState::Value(offset - 1);
467 EscapeUnicodeState::RightBrace => {
468 self.state = EscapeUnicodeState::Done;
471 EscapeUnicodeState::Done => None,
475 fn size_hint(&self) -> (usize, Option<usize>) {
477 while (self.c as usize) >> (4 * (n + 1)) != 0 {
480 let n = match self.state {
481 EscapeUnicodeState::Backslash => n + 5,
482 EscapeUnicodeState::Type => n + 4,
483 EscapeUnicodeState::LeftBrace => n + 3,
484 EscapeUnicodeState::Value(offset) => offset + 2,
485 EscapeUnicodeState::RightBrace => 1,
486 EscapeUnicodeState::Done => 0,
492 /// An iterator that yields the literal escape code of a `char`.
494 /// This `struct` is created by the [`escape_default()`] method on [`char`]. See
495 /// its documentation for more.
497 /// [`escape_default()`]: primitive.char.html#method.escape_default
498 /// [`char`]: primitive.char.html
500 #[stable(feature = "rust1
", since = "1.0.0")]
501 pub struct EscapeDefault {
502 state: EscapeDefaultState
506 enum EscapeDefaultState {
510 Unicode(EscapeUnicode),
513 #[stable(feature = "rust1
", since = "1.0.0")]
514 impl Iterator for EscapeDefault {
517 fn next(&mut self) -> Option<char> {
519 EscapeDefaultState::Backslash(c) => {
520 self.state = EscapeDefaultState::Char(c);
523 EscapeDefaultState::Char(c) => {
524 self.state = EscapeDefaultState::Done;
527 EscapeDefaultState::Done => None,
528 EscapeDefaultState::Unicode(ref mut iter) => iter.next(),
532 fn size_hint(&self) -> (usize, Option<usize>) {
534 EscapeDefaultState::Char(_) => (1, Some(1)),
535 EscapeDefaultState::Backslash(_) => (2, Some(2)),
536 EscapeDefaultState::Unicode(ref iter) => iter.size_hint(),
537 EscapeDefaultState::Done => (0, Some(0)),