77 lines
2.1 KiB
JavaScript
77 lines
2.1 KiB
JavaScript
|
|
// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
|
|
// correspond to encoded bytes (if 128 - then lower half is ASCII).
|
|
|
|
exports._sbcs = function(options) {
|
|
if (!options)
|
|
throw new Error("SBCS codec is called without the data.")
|
|
|
|
// Prepare char buffer for decoding.
|
|
if (!options.chars || (options.chars.length !== 128 && options.chars.length !== 256))
|
|
throw new Error("Encoding '"+options.type+"' has incorrect 'chars' (must be of len 128 or 256)");
|
|
|
|
if (options.chars.length === 128) {
|
|
var asciiString = "";
|
|
for (var i = 0; i < 128; i++)
|
|
asciiString += String.fromCharCode(i);
|
|
options.chars = asciiString + options.chars;
|
|
}
|
|
|
|
var decodeBuf = new Buffer(options.chars, 'ucs2');
|
|
|
|
// Encoding buffer.
|
|
var encodeBuf = new Buffer(65536);
|
|
encodeBuf.fill(options.iconv.defaultCharSingleByte.charCodeAt(0));
|
|
|
|
for (var i = 0; i < options.chars.length; i++)
|
|
encodeBuf[options.chars.charCodeAt(i)] = i;
|
|
|
|
return {
|
|
encoder: encoderSBCS,
|
|
decoder: decoderSBCS,
|
|
|
|
encodeBuf: encodeBuf,
|
|
decodeBuf: decodeBuf,
|
|
};
|
|
}
|
|
|
|
function encoderSBCS(options) {
|
|
return {
|
|
write: encoderSBCSWrite,
|
|
end: function() {},
|
|
|
|
encodeBuf: this.encodeBuf,
|
|
};
|
|
}
|
|
|
|
function encoderSBCSWrite(str) {
|
|
var buf = new Buffer(str.length);
|
|
for (var i = 0; i < str.length; i++)
|
|
buf[i] = this.encodeBuf[str.charCodeAt(i)];
|
|
|
|
return buf;
|
|
}
|
|
|
|
|
|
function decoderSBCS(options) {
|
|
return {
|
|
write: decoderSBCSWrite,
|
|
end: function() {},
|
|
|
|
decodeBuf: this.decodeBuf,
|
|
};
|
|
}
|
|
|
|
function decoderSBCSWrite(buf) {
|
|
// Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
|
|
var decodeBuf = this.decodeBuf;
|
|
var newBuf = new Buffer(buf.length*2);
|
|
var idx1 = 0, idx2 = 0;
|
|
for (var i = 0, _len = buf.length; i < _len; i++) {
|
|
idx1 = buf[i]*2; idx2 = i*2;
|
|
newBuf[idx2] = decodeBuf[idx1];
|
|
newBuf[idx2+1] = decodeBuf[idx1+1];
|
|
}
|
|
return newBuf.toString('ucs2');
|
|
}
|