You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dbcs-codec.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. "use strict";
  2. var Buffer = require("safer-buffer").Buffer;
  3. // Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
  4. // Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
  5. // To save memory and loading time, we read table files only when requested.
  6. exports._dbcs = DBCSCodec;
  7. var UNASSIGNED = -1,
  8. GB18030_CODE = -2,
  9. SEQ_START = -10,
  10. NODE_START = -1000,
  11. UNASSIGNED_NODE = new Array(0x100),
  12. DEF_CHAR = -1;
  13. for (var i = 0; i < 0x100; i++)
  14. UNASSIGNED_NODE[i] = UNASSIGNED;
  15. // Class DBCSCodec reads and initializes mapping tables.
  16. function DBCSCodec(codecOptions, iconv) {
  17. this.encodingName = codecOptions.encodingName;
  18. if (!codecOptions)
  19. throw new Error("DBCS codec is called without the data.")
  20. if (!codecOptions.table)
  21. throw new Error("Encoding '" + this.encodingName + "' has no data.");
  22. // Load tables.
  23. var mappingTable = codecOptions.table();
  24. // Decode tables: MBCS -> Unicode.
  25. // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
  26. // Trie root is decodeTables[0].
  27. // Values: >= 0 -> unicode character code. can be > 0xFFFF
  28. // == UNASSIGNED -> unknown/unassigned sequence.
  29. // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
  30. // <= NODE_START -> index of the next node in our trie to process next byte.
  31. // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.
  32. this.decodeTables = [];
  33. this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
  34. // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here.
  35. this.decodeTableSeq = [];
  36. // Actual mapping tables consist of chunks. Use them to fill up decode tables.
  37. for (var i = 0; i < mappingTable.length; i++)
  38. this._addDecodeChunk(mappingTable[i]);
  39. // Load & create GB18030 tables when needed.
  40. if (typeof codecOptions.gb18030 === 'function') {
  41. this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.
  42. // Add GB18030 common decode nodes.
  43. var commonThirdByteNodeIdx = this.decodeTables.length;
  44. this.decodeTables.push(UNASSIGNED_NODE.slice(0));
  45. var commonFourthByteNodeIdx = this.decodeTables.length;
  46. this.decodeTables.push(UNASSIGNED_NODE.slice(0));
  47. // Fill out the tree
  48. var firstByteNode = this.decodeTables[0];
  49. for (var i = 0x81; i <= 0xFE; i++) {
  50. var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]];
  51. for (var j = 0x30; j <= 0x39; j++) {
  52. if (secondByteNode[j] === UNASSIGNED) {
  53. secondByteNode[j] = NODE_START - commonThirdByteNodeIdx;
  54. } else if (secondByteNode[j] > NODE_START) {
  55. throw new Error("gb18030 decode tables conflict at byte 2");
  56. }
  57. var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]];
  58. for (var k = 0x81; k <= 0xFE; k++) {
  59. if (thirdByteNode[k] === UNASSIGNED) {
  60. thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx;
  61. } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) {
  62. continue;
  63. } else if (thirdByteNode[k] > NODE_START) {
  64. throw new Error("gb18030 decode tables conflict at byte 3");
  65. }
  66. var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]];
  67. for (var l = 0x30; l <= 0x39; l++) {
  68. if (fourthByteNode[l] === UNASSIGNED)
  69. fourthByteNode[l] = GB18030_CODE;
  70. }
  71. }
  72. }
  73. }
  74. }
  75. this.defaultCharUnicode = iconv.defaultCharUnicode;
  76. // Encode tables: Unicode -> DBCS.
  77. // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
  78. // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
  79. // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
  80. // == UNASSIGNED -> no conversion found. Output a default char.
  81. // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.
  82. this.encodeTable = [];
  83. // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
  84. // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
  85. // means end of sequence (needed when one sequence is a strict subsequence of another).
  86. // Objects are kept separately from encodeTable to increase performance.
  87. this.encodeTableSeq = [];
  88. // Some chars can be decoded, but need not be encoded.
  89. var skipEncodeChars = {};
  90. if (codecOptions.encodeSkipVals)
  91. for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
  92. var val = codecOptions.encodeSkipVals[i];
  93. if (typeof val === 'number')
  94. skipEncodeChars[val] = true;
  95. else
  96. for (var j = val.from; j <= val.to; j++)
  97. skipEncodeChars[j] = true;
  98. }
  99. // Use decode trie to recursively fill out encode tables.
  100. this._fillEncodeTable(0, 0, skipEncodeChars);
  101. // Add more encoding pairs when needed.
  102. if (codecOptions.encodeAdd) {
  103. for (var uChar in codecOptions.encodeAdd)
  104. if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
  105. this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
  106. }
  107. this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
  108. if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
  109. if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
  110. }
  111. DBCSCodec.prototype.encoder = DBCSEncoder;
  112. DBCSCodec.prototype.decoder = DBCSDecoder;
  113. // Decoder helpers
  114. DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
  115. var bytes = [];
  116. for (; addr > 0; addr >>>= 8)
  117. bytes.push(addr & 0xFF);
  118. if (bytes.length == 0)
  119. bytes.push(0);
  120. var node = this.decodeTables[0];
  121. for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
  122. var val = node[bytes[i]];
  123. if (val == UNASSIGNED) { // Create new node.
  124. node[bytes[i]] = NODE_START - this.decodeTables.length;
  125. this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
  126. }
  127. else if (val <= NODE_START) { // Existing node.
  128. node = this.decodeTables[NODE_START - val];
  129. }
  130. else
  131. throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
  132. }
  133. return node;
  134. }
  135. DBCSCodec.prototype._addDecodeChunk = function(chunk) {
  136. // First element of chunk is the hex mbcs code where we start.
  137. var curAddr = parseInt(chunk[0], 16);
  138. // Choose the decoding node where we'll write our chars.
  139. var writeTable = this._getDecodeTrieNode(curAddr);
  140. curAddr = curAddr & 0xFF;
  141. // Write all other elements of the chunk to the table.
  142. for (var k = 1; k < chunk.length; k++) {
  143. var part = chunk[k];
  144. if (typeof part === "string") { // String, write as-is.
  145. for (var l = 0; l < part.length;) {
  146. var code = part.charCodeAt(l++);
  147. if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
  148. var codeTrail = part.charCodeAt(l++);
  149. if (0xDC00 <= codeTrail && codeTrail < 0xE000)
  150. writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
  151. else
  152. throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]);
  153. }
  154. else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
  155. var len = 0xFFF - code + 2;
  156. var seq = [];
  157. for (var m = 0; m < len; m++)
  158. seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
  159. writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
  160. this.decodeTableSeq.push(seq);
  161. }
  162. else
  163. writeTable[curAddr++] = code; // Basic char
  164. }
  165. }
  166. else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
  167. var charCode = writeTable[curAddr - 1] + 1;
  168. for (var l = 0; l < part; l++)
  169. writeTable[curAddr++] = charCode++;
  170. }
  171. else
  172. throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]);
  173. }
  174. if (curAddr > 0xFF)
  175. throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
  176. }
  177. // Encoder helpers
  178. DBCSCodec.prototype._getEncodeBucket = function(uCode) {
  179. var high = uCode >> 8; // This could be > 0xFF because of astral characters.
  180. if (this.encodeTable[high] === undefined)
  181. this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
  182. return this.encodeTable[high];
  183. }
  184. DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
  185. var bucket = this._getEncodeBucket(uCode);
  186. var low = uCode & 0xFF;
  187. if (bucket[low] <= SEQ_START)
  188. this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
  189. else if (bucket[low] == UNASSIGNED)
  190. bucket[low] = dbcsCode;
  191. }
  192. DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
  193. // Get the root of character tree according to first character of the sequence.
  194. var uCode = seq[0];
  195. var bucket = this._getEncodeBucket(uCode);
  196. var low = uCode & 0xFF;
  197. var node;
  198. if (bucket[low] <= SEQ_START) {
  199. // There's already a sequence with - use it.
  200. node = this.encodeTableSeq[SEQ_START-bucket[low]];
  201. }
  202. else {
  203. // There was no sequence object - allocate a new one.
  204. node = {};
  205. if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
  206. bucket[low] = SEQ_START - this.encodeTableSeq.length;
  207. this.encodeTableSeq.push(node);
  208. }
  209. // Traverse the character tree, allocating new nodes as needed.
  210. for (var j = 1; j < seq.length-1; j++) {
  211. var oldVal = node[uCode];
  212. if (typeof oldVal === 'object')
  213. node = oldVal;
  214. else {
  215. node = node[uCode] = {}
  216. if (oldVal !== undefined)
  217. node[DEF_CHAR] = oldVal
  218. }
  219. }
  220. // Set the leaf to given dbcsCode.
  221. uCode = seq[seq.length-1];
  222. node[uCode] = dbcsCode;
  223. }
  224. DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
  225. var node = this.decodeTables[nodeIdx];
  226. var hasValues = false;
  227. var subNodeEmpty = {};
  228. for (var i = 0; i < 0x100; i++) {
  229. var uCode = node[i];
  230. var mbCode = prefix + i;
  231. if (skipEncodeChars[mbCode])
  232. continue;
  233. if (uCode >= 0) {
  234. this._setEncodeChar(uCode, mbCode);
  235. hasValues = true;
  236. } else if (uCode <= NODE_START) {
  237. var subNodeIdx = NODE_START - uCode;
  238. if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030).
  239. var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive.
  240. if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars))
  241. hasValues = true;
  242. else
  243. subNodeEmpty[subNodeIdx] = true;
  244. }
  245. } else if (uCode <= SEQ_START) {
  246. this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
  247. hasValues = true;
  248. }
  249. }
  250. return hasValues;
  251. }
  252. // == Encoder ==================================================================
  253. function DBCSEncoder(options, codec) {
  254. // Encoder state
  255. this.leadSurrogate = -1;
  256. this.seqObj = undefined;
  257. // Static data
  258. this.encodeTable = codec.encodeTable;
  259. this.encodeTableSeq = codec.encodeTableSeq;
  260. this.defaultCharSingleByte = codec.defCharSB;
  261. this.gb18030 = codec.gb18030;
  262. }
  263. DBCSEncoder.prototype.write = function(str) {
  264. var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
  265. leadSurrogate = this.leadSurrogate,
  266. seqObj = this.seqObj, nextChar = -1,
  267. i = 0, j = 0;
  268. while (true) {
  269. // 0. Get next character.
  270. if (nextChar === -1) {
  271. if (i == str.length) break;
  272. var uCode = str.charCodeAt(i++);
  273. }
  274. else {
  275. var uCode = nextChar;
  276. nextChar = -1;
  277. }
  278. // 1. Handle surrogates.
  279. if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
  280. if (uCode < 0xDC00) { // We've got lead surrogate.
  281. if (leadSurrogate === -1) {
  282. leadSurrogate = uCode;
  283. continue;
  284. } else {
  285. leadSurrogate = uCode;
  286. // Double lead surrogate found.
  287. uCode = UNASSIGNED;
  288. }
  289. } else { // We've got trail surrogate.
  290. if (leadSurrogate !== -1) {
  291. uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
  292. leadSurrogate = -1;
  293. } else {
  294. // Incomplete surrogate pair - only trail surrogate found.
  295. uCode = UNASSIGNED;
  296. }
  297. }
  298. }
  299. else if (leadSurrogate !== -1) {
  300. // Incomplete surrogate pair - only lead surrogate found.
  301. nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
  302. leadSurrogate = -1;
  303. }
  304. // 2. Convert uCode character.
  305. var dbcsCode = UNASSIGNED;
  306. if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
  307. var resCode = seqObj[uCode];
  308. if (typeof resCode === 'object') { // Sequence continues.
  309. seqObj = resCode;
  310. continue;
  311. } else if (typeof resCode == 'number') { // Sequence finished. Write it.
  312. dbcsCode = resCode;
  313. } else if (resCode == undefined) { // Current character is not part of the sequence.
  314. // Try default character for this sequence
  315. resCode = seqObj[DEF_CHAR];
  316. if (resCode !== undefined) {
  317. dbcsCode = resCode; // Found. Write it.
  318. nextChar = uCode; // Current character will be written too in the next iteration.
  319. } else {
  320. // TODO: What if we have no default? (resCode == undefined)
  321. // Then, we should write first char of the sequence as-is and try the rest recursively.
  322. // Didn't do it for now because no encoding has this situation yet.
  323. // Currently, just skip the sequence and write current char.
  324. }
  325. }
  326. seqObj = undefined;
  327. }
  328. else if (uCode >= 0) { // Regular character
  329. var subtable = this.encodeTable[uCode >> 8];
  330. if (subtable !== undefined)
  331. dbcsCode = subtable[uCode & 0xFF];
  332. if (dbcsCode <= SEQ_START) { // Sequence start
  333. seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
  334. continue;
  335. }
  336. if (dbcsCode == UNASSIGNED && this.gb18030) {
  337. // Use GB18030 algorithm to find character(s) to write.
  338. var idx = findIdx(this.gb18030.uChars, uCode);
  339. if (idx != -1) {
  340. var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
  341. newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
  342. newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
  343. newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
  344. newBuf[j++] = 0x30 + dbcsCode;
  345. continue;
  346. }
  347. }
  348. }
  349. // 3. Write dbcsCode character.
  350. if (dbcsCode === UNASSIGNED)
  351. dbcsCode = this.defaultCharSingleByte;
  352. if (dbcsCode < 0x100) {
  353. newBuf[j++] = dbcsCode;
  354. }
  355. else if (dbcsCode < 0x10000) {
  356. newBuf[j++] = dbcsCode >> 8; // high byte
  357. newBuf[j++] = dbcsCode & 0xFF; // low byte
  358. }
  359. else if (dbcsCode < 0x1000000) {
  360. newBuf[j++] = dbcsCode >> 16;
  361. newBuf[j++] = (dbcsCode >> 8) & 0xFF;
  362. newBuf[j++] = dbcsCode & 0xFF;
  363. } else {
  364. newBuf[j++] = dbcsCode >>> 24;
  365. newBuf[j++] = (dbcsCode >>> 16) & 0xFF;
  366. newBuf[j++] = (dbcsCode >>> 8) & 0xFF;
  367. newBuf[j++] = dbcsCode & 0xFF;
  368. }
  369. }
  370. this.seqObj = seqObj;
  371. this.leadSurrogate = leadSurrogate;
  372. return newBuf.slice(0, j);
  373. }
  374. DBCSEncoder.prototype.end = function() {
  375. if (this.leadSurrogate === -1 && this.seqObj === undefined)
  376. return; // All clean. Most often case.
  377. var newBuf = Buffer.alloc(10), j = 0;
  378. if (this.seqObj) { // We're in the sequence.
  379. var dbcsCode = this.seqObj[DEF_CHAR];
  380. if (dbcsCode !== undefined) { // Write beginning of the sequence.
  381. if (dbcsCode < 0x100) {
  382. newBuf[j++] = dbcsCode;
  383. }
  384. else {
  385. newBuf[j++] = dbcsCode >> 8; // high byte
  386. newBuf[j++] = dbcsCode & 0xFF; // low byte
  387. }
  388. } else {
  389. // See todo above.
  390. }
  391. this.seqObj = undefined;
  392. }
  393. if (this.leadSurrogate !== -1) {
  394. // Incomplete surrogate pair - only lead surrogate found.
  395. newBuf[j++] = this.defaultCharSingleByte;
  396. this.leadSurrogate = -1;
  397. }
  398. return newBuf.slice(0, j);
  399. }
  400. // Export for testing
  401. DBCSEncoder.prototype.findIdx = findIdx;
  402. // == Decoder ==================================================================
  403. function DBCSDecoder(options, codec) {
  404. // Decoder state
  405. this.nodeIdx = 0;
  406. this.prevBytes = [];
  407. // Static data
  408. this.decodeTables = codec.decodeTables;
  409. this.decodeTableSeq = codec.decodeTableSeq;
  410. this.defaultCharUnicode = codec.defaultCharUnicode;
  411. this.gb18030 = codec.gb18030;
  412. }
  413. DBCSDecoder.prototype.write = function(buf) {
  414. var newBuf = Buffer.alloc(buf.length*2),
  415. nodeIdx = this.nodeIdx,
  416. prevBytes = this.prevBytes, prevOffset = this.prevBytes.length,
  417. seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence.
  418. uCode;
  419. for (var i = 0, j = 0; i < buf.length; i++) {
  420. var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset];
  421. // Lookup in current trie node.
  422. var uCode = this.decodeTables[nodeIdx][curByte];
  423. if (uCode >= 0) {
  424. // Normal character, just use it.
  425. }
  426. else if (uCode === UNASSIGNED) { // Unknown char.
  427. // TODO: Callback with seq.
  428. uCode = this.defaultCharUnicode.charCodeAt(0);
  429. i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again.
  430. }
  431. else if (uCode === GB18030_CODE) {
  432. if (i >= 3) {
  433. var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30);
  434. } else {
  435. var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 +
  436. (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 +
  437. (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 +
  438. (curByte-0x30);
  439. }
  440. var idx = findIdx(this.gb18030.gbChars, ptr);
  441. uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
  442. }
  443. else if (uCode <= NODE_START) { // Go to next trie node.
  444. nodeIdx = NODE_START - uCode;
  445. continue;
  446. }
  447. else if (uCode <= SEQ_START) { // Output a sequence of chars.
  448. var seq = this.decodeTableSeq[SEQ_START - uCode];
  449. for (var k = 0; k < seq.length - 1; k++) {
  450. uCode = seq[k];
  451. newBuf[j++] = uCode & 0xFF;
  452. newBuf[j++] = uCode >> 8;
  453. }
  454. uCode = seq[seq.length-1];
  455. }
  456. else
  457. throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
  458. // Write the character to buffer, handling higher planes using surrogate pair.
  459. if (uCode >= 0x10000) {
  460. uCode -= 0x10000;
  461. var uCodeLead = 0xD800 | (uCode >> 10);
  462. newBuf[j++] = uCodeLead & 0xFF;
  463. newBuf[j++] = uCodeLead >> 8;
  464. uCode = 0xDC00 | (uCode & 0x3FF);
  465. }
  466. newBuf[j++] = uCode & 0xFF;
  467. newBuf[j++] = uCode >> 8;
  468. // Reset trie node.
  469. nodeIdx = 0; seqStart = i+1;
  470. }
  471. this.nodeIdx = nodeIdx;
  472. this.prevBytes = (seqStart >= 0)
  473. ? Array.prototype.slice.call(buf, seqStart)
  474. : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf));
  475. return newBuf.slice(0, j).toString('ucs2');
  476. }
  477. DBCSDecoder.prototype.end = function() {
  478. var ret = '';
  479. // Try to parse all remaining chars.
  480. while (this.prevBytes.length > 0) {
  481. // Skip 1 character in the buffer.
  482. ret += this.defaultCharUnicode;
  483. var bytesArr = this.prevBytes.slice(1);
  484. // Parse remaining as usual.
  485. this.prevBytes = [];
  486. this.nodeIdx = 0;
  487. if (bytesArr.length > 0)
  488. ret += this.write(bytesArr);
  489. }
  490. this.prevBytes = [];
  491. this.nodeIdx = 0;
  492. return ret;
  493. }
  494. // Binary search for GB18030. Returns largest i such that table[i] <= val.
  495. function findIdx(table, val) {
  496. if (table[0] > val)
  497. return -1;
  498. var l = 0, r = table.length;
  499. while (l < r-1) { // always table[l] <= val < table[r]
  500. var mid = l + ((r-l+1) >> 1);
  501. if (table[mid] <= val)
  502. l = mid;
  503. else
  504. r = mid;
  505. }
  506. return l;
  507. }