From a02b8322f61ccb2c5d3462dba7f36e0235af84f4 Mon Sep 17 00:00:00 2001 From: Bryan Housel Date: Wed, 11 Nov 2026 22:52:51 -0500 Subject: [PATCH 1/2] Add tests for empty lines and LCS with many repeated lines (closes: #50, re: #89) - diffComm: the empty-lines example from #50 - LCS: check against a brute-force LCS on mostly-blank random inputs - LCS: regression test with a timeout for large inputs with many empty lines Co-Authored-By: Claude Opus 5.5 --- test/LCS.test.js | 62 +++++++++++++++++++++++++++++++++++++++++++ test/diffComm.test.js | 45 +++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+) diff --git a/test/LCS.test.js b/test/LCS.test.js index 51747e1..3f13493 100644 --- a/test/LCS.test.js +++ b/test/LCS.test.js @@ -3,6 +3,38 @@ import { strict as assert } from 'bun:assert'; import * as Diff3 from '../src/diff3.mjs'; +// Walks the LCS chain into [buffer1index, buffer2index] pairs, in order, +// checking that each pair matches and that both indexes increase. +function lcsPairs(a, b, result) { + const pairs = []; + for (let c = result; c.chain !== null; c = c.chain) { + pairs.push([c.buffer1index, c.buffer2index]); + } + pairs.reverse(); + + let prev = [-1, -1]; + for (const [i, j] of pairs) { + assert.ok(i > prev[0] && j > prev[1]); + assert.deepEqual(a[i], b[j]); + prev = [i, j]; + } + return pairs; +} + +// Brute-force LCS length by dynamic programming, to check against. +function lcsLength(a, b) { + let prev = new Array(b.length + 1).fill(0); + for (const item of a) { + const row = [0]; + for (let j = 0; j < b.length; j++) { + row.push(item === b[j] ? prev[j] + 1 : Math.max(prev[j + 1], row[j])); + } + prev = row; + } + return prev[b.length]; +} + + describe('LCS', () => { it('returns the LCS of two arrays', () => { @@ -53,4 +85,34 @@ describe('LCS', () => { } }); + it('finds a longest common subsequence when inputs have many repeated lines', () => { + // Small random inputs, mostly empty lines, checked against brute force. + // Seeded so any failure replays. + let seed = 1; + const random = () => (seed = (seed * 1103515245 + 12345) >>> 0) / 2 ** 32; + const values = ['', '', '', 'a', 'b']; + const randomBuffer = () => Array.from( + { length: Math.floor(random() * 20) }, + () => values[Math.floor(random() * values.length)] + ); + + for (let t = 0; t < 1000; t++) { + const a = randomBuffer(); + const b = randomBuffer(); + const pairs = lcsPairs(a, b, Diff3.LCS(a, b)); + assert.deepEqual(pairs.length, lcsLength(a, b)); + } + }); + + it('handles large inputs with many empty lines quickly', () => { + // Regression for #84: half the lines are empty, and 5 lines are changed. + const a = Array.from({ length: 4000 }, (_, i) => (i % 2 ? `line ${i}` : '')); + const b = a.slice(); + for (const i of [100, 1001, 2000, 2999, 3900]) { + b[i] = `changed ${i}`; + } + const pairs = lcsPairs(a, b, Diff3.LCS(a, b)); + assert.deepEqual(pairs.length, a.length - 5); + }, 1000); // took about 6 s before #89, about 50 ms after + }); diff --git a/test/diffComm.test.js b/test/diffComm.test.js index e263f39..251243d 100644 --- a/test/diffComm.test.js +++ b/test/diffComm.test.js @@ -39,4 +39,49 @@ describe('diffComm', () => { assert.deepEqual(result[6].buffer2, undefined); }); + it('handles empty lines', () => { + // From #50 + const a = ['AA', '', 'b', 'c', 'ZZ', '', 'z', '', '', '90', '', 'x']; + const b = ['AA', '', 'd', 'c', 'ZZ', '', '', 'z', '', '99', '', 'x']; + const result = Diff3.diffComm(a, b); + + assert.deepEqual(result[0].common, ['AA', '']); + assert.deepEqual(result[0].buffer1, undefined); + assert.deepEqual(result[0].buffer2, undefined); + + assert.deepEqual(result[1].common, undefined); + assert.deepEqual(result[1].buffer1, ['b']); + assert.deepEqual(result[1].buffer2, ['d']); + + assert.deepEqual(result[2].common, ['c', 'ZZ', '']); + assert.deepEqual(result[2].buffer1, undefined); + assert.deepEqual(result[2].buffer2, undefined); + + assert.deepEqual(result[3].common, undefined); + assert.deepEqual(result[3].buffer1, []); + assert.deepEqual(result[3].buffer2, ['']); + + assert.deepEqual(result[4].common, ['z', '']); + assert.deepEqual(result[4].buffer1, undefined); + assert.deepEqual(result[4].buffer2, undefined); + + assert.deepEqual(result[5].common, undefined); + assert.deepEqual(result[5].buffer1, []); + assert.deepEqual(result[5].buffer2, ['99']); + + assert.deepEqual(result[6].common, ['']); + assert.deepEqual(result[6].buffer1, undefined); + assert.deepEqual(result[6].buffer2, undefined); + + assert.deepEqual(result[7].common, undefined); + assert.deepEqual(result[7].buffer1, ['90', '']); + assert.deepEqual(result[7].buffer2, []); + + assert.deepEqual(result[8].common, ['x']); + assert.deepEqual(result[8].buffer1, undefined); + assert.deepEqual(result[8].buffer2, undefined); + + assert.deepEqual(result.length, 9); + }); + }); \ No newline at end of file From 9058b3fab1e57b4543233c2ff7bd6b54c0c704a8 Mon Sep 17 00:00:00 2001 From: Bryan Housel Date: Thu, 12 Nov 2026 01:20:10 -0500 Subject: [PATCH 2/2] Speed up LCS and merges on large or repetitive inputs (closes: #84, closes: #50) - LCS: trim the common prefix, and skip straight to the matches that can change a candidate (a flag scan for small equivalence classes, a segment tree for large ones), instead of visiting every matching pair - merge, mergeDiff3, mergeDigIn: build the result in place instead of with `concat` in a loop, which was quadratic - diff3Merge: copy with a loop instead of `push(...items)`, which overflowed the call stack on large inputs - diff3MergeRegions: iterate hunks by index instead of `shift()` - Fix the seeded PRNG in the LCS random test (use `Math.imul`) - Add tests for very large merges and many conflicts Output is unchanged. Co-Authored-By: Claude Opus 5.5 --- src/diff3.mjs | 241 ++++++++++++++++++++++++++++------------ test/LCS.test.js | 2 +- test/diff3Merge.test.js | 13 +++ test/merge.test.js | 12 ++ 4 files changed, 199 insertions(+), 69 deletions(-) diff --git a/src/diff3.mjs b/src/diff3.mjs index 1565814..dbc3a0b 100644 --- a/src/diff3.mjs +++ b/src/diff3.mjs @@ -22,64 +22,164 @@ export { // // Expects two arrays, finds longest common sequence function LCS(buffer1, buffer2) { + // A common prefix always ends up in the LCS, matched item for item, + // so chain it up front and only run the algorithm on what follows. + // `candidates[0]` (below) is then the end of the prefix instead of NULLRESULT. + let prefixEnd = { buffer1index: -1, buffer2index: -1, chain: null }; // NULLRESULT + const maxPrefix = Math.min(buffer1.length, buffer2.length); + for (let p = 0; p < maxPrefix && buffer1[p] === buffer2[p]; p++) { + prefixEnd = { buffer1index: p, buffer2index: p, chain: prefixEnd }; + } + const prefixLength = prefixEnd.buffer1index + 1; + + // Most (j)s in a row can't extend any candidate: either `j` is at or before + // `candidates[r].buffer2index`, or some candidate already ends at `j`. + // With many repeated items (blank lines, braces, common words) that's nearly + // all of them, so rather than visit every `j`, we jump to the next one that can. + // + // `taken[j]` is set when a candidate ends at `j`. Small equivalence classes + // just scan it. Each large class also gets a contiguous range of "slots", one + // per `j`, in ascending order; `free` is a segment tree over the slots that + // counts the (j)s no candidate ends at, so the next one is found in O(log n). + // (Most items in real input are unique or nearly so, and keeping the tree + // updated for them would cost more than it saves.) + const SMALL_CLASS = 16; + // Use a prototype-less object so input elements that happen to match // `Object.prototype` members (`constructor`, `__proto__`, `toString`, ...) // don't shadow the lookup with inherited values. let equivalenceClasses = Object.create(null); - for (let j = 0; j < buffer2.length; j++) { + let largeClasses = []; + for (let j = prefixLength; j < buffer2.length; j++) { const item = buffer2[j]; if (equivalenceClasses[item]) { equivalenceClasses[item].push(j); + if (equivalenceClasses[item].length === SMALL_CLASS + 1) { + largeClasses.push(equivalenceClasses[item]); + } } else { equivalenceClasses[item] = [j]; } } - const NULLRESULT = { buffer1index: -1, buffer2index: -1, chain: null }; - let candidates = [NULLRESULT]; + const taken = new Uint8Array(buffer2.length); + const slotOf = new Int32Array(buffer2.length).fill(-1); + const slotStart = new Map(); // large class -> its first slot + let slotCount = 0; + for (const indices of largeClasses) { + slotStart.set(indices, slotCount); + for (let k = 0; k < indices.length; k++) { + slotOf[indices[k]] = slotCount + k; + } + slotCount += indices.length; + } + + let size = 1; + while (size < slotCount) size <<= 1; + const free = new Int32Array(2 * size); + free.fill(1, size, size + slotCount); + for (let k = size - 1; k > 0; k--) { + free[k] = free[2 * k] + free[2 * k + 1]; + } + + // Returns the first free slot at or after `slot`, or -1 if there isn't one + function nextFreeSlot(slot) { + if (slot >= slotCount) return -1; + let k = slot + size; + while (free[k] === 0) { + while (k & 1) k >>= 1; // climb out of right children + if (k === 0) return -1; // climbed past the root + k++; // move to the subtree just to the right + } + while (k < size) { + k = free[2 * k] ? 2 * k : 2 * k + 1; + } + return k - size; + } + + // Marks `buffer2[j]` as taken or free + function setTaken(j, isTaken) { + taken[j] = isTaken ? 1 : 0; + const slot = slotOf[j]; + if (slot < 0) return; + const delta = isTaken ? -1 : 1; + for (let k = slot + size; k > 0; k >>= 1) { + free[k] += delta; + } + } + + // Sets `candidates[r] = c`, keeping `taken` and `free` in step + function setCandidate(r, c) { + const old = candidates[r]; + if (old === c) return; + if (old) setTaken(old.buffer2index, false); + setTaken(c.buffer2index, true); + candidates[r] = c; + } - for (let i = 0; i < buffer1.length; i++) { + let candidates = [prefixEnd]; + + for (let i = prefixLength; i < buffer1.length; i++) { const item = buffer1[i]; - const buffer2indices = equivalenceClasses[item] || []; + const indices = equivalenceClasses[item]; + if (!indices) continue; + + const start = indices.length > SMALL_CLASS ? slotStart.get(indices) : -1; let r = 0; let c = candidates[0]; + let k = 0; // the next of `indices` to consider - for (const j of buffer2indices) { - // Find the candidate `s` (at or after `r`) that `j` extends: the one with - // `candidates[s].buffer2index < j`, where the next one, if any, is past `j`. - // The `buffer2index` values from `r` on are strictly increasing, so the - // boundary is found by binary search instead of a linear scan. - let lo = r; - let hi = candidates.length; + while (true) { + // Skip the (j)s at or before `candidates[r].buffer2index`.. + const after = candidates[r].buffer2index; + let lo = k; + let hi = indices.length; while (lo < hi) { const mid = (lo + hi) >>> 1; - if (candidates[mid].buffer2index < j) { + if (indices[mid] <= after) { lo = mid + 1; } else { hi = mid; } } - let s = candidates.length; - if (lo > r && (lo === candidates.length || candidates[lo].buffer2index > j)) { - s = lo - 1; + // ..and the (j)s that a candidate already ends at. + if (start < 0) { + while (lo < indices.length && taken[indices[lo]]) lo++; + if (lo === indices.length) break; + k = lo; + } else { + const slot = nextFreeSlot(start + lo); + if (slot === -1 || slot >= start + indices.length) break; + k = slot - start; } + const j = indices[k]; - if (s < candidates.length) { - const newCandidate = { buffer1index: i, buffer2index: j, chain: candidates[s] }; - if (r === candidates.length) { - candidates.push(c); + // `j` extends the last candidate `s` that ends before it. The + // `buffer2index` values from `r` on are strictly increasing, so the + // boundary is found by binary search. + lo = r + 1; + hi = candidates.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (candidates[mid].buffer2index < j) { + lo = mid + 1; } else { - candidates[r] = c; - } - r = s + 1; - c = newCandidate; - if (r === candidates.length) { - break; // no point in examining further (j)s + hi = mid; } } + const s = lo - 1; + + const newCandidate = { buffer1index: i, buffer2index: j, chain: candidates[s] }; + setCandidate(r, c); + r = s + 1; + c = newCandidate; + if (r === candidates.length) { + break; // no point in examining further (j)s + } + k++; } - candidates[r] = c; + setCandidate(r, c); } // At this point, we know the LCS: it's in the reverse of the @@ -253,21 +353,23 @@ function diff3MergeRegions(a, o, b) { } } - while (hunks.length) { - let hunk = hunks.shift(); + let hunkIndex = 0; + while (hunkIndex < hunks.length) { + let hunk = hunks[hunkIndex++]; let regionStart = hunk.oStart; let regionEnd = hunk.oStart + hunk.oLength; let regionHunks = [hunk]; advanceTo(regionStart); // Try to pull next overlapping hunk into this region - while (hunks.length) { - const nextHunk = hunks[0]; + while (hunkIndex < hunks.length) { + const nextHunk = hunks[hunkIndex]; const nextHunkStart = nextHunk.oStart; if (nextHunkStart > regionEnd) break; // no overlap regionEnd = Math.max(regionEnd, nextHunkStart + nextHunk.oLength); - regionHunks.push(hunks.shift()); + regionHunks.push(nextHunk); + hunkIndex++; } if (regionHunks.length === 1) { @@ -292,13 +394,12 @@ function diff3MergeRegions(a, o, b) { a: [a.length, -1, o.length, -1], b: [b.length, -1, o.length, -1] }; - while (regionHunks.length) { - hunk = regionHunks.shift(); - const oStart = hunk.oStart; - const oEnd = oStart + hunk.oLength; - const abStart = hunk.abStart; - const abEnd = abStart + hunk.abLength; - let b = bounds[hunk.ab]; + for (const regionHunk of regionHunks) { + const oStart = regionHunk.oStart; + const oEnd = oStart + regionHunk.oLength; + const abStart = regionHunk.abStart; + const abEnd = abStart + regionHunk.abLength; + let b = bounds[regionHunk.ab]; b[0] = Math.min(abStart, b[0]); b[1] = Math.max(abEnd, b[1]); b[2] = Math.min(oStart, b[2]); @@ -333,6 +434,16 @@ function diff3MergeRegions(a, o, b) { } +// Appends `items` to `target`. (`target.push(...items)` overflows the call +// stack for large arrays, and `result = result.concat(items)` in a loop copies +// the whole result every time.) +function pushAll(target, items) { + for (const item of items) { + target.push(item); + } +} + + // Applies the output of diff3MergeRegions to actually // construct the merged buffer; the returned result alternates // between 'ok' and 'conflict' blocks. @@ -369,10 +480,10 @@ function diff3Merge(a, o, b, options) { regions.forEach(region => { if (region.stable) { - okBuffer.push(...region.bufferContent); + pushAll(okBuffer, region.bufferContent); } else { if (options.excludeFalseConflicts && isFalseConflict(region.aContent, region.bContent)) { - okBuffer.push(...region.aContent); + pushAll(okBuffer, region.aContent); } else { flushOk(); results.push({ @@ -413,18 +524,16 @@ function mergeDiff3(a, o, b, options) { regions.forEach(region => { if (region.ok) { - result = result.concat(region.ok); + pushAll(result, region.ok); } else if (region.conflict) { conflict = true; - result = result.concat( - [aSection], - region.conflict.a, - [oSection], - region.conflict.o, - [xSection], - region.conflict.b, - [bSection] - ); + result.push(aSection); + pushAll(result, region.conflict.a); + result.push(oSection); + pushAll(result, region.conflict.o); + result.push(xSection); + pushAll(result, region.conflict.b); + result.push(bSection); } }); @@ -453,16 +562,14 @@ function merge(a, o, b, options) { regions.forEach(region => { if (region.ok) { - result = result.concat(region.ok); + pushAll(result, region.ok); } else if (region.conflict) { conflict = true; - result = result.concat( - [aSection], - region.conflict.a, - [xSection], - region.conflict.b, - [bSection] - ); + result.push(aSection); + pushAll(result, region.conflict.a); + result.push(xSection); + pushAll(result, region.conflict.b); + result.push(bSection); } }); @@ -491,21 +598,19 @@ function mergeDigIn(a, o, b, options) { regions.forEach(region => { if (region.ok) { - result = result.concat(region.ok); + pushAll(result, region.ok); } else { const c = diffComm(region.conflict.a, region.conflict.b); for (const inner of c) { if (inner.common) { - result = result.concat(inner.common); + pushAll(result, inner.common); } else { conflict = true; - result = result.concat( - [aSection], - inner.buffer1, - [xSection], - inner.buffer2, - [bSection] - ); + result.push(aSection); + pushAll(result, inner.buffer1); + result.push(xSection); + pushAll(result, inner.buffer2); + result.push(bSection); } } } diff --git a/test/LCS.test.js b/test/LCS.test.js index 3f13493..5ecc294 100644 --- a/test/LCS.test.js +++ b/test/LCS.test.js @@ -89,7 +89,7 @@ describe('LCS', () => { // Small random inputs, mostly empty lines, checked against brute force. // Seeded so any failure replays. let seed = 1; - const random = () => (seed = (seed * 1103515245 + 12345) >>> 0) / 2 ** 32; + const random = () => (seed = (Math.imul(seed, 1103515245) + 12345) >>> 0) / 2 ** 32; const values = ['', '', '', 'a', 'b']; const randomBuffer = () => Array.from( { length: Math.floor(random() * 20) }, diff --git a/test/diff3Merge.test.js b/test/diff3Merge.test.js index 95cbb8b..a22231c 100644 --- a/test/diff3Merge.test.js +++ b/test/diff3Merge.test.js @@ -153,4 +153,17 @@ description: "description"`; assert.deepEqual(result[0].conflict.a, ['title: "title"', 'description: "description changed"']); assert.deepEqual(result[0].conflict.b, ['title: "title changed"', 'description: "description"']); }); + + + it('handles very large inputs', () => { + // Copying a large region with `push(...items)` used to overflow the call stack + const o = Array.from({ length: 1000000 }, (_, i) => `line ${i}`); + const a = o.slice(); + const b = o.slice(); + b[999000] = 'changed'; + const result = Diff3.diff3Merge(a, o, b); + + assert.deepEqual(result.length, 1); + assert.deepEqual(result[0].ok, b); + }); }); diff --git a/test/merge.test.js b/test/merge.test.js index 60fb2e6..7ae87ff 100644 --- a/test/merge.test.js +++ b/test/merge.test.js @@ -75,4 +75,16 @@ description: "description"`; assert.deepEqual(r.result, expected); }); + it('handles many conflicts quickly', () => { + // 10,000 conflicts: every 10th line is changed differently in `a` and `b` + const o = Array.from({ length: 100000 }, (_, i) => `line ${i}`); + const a = o.map((line, i) => (i % 10 === 0 ? `a ${i}` : line)); + const b = o.map((line, i) => (i % 10 === 0 ? `b ${i}` : line)); + + const r = Diff3.merge(a, o, b); + assert.equal(r.conflict, true); + assert.deepEqual(r.result.length, 100000 + 10000 * 4); // each conflict adds 3 markers and 1 line + assert.deepEqual(r.result.slice(0, 7), ['<<<<<<<', 'a 0', '=======', 'b 0', '>>>>>>>', 'line 1', 'line 2']); + }, 1000); // took about 3 s when the result was built with `concat` + });