index.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // Copyright Joyent, Inc. and other Node contributors.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a
  4. // copy of this software and associated documentation files (the
  5. // "Software"), to deal in the Software without restriction, including
  6. // without limitation the rights to use, copy, modify, merge, publish,
  7. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8. // persons to whom the Software is furnished to do so, subject to the
  9. // following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included
  12. // in all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  17. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  18. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  20. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. var Buffer = require('buffer').Buffer;
  22. var isBufferEncoding = Buffer.isEncoding
  23. || function(encoding) {
  24. switch (encoding && encoding.toLowerCase()) {
  25. case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
  26. default: return false;
  27. }
  28. }
  29. function assertEncoding(encoding) {
  30. if (encoding && !isBufferEncoding(encoding)) {
  31. throw new Error('Unknown encoding: ' + encoding);
  32. }
  33. }
  34. // StringDecoder provides an interface for efficiently splitting a series of
  35. // buffers into a series of JS strings without breaking apart multi-byte
  36. // characters. CESU-8 is handled as part of the UTF-8 encoding.
  37. //
  38. // @TODO Handling all encodings inside a single object makes it very difficult
  39. // to reason about this code, so it should be split up in the future.
  40. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
  41. // points as used by CESU-8.
  42. var StringDecoder = exports.StringDecoder = function(encoding) {
  43. this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
  44. assertEncoding(encoding);
  45. switch (this.encoding) {
  46. case 'utf8':
  47. // CESU-8 represents each of Surrogate Pair by 3-bytes
  48. this.surrogateSize = 3;
  49. break;
  50. case 'ucs2':
  51. case 'utf16le':
  52. // UTF-16 represents each of Surrogate Pair by 2-bytes
  53. this.surrogateSize = 2;
  54. this.detectIncompleteChar = utf16DetectIncompleteChar;
  55. break;
  56. case 'base64':
  57. // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
  58. this.surrogateSize = 3;
  59. this.detectIncompleteChar = base64DetectIncompleteChar;
  60. break;
  61. default:
  62. this.write = passThroughWrite;
  63. return;
  64. }
  65. // Enough space to store all bytes of a single character. UTF-8 needs 4
  66. // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
  67. this.charBuffer = new Buffer(6);
  68. // Number of bytes received for the current incomplete multi-byte character.
  69. this.charReceived = 0;
  70. // Number of bytes expected for the current incomplete multi-byte character.
  71. this.charLength = 0;
  72. };
  73. // write decodes the given buffer and returns it as JS string that is
  74. // guaranteed to not contain any partial multi-byte characters. Any partial
  75. // character found at the end of the buffer is buffered up, and will be
  76. // returned when calling write again with the remaining bytes.
  77. //
  78. // Note: Converting a Buffer containing an orphan surrogate to a String
  79. // currently works, but converting a String to a Buffer (via `new Buffer`, or
  80. // Buffer#write) will replace incomplete surrogates with the unicode
  81. // replacement character. See https://codereview.chromium.org/121173009/ .
  82. StringDecoder.prototype.write = function(buffer) {
  83. var charStr = '';
  84. // if our last write ended with an incomplete multibyte character
  85. while (this.charLength) {
  86. // determine how many remaining bytes this buffer has to offer for this char
  87. var available = (buffer.length >= this.charLength - this.charReceived) ?
  88. this.charLength - this.charReceived :
  89. buffer.length;
  90. // add the new bytes to the char buffer
  91. buffer.copy(this.charBuffer, this.charReceived, 0, available);
  92. this.charReceived += available;
  93. if (this.charReceived < this.charLength) {
  94. // still not enough chars in this buffer? wait for more ...
  95. return '';
  96. }
  97. // remove bytes belonging to the current character from the buffer
  98. buffer = buffer.slice(available, buffer.length);
  99. // get the character that was split
  100. charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
  101. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  102. var charCode = charStr.charCodeAt(charStr.length - 1);
  103. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  104. this.charLength += this.surrogateSize;
  105. charStr = '';
  106. continue;
  107. }
  108. this.charReceived = this.charLength = 0;
  109. // if there are no more bytes in this buffer, just emit our char
  110. if (buffer.length === 0) {
  111. return charStr;
  112. }
  113. break;
  114. }
  115. // determine and set charLength / charReceived
  116. this.detectIncompleteChar(buffer);
  117. var end = buffer.length;
  118. if (this.charLength) {
  119. // buffer the incomplete character bytes we got
  120. buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
  121. end -= this.charReceived;
  122. }
  123. charStr += buffer.toString(this.encoding, 0, end);
  124. var end = charStr.length - 1;
  125. var charCode = charStr.charCodeAt(end);
  126. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  127. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  128. var size = this.surrogateSize;
  129. this.charLength += size;
  130. this.charReceived += size;
  131. this.charBuffer.copy(this.charBuffer, size, 0, size);
  132. buffer.copy(this.charBuffer, 0, 0, size);
  133. return charStr.substring(0, end);
  134. }
  135. // or just emit the charStr
  136. return charStr;
  137. };
  138. // detectIncompleteChar determines if there is an incomplete UTF-8 character at
  139. // the end of the given buffer. If so, it sets this.charLength to the byte
  140. // length that character, and sets this.charReceived to the number of bytes
  141. // that are available for this character.
  142. StringDecoder.prototype.detectIncompleteChar = function(buffer) {
  143. // determine how many bytes we have to check at the end of this buffer
  144. var i = (buffer.length >= 3) ? 3 : buffer.length;
  145. // Figure out if one of the last i bytes of our buffer announces an
  146. // incomplete char.
  147. for (; i > 0; i--) {
  148. var c = buffer[buffer.length - i];
  149. // See http://en.wikipedia.org/wiki/UTF-8#Description
  150. // 110XXXXX
  151. if (i == 1 && c >> 5 == 0x06) {
  152. this.charLength = 2;
  153. break;
  154. }
  155. // 1110XXXX
  156. if (i <= 2 && c >> 4 == 0x0E) {
  157. this.charLength = 3;
  158. break;
  159. }
  160. // 11110XXX
  161. if (i <= 3 && c >> 3 == 0x1E) {
  162. this.charLength = 4;
  163. break;
  164. }
  165. }
  166. this.charReceived = i;
  167. };
  168. StringDecoder.prototype.end = function(buffer) {
  169. var res = '';
  170. if (buffer && buffer.length)
  171. res = this.write(buffer);
  172. if (this.charReceived) {
  173. var cr = this.charReceived;
  174. var buf = this.charBuffer;
  175. var enc = this.encoding;
  176. res += buf.slice(0, cr).toString(enc);
  177. }
  178. return res;
  179. };
  180. function passThroughWrite(buffer) {
  181. return buffer.toString(this.encoding);
  182. }
  183. function utf16DetectIncompleteChar(buffer) {
  184. this.charReceived = buffer.length % 2;
  185. this.charLength = this.charReceived ? 2 : 0;
  186. }
  187. function base64DetectIncompleteChar(buffer) {
  188. this.charReceived = buffer.length % 3;
  189. this.charLength = this.charReceived ? 3 : 0;
  190. }