minimum_redundancy
is the Rust library by Piotr Beling to encode and decode data
with binary or non-binary Huffman coding.
The library can construct and concisely represent optimal prefix (minimum-redundancy) coding whose codewords are of length divisible by a given number of bits (1-bit, 2-bits, ...).
The library uses modified Huffman algorithm, with ideas from papers: - A. Brodnik, S. Carlsson, Sub-linear decoding of Huffman Codes Almost In-Place, 1998 - A. Moffat, J. Katajainen, In-Place Calculation of Minimum-Redundancy Codes. In: Akl S.G., Dehne F., Sack JR., Santoro N. (eds) Algorithms and Data Structures. WADS 1995. Lecture Notes in Computer Science, vol 955. Springer, Berlin, Heidelberg. https://doi.org/10.1007/3-540-60220-8_79
```rust use minimum_redundancy::{Coding, Code}; use maplit::hashmap;
// Construct coding with 1 bit per fragment for values 'a', 'b', 'c', // whose frequencies of occurrence are 100, 50, 10 times, respectively. let huffman = Coding::fromfrequenciesbitsperfragment(hashmap!('a' => 100, 'b' => 50, 'c' => 10), 1); // We expected the following Huffman tree: // / \ // /\ a // bc // and the following code assignment: a -> 1, b -> 00, c -> 01 asserteq!(huffman.codesforvalues(), hashmap!( 'a' => Code{bits: 0b1, fragments: 1, bitsperfragment: 1}, 'b' => Code{bits: 0b00, fragments: 2, bitsperfragment: 1}, 'c' => Code{bits: 0b01, fragments: 2, bitsperfragment: 1} )); let mut decoderfora = huffman.decoder(); asserteq!(decoderfora.consume(1), DecodingResult::Value(&'a')); let mut decoderforb = huffman.decoder(); asserteq!(decoderforb.consume(0), DecodingResult::Incomplete); asserteq!(decoderforb.consume(0), DecodingResult::Value(&'b')); let mut decoderforc = huffman.decoder(); asserteq!(decoderforc.consume(0), DecodingResult::Incomplete); asserteq!(decoderforc.consume(1), DecodingResult::Value(&'c')); asserteq!(huffman.totalfragmentscount(), 5); asserteq!(huffman.values.as_ref(), ['a', 'b', 'c']); ```