]> git.lizzy.rs Git - rust.git/commitdiff
core: Add Char::len_utf16
authorBrian Anderson <banderson@mozilla.com>
Thu, 9 Oct 2014 00:40:31 +0000 (17:40 -0700)
committerBrian Anderson <banderson@mozilla.com>
Fri, 21 Nov 2014 21:17:09 +0000 (13:17 -0800)
Missing method to pair with len_utf8.

src/libcore/char.rs
src/libcoretest/char.rs

index 82dc2becf28cfacdc0b0d0a3b5e2b16bc8ba2d69..93fa614e597fd2a844d3fd457773910aefea4e44 100644 (file)
@@ -323,6 +323,10 @@ pub trait Char {
     /// UTF-8.
     fn len_utf8(&self) -> uint;
 
+    /// Returns the amount of bytes this character would need if encoded in
+    /// UTF-16.
+    fn len_utf16(&self) -> uint;
+
     /// Encodes this character as UTF-8 into the provided byte buffer,
     /// and then returns the number of bytes written.
     ///
@@ -363,6 +367,12 @@ fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
     #[inline]
     fn len_utf8(&self) -> uint { len_utf8_bytes(*self) }
 
+    #[inline]
+    fn len_utf16(&self) -> uint {
+        let ch = *self as u32;
+        if (ch & 0xFFFF_u32) == ch { 1 } else { 2 }
+    }
+
     #[inline]
     fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
         // Marked #[inline] to allow llvm optimizing it away
index 2d5ca983fec70ff9958315338408f204952c50aa..507ddf65e55b35c9dca1b4a6d72053bc68620346 100644 (file)
@@ -197,6 +197,14 @@ fn check(input: char, expect: &[u16]) {
     check('\U0001f4a9', &[0xd83d, 0xdca9]);
 }
 
+#[test]
+fn test_len_utf16() {
+    assert!('x'.len_utf16() == 1);
+    assert!('\u00e9'.len_utf16() == 1);
+    assert!('\ua66e'.len_utf16() == 1);
+    assert!('\U0001f4a9'.len_utf16() == 2);
+}
+
 #[test]
 fn test_width() {
     assert_eq!('\x00'.width(false),Some(0));