Expand description
Manual arithmetic compression and decompression helpers.
Arithmetic coding is another entropy coder, but unlike Huffman coding it does not assign one discrete bit-pattern per symbol. Instead, it keeps a numeric interval and progressively narrows that interval as each symbol is processed. Frequent symbols claim large sub-intervals and rare symbols claim small ones, which lets the coder represent symbol probabilities more precisely than a prefix tree.
§Format Overview
The compressed stream begins with the ASCII header ARI0. It is followed by
everything the decoder needs to rebuild the exact same static probability
model:
- 4-byte magic header:
ARI0 - 8-byte little-endian original length
- 2-byte little-endian symbol count
- repeated
symbol_counttimes:- 1 byte: symbol value
- 4 bytes little-endian: symbol frequency (the symbol’s count, or for inputs over 1 GiB, the count rescaled so that the frequencies sum to at most 2^30)
- 8-byte little-endian payload bit length
- packed arithmetic-code bits in most-significant-bit-first order
The implementation below uses a classic fixed-precision arithmetic coder with E1/E2/E3 renormalization. The comments in the hot paths explain how the interval is updated and why bits are emitted or consumed when the interval moves wholly into the low half, high half, or middle band.
See the book entry Entropy coding.
Functions§
- arithmetic_
compress - Compress a byte slice with a manual arithmetic coder.
- arithmetic_
decompress - Decompress a byte slice previously produced by
arithmetic_compress. - try_
arithmetic_ compress - Fallible variant of
arithmetic_compress. - try_
arithmetic_ decompress - Fallible variant of
arithmetic_decompress.