2 // Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
3 // correspond to encoded bytes (if 128 - then lower half is ASCII).
5 exports._sbcs = function(options) {
7 throw new Error("SBCS codec is called without the data.")
9 // Prepare char buffer for decoding.
10 if (!options.chars || (options.chars.length !== 128 && options.chars.length !== 256))
11 throw new Error("Encoding '"+options.type+"' has incorrect 'chars' (must be of len 128 or 256)");
13 if (options.chars.length === 128) {
15 for (var i = 0; i < 128; i++)
16 asciiString += String.fromCharCode(i);
17 options.chars = asciiString + options.chars;
20 var decodeBuf = new Buffer(options.chars, 'ucs2');
23 var encodeBuf = new Buffer(65536);
24 encodeBuf.fill(options.iconv.defaultCharSingleByte.charCodeAt(0));
26 for (var i = 0; i < options.chars.length; i++)
27 encodeBuf[options.chars.charCodeAt(i)] = i;
38 function encoderSBCS(options) {
40 write: encoderSBCSWrite,
43 encodeBuf: this.encodeBuf,
47 function encoderSBCSWrite(str) {
48 var buf = new Buffer(str.length);
49 for (var i = 0; i < str.length; i++)
50 buf[i] = this.encodeBuf[str.charCodeAt(i)];
56 function decoderSBCS(options) {
58 write: decoderSBCSWrite,
61 decodeBuf: this.decodeBuf,
65 function decoderSBCSWrite(buf) {
66 // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
67 var decodeBuf = this.decodeBuf;
68 var newBuf = new Buffer(buf.length*2);
69 var idx1 = 0, idx2 = 0;
70 for (var i = 0, _len = buf.length; i < _len; i++) {
71 idx1 = buf[i]*2; idx2 = i*2;
72 newBuf[idx2] = decodeBuf[idx1];
73 newBuf[idx2+1] = decodeBuf[idx1+1];
75 return newBuf.toString('ucs2');