-
Notifications
You must be signed in to change notification settings - Fork 2
/
ixputil.js
112 lines (100 loc) · 2.62 KB
/
ixputil.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
(function(exports){
var fuzz = function(n){
var s, i;
s = "";
for(i = 0; i < n; i++)
s += String.fromCharCode(Math.floor(Math.random() * 256));
return s;
};
exports.fuzz = fuzz;
exports.ipack = ipack = function(fmt, data){
var wide = fmt.substring(1);
var packed = "";
switch (fmt.substring(0,1)){
case 'i': return npack(data, wide);
case 'R':
for (var x in data) {
packed += counted(data[x].toString(),2);
}
return packed;
case 'b':
case 's':
packed = data.substring(0, wide);
if (packed.length < wide) { packed = pad(packed, wide, "\0");}
return packed;
case 'S': return counted(data, wide);
default: throw "pack: unknown type is "+fmt+".";
}
};
var npack = function(n, wide){
out = "";
for (var p = 0; p < wide; p++){
out += String.fromCharCode(n & 0xFF);
n >>>= 8;
}
return out;
};
var counted = function(data, wide){
return npack(data.length, wide) + data;
};
var pad = function(s, wide, fill) {
var pwide = wide - s.length;
s += Array(pwide+1).join(fill);
return s;
};
exports.pad = pad;
exports.pack = function(data, specs){
var out = [];
specs.forEach(function(spec) {
var ss = spec.split(":");
out.push(ipack(ss[0], data[ss[1]]));
});
return out.join('');
};
function asInteger(s){
var i = 0;
for (var p = s.length - 1; p >= 0; p--) {
i *= 256;
i += s.charCodeAt(p);
}
return i;
}
var iunpack = function(fmt, data){
var wide = fmt.substring(1);
switch (fmt.substring(0,1)) {
case 'i': return asInteger(data.substring(0, wide));
case 'b':
case 's': return data.substring(0, wide);
case 'S':
//get actual count
var wide2 = asInteger(data.substring(0,wide));
data = data.substring(wide);
return data.substring(0, wide2);
case 'R':
var out = [];
while (data.length > 0) {
var len = asInteger(data.substring(0, 2));
if (len < 1) { throw "invalid size in array: "+len+" <<"+data+">>"; }
out.push(data.substring(2, 2+len));
data = data.substring(2+len);
}
return out;
default: throw "unpack: unknown type is "+fmt;
}
};
exports.unpack = function(data, specList){
var out = {};
specList.forEach(function(spec) {
var ss = spec.split(":");
var slot = ss[1];
var wide = ss[0].substring(1);
var value=iunpack(ss[0], data);
data = data.substring(wide);
if (ss[0].substring(0,1) === "S") {
data = data.substring(value.length);
}
out[slot]=value;
});
return out;
};
})(typeof(exports)==='undefined' ? this.ixputils={} : exports) ;