Last active
October 24, 2023 16:58
-
-
Save nhrones/a872b581a4685c2b6374b080d318123d to your computer and use it in GitHub Desktop.
Expandable Codec Buffer
This file contains hidden or 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
/** A resizable buffer */ | |
export let accumulator = new Uint8Array( 1 << 14 ) // 16384 | |
/** CodecBuffer class */ | |
export class CodecBuffer { | |
/** The next available byte (tail-pointer) */ | |
nextByte = 0 | |
/** extract the encoded bytes | |
* @returns - a trimmed encoded buffer | |
*/ | |
extractEncoded() { | |
return accumulator.slice(0, this.nextByte) | |
} | |
/** check fit - expand accumulator as required */ | |
requires(bytesRequired: number) { | |
if (accumulator.length < this.nextByte + bytesRequired) { | |
let newAmt = accumulator.length | |
while (newAmt < this.nextByte + bytesRequired) newAmt *= 2 | |
const newStorage = new Uint8Array(newAmt) | |
newStorage.set(accumulator, 0) | |
accumulator = newStorage | |
console.log('Increased accumulator capacity to - ', accumulator.byteLength) | |
} | |
} | |
/** add a byte to the accumulator */ | |
appendByte(val: number) { | |
this.requires(1) | |
accumulator[this.nextByte++] = val | |
} | |
/** add a buffer to the accumulator */ | |
appendBuffer(buf: Uint8Array) { | |
const len = buf.byteLength | |
this.requires(len) | |
accumulator.set(buf, this.nextByte) | |
this.nextByte += len | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The complete multi-part key encoder