https://github.com/icza/huffman
Huffman coding implementation in Go (Huffman tree, Symbol table, Huffman Reader + Writer).
https://github.com/icza/huffman
huffman-coding huffman-reader huffman-tree huffman-writer symbol-table
Last synced: 3 months ago
JSON representation
Huffman coding implementation in Go (Huffman tree, Symbol table, Huffman Reader + Writer).
- Host: GitHub
- URL: https://github.com/icza/huffman
- Owner: icza
- License: apache-2.0
- Created: 2016-06-02T06:38:32.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2023-03-30T13:38:29.000Z (about 2 years ago)
- Last Synced: 2025-03-24T10:45:44.305Z (3 months ago)
- Topics: huffman-coding, huffman-reader, huffman-tree, huffman-writer, symbol-table
- Language: Go
- Homepage:
- Size: 90.8 KB
- Stars: 31
- Watchers: 4
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# huffman

[](https://pkg.go.dev/github.com/icza/huffman)
[](https://goreportcard.com/report/github.com/icza/huffman)
[](https://codecov.io/gh/icza/huffman)[Huffman coding](https://en.wikipedia.org/wiki/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:
leaves := []*Node{
{Value: ' ', Count: 20},
{Value: 'a', Count: 40},
{Value: 'm', Count: 10},
{Value: 'l', Count: 7},
{Value: 'f', Count: 8},
{Value: 't', Count: 15},
}
root := Build(leaves)
Print(root)Output:
'a': 0
'm': 100
'l': 1010
'f': 1011
't': 110
' ': 111### Huffman Reader and Writer
[](https://godoc.org/github.com/icza/huffman/hufio)
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:
buf := &bytes.Buffer{}
w := NewWriter(buf)
if _, err := w.Write([]byte("Testing Huffman Writer + Reader.")); err != nil {
log.Panicln("Failed to write:", err)
}
if err := w.Close(); err != nil {
log.Panicln("Failed to close:", err)
}r := NewReader(bytes.NewReader(buf.Bytes()))
if data, err := ioutil.ReadAll(r); err != nil {
log.Panicln("Failed to read:", err)
} else {
log.Println("Read:", string(data))
}