react / react-0.13.3 / examples / basic-commonjs / node_modules / reactify / node_modules / react-tools / node_modules / commoner / node_modules / iconv-lite / encodings / dbcs-codec.js
81169 views"use strict"12// 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.56exports._dbcs = DBCSCodec;78var UNASSIGNED = -1,9GB18030_CODE = -2,10SEQ_START = -10,11NODE_START = -1000,12UNASSIGNED_NODE = new Array(0x100),13DEF_CHAR = -1;1415for (var i = 0; i < 0x100; i++)16UNASSIGNED_NODE[i] = UNASSIGNED;171819// Class DBCSCodec reads and initializes mapping tables.20function DBCSCodec(codecOptions, iconv) {21this.encodingName = codecOptions.encodingName;22if (!codecOptions)23throw new Error("DBCS codec is called without the data.")24if (!codecOptions.table)25throw new Error("Encoding '" + this.encodingName + "' has no data.");2627// Load tables.28var mappingTable = codecOptions.table();293031// Decode tables: MBCS -> Unicode.3233// decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.34// Trie root is decodeTables[0].35// Values: >= 0 -> unicode character code. can be > 0xFFFF36// == UNASSIGNED -> unknown/unassigned sequence.37// == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.38// <= NODE_START -> index of the next node in our trie to process next byte.39// <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.40this.decodeTables = [];41this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.4243// Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here.44this.decodeTableSeq = [];4546// Actual mapping tables consist of chunks. Use them to fill up decode tables.47for (var i = 0; i < mappingTable.length; i++)48this._addDecodeChunk(mappingTable[i]);4950this.defaultCharUnicode = iconv.defaultCharUnicode;515253// Encode tables: Unicode -> DBCS.5455// `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.56// Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.57// Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).58// == UNASSIGNED -> no conversion found. Output a default char.59// <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.60this.encodeTable = [];6162// `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of63// objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key64// means end of sequence (needed when one sequence is a strict subsequence of another).65// Objects are kept separately from encodeTable to increase performance.66this.encodeTableSeq = [];6768// Some chars can be decoded, but need not be encoded.69var skipEncodeChars = {};70if (codecOptions.encodeSkipVals)71for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {72var val = codecOptions.encodeSkipVals[i];73if (typeof val === 'number')74skipEncodeChars[val] = true;75else76for (var j = val.from; j <= val.to; j++)77skipEncodeChars[j] = true;78}7980// Use decode trie to recursively fill out encode tables.81this._fillEncodeTable(0, 0, skipEncodeChars);8283// Add more encoding pairs when needed.84if (codecOptions.encodeAdd) {85for (var uChar in codecOptions.encodeAdd)86if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))87this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);88}8990this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];91if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];92if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);939495// Load & create GB18030 tables when needed.96if (typeof codecOptions.gb18030 === 'function') {97this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.9899// Add GB18030 decode tables.100var thirdByteNodeIdx = this.decodeTables.length;101var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);102103var fourthByteNodeIdx = this.decodeTables.length;104var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);105106for (var i = 0x81; i <= 0xFE; i++) {107var secondByteNodeIdx = NODE_START - this.decodeTables[0][i];108var secondByteNode = this.decodeTables[secondByteNodeIdx];109for (var j = 0x30; j <= 0x39; j++)110secondByteNode[j] = NODE_START - thirdByteNodeIdx;111}112for (var i = 0x81; i <= 0xFE; i++)113thirdByteNode[i] = NODE_START - fourthByteNodeIdx;114for (var i = 0x30; i <= 0x39; i++)115fourthByteNode[i] = GB18030_CODE116}117}118119DBCSCodec.prototype.encoder = DBCSEncoder;120DBCSCodec.prototype.decoder = DBCSDecoder;121122// Decoder helpers123DBCSCodec.prototype._getDecodeTrieNode = function(addr) {124var bytes = [];125for (; addr > 0; addr >>= 8)126bytes.push(addr & 0xFF);127if (bytes.length == 0)128bytes.push(0);129130var node = this.decodeTables[0];131for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.132var val = node[bytes[i]];133134if (val == UNASSIGNED) { // Create new node.135node[bytes[i]] = NODE_START - this.decodeTables.length;136this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));137}138else if (val <= NODE_START) { // Existing node.139node = this.decodeTables[NODE_START - val];140}141else142throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));143}144return node;145}146147148DBCSCodec.prototype._addDecodeChunk = function(chunk) {149// First element of chunk is the hex mbcs code where we start.150var curAddr = parseInt(chunk[0], 16);151152// Choose the decoding node where we'll write our chars.153var writeTable = this._getDecodeTrieNode(curAddr);154curAddr = curAddr & 0xFF;155156// Write all other elements of the chunk to the table.157for (var k = 1; k < chunk.length; k++) {158var part = chunk[k];159if (typeof part === "string") { // String, write as-is.160for (var l = 0; l < part.length;) {161var code = part.charCodeAt(l++);162if (0xD800 <= code && code < 0xDC00) { // Decode surrogate163var codeTrail = part.charCodeAt(l++);164if (0xDC00 <= codeTrail && codeTrail < 0xE000)165writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);166else167throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]);168}169else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)170var len = 0xFFF - code + 2;171var seq = [];172for (var m = 0; m < len; m++)173seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.174175writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;176this.decodeTableSeq.push(seq);177}178else179writeTable[curAddr++] = code; // Basic char180}181}182else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.183var charCode = writeTable[curAddr - 1] + 1;184for (var l = 0; l < part; l++)185writeTable[curAddr++] = charCode++;186}187else188throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]);189}190if (curAddr > 0xFF)191throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);192}193194// Encoder helpers195DBCSCodec.prototype._getEncodeBucket = function(uCode) {196var high = uCode >> 8; // This could be > 0xFF because of astral characters.197if (this.encodeTable[high] === undefined)198this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.199return this.encodeTable[high];200}201202DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {203var bucket = this._getEncodeBucket(uCode);204var low = uCode & 0xFF;205if (bucket[low] <= SEQ_START)206this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.207else if (bucket[low] == UNASSIGNED)208bucket[low] = dbcsCode;209}210211DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {212213// Get the root of character tree according to first character of the sequence.214var uCode = seq[0];215var bucket = this._getEncodeBucket(uCode);216var low = uCode & 0xFF;217218var node;219if (bucket[low] <= SEQ_START) {220// There's already a sequence with - use it.221node = this.encodeTableSeq[SEQ_START-bucket[low]];222}223else {224// There was no sequence object - allocate a new one.225node = {};226if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.227bucket[low] = SEQ_START - this.encodeTableSeq.length;228this.encodeTableSeq.push(node);229}230231// Traverse the character tree, allocating new nodes as needed.232for (var j = 1; j < seq.length-1; j++) {233var oldVal = node[uCode];234if (typeof oldVal === 'object')235node = oldVal;236else {237node = node[uCode] = {}238if (oldVal !== undefined)239node[DEF_CHAR] = oldVal240}241}242243// Set the leaf to given dbcsCode.244uCode = seq[seq.length-1];245node[uCode] = dbcsCode;246}247248DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {249var node = this.decodeTables[nodeIdx];250for (var i = 0; i < 0x100; i++) {251var uCode = node[i];252var mbCode = prefix + i;253if (skipEncodeChars[mbCode])254continue;255256if (uCode >= 0)257this._setEncodeChar(uCode, mbCode);258else if (uCode <= NODE_START)259this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);260else if (uCode <= SEQ_START)261this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);262}263}264265266267// == Encoder ==================================================================268269function DBCSEncoder(options, codec) {270// Encoder state271this.leadSurrogate = -1;272this.seqObj = undefined;273274// Static data275this.encodeTable = codec.encodeTable;276this.encodeTableSeq = codec.encodeTableSeq;277this.defaultCharSingleByte = codec.defCharSB;278this.gb18030 = codec.gb18030;279}280281DBCSEncoder.prototype.write = function(str) {282var newBuf = new Buffer(str.length * (this.gb18030 ? 4 : 3)),283leadSurrogate = this.leadSurrogate,284seqObj = this.seqObj, nextChar = -1,285i = 0, j = 0;286287while (true) {288// 0. Get next character.289if (nextChar === -1) {290if (i == str.length) break;291var uCode = str.charCodeAt(i++);292}293else {294var uCode = nextChar;295nextChar = -1;296}297298// 1. Handle surrogates.299if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.300if (uCode < 0xDC00) { // We've got lead surrogate.301if (leadSurrogate === -1) {302leadSurrogate = uCode;303continue;304} else {305leadSurrogate = uCode;306// Double lead surrogate found.307uCode = UNASSIGNED;308}309} else { // We've got trail surrogate.310if (leadSurrogate !== -1) {311uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);312leadSurrogate = -1;313} else {314// Incomplete surrogate pair - only trail surrogate found.315uCode = UNASSIGNED;316}317318}319}320else if (leadSurrogate !== -1) {321// Incomplete surrogate pair - only lead surrogate found.322nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.323leadSurrogate = -1;324}325326// 2. Convert uCode character.327var dbcsCode = UNASSIGNED;328if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence329var resCode = seqObj[uCode];330if (typeof resCode === 'object') { // Sequence continues.331seqObj = resCode;332continue;333334} else if (typeof resCode == 'number') { // Sequence finished. Write it.335dbcsCode = resCode;336337} else if (resCode == undefined) { // Current character is not part of the sequence.338339// Try default character for this sequence340resCode = seqObj[DEF_CHAR];341if (resCode !== undefined) {342dbcsCode = resCode; // Found. Write it.343nextChar = uCode; // Current character will be written too in the next iteration.344345} else {346// TODO: What if we have no default? (resCode == undefined)347// Then, we should write first char of the sequence as-is and try the rest recursively.348// Didn't do it for now because no encoding has this situation yet.349// Currently, just skip the sequence and write current char.350}351}352seqObj = undefined;353}354else if (uCode >= 0) { // Regular character355var subtable = this.encodeTable[uCode >> 8];356if (subtable !== undefined)357dbcsCode = subtable[uCode & 0xFF];358359if (dbcsCode <= SEQ_START) { // Sequence start360seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];361continue;362}363364if (dbcsCode == UNASSIGNED && this.gb18030) {365// Use GB18030 algorithm to find character(s) to write.366var idx = findIdx(this.gb18030.uChars, uCode);367if (idx != -1) {368var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);369newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;370newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;371newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;372newBuf[j++] = 0x30 + dbcsCode;373continue;374}375}376}377378// 3. Write dbcsCode character.379if (dbcsCode === UNASSIGNED)380dbcsCode = this.defaultCharSingleByte;381382if (dbcsCode < 0x100) {383newBuf[j++] = dbcsCode;384}385else if (dbcsCode < 0x10000) {386newBuf[j++] = dbcsCode >> 8; // high byte387newBuf[j++] = dbcsCode & 0xFF; // low byte388}389else {390newBuf[j++] = dbcsCode >> 16;391newBuf[j++] = (dbcsCode >> 8) & 0xFF;392newBuf[j++] = dbcsCode & 0xFF;393}394}395396this.seqObj = seqObj;397this.leadSurrogate = leadSurrogate;398return newBuf.slice(0, j);399}400401DBCSEncoder.prototype.end = function() {402if (this.leadSurrogate === -1 && this.seqObj === undefined)403return; // All clean. Most often case.404405var newBuf = new Buffer(10), j = 0;406407if (this.seqObj) { // We're in the sequence.408var dbcsCode = this.seqObj[DEF_CHAR];409if (dbcsCode !== undefined) { // Write beginning of the sequence.410if (dbcsCode < 0x100) {411newBuf[j++] = dbcsCode;412}413else {414newBuf[j++] = dbcsCode >> 8; // high byte415newBuf[j++] = dbcsCode & 0xFF; // low byte416}417} else {418// See todo above.419}420this.seqObj = undefined;421}422423if (this.leadSurrogate !== -1) {424// Incomplete surrogate pair - only lead surrogate found.425newBuf[j++] = this.defaultCharSingleByte;426this.leadSurrogate = -1;427}428429return newBuf.slice(0, j);430}431432// Export for testing433DBCSEncoder.prototype.findIdx = findIdx;434435436// == Decoder ==================================================================437438function DBCSDecoder(options, codec) {439// Decoder state440this.nodeIdx = 0;441this.prevBuf = new Buffer(0);442443// Static data444this.decodeTables = codec.decodeTables;445this.decodeTableSeq = codec.decodeTableSeq;446this.defaultCharUnicode = codec.defaultCharUnicode;447this.gb18030 = codec.gb18030;448}449450DBCSDecoder.prototype.write = function(buf) {451var newBuf = new Buffer(buf.length*2),452nodeIdx = this.nodeIdx,453prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length,454seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence.455uCode;456457if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later.458prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]);459460for (var i = 0, j = 0; i < buf.length; i++) {461var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset];462463// Lookup in current trie node.464var uCode = this.decodeTables[nodeIdx][curByte];465466if (uCode >= 0) {467// Normal character, just use it.468}469else if (uCode === UNASSIGNED) { // Unknown char.470// TODO: Callback with seq.471//var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);472i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle).473uCode = this.defaultCharUnicode.charCodeAt(0);474}475else if (uCode === GB18030_CODE) {476var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);477var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30);478var idx = findIdx(this.gb18030.gbChars, ptr);479uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];480}481else if (uCode <= NODE_START) { // Go to next trie node.482nodeIdx = NODE_START - uCode;483continue;484}485else if (uCode <= SEQ_START) { // Output a sequence of chars.486var seq = this.decodeTableSeq[SEQ_START - uCode];487for (var k = 0; k < seq.length - 1; k++) {488uCode = seq[k];489newBuf[j++] = uCode & 0xFF;490newBuf[j++] = uCode >> 8;491}492uCode = seq[seq.length-1];493}494else495throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);496497// Write the character to buffer, handling higher planes using surrogate pair.498if (uCode > 0xFFFF) {499uCode -= 0x10000;500var uCodeLead = 0xD800 + Math.floor(uCode / 0x400);501newBuf[j++] = uCodeLead & 0xFF;502newBuf[j++] = uCodeLead >> 8;503504uCode = 0xDC00 + uCode % 0x400;505}506newBuf[j++] = uCode & 0xFF;507newBuf[j++] = uCode >> 8;508509// Reset trie node.510nodeIdx = 0; seqStart = i+1;511}512513this.nodeIdx = nodeIdx;514this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);515return newBuf.slice(0, j).toString('ucs2');516}517518DBCSDecoder.prototype.end = function() {519var ret = '';520521// Try to parse all remaining chars.522while (this.prevBuf.length > 0) {523// Skip 1 character in the buffer.524ret += this.defaultCharUnicode;525var buf = this.prevBuf.slice(1);526527// Parse remaining as usual.528this.prevBuf = new Buffer(0);529this.nodeIdx = 0;530if (buf.length > 0)531ret += this.write(buf);532}533534this.nodeIdx = 0;535return ret;536}537538// Binary search for GB18030. Returns largest i such that table[i] <= val.539function findIdx(table, val) {540if (table[0] > val)541return -1;542543var l = 0, r = table.length;544while (l < r-1) { // always table[l] <= val < table[r]545var mid = l + Math.floor((r-l+1)/2);546if (table[mid] <= val)547l = mid;548else549r = mid;550}551return l;552}553554555556