86 lines · 2.7 KB
1 import { describe, it, expect } from 'vitest';
2 import { applyDelta, readOfsOffset } from '../delta.js';
3
4 const encoder = new TextEncoder();
5
6 describe('applyDelta', () => {
7 it('should apply an insert-only delta', () => {
8 const base = encoder.encode('hello');
9 // Delta: source size 5, target size 11, insert "hello world"
10 const delta = new Uint8Array([
11 5, // source size: 5
12 11, // target size: 11
13 11, // insert 11 bytes
14 ...encoder.encode('hello world'),
15 ]);
16
17 const result = applyDelta(base, delta);
18 expect(new TextDecoder().decode(result)).toBe('hello world');
19 });
20
21 it('should apply a copy-only delta', () => {
22 const base = encoder.encode('hello world');
23 // Delta: source size 11, target size 5, copy 5 bytes from offset 0
24 const delta = new Uint8Array([
25 11, // source size: 11
26 5, // target size: 5
27 0x80 | 0x01 | 0x10, // copy: offset byte + size byte present
28 0, // offset: 0
29 5, // size: 5
30 ]);
31
32 const result = applyDelta(base, delta);
33 expect(new TextDecoder().decode(result)).toBe('hello');
34 });
35
36 it('should apply a mixed copy+insert delta', () => {
37 const base = encoder.encode('hello world');
38 // Copy "hello" (5 bytes from offset 0), then insert " there"
39 const delta = new Uint8Array([
40 11, // source size: 11
41 11, // target size: 11 ("hello there")
42 // Copy instruction: offset=0, size=5
43 0x80 | 0x01 | 0x10,
44 0, // offset: 0
45 5, // size: 5
46 // Insert instruction: 6 bytes " there"
47 6,
48 ...encoder.encode(' there'),
49 ]);
50
51 const result = applyDelta(base, delta);
52 expect(new TextDecoder().decode(result)).toBe('hello there');
53 });
54
55 it('should throw on source size mismatch', () => {
56 const base = encoder.encode('hi');
57 const delta = new Uint8Array([
58 10, // says source is 10 bytes
59 5,
60 5,
61 ...encoder.encode('hello'),
62 ]);
63
64 expect(() => applyDelta(base, delta)).toThrow('source size mismatch');
65 });
66 });
67
68 describe('readOfsOffset', () => {
69 it('should read a single-byte offset', () => {
70 const buf = new Uint8Array([42]);
71 const { value, bytesRead } = readOfsOffset(buf, 0);
72 expect(value).toBe(42);
73 expect(bytesRead).toBe(1);
74 });
75
76 it('should read a multi-byte offset', () => {
77 // First byte: 0x80 | 0x01 = 129 (continuation bit set, value = 1)
78 // Second byte: 0x00 (value = 0)
79 // Decoded: ((1 + 1) << 7) | 0 = 256
80 const buf = new Uint8Array([0x81, 0x00]);
81 const { value, bytesRead } = readOfsOffset(buf, 0);
82 expect(value).toBe(256);
83 expect(bytesRead).toBe(2);
84 });
85 });
86