Checksums
CRC-8/16/32/64, Adler-32, and the Checksum marker
Checksum(algorithm, fields=(...)) marks an integer field as a checksum over the encoded bytes of the named fields. The checksum is computed on encode (after offsets are patched, so a checksum covering an offset field digests the final bytes) and verified on decode; a mismatch raises DecodeError. The checksum field is derived — it takes no constructor argument and is stored as 0 until encoded. A checksum must cover earlier fields, and cannot cover another checksum or a conditional field (unless the checksum shares the field’s exact When condition).
These algorithms are built in, as plain functions from bytes to int:
| Algorithm | Catalogued model | Field |
|---|---|---|
CRC8 | CRC-8/SMBUS | UInt8 |
CRC16 | CRC-16/CCITT-FALSE (IBM-3740) | UInt16 |
CRC16Modbus | CRC-16/MODBUS | UInt16 |
CRC32 | CRC-32/ISO-HDLC (zlib, Ethernet) | UInt32 |
CRC32C | CRC-32C (Castagnoli, iSCSI) | UInt32 |
CRC64 | CRC-64/XZ | UInt64 |
Adler32 | Adler-32 | UInt32 |
The CRCs are computed by fastcrc, which uses SIMD carry-less multiplication where the CPU supports it. Any callable taking bytes and returning an int can be used as the algorithm (ChecksumAlgorithm), including any other fastcrc model: Checksum(fastcrc.crc16.xmodem, fields=(...)).
from dataclasses import field
from typing import Annotated
from binal import (
Adler32,
BinaryModel,
Checksum,
CRC16,
CRC32,
Prefixed,
UInt16,
UInt32,
)
class Packet(BinaryModel, byte_order="big"):
body: Annotated[bytes, Prefixed(UInt16)]
crc: Annotated[UInt32, Checksum(CRC32, fields=("body",))] = field(init=False)
class Frame(BinaryModel, byte_order="big"):
body: Annotated[bytes, Prefixed(UInt16)]
crc: Annotated[UInt16, Checksum(CRC16, fields=("body",))] = field(init=False)
adler: Annotated[UInt32, Checksum(Adler32, fields=("body",))] = field(init=False)
packet = Packet(body=b"hello")
Packet.decode(packet.encode()) == packet # True
# Corrupt one byte of the body: decode raises DecodeError.
corrupt = bytearray(packet.encode())
corrupt[3] ^= 0xFF
Packet.decode(bytes(corrupt)) # DecodeError: checksum mismatch The checksum is computed over the encoded bytes of the listed fields, concatenated in the order listed — not over the whole record, and not over the Python values. For a checksum over a bit field, the digest covers the byte(s) the bits occupy. On decode, checksum verification happens before model validation, so a corrupt record fails on the checksum rather than on a downstream invariant.