-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (89 loc) · 2.92 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const assert = require('assert');
module.exports = Put;
function Put () {
if (!(this instanceof Put)) return new Put;
var words = [];
var len = 0;
this.put = function (buf) {
words.push({ buffer : buf });
len += buf.length;
return this;
};
this.word8 = function (x) {
words.push({ bytes : 1, value : x });
len += 1;
return this;
};
this.floatle = function (x) {
words.push({ bytes : 'float', endian : 'little', value : x });
len += 4;
return this;
};
[ 8, 16, 24, 32, 64 ].forEach((function (bits) {
this['word' + bits + 'be'] = function (x) {
words.push({ endian : 'big', bytes : bits / 8, value : x });
len += bits / 8;
return this;
};
this['word' + bits + 'le'] = function (x) {
words.push({ endian : 'little', bytes : bits / 8, value : x });
len += bits / 8;
return this;
};
}).bind(this));
this.pad = function (bytes) {
assert(Number.isInteger(bytes), "pad(bytes) must be supplied with an integer!");
words.push({ endian : 'big', bytes : bytes, value : 0 });
len += bytes;
return this;
};
this.length = function () {
return len;
};
this.buffer = function () {
var buf = Buffer.alloc(len);
var offset = 0;
words.forEach(function (word) {
if (word.buffer) {
word.buffer.copy(buf, offset, 0);
offset += word.buffer.length;
}
else if (word.bytes === 'float') {
// s * f * 2^e
var v = Math.abs(word.value);
var s = (word.value >= 0) * 1;
var e = Math.ceil(Math.log(v) / Math.LN2);
var f = v / (1 << e);
console.dir([s,e,f]);
console.log(word.value);
// s:1, e:7, f:23
// [seeeeeee][efffffff][ffffffff][ffffffff]
buf[offset++] = (s << 7) & ~~(e / 2);
buf[offset++] = ((e & 1) << 7) & ~~(f / (1 << 16));
buf[offset++] = 0;
buf[offset++] = 0;
offset += 4;
}
else {
var big = word.endian === 'big';
var ix = big ? [ (word.bytes - 1) * 8, -8 ] : [ 0, 8 ];
for (
var i = ix[0];
big ? i >= 0 : i < word.bytes * 8;
i += ix[1]
) {
if (i >= 32) {
buf[offset++] = Math.floor(word.value / Math.pow(2, i)) & 0xff;
}
else {
buf[offset++] = (word.value >> i) & 0xff;
}
}
}
});
return buf;
};
this.write = function (stream) {
stream.write(this.buffer());
};
}