-
Notifications
You must be signed in to change notification settings - Fork 0
/
byteBuffer.js
88 lines (70 loc) · 1.78 KB
/
byteBuffer.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
class ByteBuffer {
constructor(maximumSize) {
this.index = 0;
this.array = new Uint8Array(Math.max(maximumSize, 1));
}
initializeWithArray(bytes) {
this.index = 0;
this.array = bytes;
}
putBytes(bytes) {
for (let i = 0; i < bytes.length; i++) {
this.array[this.index++] = bytes[i];
}
}
putByte(byte) {
this.array[this.index++] = byte;
}
putIntegerValue(value, length) {
value = Math.floor(value);
for (let i = 0; i < length; i++) {
this.array[this.index + length - 1 - i] = value % 256;
value = Math.floor(value / 256);
}
this.index += length;
}
putShort(value) {
this.putIntegerValue(value, 2);
}
putInt(value) {
this.putIntegerValue(value, 4);
}
putLong(value) {
this.putIntegerValue(value, 8);
}
toArray() {
let result = new Uint8Array(this.index);
for (let i = 0; i < this.index; i++) {
result[i] = this.array[i];
}
return result;
}
readBytes(length) {
const result = new Uint8Array(length);
for (let i = 0; i < length; i++) {
result[i] = this.array[this.index++];
}
return result;
}
readByte() {
return this.array[this.index++];
}
readIntegerValue(length) {
let result = 0;
for (let i = 0; i < length; i++) {
result *= 256;
result += this.array[this.index + i];
}
this.index += length;
return result;
}
readShort() {
return this.readIntegerValue(2);
}
readInt() {
return this.readIntegerValue(4);
}
readLong() {
return this.readIntegerValue(8);
}
}