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 //! A Unicode scalar value
13 //! This module provides the `CharExt` trait, as well as its
14 //! implementation for the primitive `char` type, in order to allow
15 //! basic character manipulation.
17 //! A `char` represents a
19 //! value](http://www.unicode.org/glossary/#unicode_scalar_value)*, as it can
20 //! contain any Unicode code point except high-surrogate and low-surrogate code
23 //! As such, only values in the ranges \[0x0,0xD7FF\] and \[0xE000,0x10FFFF\]
24 //! (inclusive) are allowed. A `char` can always be safely cast to a `u32`;
25 //! however the converse is not always true due to the above range limits
26 //! and, as such, should be performed via the `from_u32` function.
28 //! *[See also the `char` primitive type](../primitive.char.html).*
30 #![stable(feature = "rust1", since = "1.0.0")]
32 use core::char::CharExt as C;
33 use core::option::Option::{self, Some, None};
34 use core::iter::Iterator;
35 use tables::{derived_property, property, general_category, conversions, charwidth};
38 pub use core::char::{MAX, from_u32, from_u32_unchecked, from_digit, EscapeUnicode, EscapeDefault};
42 pub use normalize::{decompose_canonical, decompose_compatible, compose};
44 pub use tables::normalization::canonical_combining_class;
45 pub use tables::UNICODE_VERSION;
47 /// An iterator over the lowercase mapping of a given character, returned from
48 /// the [`to_lowercase` method](../primitive.char.html#method.to_lowercase) on
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub struct ToLowercase(CaseMappingIter);
53 #[stable(feature = "rust1", since = "1.0.0")]
54 impl Iterator for ToLowercase {
56 fn next(&mut self) -> Option<char> { self.0.next() }
59 /// An iterator over the uppercase mapping of a given character, returned from
60 /// the [`to_uppercase` method](../primitive.char.html#method.to_uppercase) on
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub struct ToUppercase(CaseMappingIter);
65 #[stable(feature = "rust1", since = "1.0.0")]
66 impl Iterator for ToUppercase {
68 fn next(&mut self) -> Option<char> { self.0.next() }
72 enum CaseMappingIter {
73 Three(char, char, char),
79 impl CaseMappingIter {
80 fn new(chars: [char; 3]) -> CaseMappingIter {
83 CaseMappingIter::One(chars[0]) // Including if chars[0] == '\0'
85 CaseMappingIter::Two(chars[0], chars[1])
88 CaseMappingIter::Three(chars[0], chars[1], chars[2])
93 impl Iterator for CaseMappingIter {
95 fn next(&mut self) -> Option<char> {
97 CaseMappingIter::Three(a, b, c) => {
98 *self = CaseMappingIter::Two(b, c);
101 CaseMappingIter::Two(b, c) => {
102 *self = CaseMappingIter::One(c);
105 CaseMappingIter::One(c) => {
106 *self = CaseMappingIter::Zero;
109 CaseMappingIter::Zero => None,
114 #[stable(feature = "rust1", since = "1.0.0")]
117 /// Checks if a `char` parses as a numeric digit in the given radix.
119 /// Compared to `is_numeric()`, this function only recognizes the characters
120 /// `0-9`, `a-z` and `A-Z`.
124 /// Returns `true` if `c` is a valid digit under `radix`, and `false`
129 /// Panics if given a radix > 36.
136 /// assert!(c.is_digit(10));
138 /// assert!('f'.is_digit(16));
140 #[stable(feature = "rust1", since = "1.0.0")]
142 pub fn is_digit(self, radix: u32) -> bool { C::is_digit(self, radix) }
144 /// Converts a character to the corresponding digit.
148 /// If `c` is between '0' and '9', the corresponding value between 0 and
149 /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
150 /// none if the character does not refer to a digit in the given radix.
154 /// Panics if given a radix outside the range [0..36].
161 /// assert_eq!(c.to_digit(10), Some(1));
163 /// assert_eq!('f'.to_digit(16), Some(15));
165 #[stable(feature = "rust1", since = "1.0.0")]
167 pub fn to_digit(self, radix: u32) -> Option<u32> { C::to_digit(self, radix) }
169 /// Returns an iterator that yields the hexadecimal Unicode escape of a
170 /// character, as `char`s.
172 /// All characters are escaped with Rust syntax of the form `\\u{NNNN}`
173 /// where `NNNN` is the shortest hexadecimal representation of the code
179 /// for c in '❤'.escape_unicode() {
191 /// Collecting into a `String`:
194 /// let heart: String = '❤'.escape_unicode().collect();
196 /// assert_eq!(heart, r"\u{2764}");
198 #[stable(feature = "rust1", since = "1.0.0")]
200 pub fn escape_unicode(self) -> EscapeUnicode { C::escape_unicode(self) }
202 /// Returns an iterator that yields the 'default' ASCII and
203 /// C++11-like literal escape of a character, as `char`s.
205 /// The default is chosen with a bias toward producing literals that are
206 /// legal in a variety of languages, including C++11 and similar C-family
207 /// languages. The exact rules are:
209 /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
210 /// * Single-quote, double-quote and backslash chars are backslash-
212 /// * Any other chars in the range [0x20,0x7e] are not escaped.
213 /// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
218 /// for i in '"'.escape_default() {
219 /// println!("{}", i);
230 /// Collecting into a `String`:
233 /// let quote: String = '"'.escape_default().collect();
235 /// assert_eq!(quote, "\\\"");
237 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn escape_default(self) -> EscapeDefault { C::escape_default(self) }
241 /// Returns the number of bytes this character would need if encoded in
247 /// let n = 'ß'.len_utf8();
249 /// assert_eq!(n, 2);
251 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn len_utf8(self) -> usize { C::len_utf8(self) }
255 /// Returns the number of 16-bit code units this character would need if
256 /// encoded in UTF-16.
261 /// let n = 'ß'.len_utf16();
263 /// assert_eq!(n, 1);
265 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn len_utf16(self) -> usize { C::len_utf16(self) }
269 /// Encodes this character as UTF-8 into the provided byte buffer, and then
270 /// returns the number of bytes written.
272 /// If the buffer is not large enough, nothing will be written into it and a
273 /// `None` will be returned. A buffer of length four is large enough to
274 /// encode any `char`.
278 /// In both of these examples, 'ß' takes two bytes to encode.
281 /// #![feature(unicode)]
283 /// let mut b = [0; 2];
285 /// let result = 'ß'.encode_utf8(&mut b);
287 /// assert_eq!(result, Some(2));
290 /// A buffer that's too small:
293 /// #![feature(unicode)]
295 /// let mut b = [0; 1];
297 /// let result = 'ß'.encode_utf8(&mut b);
299 /// assert_eq!(result, None);
301 #[unstable(feature = "unicode",
302 reason = "pending decision about Iterator/Writer/Reader")]
304 pub fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> {
305 C::encode_utf8(self, dst)
308 /// Encodes this character as UTF-16 into the provided `u16` buffer, and
309 /// then returns the number of `u16`s written.
311 /// If the buffer is not large enough, nothing will be written into it and a
312 /// `None` will be returned. A buffer of length 2 is large enough to encode
317 /// In both of these examples, 'ß' takes one `u16` to encode.
320 /// #![feature(unicode)]
322 /// let mut b = [0; 1];
324 /// let result = 'ß'.encode_utf16(&mut b);
326 /// assert_eq!(result, Some(1));
329 /// A buffer that's too small:
332 /// #![feature(unicode)]
334 /// let mut b = [0; 0];
336 /// let result = 'ß'.encode_utf8(&mut b);
338 /// assert_eq!(result, None);
340 #[unstable(feature = "unicode",
341 reason = "pending decision about Iterator/Writer/Reader")]
343 pub fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> {
344 C::encode_utf16(self, dst)
347 /// Returns whether the specified character is considered a Unicode
348 /// alphabetic code point.
349 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn is_alphabetic(self) -> bool {
353 'a' ... 'z' | 'A' ... 'Z' => true,
354 c if c > '\x7f' => derived_property::Alphabetic(c),
359 /// Returns whether the specified character satisfies the 'XID_Start'
360 /// Unicode property.
362 /// 'XID_Start' is a Unicode Derived Property specified in
363 /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
364 /// mostly similar to ID_Start but modified for closure under NFKx.
365 #[unstable(feature = "unicode",
366 reason = "mainly needed for compiler internals")]
368 pub fn is_xid_start(self) -> bool { derived_property::XID_Start(self) }
370 /// Returns whether the specified `char` satisfies the 'XID_Continue'
371 /// Unicode property.
373 /// 'XID_Continue' is a Unicode Derived Property specified in
374 /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
375 /// mostly similar to 'ID_Continue' but modified for closure under NFKx.
376 #[unstable(feature = "unicode",
377 reason = "mainly needed for compiler internals")]
379 pub fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) }
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 #[stable(feature = "rust1", since = "1.0.0")]
387 pub fn is_lowercase(self) -> bool {
390 c if c > '\x7f' => derived_property::Lowercase(c),
395 /// Indicates whether a character is in uppercase.
397 /// This is defined according to the terms of the Unicode Derived Core
398 /// Property `Uppercase`.
399 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn is_uppercase(self) -> bool {
404 c if c > '\x7f' => derived_property::Uppercase(c),
409 /// Indicates whether a character is whitespace.
411 /// Whitespace is defined in terms of the Unicode Property `White_Space`.
412 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn is_whitespace(self) -> bool {
416 ' ' | '\x09' ... '\x0d' => true,
417 c if c > '\x7f' => property::White_Space(c),
422 /// Indicates whether a character is alphanumeric.
424 /// Alphanumericness is defined in terms of the Unicode General Categories
425 /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
426 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn is_alphanumeric(self) -> bool {
429 self.is_alphabetic() || self.is_numeric()
432 /// Indicates whether a character is a control code point.
434 /// Control code points are defined in terms of the Unicode General
436 #[stable(feature = "rust1", since = "1.0.0")]
438 pub fn is_control(self) -> bool { general_category::Cc(self) }
440 /// Indicates whether the character is numeric (Nd, Nl, or No).
441 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn is_numeric(self) -> bool {
446 c if c > '\x7f' => general_category::N(c),
451 /// Converts a character to its lowercase equivalent.
453 /// This performs complex unconditional mappings with no tailoring.
454 /// See `to_uppercase()` for references and more information.
458 /// Returns an iterator which yields the characters corresponding to the
459 /// lowercase equivalent of the character. If no conversion is possible then
460 /// an iterator with just the input character is returned.
465 /// assert_eq!(Some('c'), 'C'.to_lowercase().next());
467 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn to_lowercase(self) -> ToLowercase {
470 ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
473 /// Converts a character to its uppercase equivalent.
475 /// This performs complex unconditional mappings with no tailoring:
476 /// it maps one Unicode character to its uppercase equivalent
477 /// according to the Unicode database [1]
478 /// and the additional complex mappings [`SpecialCasing.txt`].
479 /// Conditional mappings (based on context or language) are not considerd here.
481 /// A full reference can be found here [2].
485 /// Returns an iterator which yields the characters corresponding to the
486 /// uppercase equivalent of the character. If no conversion is possible then
487 /// an iterator with just the input character is returned.
489 /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
491 /// [`SpecialCasing.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt
493 /// [2]: http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
498 /// assert_eq!(Some('C'), 'c'.to_uppercase().next());
500 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn to_uppercase(self) -> ToUppercase {
503 ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
506 /// Returns this character's displayed width in columns, or `None` if it is a
507 /// control character other than `'\x00'`.
509 /// `is_cjk` determines behavior for characters in the Ambiguous category:
510 /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1.
511 /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`.
512 /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
513 /// recommends that these characters be treated as 1 column (i.e.,
514 /// `is_cjk` = `false`) if the context cannot be reliably determined.
515 #[deprecated(reason = "use the crates.io `unicode-width` library instead",
517 #[unstable(feature = "unicode",
518 reason = "needs expert opinion. is_cjk flag stands out as ugly")]
520 pub fn width(self, is_cjk: bool) -> Option<usize> {
521 charwidth::width(self, is_cjk)