Function huff_coding::comp::compress[][src]

pub fn compress<L: HuffLetter>(letters: &[L]) -> CompressData<L>

Compress the provided slice of letters (types implementing HuffLetter), using binary codes generated with a HuffTree struct, into a byte slice (returned with additional data in the form of CompressData).

The letters are counted into a Weights collection to create a HuffTree using the build_weights_map function, which can be optimized a lot for certain letter types. Because of this fact, it’s generally faster to use the compress_with_tree function, providing a HuffTree built with our own Weights collection (an example of such collection is implemented in the crate on u8 in the form of ByteWeights).

The returned CompressData can be decompressed into the original letter slice with the decompress function.

How it works


It just reads every letter’s code in the created HuffTree and inserts them into a Vec<u8>. The codes themselves are mostly not a multiple of 8 bits long, so some of them can be used as padding in the last byte. The padding information, as well as the tree used to compress the slice are included in the returned CompressData.

Example


use huff_coding::prelude::{
    compress,
    decompress
};
 
let bytes = b"abbccc";
let nums = &[-97, -98, -98, -99, -99, -99];
let chars = &['a', 'b', 'b', 'c', 'c', 'c'];
let strs = &["ay", "bee", "bee", "cee", "cee", "cee"];
 
let comp_bytes = compress(bytes);
let comp_nums = compress(nums);
let comp_chars = compress(chars);
let comp_strs = compress(strs);
 
assert_eq!(bytes.to_vec(), decompress(&comp_bytes));
assert_eq!(nums.to_vec(), decompress(&comp_nums));
assert_eq!(chars.to_vec(), decompress(&comp_chars));
assert_eq!(strs.to_vec(), decompress(&comp_strs));