huff_coding

Build Status

An implementation of the Huffman coding algorithm, enabling one to create a Huffman tree with any alphabet they choose.

It mainly revolves around the HuffTree struct, which provides a way to generate Huffman prefix codes for any collection of types implementing the HuffLetter trait, where for every letter there is a corresponding weight (To ensure this, the Weights trait must be implemented on the provided collection). If the provided letters also implement the HuffLetterAsBytes trait, the tree can be easily read or returned in binary form.

```rust use huff_coding::{

prelude::*,

bitvec::prelude::*,

};

// every primitive type (except floats) implements HuffLetter let bytes = [0xff, 0xff, 0xff, 0xaa, 0xaa, 0xcc]; let chars = ['a', 'a', 'a', 'b', 'b', 'c']; let ints = [-32, 123, -32, -32, 75, 123];

// ------ building weights structs ------

// building weights with the ByteWeights struct let byteweights = ByteWeights::frombytes(&bytes); // building weights in the form of a HashMap let charweights = buildweightsmap(&chars); let intweights = buildweightsmap(&ints);

// ------ initializing HuffTrees ------

let treebytes = HuffTree::fromweights(byteweights); let treechars = HuffTree::fromweights(charweights); let treeints = HuffTree::fromweights(int_weights);

// ------ reading codes from a tree ------ let charcodes = treechars.readcodes(); asserteq!( charcodes.get(&'a').unwrap(), &bitvec![Msb0, u8; 0] ); asserteq!( charcodes.get(&'b').unwrap(), &bitvec![Msb0, u8; 1, 1] ); asserteq!( char_codes.get(&'c').unwrap(), &bitvec![Msb0, u8; 1, 0] );

// ------ HuffTree in binary ------

// every integer implements HuffLetterAsBytes let treebytesbin = treebytes.asbin(); asserteq!(treebytesbin.tostring(), "[10111111, 11101100, 11000101, 01010]"); // reading a HuffTree from a binary representation let treebytesfrombin = HuffTree::::tryfrombin(treebytesbin).unwrap(); asserteq!(treebytes.readcodes(), treebytesfrombin.readcodes()); ```

Included are also example compression/decompression functions using my implementation of this algorithm.

```rust use huff_coding::prelude::*;

let bytes = b"abbccc"; let compdata = compress(bytes); let decompbytes = decompress(&comp_data);

asserteq!(bytes.tovec(), decomp_bytes); ```

Every binary representation in the crate is made thanks to the bitvec crate which I've re-exported for convenience.