-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathDecodeStream.js
85 lines (74 loc) · 1.85 KB
/
DecodeStream.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
// Node back-compat.
const ENCODING_MAPPING = {
utf16le: 'utf-16le',
ucs2: 'utf-16le',
utf16be: 'utf-16be'
}
export class DecodeStream {
constructor(buffer) {
this.buffer = buffer;
this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
this.pos = 0;
this.length = this.buffer.length;
}
readString(length, encoding = 'ascii') {
encoding = ENCODING_MAPPING[encoding] || encoding;
let buf = this.readBuffer(length);
try {
let decoder = new TextDecoder(encoding);
return decoder.decode(buf);
} catch (err) {
return buf;
}
}
readBuffer(length) {
return this.buffer.slice(this.pos, (this.pos += length));
}
readUInt24BE() {
return (this.readUInt16BE() << 8) + this.readUInt8();
}
readUInt24LE() {
return this.readUInt16LE() + (this.readUInt8() << 16);
}
readInt24BE() {
return (this.readInt16BE() << 8) + this.readUInt8();
}
readInt24LE() {
return this.readUInt16LE() + (this.readInt8() << 16);
}
}
DecodeStream.TYPES = {
UInt8: 1,
UInt16: 2,
UInt24: 3,
UInt32: 4,
Int8: 1,
Int16: 2,
Int24: 3,
Int32: 4,
Float: 4,
Double: 8
};
for (let key of Object.getOwnPropertyNames(DataView.prototype)) {
if (key.slice(0, 3) === 'get') {
let type = key.slice(3).replace('Ui', 'UI');
if (type === 'Float32') {
type = 'Float';
} else if (type === 'Float64') {
type = 'Double';
}
let bytes = DecodeStream.TYPES[type];
DecodeStream.prototype['read' + type + (bytes === 1 ? '' : 'BE')] = function () {
const ret = this.view[key](this.pos, false);
this.pos += bytes;
return ret;
};
if (bytes !== 1) {
DecodeStream.prototype['read' + type + 'LE'] = function () {
const ret = this.view[key](this.pos, true);
this.pos += bytes;
return ret;
};
}
}
}