2.3 KiB
CRC-32
(no submodules)
Purpose
Implements the standard IEEE 802.3 CRC-32 algorithm (polynomial 0xEDB88320, reflected) used for PNG chunk integrity verification. The implementation is a pure TypeScript, lookup-table-based computation that works in any JavaScript runtime without native bindings or Node.js built-ins.
Features
- Single-buffer
crc32()for straightforward integrity checks - Multi-chunk
crc32Multi()that avoids buffer concatenation allocation - Pre-computed 256-entry lookup table for O(n) throughput
- Returns unsigned 32-bit integer (safe for comparison with
>>>0normalised values)
Usage: Basic Example
import { crc32 } from "@suaveplan/exif/binary";
// Standard check value: crc32("123456789") === 0xCBF43926
const encoder = new TextEncoder();
const checkValue = crc32(encoder.encode("123456789"));
console.log(checkValue.toString(16)); // "cbf43926"
Usage: Advanced Example
import { crc32Multi } from "@suaveplan/exif/binary";
// PNG chunk CRC: covers chunk type bytes + chunk data bytes
function pngChunkCrc(type: Uint8Array, data: Uint8Array): number {
return crc32Multi([type, data]);
}
const typeBytes = new TextEncoder().encode("IHDR");
const ihdrData = new Uint8Array([0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]);
const checksum = pngChunkCrc(typeBytes, ihdrData);
API Reference
crc32(data: Uint8Array): number
Computes the CRC-32 of data. Returns an unsigned 32-bit integer. The standard test vector is: crc32(new TextEncoder().encode("123456789")) === 0xCBF43926.
crc32Multi(chunks: Uint8Array[]): number
Computes the CRC-32 of all chunks as if they were concatenated, without allocating a combined buffer. Returns an unsigned 32-bit integer. Equivalent to crc32(concat(...chunks)).
Implementation Notes
The lookup table is built once at module load time using the standard reflected polynomial 0xEDB88320 (the bit-reversal of 0x04C11DB7). Each byte of input XORs into the low 8 bits of the running CRC, selects a table entry, then is combined with the shifted CRC via XOR. The final >>> 0 ensures the result is a non-negative JavaScript number even when the high bit is set. crc32Multi avoids buffer allocation by maintaining the running CRC across chunk boundaries.