UNPKG

2.19 kBJavaScriptView Raw
1"use strict";
2var Buffer = require("safer-buffer").Buffer;
3
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).
6
7exports._sbcs = SBCSCodec;
8function SBCSCodec(codecOptions, iconv) {
9 if (!codecOptions)
10 throw new Error("SBCS codec is called without the data.")
11
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)");
15
16 if (codecOptions.chars.length === 128) {
17 var asciiString = "";
18 for (var i = 0; i < 128; i++)
19 asciiString += String.fromCharCode(i);
20 codecOptions.chars = asciiString + codecOptions.chars;
21 }
22
23 this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
24
25 // Encoding buffer.
26 var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
27
28 for (var i = 0; i < codecOptions.chars.length; i++)
29 encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
30
31 this.encodeBuf = encodeBuf;
32}
33
34SBCSCodec.prototype.encoder = SBCSEncoder;
35SBCSCodec.prototype.decoder = SBCSDecoder;
36
37
38function SBCSEncoder(options, codec) {
39 this.encodeBuf = codec.encodeBuf;
40}
41
42SBCSEncoder.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)];
46
47 return buf;
48}
49
50SBCSEncoder.prototype.end = function() {
51}
52
53
54function SBCSDecoder(options, codec) {
55 this.decodeBuf = codec.decodeBuf;
56}
57
58SBCSDecoder.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];
67 }
68 return newBuf.toString('ucs2');
69}
70
71SBCSDecoder.prototype.end = function() {
72}