Created
May 1, 2019 12:51
-
-
Save gfx/dc0f37b4a42f000ab8c5f47468e29f9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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