Last active
April 12, 2024 19:39
-
-
Save MarkTiedemann/c51af2c86175336a81dadf4d9973815c to your computer and use it in GitHub Desktop.
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
function DataAppender(array = new Uint8Array(8)) { | |
let length = array.length; | |
let offset = 0; | |
let view = new DataView(array.buffer); | |
const textEncoder = new TextEncoder(); | |
const grow = () => { | |
length = array.length * 2; | |
const newArray = new Uint8Array(length); | |
newArray.set(array); | |
array = newArray; | |
view = new DataView(array.buffer); | |
}; | |
const max8 = 2 ** 8 - 1; | |
const max16 = 2 ** 16 - 1; | |
const max32 = 2 ** 32 - 1; | |
return { | |
array: () => array.subarray(0, offset), | |
u8: (n: number) => { | |
if (n > max8) | |
throw new RangeError(`${n} > ${max8}`); | |
if (offset + 1 > length) | |
grow(); | |
view.setUint8(offset, n); | |
offset += 1; | |
}, | |
u16: (n: number) => { | |
if (n > max16) | |
throw new RangeError(`${n} > ${max16}`); | |
if (offset + 2 > length) | |
grow(); | |
view.setUint16(offset, n); | |
offset += 2; | |
}, | |
u32: (n: number) => { | |
if (n > max16) | |
throw new RangeError(`${n} > ${max32}`); | |
if (offset + 4 > length) | |
grow(); | |
view.setUint32(offset, n); | |
offset += 4; | |
}, | |
u64: (n: number) => { | |
if (offset + 8 > length) | |
grow(); | |
view.setBigUint64(offset, BigInt(n)); | |
offset += 8; | |
}, | |
str: (s: string) => { | |
const bytes = textEncoder.encode(s); | |
while (offset + bytes.length > length) | |
grow(); | |
array.set(bytes, offset); | |
offset += bytes.length; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment