Skip to main content

Crate ans

Crate ans 

Source
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 (frequencies) and the precision.
  • Batch and streaming: encode/decode for one-shot use, RansEncoder/RansDecoder for symbol-at-a-time control.
  • No I/O: this crate is pure in-memory coding.
  • no_std: works without std (requires alloc).

§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

  • This is not tuned for maximum speed; it is meant to be correct and easy to integrate.
  • Encoding returns a byte vector in a stack format: the decoder consumes bytes from the end (LIFO). This avoids reversing buffers.

Structs§

FrequencyTable
A frequency model for rANS with total (T = 2^{precision_bits}).
RansDecoder
A symbol-at-a-time rANS decoder.
RansEncoder
A symbol-at-a-time rANS encoder.

Enums§

AnsError
Errors for rANS operations.

Functions§

decode
Decode len symbols from an rANS byte stream produced by encode.
encode
Encode symbols into a byte stream using rANS with the given frequency table.