Skip to content

Instantly share code, notes, and snippets.

@uandysmith
Created April 14, 2023 08:45
Show Gist options
  • Save uandysmith/689796ce3e4365d512ced49f008c2a19 to your computer and use it in GitHub Desktop.
Save uandysmith/689796ce3e4365d512ced49f008c2a19 to your computer and use it in GitHub Desktop.
function oldSizeOfByteProperty(prop: {key: Uint8Array, value: Uint8Array}) {
return prop.value.length;
}
function newSizeOfByteProperty(prop: {key: Uint8Array, value: Uint8Array}) {
return sizeOfEncodedBytes(prop.key) + sizeOfEncodedBytes(prop.value);
}
function newSizeOfProperty(prop: {key: string, value: string}) {
return sizeOfEncodedStr(prop.key) + sizeOfEncodedStr(prop.value);
}
/*
Helper functions
*/
function sizeOfInt(i: number) {
if (i < 0 || i > 0xffffffff) throw new Error('out of range');
if(i < 0b11_1111) {
return 1;
} else if (i < 0b11_1111_1111_1111) {
return 2;
} else if (i < 0b11_1111_1111_1111_1111_1111_1111_1111) {
return 4;
} else {
return 5;
}
}
const UTF8_ENCODER = new TextEncoder();
function sizeOfEncodedStr(v: string) {
const encoded = UTF8_ENCODER.encode(v);
return sizeOfInt(encoded.length) + encoded.length;
}
function sizeOfEncodedBytes(bytes: Uint8Array) {
return sizeOfInt(bytes.length) + bytes.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment