Repository navigation
Expand file tree
/
Copy pathstack.ts
More file actions
107 lines (86 loc) · 2.48 KB
/
Copy pathstack.ts
File metadata and controls
107 lines (86 loc) · 2.48 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
107
class StackEntry<T extends ArrayBufferView> {
constructor(
readonly block: T,
readonly offset: number, // in bytes
readonly size: number // in butes
) {}
}
type TypedArrayConstructor =
| Int8ArrayConstructor
| Uint8ArrayConstructor
| Int16ArrayConstructor
| Uint16ArrayConstructor
| Int32ArrayConstructor
| Uint32ArrayConstructor
| Float32ArrayConstructor
| Float64ArrayConstructor;
export class Stack {
readonly size: number = 0;
private readonly stack: StackEntry<ArrayBufferView>[] = [];
private readonly end: number = 0;
private offset = 0;
constructor(readonly buffer: Uint8Array) {
this.size = buffer.length;
this.offset = buffer.byteOffset;
this.end = buffer.byteOffset + buffer.length;
}
pushInt8(length: number): Int8Array {
return this.pushTypedArray(Int8Array, length);
}
pushUint8(length: number): Uint8Array {
return this.pushTypedArray(Uint8Array, length);
}
pushInt16(length: number): Int16Array {
return this.pushTypedArray(Int16Array, length);
}
pushUint16(length: number): Uint16Array {
return this.pushTypedArray(Uint16Array, length);
}
pushInt32(length: number): Int32Array {
return this.pushTypedArray(Int32Array, length);
}
pushUint32(length: number): Uint32Array {
return this.pushTypedArray(Uint32Array, length);
}
pushFloat32(length: number): Float32Array {
return this.pushTypedArray(Float32Array, length);
}
pushFloat64(length: number): Float64Array {
return this.pushTypedArray(Float64Array, length);
}
pop(count = 1): void {
while (count > 0 && this.stack.length > 0) {
const entry = this.stack.pop();
this.offset -= entry.size;
count--;
}
}
clear(): void {
this.stack.length = 0;
this.offset = this.buffer.byteOffset;
this.buffer.fill(0);
}
dump(): StackEntry<ArrayBufferView>[] {
return this.stack;
}
private pushTypedArray<T extends ArrayBufferView>(
type: TypedArrayConstructor,
length: number
): T {
const bytes = length * type.BYTES_PER_ELEMENT;
if (bytes + this.offset > this.end) {
const free = this.end - this.offset;
throw new Error(
`Stack.push: Not enough memory to allocate, requested: ${bytes}, free: ${free} bytes`
);
}
const entry = new StackEntry(
new type(this.buffer.buffer, this.offset, length),
this.offset,
bytes
);
this.offset += bytes;
this.stack.push(entry);
return entry.block as unknown as T;
}
}