项目作者: icza

项目描述 :
Huffman coding implementation in Go (Huffman tree, Symbol table, Huffman Reader + Writer).
高级语言: Go
项目地址: git://github.com/icza/huffman.git
创建时间: 2016-06-02T06:38:32Z
项目社区:https://github.com/icza/huffman

开源协议:Apache License 2.0

下载


huffman

Build Status
Go Reference
Go Report Card
codecov

Huffman coding implementation in Go
(Huffman tree, Symbol table, Huffman Reader + Writer).

Huffman Tree

Use the Build() function to build a Huffman tree. Use the Print() function to print Huffman codes
of all leaves of a tree (for verification).

Example:

  1. leaves := []*Node{
  2. {Value: ' ', Count: 20},
  3. {Value: 'a', Count: 40},
  4. {Value: 'm', Count: 10},
  5. {Value: 'l', Count: 7},
  6. {Value: 'f', Count: 8},
  7. {Value: 't', Count: 15},
  8. }
  9. root := Build(leaves)
  10. Print(root)

Output:

  1. 'a': 0
  2. 'm': 100
  3. 'l': 1010
  4. 'f': 1011
  5. 't': 110
  6. ' ': 111

Huffman Reader and Writer

GoDoc

The hufio package implements a Huffman Reader and Writer. You may use these to transmit Huffman code of your data.

This Reader and Writer internally manages a Symbol Table (the frequency of encountered symbols, updated dynamically).
The Writer computes and sends the Huffman code of the data, the Reader receives the Huffman code and “reconstructs”
the original data based on that.

The implementation uses a sliding window which is used to manage the symbol table.
The sliding window is optional, that is, if no window is used, the symbol table is calculated based on
all previously encountered symbols.

Writer + Reader example:

  1. buf := &bytes.Buffer{}
  2. w := NewWriter(buf)
  3. if _, err := w.Write([]byte("Testing Huffman Writer + Reader.")); err != nil {
  4. log.Panicln("Failed to write:", err)
  5. }
  6. if err := w.Close(); err != nil {
  7. log.Panicln("Failed to close:", err)
  8. }
  9. r := NewReader(bytes.NewReader(buf.Bytes()))
  10. if data, err := ioutil.ReadAll(r); err != nil {
  11. log.Panicln("Failed to read:", err)
  12. } else {
  13. log.Println("Read:", string(data))
  14. }