2 // Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
3 // Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
4 // To save memory and loading time, we read table files only when requested.
6 exports._dbcs = function(options) {
7 return new DBCSCodec(options);
14 UNASSIGNED_NODE = new Array(0x100),
17 for (var i = 0; i < 0x100; i++)
18 UNASSIGNED_NODE[i] = UNASSIGNED;
21 // Class DBCSCodec reads and initializes mapping tables.
22 function DBCSCodec(options) {
23 this.options = options;
25 throw new Error("DBCS codec is called without the data.")
27 throw new Error("Encoding '" + options.encodingName + "' has no data.");
30 var mappingTable = options.table();
33 // Decode tables: MBCS -> Unicode.
35 // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
36 // Trie root is decodeTables[0].
37 // Values: >= 0 -> unicode character code. can be > 0xFFFF
38 // == UNASSIGNED -> unknown/unassigned sequence.
39 // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
40 // <= NODE_START -> index of the next node in our trie to process next byte.
41 // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.
42 this.decodeTables = [];
43 this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
45 // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here.
46 this.decodeTableSeq = [];
48 // Actual mapping tables consist of chunks. Use them to fill up decode tables.
49 for (var i = 0; i < mappingTable.length; i++)
50 this._addDecodeChunk(mappingTable[i]);
52 this.defaultCharUnicode = options.iconv.defaultCharUnicode;
55 // Encode tables: Unicode -> DBCS.
57 // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
58 // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
59 // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
60 // == UNASSIGNED -> no conversion found. Output a default char.
61 // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.
62 this.encodeTable = [];
64 // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
65 // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
66 // means end of sequence (needed when one sequence is a strict subsequence of another).
67 // Objects are kept separately from encodeTable to increase performance.
68 this.encodeTableSeq = [];
70 // Some chars can be decoded, but need not be encoded.
71 var skipEncodeChars = {};
72 if (options.encodeSkipVals)
73 for (var i = 0; i < options.encodeSkipVals.length; i++) {
74 var range = options.encodeSkipVals[i];
75 for (var j = range.from; j <= range.to; j++)
76 skipEncodeChars[j] = true;
79 // Use decode trie to recursively fill out encode tables.
80 this._fillEncodeTable(0, 0, skipEncodeChars);
82 // Add more encoding pairs when needed.
83 for (var uChar in options.encodeAdd || {})
84 this._setEncodeChar(uChar.charCodeAt(0), options.encodeAdd[uChar]);
86 this.defCharSB = this.encodeTable[0][options.iconv.defaultCharSingleByte.charCodeAt(0)];
87 if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
88 if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
91 // Load & create GB18030 tables when needed.
92 if (typeof options.gb18030 === 'function') {
93 this.gb18030 = options.gb18030(); // Load GB18030 ranges.
95 // Add GB18030 decode tables.
96 var thirdByteNodeIdx = this.decodeTables.length;
97 var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);
99 var fourthByteNodeIdx = this.decodeTables.length;
100 var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);
102 for (var i = 0x81; i <= 0xFE; i++) {
103 var secondByteNodeIdx = NODE_START - this.decodeTables[0][i];
104 var secondByteNode = this.decodeTables[secondByteNodeIdx];
105 for (var j = 0x30; j <= 0x39; j++)
106 secondByteNode[j] = NODE_START - thirdByteNodeIdx;
108 for (var i = 0x81; i <= 0xFE; i++)
109 thirdByteNode[i] = NODE_START - fourthByteNodeIdx;
110 for (var i = 0x30; i <= 0x39; i++)
111 fourthByteNode[i] = GB18030_CODE
115 // Public interface: create encoder and decoder objects.
116 // The methods (write, end) are simple functions to not inhibit optimizations.
117 DBCSCodec.prototype.encoder = function encoderDBCS(options) {
120 write: encoderDBCSWrite,
128 encodeTable: this.encodeTable,
129 encodeTableSeq: this.encodeTableSeq,
130 defaultCharSingleByte: this.defCharSB,
131 gb18030: this.gb18030,
133 // Export for testing
138 DBCSCodec.prototype.decoder = function decoderDBCS(options) {
141 write: decoderDBCSWrite,
146 prevBuf: new Buffer(0),
149 decodeTables: this.decodeTables,
150 decodeTableSeq: this.decodeTableSeq,
151 defaultCharUnicode: this.defaultCharUnicode,
152 gb18030: this.gb18030,
159 DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
161 for (; addr > 0; addr >>= 8)
162 bytes.push(addr & 0xFF);
163 if (bytes.length == 0)
166 var node = this.decodeTables[0];
167 for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
168 var val = node[bytes[i]];
170 if (val == UNASSIGNED) { // Create new node.
171 node[bytes[i]] = NODE_START - this.decodeTables.length;
172 this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
174 else if (val <= NODE_START) { // Existing node.
175 node = this.decodeTables[NODE_START - val];
178 throw new Error("Overwrite byte in " + this.options.encodingName + ", addr: " + addr.toString(16));
184 DBCSCodec.prototype._addDecodeChunk = function(chunk) {
185 // First element of chunk is the hex mbcs code where we start.
186 var curAddr = parseInt(chunk[0], 16);
188 // Choose the decoding node where we'll write our chars.
189 var writeTable = this._getDecodeTrieNode(curAddr);
190 curAddr = curAddr & 0xFF;
192 // Write all other elements of the chunk to the table.
193 for (var k = 1; k < chunk.length; k++) {
195 if (typeof part === "string") { // String, write as-is.
196 for (var l = 0; l < part.length;) {
197 var code = part.charCodeAt(l++);
198 if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
199 var codeTrail = part.charCodeAt(l++);
200 if (0xDC00 <= codeTrail && codeTrail < 0xE000)
201 writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
203 throw new Error("Incorrect surrogate pair in " + this.options.encodingName + " at chunk " + chunk[0]);
205 else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
206 var len = 0xFFF - code + 2;
208 for (var m = 0; m < len; m++)
209 seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
211 writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
212 this.decodeTableSeq.push(seq);
215 writeTable[curAddr++] = code; // Basic char
218 else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
219 var charCode = writeTable[curAddr - 1] + 1;
220 for (var l = 0; l < part; l++)
221 writeTable[curAddr++] = charCode++;
224 throw new Error("Incorrect type '" + typeof part + "' given in " + this.options.encodingName + " at chunk " + chunk[0]);
227 throw new Error("Incorrect chunk in " + this.options.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
231 DBCSCodec.prototype._getEncodeBucket = function(uCode) {
232 var high = uCode >> 8; // This could be > 0xFF because of astral characters.
233 if (this.encodeTable[high] === undefined)
234 this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
235 return this.encodeTable[high];
238 DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
239 var bucket = this._getEncodeBucket(uCode);
240 var low = uCode & 0xFF;
241 if (bucket[low] <= SEQ_START)
242 this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
243 else if (bucket[low] == UNASSIGNED)
244 bucket[low] = dbcsCode;
247 DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
249 // Get the root of character tree according to first character of the sequence.
251 var bucket = this._getEncodeBucket(uCode);
252 var low = uCode & 0xFF;
255 if (bucket[low] <= SEQ_START) {
256 // There's already a sequence with - use it.
257 node = this.encodeTableSeq[SEQ_START-bucket[low]];
260 // There was no sequence object - allocate a new one.
262 if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
263 bucket[low] = SEQ_START - this.encodeTableSeq.length;
264 this.encodeTableSeq.push(node);
267 // Traverse the character tree, allocating new nodes as needed.
268 for (var j = 1; j < seq.length-1; j++) {
269 var oldVal = node[uCode];
270 if (typeof oldVal === 'object')
273 node = node[uCode] = {}
274 if (oldVal !== undefined)
275 node[DEF_CHAR] = oldVal
279 // Set the leaf to given dbcsCode.
280 uCode = seq[seq.length-1];
281 node[uCode] = dbcsCode;
284 DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
285 var node = this.decodeTables[nodeIdx];
286 for (var i = 0; i < 0x100; i++) {
288 var mbCode = prefix + i;
289 if (skipEncodeChars[mbCode])
293 this._setEncodeChar(uCode, mbCode);
294 else if (uCode <= NODE_START)
295 this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);
296 else if (uCode <= SEQ_START)
297 this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
303 // == Actual Encoding ==========================================================
306 function encoderDBCSWrite(str) {
307 var newBuf = new Buffer(str.length * (this.gb18030 ? 4 : 3)),
308 leadSurrogate = this.leadSurrogate,
309 seqObj = this.seqObj, nextChar = -1,
313 // 0. Get next character.
314 if (nextChar === -1) {
315 if (i == str.length) break;
316 var uCode = str.charCodeAt(i++);
319 var uCode = nextChar;
323 // 1. Handle surrogates.
324 if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
325 if (uCode < 0xDC00) { // We've got lead surrogate.
326 if (leadSurrogate === -1) {
327 leadSurrogate = uCode;
330 leadSurrogate = uCode;
331 // Double lead surrogate found.
334 } else { // We've got trail surrogate.
335 if (leadSurrogate !== -1) {
336 uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
339 // Incomplete surrogate pair - only trail surrogate found.
345 else if (leadSurrogate !== -1) {
346 // Incomplete surrogate pair - only lead surrogate found.
347 nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
351 // 2. Convert uCode character.
352 var dbcsCode = UNASSIGNED;
353 if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
354 var resCode = seqObj[uCode];
355 if (typeof resCode === 'object') { // Sequence continues.
359 } else if (typeof resCode == 'number') { // Sequence finished. Write it.
362 } else if (resCode == undefined) { // Current character is not part of the sequence.
364 // Try default character for this sequence
365 resCode = seqObj[DEF_CHAR];
366 if (resCode !== undefined) {
367 dbcsCode = resCode; // Found. Write it.
368 nextChar = uCode; // Current character will be written too in the next iteration.
371 // TODO: What if we have no default? (resCode == undefined)
372 // Then, we should write first char of the sequence as-is and try the rest recursively.
373 // Didn't do it for now because no encoding has this situation yet.
374 // Currently, just skip the sequence and write current char.
379 else if (uCode >= 0) { // Regular character
380 var subtable = this.encodeTable[uCode >> 8];
381 if (subtable !== undefined)
382 dbcsCode = subtable[uCode & 0xFF];
384 if (dbcsCode <= SEQ_START) { // Sequence start
385 seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
389 if (dbcsCode == UNASSIGNED && this.gb18030) {
390 // Use GB18030 algorithm to find character(s) to write.
391 var idx = findIdx(this.gb18030.uChars, uCode);
393 var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
394 newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
395 newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
396 newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
397 newBuf[j++] = 0x30 + dbcsCode;
403 // 3. Write dbcsCode character.
404 if (dbcsCode === UNASSIGNED)
405 dbcsCode = this.defaultCharSingleByte;
407 if (dbcsCode < 0x100) {
408 newBuf[j++] = dbcsCode;
410 else if (dbcsCode < 0x10000) {
411 newBuf[j++] = dbcsCode >> 8; // high byte
412 newBuf[j++] = dbcsCode & 0xFF; // low byte
415 newBuf[j++] = dbcsCode >> 16;
416 newBuf[j++] = (dbcsCode >> 8) & 0xFF;
417 newBuf[j++] = dbcsCode & 0xFF;
421 this.seqObj = seqObj;
422 this.leadSurrogate = leadSurrogate;
423 return newBuf.slice(0, j);
426 function encoderDBCSEnd() {
427 if (this.leadSurrogate === -1 && this.seqObj === undefined)
428 return; // All clean. Most often case.
430 var newBuf = new Buffer(10), j = 0;
432 if (this.seqObj) { // We're in the sequence.
433 var dbcsCode = this.seqObj[DEF_CHAR];
434 if (dbcsCode !== undefined) { // Write beginning of the sequence.
435 if (dbcsCode < 0x100) {
436 newBuf[j++] = dbcsCode;
439 newBuf[j++] = dbcsCode >> 8; // high byte
440 newBuf[j++] = dbcsCode & 0xFF; // low byte
445 this.seqObj = undefined;
448 if (this.leadSurrogate !== -1) {
449 // Incomplete surrogate pair - only lead surrogate found.
450 newBuf[j++] = this.defaultCharSingleByte;
451 this.leadSurrogate = -1;
454 return newBuf.slice(0, j);
458 // == Actual Decoding ==========================================================
461 function decoderDBCSWrite(buf) {
462 var newBuf = new Buffer(buf.length*2),
463 nodeIdx = this.nodeIdx,
464 prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length,
465 seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence.
468 if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later.
469 prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]);
471 for (var i = 0, j = 0; i < buf.length; i++) {
472 var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset];
474 // TODO: Check curByte is number 0 <= < 256
476 // Lookup in current trie node.
477 var uCode = this.decodeTables[nodeIdx][curByte];
480 // Normal character, just use it.
482 else if (uCode === UNASSIGNED) { // Unknown char.
483 // TODO: Callback with seq.
484 //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
485 i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle).
486 uCode = this.defaultCharUnicode.charCodeAt(0);
488 else if (uCode === GB18030_CODE) {
489 var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
490 var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30);
491 var idx = findIdx(this.gb18030.gbChars, ptr);
492 uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
494 else if (uCode <= NODE_START) { // Go to next trie node.
495 nodeIdx = NODE_START - uCode;
498 else if (uCode <= SEQ_START) { // Output a sequence of chars.
499 var seq = this.decodeTableSeq[SEQ_START - uCode];
500 for (var k = 0; k < seq.length - 1; k++) {
502 newBuf[j++] = uCode & 0xFF;
503 newBuf[j++] = uCode >> 8;
505 uCode = seq[seq.length-1];
508 throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
510 // Write the character to buffer, handling higher planes using surrogate pair.
511 if (uCode > 0xFFFF) {
513 var uCodeLead = 0xD800 + Math.floor(uCode / 0x400);
514 newBuf[j++] = uCodeLead & 0xFF;
515 newBuf[j++] = uCodeLead >> 8;
517 uCode = 0xDC00 + uCode % 0x400;
519 newBuf[j++] = uCode & 0xFF;
520 newBuf[j++] = uCode >> 8;
523 nodeIdx = 0; seqStart = i+1;
526 this.nodeIdx = nodeIdx;
527 this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);
528 return newBuf.slice(0, j).toString('ucs2');
531 function decoderDBCSEnd() {
534 // Try to parse all remaining chars.
535 while (this.prevBuf.length > 0) {
536 // Skip 1 character in the buffer.
537 ret += this.defaultCharUnicode;
538 var buf = this.prevBuf.slice(1);
540 // Parse remaining as usual.
541 this.prevBuf = new Buffer(0);
544 ret += decoderDBCSWrite.call(this, buf);
551 // Binary search for GB18030. Returns largest i such that table[i] <= val.
552 function findIdx(table, val) {
556 var l = 0, r = table.length;
557 while (l < r-1) { // always table[l] <= val < table[r]
558 var mid = l + Math.floor((r-l+1)/2);
559 if (table[mid] <= val)