-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.go
47 lines (36 loc) · 852 Bytes
/
encode.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
41
42
43
44
45
46
47
package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
)
const buffSize = 16 * 1024
func encode(r io.ReadSeeker) ([]byte, error) {
// build huffman tree
tree, err := buildHuffmanTree(r)
if err != nil {
return nil, fmt.Errorf("failed to build huffman tree: %w", err)
}
treeJson, err := json.Marshal(tree)
if err != nil {
return nil, fmt.Errorf("failed to encode tree: %w", err)
}
byteCount := uint32(len(treeJson))
// write count
// write treeJson
// use tree to write bytes
encoding := make([]byte, 4+len(treeJson))
binary.BigEndian.PutUint32(encoding, byteCount)
copy(encoding[4:], treeJson)
_, err = r.Seek(0, 0)
if err != nil {
return nil, err
}
compressedBytes, err := tree.compress(r)
if err != nil {
return nil, err
}
encoding = append(encoding, compressedBytes...)
return encoding, nil
}