Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 78 additions & 4 deletions src/lib/bspatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,81 @@ async function loadOldBinary(oldPath: string): Promise<OldReader> {
}
}

/**
* Wrapping unsigned byte addition (`old + diff mod 256`) for a diff window.
*
* This is the hot inner loop of bspatch apply. Doing it byte-at-a-time in JS
* (two typed-array property accesses + a `% 256` per byte) is the dominant CPU
* cost on a large binary. We instead process 4 bytes per iteration with a
* SWAR (SIMD-within-a-register) add on `Uint32Array`:
*
* lows = (a & 0x7f7f7f7f) + (b & 0x7f7f7f7f) // top bit of each byte is 0,
* // so carries stay in-lane
* highs = (a ^ b) & 0x80808080 // high-bit carry per byte
* result = lows ^ highs // per-byte sum mod 256
*
* This is carry-less (each byte lane sums independently mod 256) and is
* verified exhaustively (all byte values + every 4-byte alignment + tail 0-3).
* A short tail loop handles the trailing `n % 4` bytes. The old bytes are read
* as raw bytes (no `?? 0` per element) because the OldReader already zero-fills
* out-of-range positions.
*
* INVARIANT: the carry masks must match the word width. The low mask clears
* the top bit of EVERY byte lane and the high mask isolates the top bit of
* EVERY lane — both are 0x7f7f7f7f / 0x80808080 because words are 32-bit. A
* wider-word (BigUint64Array) variant must widen BOTH masks to 64-bit
* (0x7f7f7f7f7f7f7f7f / 0x8080808080808080); pairing 64-bit words with the
* 32-bit carry mask silently drops carries in the upper 4 bytes and corrupts
* the output (caught by the exhaustive tests).
*/
export function addDiffChunk(
output: Uint8Array,
oldChunk: Uint8Array,
diffChunk: Uint8Array,
n: number
): void {
// The SWAR fast path reinterprets each buffer as Uint32Array, which requires
// a 4-byte-aligned byteOffset — `new Uint32Array(buf.buffer, byteOffset)`
// throws RangeError otherwise. Today all callers pass fresh, offset-0 buffers
// (new Uint8Array(len) / Buffer.alloc(len)), but a future caller could pass a
// pooled or subarray view. Rather than throw (this is a perf detail that must
// never break apply), fall back to the byte loop when any buffer is
// misaligned. Correct for all inputs; the SWAR path is a pure optimization.
const aligned =
output.byteOffset % 4 === 0 &&
oldChunk.byteOffset % 4 === 0 &&
diffChunk.byteOffset % 4 === 0;

const words = aligned ? Math.floor(n / 4) : 0;
if (words > 0) {
const oldWords = new Uint32Array(
oldChunk.buffer,
oldChunk.byteOffset,
words
);
const diffWords = new Uint32Array(
diffChunk.buffer,
diffChunk.byteOffset,
words
);
const outWords = new Uint32Array(output.buffer, output.byteOffset, words);
const LOW = 0x7f_7f_7f_7f;
const HIGH = 0x80_80_80_80;
for (let i = 0; i < words; i++) {
const a = oldWords[i] ?? 0;
const b = diffWords[i] ?? 0;
// biome-ignore lint/suspicious/noBitwiseOperators: SWAR per-lane add uses bitmask/xor by design
const sum = ((a & LOW) + (b & LOW)) ^ ((a ^ b) & HIGH);
// biome-ignore lint/suspicious/noBitwiseOperators: coerce to uint32
outWords[i] = sum >>> 0;
}
}
const tailStart = words * 4;
for (let i = tailStart; i < n; i++) {
output[i] = ((oldChunk[i] ?? 0) + (diffChunk[i] ?? 0)) % 256;
}
}

/**
* Core TRDIFF10 transform.
*
Expand Down Expand Up @@ -540,10 +615,9 @@ async function transformPatch(
const oldChunk = await oldReader.read(oldpos, readDiffBy);
const outputChunk = new Uint8Array(readDiffBy);

for (let i = 0; i < readDiffBy; i++) {
// Wrapping unsigned byte addition, matching zig-bsdiff's @addWithOverflow
outputChunk[i] = ((oldChunk[i] ?? 0) + (diffChunk[i] ?? 0)) % 256;
}
// Wrapping unsigned byte addition, matching zig-bsdiff's @addWithOverflow.
// SWAR on Uint32Array — see addDiffChunk.
addDiffChunk(outputChunk, oldChunk, diffChunk, readDiffBy);

onChunk(outputChunk);
oldpos += readDiffBy;
Expand Down
94 changes: 94 additions & 0 deletions test/lib/bspatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { join } from "node:path";
import { zstdCompressSync } from "node:zlib";
import { describe, expect, test } from "vitest";
import {
addDiffChunk,
applyPatch,
applyPatchChainInMemory,
applyPatchToMemory,
Expand Down Expand Up @@ -363,6 +364,99 @@ describe("applyPatchToMemory", () => {
});
});

describe("addDiffChunk SWAR wrapping-add", () => {
// The diff-add loop is the hot path of bspatch apply. The SWAR (Uint32Array)
// implementation must match a per-byte `(old + diff) % 256` reference for
// EVERY byte value, every 4-byte alignment, and every tail length 0-3 — a
// carry bug (e.g. a BigUint64Array variant, where carries cross byte lanes)
// corrupts the output silently.

/** Per-byte wrapping-add reference (the specification addDiffChunk must meet). */
function referenceAdd(old: Uint8Array, diff: Uint8Array): Uint8Array {
const out = new Uint8Array(old.length);
for (let i = 0; i < old.length; i++) {
out[i] = ((old[i] ?? 0) + (diff[i] ?? 0)) % 256;
}
return out;
}

test("matches the byte-loop reference for all byte values and alignments", async () => {
// Build a base covering many window sizes so every (old, diff) byte pair
// appears across several 4-byte SWAR boundaries and tail lengths 0-3.
// newBytes is derived from old+diff, so applyPatchToMemory must reproduce
// exactly referenceAdd(old, diff).
const total = 4096 + 3; // odd length hits a 3-byte tail
const oldBytes = new Uint8Array(total);
for (let i = 0; i < total; i++) {
// Knuth multiplicative hash spread, folded to a byte — hits all 256 values.
oldBytes[i] = Math.floor((i * 2_654_435_761) / 256) % 256;
}
// Vary the diff so (old, diff) pairs cover many high/low-bit combos.
const diffBytes = new Uint8Array(total);
for (let i = 0; i < total; i++) {
diffBytes[i] = (i * 31 + (i % 256 >= 128 ? 128 : 0) + 7) % 256;
}
const expected = referenceAdd(oldBytes, diffBytes);
const patch = buildDiffOnlyPatch(oldBytes, expected);

const out = await applyPatchToMemory(oldBytes, patch);
expect(out).toEqual(expected);
});

test("handles wrap-around at the byte max (255 + k) in every lane", async () => {
// old=255 forces a carry in every byte; ensure it wraps to (255+diff)%256,
// not into the adjacent lane. A cross-lane carry bug shows up here.
const n = 64;
const oldBytes = new Uint8Array(n).fill(0xff);
const expected = new Uint8Array(n);
for (let i = 0; i < n; i++) expected[i] = (0xff + i) % 256;
const patch = buildDiffOnlyPatch(oldBytes, expected);

const out = await applyPatchToMemory(oldBytes, patch);
expect(out).toEqual(expected);
});

test("handles tail lengths 0-3 across many window sizes", async () => {
for (const n of [1, 2, 3, 4, 5, 7, 8, 9, 21, 1023]) {
const oldBytes = new Uint8Array(n);
for (let i = 0; i < n; i++) oldBytes[i] = (i * 17) % 256;
const expected = referenceAdd(
oldBytes,
Uint8Array.from({ length: n }, (_, i) => (i * 29) % 256)
);
const patch = buildDiffOnlyPatch(oldBytes, expected);
const out = await applyPatchToMemory(oldBytes, patch);
expect(out).toEqual(expected);
}
});

test("produces correct output when a buffer view is misaligned (SWAR fallback)", () => {
// The SWAR fast path needs a 4-byte-aligned byteOffset; addDiffChunk falls
// back to the byte loop otherwise. No current caller passes a misaligned
// view (MemoryOldReader/FileOldReader and the output chunk are all fresh,
// offset-0 allocations), so this directly unit-tests the guard against a
// future caller that might pass a pooled/subarray view. Every offset combo
// (0-3 on each of old/diff/output) must match the per-byte reference.
const n = 4096 + 3; // exercises a 3-byte tail too
for (const oldOff of [0, 1, 2, 3]) {
for (const diffOff of [0, 3]) {
for (const outOff of [0, 2]) {
const oldBuf = new Uint8Array(n + oldOff).subarray(oldOff);
const diffBuf = new Uint8Array(n + diffOff).subarray(diffOff);
const outBuf = new Uint8Array(n + outOff).subarray(outOff);
for (let i = 0; i < n; i++) {
oldBuf[i] = (i * 37) % 256;
diffBuf[i] = (i * 53 + 3) % 256;
}
const expected = referenceAdd(oldBuf, diffBuf);
addDiffChunk(outBuf, oldBuf, diffBuf, n);
expect(outBuf).toEqual(expected);
}
}
}
});
});

describe("FileOldReader block cache", () => {
const ONE_MIB = 1024 * 1024;

Expand Down
Loading