1.8 KiB
crc32
Purpose
Computes the IEEE 802.3 CRC-32 (polynomial 0xEDB88320, little-endian reflected) used by every ZIP entry. The CRC stored in the central directory MUST equal crc32(plaintext); ZIP readers cross-check this value on every decompression to detect bit rot or tampering. ZIP encoders compute it once per entry and store it in both the local header and CDR.
Features
- 256-entry lookup table built lazily on first call (zero cost when CRC is unused, e.g. write-path skip).
- Returns an unsigned 32-bit
numberwith>>> 0so callers never see negative integers from JS sign-bit propagation. - Pure function with no external dependencies; safe to embed in any tier (universal, browser, server).
Usage: Basic
import { crc32 } from "@suaveplan/drive-storage-zip/parser";
const value = crc32(new TextEncoder().encode("hello"));
Usage: Advanced
import { crc32 } from "@suaveplan/drive-storage-zip/parser";
function verifyEntry(plaintext: Uint8Array, expected: number) {
const actual = crc32(plaintext);
if (actual !== expected) throw new Error(`crc mismatch: ${actual} !== ${expected}`);
}
API Reference
crc32(bytes: Uint8Array): number — synchronous, deterministic, allocation-free after table init; returns the unsigned 32-bit CRC.
Implementation Notes
The lookup table is Uint32Array(256) so indexing is bounds-checked and free of GC pressure. The inner loop does one XOR and one table lookup per byte; throughput on a modern V8 build is ~500 MB/s, which is adequate even for multi-GB archives because the ZIP read path is bottlenecked on inflate, not CRC. For specialised pipelines requiring incremental CRC accumulation, the function can be lifted into a class — the polynomial and reflected representation are unchanged.