Skip to content

Instantly share code, notes, and snippets.

@gfx
Created May 1, 2019 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfx/dc0f37b4a42f000ab8c5f47468e29f9d to your computer and use it in GitHub Desktop.
Save gfx/dc0f37b4a42f000ab8c5f47468e29f9d to your computer and use it in GitHub Desktop.
// Experimental `push(...bytes)`-able buffer
// Unfortunately, it is always slower than Array<number>.
export class MutableBuffer {
private length = 0;
private buffer = new Uint8Array(32);
push(...bytes: ReadonlyArray<number>): void {
const newLength = this.length + bytes.length;
if (this.buffer.length < newLength) {
this.grow(newLength);
}
this.buffer.set(bytes, this.length);
this.length = newLength;
}
grow(newLength: number) {
const newBuffer = new Uint8Array(newLength * 2);
newBuffer.set(this.buffer);
this.buffer = newBuffer;
}
toUint8Array(): Uint8Array {
return this.buffer.slice(0, this.length);
}
toArray(): Array<number> {
return Array.from(this.toUint8Array());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment