File size: 1,570 Bytes
d283c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { describe, it, expect } from 'vitest';
import { BchCodec } from '../core/bch.js';

describe('BCH', () => {
  const bch63 = new BchCodec({ n: 63, k: 36, t: 5, m: 6 });

  it('should encode and decode without errors (63,36,5)', () => {
    const message = new Uint8Array(36);
    for (let i = 0; i < 36; i++) message[i] = Math.random() > 0.5 ? 1 : 0;

    const codeword = bch63.encode(message);
    expect(codeword.length).toBe(63);

    const decoded = bch63.decode(codeword);
    expect(decoded).not.toBeNull();
    expect(Array.from(decoded!)).toEqual(Array.from(message));
  });

  it('should correct up to t=5 errors (63,36,5)', () => {
    const message = new Uint8Array(36);
    for (let i = 0; i < 36; i++) message[i] = Math.random() > 0.5 ? 1 : 0;

    const codeword = bch63.encode(message);

    // Introduce 5 errors at random positions
    const errorPositions = new Set<number>();
    while (errorPositions.size < 5) {
      errorPositions.add(Math.floor(Math.random() * 63));
    }
    const corrupted = new Uint8Array(codeword);
    for (const pos of errorPositions) {
      corrupted[pos] ^= 1;
    }

    const decoded = bch63.decode(corrupted);
    expect(decoded).not.toBeNull();
    expect(Array.from(decoded!)).toEqual(Array.from(message));
  });

  it('should handle zero message', () => {
    const message = new Uint8Array(36); // all zeros
    const codeword = bch63.encode(message);
    const decoded = bch63.decode(codeword);
    expect(decoded).not.toBeNull();
    expect(Array.from(decoded!)).toEqual(Array.from(message));
  });
});