Skip to content
File

Blob: test/ofs-delta-known-encodings.test.ts

typescript51 lines
1import { assert, test } from "vitest";
2import { encodeOfsDeltaDistance } from "@/worker/git";
3 
4const toHex = (u8: Uint8Array) =>
5 Array.from(u8)
6 .map((b) => b.toString(16).padStart(2, "0"))
7 .join("");
8 
9// Mirror of the decoder in src/worker/git/pack/assembler.ts for verification
10function decodeOfsDeltaDistance(bytes: Uint8Array): number {
11 let p = 0;
12 let b = bytes[p++];
13 let x = b & 0x7f;
14 while (b & 0x80) {
15 b = bytes[p++];
16 x = ((x + 1) << 7) | (b & 0x7f);
17 }
18 return x >>> 0;
19}
20 
21const known: { n: number; hex: string }[] = [
22 { n: 0x01, hex: "01" },
23 { n: 0x7f, hex: "7f" },
24 { n: 0x80, hex: "8000" },
25 { n: 0x81, hex: "8001" },
26 { n: 0x100, hex: "8100" },
27 { n: 0x3fff, hex: "fe7f" },
28 { n: 0x4000, hex: "ff00" },
29 { n: 0x1ffff, hex: "86fe7f" },
30 { n: 0x20000, hex: "86ff00" },
31];
32 
33test("ofs-delta encoder encodes known values to expected bytes", () => {
34 for (const { n, hex } of known) {
35 const enc = encodeOfsDeltaDistance(n);
36 assert.strictEqual(toHex(enc), hex, `encoding mismatch for ${n}`);
37 }
38});
39 
40test("ofs-delta encoder round-trips a range of values", () => {
41 const values = [
42 1, 2, 3, 10, 0x7e, 0x7f, 0x80, 0x81, 0xff, 0x100, 0x1234, 0x3fff, 0x4000, 0x1ffff, 0x20000,
43 0x1fffff, 0x200000,
44 ];
45 for (const n of values) {
46 const enc = encodeOfsDeltaDistance(n);
47 const dec = decodeOfsDeltaDistance(enc);
48 assert.strictEqual(dec, n, `round-trip failed for ${n} (enc=${toHex(enc)})`);
49 }
50});