Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81169 views
1
"use strict"
2
3
// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
4
// correspond to encoded bytes (if 128 - then lower half is ASCII).
5
6
exports._sbcs = SBCSCodec;
7
function SBCSCodec(codecOptions, iconv) {
8
if (!codecOptions)
9
throw new Error("SBCS codec is called without the data.")
10
11
// Prepare char buffer for decoding.
12
if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
13
throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
14
15
if (codecOptions.chars.length === 128) {
16
var asciiString = "";
17
for (var i = 0; i < 128; i++)
18
asciiString += String.fromCharCode(i);
19
codecOptions.chars = asciiString + codecOptions.chars;
20
}
21
22
this.decodeBuf = new Buffer(codecOptions.chars, 'ucs2');
23
24
// Encoding buffer.
25
var encodeBuf = new Buffer(65536);
26
encodeBuf.fill(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
34
SBCSCodec.prototype.encoder = SBCSEncoder;
35
SBCSCodec.prototype.decoder = SBCSDecoder;
36
37
38
function SBCSEncoder(options, codec) {
39
this.encodeBuf = codec.encodeBuf;
40
}
41
42
SBCSEncoder.prototype.write = function(str) {
43
var buf = new Buffer(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
50
SBCSEncoder.prototype.end = function() {
51
}
52
53
54
function SBCSDecoder(options, codec) {
55
this.decodeBuf = codec.decodeBuf;
56
}
57
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 = new Buffer(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
71
SBCSDecoder.prototype.end = function() {
72
}
73
74