utf8.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. 'use strict';
  2. var utils = require('./utils');
  3. var support = require('./support');
  4. var nodeBuffer = require('./nodeBuffer');
  5. /**
  6. * The following functions come from pako, from pako/lib/utils/strings
  7. * released under the MIT license, see pako https://github.com/nodeca/pako/
  8. */
  9. // Table with utf8 lengths (calculated by first byte of sequence)
  10. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  11. // because max possible codepoint is 0x10ffff
  12. var _utf8len = new Array(256);
  13. for (var i=0; i<256; i++) {
  14. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  15. }
  16. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17. // convert string to array (typed, when possible)
  18. var string2buf = function (str) {
  19. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20. // count binary size
  21. for (m_pos = 0; m_pos < str_len; m_pos++) {
  22. c = str.charCodeAt(m_pos);
  23. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  24. c2 = str.charCodeAt(m_pos+1);
  25. if ((c2 & 0xfc00) === 0xdc00) {
  26. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  27. m_pos++;
  28. }
  29. }
  30. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  31. }
  32. // allocate buffer
  33. if (support.uint8array) {
  34. buf = new Uint8Array(buf_len);
  35. } else {
  36. buf = new Array(buf_len);
  37. }
  38. // convert
  39. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  40. c = str.charCodeAt(m_pos);
  41. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  42. c2 = str.charCodeAt(m_pos+1);
  43. if ((c2 & 0xfc00) === 0xdc00) {
  44. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  45. m_pos++;
  46. }
  47. }
  48. if (c < 0x80) {
  49. /* one byte */
  50. buf[i++] = c;
  51. } else if (c < 0x800) {
  52. /* two bytes */
  53. buf[i++] = 0xC0 | (c >>> 6);
  54. buf[i++] = 0x80 | (c & 0x3f);
  55. } else if (c < 0x10000) {
  56. /* three bytes */
  57. buf[i++] = 0xE0 | (c >>> 12);
  58. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  59. buf[i++] = 0x80 | (c & 0x3f);
  60. } else {
  61. /* four bytes */
  62. buf[i++] = 0xf0 | (c >>> 18);
  63. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  64. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  65. buf[i++] = 0x80 | (c & 0x3f);
  66. }
  67. }
  68. return buf;
  69. };
  70. // Calculate max possible position in utf8 buffer,
  71. // that will not break sequence. If that's not possible
  72. // - (very small limits) return max size as is.
  73. //
  74. // buf[] - utf8 bytes array
  75. // max - length limit (mandatory);
  76. var utf8border = function(buf, max) {
  77. var pos;
  78. max = max || buf.length;
  79. if (max > buf.length) { max = buf.length; }
  80. // go back from last position, until start of sequence found
  81. pos = max-1;
  82. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  83. // Fuckup - very small and broken sequence,
  84. // return max, because we should return something anyway.
  85. if (pos < 0) { return max; }
  86. // If we came to start of buffer - that means vuffer is too small,
  87. // return max too.
  88. if (pos === 0) { return max; }
  89. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  90. };
  91. // convert array to string
  92. var buf2string = function (buf) {
  93. var str, i, out, c, c_len;
  94. var len = buf.length;
  95. // Reserve max possible length (2 words per char)
  96. // NB: by unknown reasons, Array is significantly faster for
  97. // String.fromCharCode.apply than Uint16Array.
  98. var utf16buf = new Array(len*2);
  99. for (out=0, i=0; i<len;) {
  100. c = buf[i++];
  101. // quick process ascii
  102. if (c < 0x80) { utf16buf[out++] = c; continue; }
  103. c_len = _utf8len[c];
  104. // skip 5 & 6 byte codes
  105. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  106. // apply mask on first byte
  107. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  108. // join the rest
  109. while (c_len > 1 && i < len) {
  110. c = (c << 6) | (buf[i++] & 0x3f);
  111. c_len--;
  112. }
  113. // terminated by end of string?
  114. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  115. if (c < 0x10000) {
  116. utf16buf[out++] = c;
  117. } else {
  118. c -= 0x10000;
  119. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  120. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  121. }
  122. }
  123. // shrinkBuf(utf16buf, out)
  124. if (utf16buf.length !== out) {
  125. if(utf16buf.subarray) {
  126. utf16buf = utf16buf.subarray(0, out);
  127. } else {
  128. utf16buf.length = out;
  129. }
  130. }
  131. // return String.fromCharCode.apply(null, utf16buf);
  132. return utils.applyFromCharCode(utf16buf);
  133. };
  134. // That's all for the pako functions.
  135. /**
  136. * Transform a javascript string into an array (typed if possible) of bytes,
  137. * UTF-8 encoded.
  138. * @param {String} str the string to encode
  139. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  140. */
  141. exports.utf8encode = function utf8encode(str) {
  142. if (support.nodebuffer) {
  143. return nodeBuffer(str, "utf-8");
  144. }
  145. return string2buf(str);
  146. };
  147. /**
  148. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  149. * string into a javascript string.
  150. * @param {Array|Uint8Array|Buffer} buf the data de decode
  151. * @return {String} the decoded string.
  152. */
  153. exports.utf8decode = function utf8decode(buf) {
  154. if (support.nodebuffer) {
  155. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  156. }
  157. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  158. // return buf2string(buf);
  159. // Chrome prefers to work with "small" chunks of data
  160. // for the method buf2string.
  161. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  162. var result = [], k = 0, len = buf.length, chunk = 65536;
  163. while (k < len) {
  164. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  165. if (support.uint8array) {
  166. result.push(buf2string(buf.subarray(k, nextBoundary)));
  167. } else {
  168. result.push(buf2string(buf.slice(k, nextBoundary)));
  169. }
  170. k = nextBoundary;
  171. }
  172. return result.join("");
  173. };
  174. // vim: set shiftwidth=4 softtabstop=4: