about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorSimon Sapin <simon.sapin@exyr.org>2014-11-17 20:11:54 +0000
committerSimon Sapin <simon.sapin@exyr.org>2014-11-20 14:05:28 +0000
commitdff48a99d6bf9d2c4828f187bfa2c9ba382fe791 (patch)
tree72b81065048982415c7bb93747b89dbaed292f04 /src/libcore
parent1d81776209cfa2b5cb1825bdbf3965a7a7f0440a (diff)
Add Utf16Encoder. Generalize Utf16CodeUnits for any Iterator<char>.
This allows encoding to UTF-16 something that is not in UTF-8, e.g. a
`[char]` UTF-32 string.

This might help with https://github.com/servo/servo/issues/4023
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/str.rs28
1 files changed, 25 insertions, 3 deletions
diff --git a/src/libcore/str.rs b/src/libcore/str.rs
index 24f26b15f27..68e490ecb19 100644
--- a/src/libcore/str.rs
+++ b/src/libcore/str.rs
@@ -762,12 +762,34 @@ impl<'a> Iterator<&'a str> for StrSplits<'a> {
 /// Use with the `std::iter` module.
 #[deriving(Clone)]
 pub struct Utf16CodeUnits<'a> {
-    chars: Chars<'a>,
-    extra: u16
+    encoder: Utf16Encoder<Chars<'a>>
 }
 
 impl<'a> Iterator<u16> for Utf16CodeUnits<'a> {
     #[inline]
+    fn next(&mut self) -> Option<u16> { self.encoder.next() }
+
+    #[inline]
+    fn size_hint(&self) -> (uint, Option<uint>) { self.encoder.size_hint() }
+}
+
+
+/// Iterator adaptor for encoding `char`s to UTF-16.
+#[deriving(Clone)]
+pub struct Utf16Encoder<I> {
+    chars: I,
+    extra: u16
+}
+
+impl<I> Utf16Encoder<I> {
+    /// Create an UTF-16 encoder from any `char` iterator.
+    pub fn new(chars: I) -> Utf16Encoder<I> where I: Iterator<char> {
+        Utf16Encoder { chars: chars, extra: 0 }
+    }
+}
+
+impl<I> Iterator<u16> for Utf16Encoder<I> where I: Iterator<char> {
+    #[inline]
     fn next(&mut self) -> Option<u16> {
         if self.extra != 0 {
             let tmp = self.extra;
@@ -2225,7 +2247,7 @@ impl StrPrelude for str {
 
     #[inline]
     fn utf16_units(&self) -> Utf16CodeUnits {
-        Utf16CodeUnits{ chars: self.chars(), extra: 0}
+        Utf16CodeUnits { encoder: Utf16Encoder::new(self.chars()) }
     }
 
     #[inline]