-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecompress.go
40 lines (33 loc) · 865 Bytes
/
decompress.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package huffman
import (
"bytes"
"encoding/gob"
"log"
"strings"
"github.com/gossie/bitset"
)
// Decompress decompresses the given data back into a string.
func Decompress(compressedContent []byte) string {
exported := exportFormat{}
decoder := gob.NewDecoder(bytes.NewReader(compressedContent))
err := decoder.Decode(&exported)
if err != nil {
log.Fatal(err)
}
compressionResult := CompressionResult{bitset.From(exported.Data), exported.Table, exported.Size}
root := fromMapping(compressionResult.table)
currentNode := root
var text strings.Builder
for i := uint(0); i < compressionResult.size; i++ {
if compressionResult.data.IsSet(i) {
currentNode = *currentNode.one
} else {
currentNode = *currentNode.zero
}
if currentNode.Leaf() {
text.WriteRune(currentNode.letter)
currentNode = root
}
}
return text.String()
}