codekingpro/portable-devtools
114k
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
13 // Prepare char buffer for decoding.
14 if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) {
15 throw new Error("Encoding '" + codecOptions.type + "' has incorrect 'chars' (must be of len 128 or 256)")
16 }
17
18 if (codecOptions.chars.length === 128) {
19 var asciiString = ""
20 for (var i = 0; i < 128; i++) {
21 asciiString += String.fromCharCode(i)
22 }
23 codecOptions.chars = asciiString + codecOptions.chars
24 }
25
26 this.decodeBuf = Buffer.from(codecOptions.chars, "ucs2")
27
28 // Encoding buffer.
29 var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0))
30
31 for (var i = 0; i < codecOptions.chars.length; i++) {
32 encodeBuf[codecOptions.chars.charCodeAt(i)] = i
33 }
34
35 this.encodeBuf = encodeBuf
36}
37
38SBCSCodec.prototype.encoder = SBCSEncoder
39SBCSCodec.prototype.decoder = SBCSDecoder
40
41function SBCSEncoder (options, codec) {
42 this.encodeBuf = codec.encodeBuf
43}
44
45SBCSEncoder.prototype.write = function (str) {
46 var buf = Buffer.alloc(str.length)
47 for (var i = 0; i < str.length; i++) {
48 buf[i] = this.encodeBuf[str.charCodeAt(i)]
49 }
50
51 return buf
52}
53
54SBCSEncoder.prototype.end = function () {
55}
56
57function SBCSDecoder (options, codec) {
58 this.decodeBuf = codec.decodeBuf
59}
60
61SBCSDecoder.prototype.write = function (buf) {
62 // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
63 var decodeBuf = this.decodeBuf
64 var newBuf = Buffer.alloc(buf.length * 2)
65 var idx1 = 0; var idx2 = 0
66 for (var i = 0; i < buf.length; i++) {
67 idx1 = buf[i] * 2; idx2 = i * 2
68 newBuf[idx2] = decodeBuf[idx1]
69 newBuf[idx2 + 1] = decodeBuf[idx1 + 1]
70 }
71 return newBuf.toString("ucs2")
72}
73
74SBCSDecoder.prototype.end = function () {
75}
76 