File size: 971 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
import { describe, it, expect } from 'vitest';
import { crcAppend, crcVerify } from '../core/crc.js';

describe('CRC', () => {
  for (const bits of [4, 8, 16] as const) {
    it(`should append and verify CRC-${bits}`, () => {
      const data = new Uint8Array(32);
      for (let i = 0; i < 32; i++) data[i] = Math.random() > 0.5 ? 1 : 0;

      const withCrc = crcAppend(data, bits);
      expect(withCrc.length).toBe(32 + bits);

      const verified = crcVerify(withCrc, bits);
      expect(verified).not.toBeNull();
      expect(Array.from(verified!)).toEqual(Array.from(data));
    });

    it(`should reject corrupted data with CRC-${bits}`, () => {
      const data = new Uint8Array(32);
      for (let i = 0; i < 32; i++) data[i] = Math.random() > 0.5 ? 1 : 0;

      const withCrc = crcAppend(data, bits);
      // Flip a bit in the data
      withCrc[5] ^= 1;

      const verified = crcVerify(withCrc, bits);
      expect(verified).toBeNull();
    });
  }
});