Expand description
Asymmetric Numeral Systems (ANS) entropy coding primitives.
This crate provides a small, dependency-light implementation of rANS (range Asymmetric Numeral Systems), suitable as a building block for higher-level compression schemes (e.g. “bits-back” constructions used in ROC / set coding).
§Design
- Explicit model: callers provide counts, floats, or pre-normalized frequencies.
- Batch and streaming:
encode/decodefor one-shot use,RansEncoder/RansDecoderfor symbol-at-a-time control. - 32-bit and 64-bit:
Rans64Encoder/Rans64Decoderemit u32 words for finer precision (the variant used by JPEG XL, LZFSE). - Bits-back:
RansDecoder::peek/RansDecoder::advancedecompose decoding for BB-ANS and ROC constructions. no_std: zero dependencies, works withoutstd(requiresalloc).
§Not this
- Not a compression framework: no file I/O, no adaptive models, no
pipeline orchestration. Use
constrictionif you need a full entropy coding toolkit. - Not tANS / FSE: this crate implements rANS only. tANS (used by zstd) has different table construction and performance characteristics.
- Not speed-optimized: no SIMD, no interleaved streams. Correct and easy to integrate.
- Not encryption: an entropy coder is not a cryptographic primitive.
§Batch example
use ans::{decode, encode, FrequencyTable};
let counts = [10u32, 20, 70]; // A, B, C
let table = FrequencyTable::from_counts(&counts, 14)?;
let message = [0u32, 2, 1, 2, 2, 0];
let bytes = encode(&message, &table)?;
let back = decode(&bytes, &table, message.len())?;
assert_eq!(back, message);
§Streaming example
use ans::{RansEncoder, RansDecoder, FrequencyTable};
let table = FrequencyTable::from_counts(&[3, 7], 12)?;
let message = [0u32, 1, 1, 0, 1];
// Encode symbols in reverse order (rANS requirement).
let mut enc = RansEncoder::new();
for &sym in message.iter().rev() {
enc.put(sym, &table)?;
}
let bytes = enc.finish();
// Decode symbols in forward order.
let mut dec = RansDecoder::new(&bytes)?;
let mut decoded = Vec::new();
for _ in 0..message.len() {
decoded.push(dec.get(&table)?);
}
assert_eq!(decoded, message);
§Notes
- Encoding returns a byte vector in stack format: the decoder consumes bytes from the end (LIFO).
Structs§
- Frequency
Table - A frequency model for rANS with total (T = 2^{precision_bits}).
- Rans64
Decoder - A symbol-at-a-time 64-bit rANS decoder.
- Rans64
Encoder - A symbol-at-a-time 64-bit rANS encoder.
- Rans
Decoder - A symbol-at-a-time rANS decoder.
- Rans
Encoder - A symbol-at-a-time rANS encoder.
Enums§
- AnsError
- Errors for rANS operations.
Functions§
- decode
- Decode
lensymbols from an rANS byte stream produced byencode. - decode64
- Decode
lensymbols from a 64-bit rANS byte stream produced byencode64. - encode
- Encode
symbolsinto a byte stream using rANS with the given frequencytable. - encode64
- Encode
symbolsusing 64-bit rANS with the given frequencytable.