Improve the implementation in src/core/writer.js a little bit

- Let the `writeString` helper function return the new offset, to avoid having to recompute that in multiple spots.

 - In the `computeMD5` helper function we can create the `md5Buffer` via Array-destructuring, rather than using a manual loop.
This commit is contained in:
Jonas Jenwald 2025-03-20 12:10:15 +01:00
parent a229914b46
commit 50eb97afb3

View File

@ -168,26 +168,28 @@ function writeInt(number, size, offset, buffer) {
} }
function writeString(string, offset, buffer) { function writeString(string, offset, buffer) {
for (let i = 0, len = string.length; i < len; i++) { const ii = string.length;
for (let i = 0; i < ii; i++) {
buffer[offset + i] = string.charCodeAt(i) & 0xff; buffer[offset + i] = string.charCodeAt(i) & 0xff;
} }
return offset + ii;
} }
function computeMD5(filesize, xrefInfo) { function computeMD5(filesize, xrefInfo) {
const time = Math.floor(Date.now() / 1000); const time = Math.floor(Date.now() / 1000);
const filename = xrefInfo.filename || ""; const filename = xrefInfo.filename || "";
const md5Buffer = [time.toString(), filename, filesize.toString()]; const md5Buffer = [
let md5BufferLen = md5Buffer.reduce((a, str) => a + str.length, 0); time.toString(),
for (const value of Object.values(xrefInfo.info)) { filename,
md5Buffer.push(value); filesize.toString(),
md5BufferLen += value.length; ...Object.values(xrefInfo.info),
} ];
const md5BufferLen = md5Buffer.reduce((a, str) => a + str.length, 0);
const array = new Uint8Array(md5BufferLen); const array = new Uint8Array(md5BufferLen);
let offset = 0; let offset = 0;
for (const str of md5Buffer) { for (const str of md5Buffer) {
writeString(str, offset, array); offset = writeString(str, offset, array);
offset += str.length;
} }
return bytesToString(calculateMD5(array, 0, array.length)); return bytesToString(calculateMD5(array, 0, array.length));
} }
@ -477,8 +479,7 @@ async function incrementalUpdate({
// New data // New data
for (const str of buffer) { for (const str of buffer) {
writeString(str, offset, array); offset = writeString(str, offset, array);
offset += str.length;
} }
return array; return array;