-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTnglWriter.js
More file actions
106 lines (90 loc) · 2.32 KB
/
TnglWriter.js
File metadata and controls
106 lines (90 loc) · 2.32 KB
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
export class TnglWriter {
constructor(buffer_size = 65535) {
this._buffer = new ArrayBuffer(buffer_size);
this._dataView = new DataView(this._buffer);
// this._dataView = dataView;
this._index = 0;
}
writeValue(value, byteCount) {
if (this._index + byteCount <= this._dataView.byteLength) {
for (let i = 0; i < byteCount; i++) {
this._dataView.setUint8(this._index++, value & 0xff);
value = Math.floor(value / Math.pow(2, 8));
}
} else {
console.warn("End of the data");
throw "Tried to write out of range";
}
}
writeBytes(bytes, size) {
if (size === null) {
size = bytes.byteLength;
}
if (this._index + size <= this._dataView.byteLength) {
for (let i = 0; i < size; i++) {
if (i < bytes.byteLength) {
this._dataView.setUint8(this._index++, bytes[i]);
} else {
this._dataView.setUint8(this._index++, 0);
}
}
} else {
console.warn("End of the data");
throw "Tried to write out of range";
}
}
writeString(string, length) {
if (length === null) {
length = string.length;
}
if (this._index + length <= this._dataView.byteLength) {
for (let i = 0; i < length; i++) {
this._dataView.setUint8(this._index++, string.charCodeAt(i));
}
} else {
console.warn("End of the data");
throw "Tried to write out of range";
}
}
writeFlag(value) {
return this.writeValue(value, 1);
}
writeUint8(value) {
return this.writeValue(value, 1);
}
writeInt16(value) {
return this.writeValue(value, 2);
}
writeUint16(value) {
return this.writeValue(value, 2);
}
writeInt32(value) {
return this.writeValue(value, 4);
}
writeUint32(value) {
return this.writeValue(value, 4);
}
get available() {
return this._dataView.byteLength - this._index;
}
foward(byteCount) {
if (this._index + byteCount <= this._dataView.byteLength) {
this._index += byteCount;
} else {
this._index = this._dataView.byteLength;
}
}
back(byteCount) {
if (this._index >= byteCount) {
this._index -= byteCount;
} else {
this._index = 0;
}
}
get bytes() {
return new DataView(this._buffer.slice(0, this._index));
}
get written() {
return this._index;
}
}