-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathStruct.js
113 lines (93 loc) · 2.33 KB
/
Struct.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
113
import {Base} from './Base.js';
import * as utils from './utils.js';
export class Struct extends Base {
constructor(fields = {}) {
super();
this.fields = fields;
}
decode(stream, parent, length = 0) {
const res = this._setup(stream, parent, length);
this._parseFields(stream, res, this.fields);
if (this.process != null) {
this.process.call(res, stream);
}
return res;
}
_setup(stream, parent, length) {
const res = {};
// define hidden properties
Object.defineProperties(res, {
parent: { value: parent },
_startOffset: { value: stream.pos },
_currentOffset: { value: 0, writable: true },
_length: { value: length }
});
return res;
}
_parseFields(stream, res, fields) {
for (let key in fields) {
var val;
const type = fields[key];
if (typeof type === 'function') {
val = type.call(res, res);
} else {
val = type.decode(stream, res);
}
if (val !== undefined) {
if (val instanceof utils.PropertyDescriptor) {
Object.defineProperty(res, key, val);
} else {
res[key] = val;
}
}
res._currentOffset = stream.pos - res._startOffset;
}
}
size(val, parent, includePointers = true) {
if (val == null) { val = {}; }
const ctx = {
parent,
val,
pointerSize: 0
};
if (this.preEncode != null) {
this.preEncode.call(val);
}
let size = 0;
for (let key in this.fields) {
const type = this.fields[key];
if (type.size != null) {
size += type.size(val[key], ctx);
}
}
if (includePointers) {
size += ctx.pointerSize;
}
return size;
}
encode(stream, val, parent) {
let type;
if (this.preEncode != null) {
this.preEncode.call(val, stream);
}
const ctx = {
pointers: [],
startOffset: stream.pos,
parent,
val,
pointerSize: 0
};
ctx.pointerOffset = stream.pos + this.size(val, ctx, false);
for (let key in this.fields) {
type = this.fields[key];
if (type.encode != null) {
type.encode(stream, val[key], ctx);
}
}
let i = 0;
while (i < ctx.pointers.length) {
const ptr = ctx.pointers[i++];
ptr.type.encode(stream, ptr.val, ptr.parent);
}
}
}