-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct.js
More file actions
53 lines (53 loc) · 1.54 KB
/
struct.js
File metadata and controls
53 lines (53 loc) · 1.54 KB
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
'use strict';
function struct(...components) {
const result = { index: {}, size: 0 };
for (const component of components) {
const [type, name, arraySize] = component;
if (arraySize) {
const arr = [];
for (let i = 0; i < arraySize; i++) arr.push([type, i]);
const array = struct(...arr);
result.index[name] = Object.assign({}, array, { offset: result.size });
result.size += array.size;
} else {
result.index[name] = Object.assign({}, type, { offset: result.size });
result.size += type.size;
}
}
return result;
}
class Struct {
constructor(struct) {
this.index = struct.index;
this.size = struct.size;
this.buffer = Buffer.alloc(struct.size);
}
get data() {
return this._objectify();
}
set data(value) {
return Object.assign(this.data, value);
}
_objectify(index = this.index, offset = 0) {
const that = this;
const result = {};
for (const element in index) {
const cell = index[element];
if (cell.index) {
Object.defineProperty(result, element, {
enumerable: true,
get: () => that._objectify(cell.index, cell.offset + offset),
set: obj => Object.assign(result[element], obj)
});
} else {
Object.defineProperty(result, element, {
enumerable: true,
get: () => cell.read(that.buffer, cell.offset + offset),
set: value => cell.write(that.buffer, cell.offset + offset, value)
});
}
}
return result;
}
}
module.exports = { struct, Struct };