2 var Buffer = require("safer-buffer").Buffer;
4 // Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
5 // correspond to encoded bytes (if 128 - then lower half is ASCII).
7 exports._sbcs = SBCSCodec;
8 function SBCSCodec(codecOptions, iconv) {
10 throw new Error("SBCS codec is called without the data.")
12 // Prepare char buffer for decoding.
13 if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
14 throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
16 if (codecOptions.chars.length === 128) {
18 for (var i = 0; i < 128; i++)
19 asciiString += String.fromCharCode(i);
20 codecOptions.chars = asciiString + codecOptions.chars;
23 this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
26 var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
28 for (var i = 0; i < codecOptions.chars.length; i++)
29 encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
31 this.encodeBuf = encodeBuf;
34 SBCSCodec.prototype.encoder = SBCSEncoder;
35 SBCSCodec.prototype.decoder = SBCSDecoder;
38 function SBCSEncoder(options, codec) {
39 this.encodeBuf = codec.encodeBuf;
42 SBCSEncoder.prototype.write = function(str) {
43 var buf = Buffer.alloc(str.length);
44 for (var i = 0; i < str.length; i++)
45 buf[i] = this.encodeBuf[str.charCodeAt(i)];
50 SBCSEncoder.prototype.end = function() {
54 function SBCSDecoder(options, codec) {
55 this.decodeBuf = codec.decodeBuf;
58 SBCSDecoder.prototype.write = function(buf) {
59 // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
60 var decodeBuf = this.decodeBuf;
61 var newBuf = Buffer.alloc(buf.length*2);
62 var idx1 = 0, idx2 = 0;
63 for (var i = 0; i < buf.length; i++) {
64 idx1 = buf[i]*2; idx2 = i*2;
65 newBuf[idx2] = decodeBuf[idx1];
66 newBuf[idx2+1] = decodeBuf[idx1+1];
68 return newBuf.toString('ucs2');
71 SBCSDecoder.prototype.end = function() {