-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathWritableBuffer.ts
More file actions
35 lines (28 loc) · 883 Bytes
/
WritableBuffer.ts
File metadata and controls
35 lines (28 loc) · 883 Bytes
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
import { Writable } from "../Writable";
// Experimental `push(...bytes)`-able buffer
// Unfortunately, it is always slower than Array<number>.
export class WritableBuffer implements Writable<number> {
private length = 0;
private buffer = new Uint8Array(128);
push(...bytes: ReadonlyArray<number>): void {
const offset = this.length;
const bytesLen = bytes.length;
const newLength = offset + bytesLen;
if (this.buffer.length < newLength) {
this.grow(newLength);
}
const buffer = this.buffer;
for (let i = 0; i < bytesLen; i++) {
buffer[offset + i] = bytes[i];
}
this.length = newLength;
}
grow(newLength: number) {
const newBuffer = new Uint8Array(newLength * 2);
newBuffer.set(this.buffer);
this.buffer = newBuffer;
}
toUint8Array(): Uint8Array {
return this.buffer.subarray(0, this.length);
}
}