]> git.saurik.com Git - utf16js.git/commitdiff
Factor UTF-16 functions into their own module.
authorJay Freeman (saurik) <saurik@saurik.com>
Wed, 26 Dec 2012 14:29:26 +0000 (14:29 +0000)
committerJay Freeman (saurik) <saurik@saurik.com>
Wed, 26 Dec 2012 14:29:26 +0000 (14:29 +0000)
utf16.js [new file with mode: 0644]

diff --git a/utf16.js b/utf16.js
new file mode 100644 (file)
index 0000000..89322ec
--- /dev/null
+++ b/utf16.js
@@ -0,0 +1,44 @@
+if (typeof define !== 'function') { var define = require('amdefine')(module) }
+
+define(function(require) {
+
+var decode = function(array, string) {
+    for (var i = 0, e = string.length; i != e; ++i) {
+        var unit = string.charCodeAt(i);
+        var part = unit & 0xfc00;
+        if (part == 0xdc00)
+            return null;
+        else if (part != 0xd800)
+            array.push(unit);
+        else if (++i == e)
+            return null;
+        else {
+            var next = string.charCodeAt(i);
+            if ((next & 0xfc00) != 0xdc00)
+                return null;
+            array.push(0x10000 | (unit & 0x03ff) << 10 | next & 0x03ff);
+        }
+    }
+
+    return array;
+};
+
+var encode = function(array) {
+    var units = [];
+    for (var i = 0, e = array.length; i != e; ++i) {
+        var point = array[i];
+        if (point < 0x10000)
+            units.push(point);
+        else {
+            point -= 0x10000;
+            units.push(0xd800 | (0xffc00 & point) >> 10, 0xdc00 | 0x03ff & point);
+        }
+    } return String.fromCharCode.apply(String, units);
+};
+
+return {
+    decode: decode,
+    encode: encode,
+};
+
+});