Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

48 lines · 1.8 KBRaw History
1/** Apply a git delta (as found in OFS_DELTA / REF_DELTA pack entries) to a base. */
2export function applyDelta(base: Uint8Array, delta: Uint8Array, maxSize = Infinity): Uint8Array {
3 let i = 0;
4 const varint = (): number => {
5 let result = 0;
6 let shift = 0;
7 let c: number;
8 do {
9 c = delta[i++]!;
10 result += (c & 0x7f) * 2 ** shift;
11 shift += 7;
12 } while (c & 0x80);
13 return result;
14 };
15 const srcSize = varint();
16 if (srcSize !== base.length) throw new Error(`delta base size mismatch: ${srcSize} != ${base.length}`);
17 const dstSize = varint();
18 if (dstSize > maxSize) throw new Error(`delta result of ${dstSize} bytes is larger than the ${maxSize} bytes allowed`);
19 const out = new Uint8Array(dstSize);
20 let o = 0;
21 while (i < delta.length) {
22 const op = delta[i++]!;
23 if (op & 0x80) {
24 let off = 0;
25 let size = 0;
26 if (op & 0x01) off |= delta[i++]!;
27 if (op & 0x02) off |= delta[i++]! << 8;
28 if (op & 0x04) off |= delta[i++]! << 16;
29 if (op & 0x08) off = (off | (delta[i++]! << 24)) >>> 0;
30 if (op & 0x10) size |= delta[i++]!;
31 if (op & 0x20) size |= delta[i++]! << 8;
32 if (op & 0x40) size |= delta[i++]! << 16;
33 if (size === 0) size = 0x10000;
34 if (off + size > base.length || o + size > dstSize) throw new Error("delta copy out of range");
35 out.set(base.subarray(off, off + size), o);
36 o += size;
37 } else if (op > 0) {
38 if (o + op > dstSize || i + op > delta.length) throw new Error("delta insert out of range");
39 out.set(delta.subarray(i, i + op), o);
40 i += op;
41 o += op;
42 } else {
43 throw new Error("invalid delta opcode 0");
44 }
45 }
46 if (o !== dstSize) throw new Error(`delta produced ${o} bytes, expected ${dstSize}`);
47 return out;
48}