dbcs-codec.js 20 KB

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