-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (44 loc) · 1.1 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
"use strict";
const types = require("./lib/types.js");
class Construction {
constructor() {
if(typeof arguments[0] == "string") {
this.endianness = arguments[0];
this.struct = arguments[1];
} else {
this.endianness = "BE";
this.struct = arguments[1];
}
if(["BE", "LE"].indexOf(this.endianness) < 0) {
throw new Error("Endianness must be LE or BE");
}
if(typeof this.struct !== "object") {
throw new Error("Structure definition must be an object");
}
this.size = 0;
for(let key in this.struct) {
this.size += this.struct[key].size;
}
}
write(obj) {
let offset = 0;
let buf = Buffer.allocUnsafe(this.size);
for(let key in this.struct) {
const type = this.struct[key];
type["write" + this.endianness].call(buf, obj[key], offset);
offset += type.size;
}
return buf;
}
read(buf, obj = {}) {
let offset = 0;
for(let key in this.struct) {
const type = this.struct[key];
obj[key] = type["read" + this.endianness].call(buf, offset);
offset += type.size;
}
return obj;
}
};
Construction.types = types;
module.exports = Construction;