This repository has been archived by the owner on Feb 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
107 lines (83 loc) · 2.35 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
104
105
106
107
const assert = require('assert');
module.exports = class BufferReader {
constructor(buffer) {
assert(Buffer.isBuffer(buffer), 'Invalid buffer.');
this.buffer = buffer;
this.offset = 0;
}
seek(offset, fromBeginning = true) {
if(!fromBeginning) {
offset += this.offset;
}
this._checkOffsetInRange(offset);
this.offset = offset;
}
nextDoubleLE() {
return this._nextXX('DoubleLE', 8);
}
nextDoubleBE() {
return this._nextXX('DoubleBE', 8);
}
nextFloatLE() {
return this._nextXX('FloatLE', 4);
}
nextFloatBE() {
return this._nextXX('FloatBE', 4);
}
nextInt32LE() {
return this._nextXX('Int32LE', 4);
}
nextInt32BE() {
return this._nextXX('Int32BE', 4);
}
nextUInt32LE() {
return this._nextXX('UInt32LE', 4);
}
nextUInt32BE() {
return this._nextXX('UInt32BE', 4);
}
nextUInt16LE() {
return this._nextXX('UInt16LE', 2);
}
nextUInt16BE() {
return this._nextXX('UInt16BE', 2);
}
nextInt16LE() {
return this._nextXX('Int16LE', 2);
}
nextInt16BE() {
return this._nextXX('Int16BE', 2);
}
nextUInt8() {
return this._nextXX('UInt8', 1);
}
nextInt8() {
return this._nextXX('Int8', 1);
}
nextBuffer(length) {
this._checkPositive(length);
this._checkOffsetInRange(this.offset + length);
const buffer = this.buffer.slice(this.offset, this.offset + length);
this.offset += length;
return buffer;
}
nextString(length, encoding = 'utf-8') {
this._checkPositive(length);
this._checkOffsetInRange(this.offset + length);
const str = this.buffer.toString(encoding, this.offset, this.offset + length);
this.offset += length;
return str;
}
_nextXX(type, size) {
this._checkOffsetInRange(this.offset + size, 'Offset');
const v = this.buffer[`read${type}`](this.offset);
this.offset += size;
return v;
}
_checkPositive(number, name = 'Length') {
assert(number >= 0, `${name} must be positive.`);
}
_checkOffsetInRange(offset) {
assert(offset >= 0 && offset <= this.buffer.length, 'Offset out of range.');
}
}