-
Notifications
You must be signed in to change notification settings - Fork 1
/
ByteReader.ts
82 lines (72 loc) · 2.87 KB
/
ByteReader.ts
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
import {ByteOrder} from "./ByteOrder";
/**
* This class was heavily influenced by https://github.com/cschwarz/wkx/blob/master/lib/binaryreader.js
*/
export class ByteReader {
buffer: Buffer;
position: number;
byteOrder: ByteOrder
public readUInt8: Function;
public readUInt16: Function;
public readUInt32: Function;
public readInt8: Function;
public readInt16: Function;
public readInt32: Function;
public readFloat: Function;
public readDouble: Function;
public readByte: Function;
public readInt: Function;
constructor(buffer: Buffer, byteOrder: ByteOrder = ByteOrder.BIG_ENDIAN) {
this.buffer = buffer;
this.position = 0;
this.setByteOrder(byteOrder);
}
private _read(read, size) {
return function () {
let value = read.call(this.buffer, this.position);
this.position += size;
return value;
}.bind(this);
}
readVarInt(): any {
let nextByte,
result = 0,
bytesRead = 0;
do {
nextByte = this.buffer[this.position + bytesRead];
result += (nextByte & 0x7F) << (7 * bytesRead);
bytesRead++;
} while (nextByte >= 0x80);
this.position += bytesRead;
return result;
};
public getByteOrder(): ByteOrder {
return this.byteOrder;
}
public setByteOrder(byteOrder: ByteOrder): void {
this.byteOrder = byteOrder;
if (byteOrder === ByteOrder.BIG_ENDIAN) {
this.readUInt8 = this._read(Buffer.prototype.readUInt8, 1);
this.readUInt16 = this._read(Buffer.prototype.readUInt16BE, 2);
this.readUInt32 = this._read(Buffer.prototype.readUInt32BE, 4);
this.readInt8 = this._read(Buffer.prototype.readInt8, 1);
this.readInt16 = this._read(Buffer.prototype.readInt16BE, 2);
this.readInt32 = this._read(Buffer.prototype.readInt32BE, 4);
this.readFloat = this._read(Buffer.prototype.readFloatBE, 4);
this.readDouble = this._read(Buffer.prototype.readDoubleBE, 8);
this.readByte = this.readUInt8;
this.readInt = this.readUInt32;
} else {
this.readUInt8 = this._read(Buffer.prototype.readUInt8, 1);
this.readUInt16 = this._read(Buffer.prototype.readUInt16LE, 2);
this.readUInt32 = this._read(Buffer.prototype.readUInt32LE, 4);
this.readInt8 = this._read(Buffer.prototype.readInt8, 1);
this.readInt16 = this._read(Buffer.prototype.readInt16LE, 2);
this.readInt32 = this._read(Buffer.prototype.readInt32LE, 4);
this.readFloat = this._read(Buffer.prototype.readFloatLE, 4);
this.readDouble = this._read(Buffer.prototype.readDoubleLE, 8);
this.readByte = this.readUInt8;
this.readInt = this.readUInt32;
}
}
}