Merge "LOG SQL dump files getting installed"
[sdnc/oam.git] / dgbuilder / dgeflows / node_modules / body-parser / node_modules / iconv-lite / encodings / dbcs-codec.js
1
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.
5
6 exports._dbcs = function(options) {
7     return new DBCSCodec(options);
8 }
9
10 var UNASSIGNED = -1,
11     GB18030_CODE = -2,
12     SEQ_START  = -10,
13     NODE_START = -1000,
14     UNASSIGNED_NODE = new Array(0x100),
15     DEF_CHAR = -1;
16
17 for (var i = 0; i < 0x100; i++)
18     UNASSIGNED_NODE[i] = UNASSIGNED;
19
20
21 // Class DBCSCodec reads and initializes mapping tables.
22 function DBCSCodec(options) {
23     this.options = options;
24     if (!options)
25         throw new Error("DBCS codec is called without the data.")
26     if (!options.table)
27         throw new Error("Encoding '" + options.encodingName + "' has no data.");
28
29     // Load tables.
30     var mappingTable = options.table();
31
32
33     // Decode tables: MBCS -> Unicode.
34
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.
44
45     // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. 
46     this.decodeTableSeq = [];
47
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]);
51
52     this.defaultCharUnicode = options.iconv.defaultCharUnicode;
53
54     
55     // Encode tables: Unicode -> DBCS.
56
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 = [];
63     
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 = [];
69
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;
77         }
78         
79     // Use decode trie to recursively fill out encode tables.
80     this._fillEncodeTable(0, 0, skipEncodeChars);
81
82     // Add more encoding pairs when needed.
83     for (var uChar in options.encodeAdd || {})
84         this._setEncodeChar(uChar.charCodeAt(0), options.encodeAdd[uChar]);
85
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);
89
90
91     // Load & create GB18030 tables when needed.
92     if (typeof options.gb18030 === 'function') {
93         this.gb18030 = options.gb18030(); // Load GB18030 ranges.
94
95         // Add GB18030 decode tables.
96         var thirdByteNodeIdx = this.decodeTables.length;
97         var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);
98
99         var fourthByteNodeIdx = this.decodeTables.length;
100         var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);
101
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;
107         }
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
112     }        
113 }
114
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) {
118     return {
119         // Methods
120         write: encoderDBCSWrite,
121         end: encoderDBCSEnd,
122
123         // Encoder state
124         leadSurrogate: -1,
125         seqObj: undefined,
126         
127         // Static data
128         encodeTable: this.encodeTable,
129         encodeTableSeq: this.encodeTableSeq,
130         defaultCharSingleByte: this.defCharSB,
131         gb18030: this.gb18030,
132
133         // Export for testing
134         findIdx: findIdx,
135     }
136 }
137
138 DBCSCodec.prototype.decoder = function decoderDBCS(options) {
139     return {
140         // Methods
141         write: decoderDBCSWrite,
142         end: decoderDBCSEnd,
143
144         // Decoder state
145         nodeIdx: 0,
146         prevBuf: new Buffer(0),
147
148         // Static data
149         decodeTables: this.decodeTables,
150         decodeTableSeq: this.decodeTableSeq,
151         defaultCharUnicode: this.defaultCharUnicode,
152         gb18030: this.gb18030,
153     }
154 }
155
156
157
158 // Decoder helpers
159 DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
160     var bytes = [];
161     for (; addr > 0; addr >>= 8)
162         bytes.push(addr & 0xFF);
163     if (bytes.length == 0)
164         bytes.push(0);
165
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]];
169
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));
173         }
174         else if (val <= NODE_START) { // Existing node.
175             node = this.decodeTables[NODE_START - val];
176         }
177         else
178             throw new Error("Overwrite byte in " + this.options.encodingName + ", addr: " + addr.toString(16));
179     }
180     return node;
181 }
182
183
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);
187
188     // Choose the decoding node where we'll write our chars.
189     var writeTable = this._getDecodeTrieNode(curAddr);
190     curAddr = curAddr & 0xFF;
191
192     // Write all other elements of the chunk to the table.
193     for (var k = 1; k < chunk.length; k++) {
194         var part = chunk[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);
202                     else
203                         throw new Error("Incorrect surrogate pair in "  + this.options.encodingName + " at chunk " + chunk[0]);
204                 }
205                 else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
206                     var len = 0xFFF - code + 2;
207                     var seq = [];
208                     for (var m = 0; m < len; m++)
209                         seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
210
211                     writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
212                     this.decodeTableSeq.push(seq);
213                 }
214                 else
215                     writeTable[curAddr++] = code; // Basic char
216             }
217         } 
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++;
222         }
223         else
224             throw new Error("Incorrect type '" + typeof part + "' given in "  + this.options.encodingName + " at chunk " + chunk[0]);
225     }
226     if (curAddr > 0xFF)
227         throw new Error("Incorrect chunk in "  + this.options.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
228 }
229
230 // Encoder helpers
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];
236 }
237
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;
245 }
246
247 DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
248     
249     // Get the root of character tree according to first character of the sequence.
250     var uCode = seq[0];
251     var bucket = this._getEncodeBucket(uCode);
252     var low = uCode & 0xFF;
253
254     var node;
255     if (bucket[low] <= SEQ_START) {
256         // There's already a sequence with  - use it.
257         node = this.encodeTableSeq[SEQ_START-bucket[low]];
258     }
259     else {
260         // There was no sequence object - allocate a new one.
261         node = {};
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);
265     }
266
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')
271             node = oldVal;
272         else {
273             node = node[uCode] = {}
274             if (oldVal !== undefined)
275                 node[DEF_CHAR] = oldVal
276         }
277     }
278
279     // Set the leaf to given dbcsCode.
280     uCode = seq[seq.length-1];
281     node[uCode] = dbcsCode;
282 }
283
284 DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
285     var node = this.decodeTables[nodeIdx];
286     for (var i = 0; i < 0x100; i++) {
287         var uCode = node[i];
288         var mbCode = prefix + i;
289         if (skipEncodeChars[mbCode])
290             continue;
291
292         if (uCode >= 0)
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);
298     }
299 }
300
301
302
303 // == Actual Encoding ==========================================================
304
305
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,
310         i = 0, j = 0;
311
312     while (true) {
313         // 0. Get next character.
314         if (nextChar === -1) {
315             if (i == str.length) break;
316             var uCode = str.charCodeAt(i++);
317         }
318         else {
319             var uCode = nextChar;
320             nextChar = -1;    
321         }
322
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;
328                     continue;
329                 } else {
330                     leadSurrogate = uCode;
331                     // Double lead surrogate found.
332                     uCode = UNASSIGNED;
333                 }
334             } else { // We've got trail surrogate.
335                 if (leadSurrogate !== -1) {
336                     uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
337                     leadSurrogate = -1;
338                 } else {
339                     // Incomplete surrogate pair - only trail surrogate found.
340                     uCode = UNASSIGNED;
341                 }
342                 
343             }
344         }
345         else if (leadSurrogate !== -1) {
346             // Incomplete surrogate pair - only lead surrogate found.
347             nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
348             leadSurrogate = -1;
349         }
350
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.
356                 seqObj = resCode;
357                 continue;
358
359             } else if (typeof resCode == 'number') { // Sequence finished. Write it.
360                 dbcsCode = resCode;
361
362             } else if (resCode == undefined) { // Current character is not part of the sequence.
363
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.
369
370                 } else {
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.
375                 }
376             }
377             seqObj = undefined;
378         }
379         else if (uCode >= 0) {  // Regular character
380             var subtable = this.encodeTable[uCode >> 8];
381             if (subtable !== undefined)
382                 dbcsCode = subtable[uCode & 0xFF];
383             
384             if (dbcsCode <= SEQ_START) { // Sequence start
385                 seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
386                 continue;
387             }
388
389             if (dbcsCode == UNASSIGNED && this.gb18030) {
390                 // Use GB18030 algorithm to find character(s) to write.
391                 var idx = findIdx(this.gb18030.uChars, uCode);
392                 if (idx != -1) {
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;
398                     continue;
399                 }
400             }
401         }
402
403         // 3. Write dbcsCode character.
404         if (dbcsCode === UNASSIGNED)
405             dbcsCode = this.defaultCharSingleByte;
406         
407         if (dbcsCode < 0x100) {
408             newBuf[j++] = dbcsCode;
409         }
410         else if (dbcsCode < 0x10000) {
411             newBuf[j++] = dbcsCode >> 8;   // high byte
412             newBuf[j++] = dbcsCode & 0xFF; // low byte
413         }
414         else {
415             newBuf[j++] = dbcsCode >> 16;
416             newBuf[j++] = (dbcsCode >> 8) & 0xFF;
417             newBuf[j++] = dbcsCode & 0xFF;
418         }
419     }
420
421     this.seqObj = seqObj;
422     this.leadSurrogate = leadSurrogate;
423     return newBuf.slice(0, j);
424 }
425
426 function encoderDBCSEnd() {
427     if (this.leadSurrogate === -1 && this.seqObj === undefined)
428         return; // All clean. Most often case.
429
430     var newBuf = new Buffer(10), j = 0;
431
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;
437             }
438             else {
439                 newBuf[j++] = dbcsCode >> 8;   // high byte
440                 newBuf[j++] = dbcsCode & 0xFF; // low byte
441             }
442         } else {
443             // See todo above.
444         }
445         this.seqObj = undefined;
446     }
447
448     if (this.leadSurrogate !== -1) {
449         // Incomplete surrogate pair - only lead surrogate found.
450         newBuf[j++] = this.defaultCharSingleByte;
451         this.leadSurrogate = -1;
452     }
453     
454     return newBuf.slice(0, j);
455 }
456
457
458 // == Actual Decoding ==========================================================
459
460
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.
466         uCode;
467
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)]);
470     
471     for (var i = 0, j = 0; i < buf.length; i++) {
472         var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset];
473
474         // TODO: Check curByte is number 0 <= < 256
475
476         // Lookup in current trie node.
477         var uCode = this.decodeTables[nodeIdx][curByte];
478
479         if (uCode >= 0) { 
480             // Normal character, just use it.
481         }
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);
487         }
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];
493         }
494         else if (uCode <= NODE_START) { // Go to next trie node.
495             nodeIdx = NODE_START - uCode;
496             continue;
497         }
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++) {
501                 uCode = seq[k];
502                 newBuf[j++] = uCode & 0xFF;
503                 newBuf[j++] = uCode >> 8;
504             }
505             uCode = seq[seq.length-1];
506         }
507         else
508             throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
509
510         // Write the character to buffer, handling higher planes using surrogate pair.
511         if (uCode > 0xFFFF) { 
512             uCode -= 0x10000;
513             var uCodeLead = 0xD800 + Math.floor(uCode / 0x400);
514             newBuf[j++] = uCodeLead & 0xFF;
515             newBuf[j++] = uCodeLead >> 8;
516
517             uCode = 0xDC00 + uCode % 0x400;
518         }
519         newBuf[j++] = uCode & 0xFF;
520         newBuf[j++] = uCode >> 8;
521
522         // Reset trie node.
523         nodeIdx = 0; seqStart = i+1;
524     }
525
526     this.nodeIdx = nodeIdx;
527     this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);
528     return newBuf.slice(0, j).toString('ucs2');
529 }
530
531 function decoderDBCSEnd() {
532     var ret = '';
533
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);
539
540         // Parse remaining as usual.
541         this.prevBuf = new Buffer(0);
542         this.nodeIdx = 0;
543         if (buf.length > 0)
544             ret += decoderDBCSWrite.call(this, buf);
545     }
546
547     this.nodeIdx = 0;
548     return ret;
549 }
550
551 // Binary search for GB18030. Returns largest i such that table[i] <= val.
552 function findIdx(table, val) {
553     if (table[0] > val)
554         return -1;
555
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)
560             l = mid;
561         else
562             r = mid;
563     }
564     return l;
565 }
566