-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
87 lines (66 loc) · 2.07 KB
/
index.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
function BinaryFormat(fields) {
var offsetTable = {};
var maskTable = {};
this.start = 0;
this.end = fields.length - 1;
function calculateOffset(index) {
var tail = fields.slice(index + 1, fields.length);
return tail.reduce(function(acc, field) {
return acc += field.length;
}, 0);
}
this.fields = fields.map(function(field, index) {
if(field.length > 32) {
throw new Error('Javascript only supports bitwise operations for ' +
'32 bit integers! ' + field.name + ':' + field.length);
}
// turns int:n into 2^n-1 where n > 0
maskTable[field.name] = (2 << (field.length - 1)) - 1;
offsetTable[field.name] = calculateOffset(index);
return field;
});
this.offsetTable = offsetTable;
this.maskTable = maskTable;
}
BinaryFormat.prototype.pack = function() {
var packed, field, i;
for(i = this.start; i <= this.end; i++) {
field = this.fields[i];
// make space for the next value
packed <<= field.length;
// store the value
packed |= arguments[i];
}
return packed;
};
BinaryFormat.prototype.unpack = function(packed) {
var field, unpacked, index;
unpacked = {};
for(index = this.end; index >= this.start; index--) {
field = this.fields[index];
// use the mask to separate the relevant bits
unpacked[field.name] = packed & this.maskTable[field.name];
// shift on for the next field
packed >>= field.length;
}
return unpacked;
};
BinaryFormat.prototype.unpackArray = function(packed) {
var field, unpacked, index;
index = this.end + 1;
unpacked = new Array(index);
while (index--) {
field = this.fields[index];
// use the mask to separate the relevant bits
unpacked[index] = packed & this.maskTable[field.name];
// shift on for the next field
packed >>= field.length;
}
return unpacked;
};
BinaryFormat.prototype.unpackField = function(packed, targetfieldName) {
return (packed >> this.offsetTable[targetfieldName]) & this.maskTable[targetfieldName];
};
if(typeof module !== 'undefined' && module.exports) {
module.exports = BinaryFormat;
}