crc32
Calculate CRC-32/ISO-HDLC checksums in pure Gleam.
This module is the supported public API for the crc32 package. It provides
both one-shot checksum calculation and immutable incremental state for data
processed in chunks.
The implemented algorithm is CRC-32/ISO-HDLC, the conventional reflected
CRC-32 variant commonly used by ZIP, gzip, PNG, and Ethernet. The standard
check value for the ASCII bytes "123456789" is 0xCBF43926.
The public API intentionally works with BitArray values and returns the
finalized checksum as a Gleam Int. Hexadecimal formatting is left to
callers that need textual output.
import crc32
pub fn main() {
let checksum = crc32.checksum(<<"123456789":utf8>>)
assert checksum == 0xCBF43926
}
import crc32
pub fn main() {
let checksum =
crc32.new()
|> crc32.update(<<"hello ":utf8>>)
|> crc32.update(<<"world":utf8>>)
|> crc32.finalize()
assert checksum == crc32.checksum(<<"hello world":utf8>>)
}
CRC-32 is useful for detecting accidental corruption. It is not a cryptographic hash and must not be used for authentication or tamper resistance.
Types
Values
pub fn checksum(data: BitArray) -> Int
pub fn finalize(crc: Crc32) -> Int
Finalize an incremental calculation and return its CRC-32 checksum.
The returned Int is the finalized CRC-32/ISO-HDLC value after the
algorithm’s final XOR step.
Examples
let checksum =
crc32.new()
|> crc32.update(data)
|> crc32.finalize()
pub fn new() -> Crc32
pub fn update(crc: Crc32, data: BitArray) -> Crc32
Feed another chunk of bytes into an incremental CRC-32 calculation.
This function is pipeline-friendly and returns a new state value. Updating
with multiple chunks produces the same finalized checksum as processing the
concatenated bytes in a single call to checksum.
Examples
crc32.new()
|> crc32.update(<<"hello ":utf8>>)
|> crc32.update(<<"world":utf8>>)
|> crc32.finalize()
// => same as crc32.checksum(<<"hello world":utf8>>)
pub fn verify(crc: Crc32, expected: Int) -> Bool
Finalize an incremental calculation and compare it with an expected checksum.
This is a convenience helper for verification workflows. The expected
value should be the finalized CRC-32/ISO-HDLC checksum, typically written as
a hexadecimal integer literal in source code.
Examples
let valid =
crc32.new()
|> crc32.update(data)
|> crc32.verify(expected)