utf32.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. 'use strict';
  2. var Buffer = require('safer-buffer').Buffer;
  3. // == UTF32-LE/BE codec. ==========================================================
  4. exports._utf32 = Utf32Codec;
  5. function Utf32Codec(codecOptions, iconv) {
  6. this.iconv = iconv;
  7. this.bomAware = true;
  8. this.isLE = codecOptions.isLE;
  9. }
  10. exports.utf32le = { type: '_utf32', isLE: true };
  11. exports.utf32be = { type: '_utf32', isLE: false };
  12. // Aliases
  13. exports.ucs4le = 'utf32le';
  14. exports.ucs4be = 'utf32be';
  15. Utf32Codec.prototype.encoder = Utf32Encoder;
  16. Utf32Codec.prototype.decoder = Utf32Decoder;
  17. // -- Encoding
  18. function Utf32Encoder(options, codec) {
  19. this.isLE = codec.isLE;
  20. this.highSurrogate = 0;
  21. }
  22. Utf32Encoder.prototype.write = function(str) {
  23. var src = Buffer.from(str, 'ucs2');
  24. var dst = Buffer.alloc(src.length * 2);
  25. var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
  26. var offset = 0;
  27. for (var i = 0; i < src.length; i += 2) {
  28. var code = src.readUInt16LE(i);
  29. var isHighSurrogate = (0xD800 <= code && code < 0xDC00);
  30. var isLowSurrogate = (0xDC00 <= code && code < 0xE000);
  31. if (this.highSurrogate) {
  32. if (isHighSurrogate || !isLowSurrogate) {
  33. // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low
  34. // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character
  35. // (technically wrong, but expected by some applications, like Windows file names).
  36. write32.call(dst, this.highSurrogate, offset);
  37. offset += 4;
  38. }
  39. else {
  40. // Create 32-bit value from high and low surrogates;
  41. var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000;
  42. write32.call(dst, codepoint, offset);
  43. offset += 4;
  44. this.highSurrogate = 0;
  45. continue;
  46. }
  47. }
  48. if (isHighSurrogate)
  49. this.highSurrogate = code;
  50. else {
  51. // Even if the current character is a low surrogate, with no previous high surrogate, we'll
  52. // encode it as a semi-invalid stand-alone character for the same reasons expressed above for
  53. // unpaired high surrogates.
  54. write32.call(dst, code, offset);
  55. offset += 4;
  56. this.highSurrogate = 0;
  57. }
  58. }
  59. if (offset < dst.length)
  60. dst = dst.slice(0, offset);
  61. return dst;
  62. };
  63. Utf32Encoder.prototype.end = function() {
  64. // Treat any leftover high surrogate as a semi-valid independent character.
  65. if (!this.highSurrogate)
  66. return;
  67. var buf = Buffer.alloc(4);
  68. if (this.isLE)
  69. buf.writeUInt32LE(this.highSurrogate, 0);
  70. else
  71. buf.writeUInt32BE(this.highSurrogate, 0);
  72. this.highSurrogate = 0;
  73. return buf;
  74. };
  75. // -- Decoding
  76. function Utf32Decoder(options, codec) {
  77. this.isLE = codec.isLE;
  78. this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);
  79. this.overflow = null;
  80. }
  81. Utf32Decoder.prototype.write = function(src) {
  82. if (src.length === 0)
  83. return '';
  84. if (this.overflow)
  85. src = Buffer.concat([this.overflow, src]);
  86. var goodLength = src.length - src.length % 4;
  87. if (src.length !== goodLength) {
  88. this.overflow = src.slice(goodLength);
  89. src = src.slice(0, goodLength);
  90. }
  91. else
  92. this.overflow = null;
  93. var dst = Buffer.alloc(goodLength);
  94. var offset = 0;
  95. for (var i = 0; i < goodLength; i += 4) {
  96. var codepoint = this.isLE ? src.readUInt32LE(i) : src.readUInt32BE(i);
  97. if (codepoint < 0x10000) {
  98. // Simple 16-bit character
  99. dst.writeUInt16LE(codepoint, offset);
  100. offset += 2;
  101. }
  102. else {
  103. if (codepoint > 0x10FFFF) {
  104. // Not a valid Unicode codepoint
  105. dst.writeUInt16LE(this.badChar, offset);
  106. offset += 2;
  107. }
  108. else {
  109. // Create high and low surrogates.
  110. codepoint -= 0x10000;
  111. var high = 0xD800 | (codepoint >> 10);
  112. var low = 0xDC00 + (codepoint & 0x3FF);
  113. dst.writeUInt16LE(high, offset);
  114. offset += 2;
  115. dst.writeUInt16LE(low, offset);
  116. offset += 2;
  117. }
  118. }
  119. }
  120. return dst.slice(0, offset).toString('ucs2');
  121. };
  122. Utf32Decoder.prototype.end = function() {
  123. this.overflow = null;
  124. };
  125. // == UTF-32 Auto codec =============================================================
  126. // Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic.
  127. // Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32
  128. // Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'});
  129. // Encoder prepends BOM (which can be overridden with (addBOM: false}).
  130. exports.utf32 = Utf32AutoCodec;
  131. exports.ucs4 = Utf32AutoCodec;
  132. function Utf32AutoCodec(options, iconv) {
  133. this.iconv = iconv;
  134. }
  135. Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder;
  136. Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder;
  137. // -- Encoding
  138. function Utf32AutoEncoder(options, codec) {
  139. options = options || {};
  140. if (options.addBOM === undefined)
  141. options.addBOM = true;
  142. this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options);
  143. }
  144. Utf32AutoEncoder.prototype.write = function(str) {
  145. return this.encoder.write(str);
  146. };
  147. Utf32AutoEncoder.prototype.end = function() {
  148. return this.encoder.end();
  149. };
  150. // -- Decoding
  151. function Utf32AutoDecoder(options, codec) {
  152. this.decoder = null;
  153. this.initialBytes = [];
  154. this.initialBytesLen = 0;
  155. this.options = options || {};
  156. this.iconv = codec.iconv;
  157. }
  158. Utf32AutoDecoder.prototype.write = function(buf) {
  159. if (!this.decoder) {
  160. // Codec is not chosen yet. Accumulate initial bytes.
  161. this.initialBytes.push(buf);
  162. this.initialBytesLen += buf.length;
  163. if (this.initialBytesLen < 32) // We need more bytes to use space heuristic (see below)
  164. return '';
  165. // We have enough bytes -> detect endianness.
  166. var buf2 = Buffer.concat(this.initialBytes),
  167. encoding = detectEncoding(buf2, this.options.defaultEncoding);
  168. this.decoder = this.iconv.getDecoder(encoding, this.options);
  169. this.initialBytes.length = this.initialBytesLen = 0;
  170. }
  171. return this.decoder.write(buf);
  172. };
  173. Utf32AutoDecoder.prototype.end = function() {
  174. if (!this.decoder) {
  175. var buf = Buffer.concat(this.initialBytes),
  176. encoding = detectEncoding(buf, this.options.defaultEncoding);
  177. this.decoder = this.iconv.getDecoder(encoding, this.options);
  178. var res = this.decoder.write(buf),
  179. trail = this.decoder.end();
  180. return trail ? (res + trail) : res;
  181. }
  182. return this.decoder.end();
  183. };
  184. function detectEncoding(buf, defaultEncoding) {
  185. var enc = defaultEncoding || 'utf-32le';
  186. if (buf.length >= 4) {
  187. // Check BOM.
  188. if (buf.readUInt32BE(0) === 0xFEFF) // UTF-32LE BOM
  189. enc = 'utf-32be';
  190. else if (buf.readUInt32LE(0) === 0xFEFF) // UTF-32LE BOM
  191. enc = 'utf-32le';
  192. else {
  193. // No BOM found. Try to deduce encoding from initial content.
  194. // Using the wrong endian-ism for UTF-32 will very often result in codepoints that are beyond
  195. // the valid Unicode limit of 0x10FFFF. That will be used as the primary determinant.
  196. //
  197. // Further, we can suppose the content is mostly plain ASCII chars (U+00**).
  198. // So, we count ASCII as if it was LE or BE, and decide from that.
  199. var invalidLE = 0, invalidBE = 0;
  200. var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions
  201. _len = Math.min(buf.length - (buf.length % 4), 128); // Len is always even.
  202. for (var i = 0; i < _len; i += 4) {
  203. var b0 = buf[i], b1 = buf[i + 1], b2 = buf[i + 2], b3 = buf[i + 3];
  204. if (b0 !== 0 || b1 > 0x10) ++invalidBE;
  205. if (b3 !== 0 || b2 > 0x10) ++invalidLE;
  206. if (b0 === 0 && b1 === 0 && b2 === 0 && b3 !== 0) asciiCharsBE++;
  207. if (b0 !== 0 && b1 === 0 && b2 === 0 && b3 === 0) asciiCharsLE++;
  208. }
  209. if (invalidBE < invalidLE)
  210. enc = 'utf-32be';
  211. else if (invalidLE < invalidBE)
  212. enc = 'utf-32le';
  213. if (asciiCharsBE > asciiCharsLE)
  214. enc = 'utf-32be';
  215. else if (asciiCharsBE < asciiCharsLE)
  216. enc = 'utf-32le';
  217. }
  218. }
  219. return enc;
  220. }