-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
383 lines (319 loc) · 7.48 KB
/
main.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package main
import (
"bytes"
"encoding/binary"
"encoding/gob"
"flag"
"fmt"
"io"
"os"
"sort"
"strconv"
)
type HuffmanNode struct {
Value byte
Frequency int
LeftChild *HuffmanNode
RightChild *HuffmanNode
}
type FileHeader struct {
TreeSize int64
DataSize int64
CompressAmount int8
}
type HuffmanRoot struct {
root *HuffmanNode
}
func StringToByteArray(input string) []byte {
var byteArray []byte = make([]byte, len(input)/8)
currentByte := byte(0)
bitCount := 0
bit := 0
for i, char := range input {
bit, _ = strconv.Atoi(string(char))
currentByte = (currentByte << 1) | byte(bit)
bitCount++
if bitCount == 8 {
byteArray[i/8] = currentByte
currentByte = byte(0)
bitCount = 0
}
}
if bitCount > 0 {
currentByte <<= (8 - bitCount)
byteArray = append(byteArray, currentByte)
}
return byteArray
}
func readChunks(filename string, chunkSize int) ([]byte, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
// Get file size
fileInfo, err := file.Stat()
if err != nil {
return nil, err
}
fileSize := fileInfo.Size()
// Calculate the number of chunks
numChunks := int(fileSize) / chunkSize
if int(fileSize)%chunkSize != 0 {
numChunks++
}
// Create a byte array to store the file content
fileContent := make([]byte, 0, fileSize)
// Read file in chunks
buffer := make([]byte, chunkSize)
for i := 0; i < numChunks; i++ {
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
return nil, err
}
fileContent = append(fileContent, buffer[:n]...)
}
return fileContent, nil
}
func (encoder *HuffmanRoot) Encode(data []byte) ([]byte, error) {
codes := generateHuffmanCodes(encoder.root)
compressed := compressData(data, codes)
return compressed, nil
}
func compressData(data []byte, codes map[byte]string) []byte {
var buffer bytes.Buffer
for _, b := range data {
_, err := buffer.WriteString(codes[b])
if err != nil {
fmt.Println("error")
}
}
ham := StringToByteArray(buffer.String())
return ham
}
func (encoder *HuffmanRoot) SerializeTree() ([]byte, error) {
buffer := new(bytes.Buffer)
enc := gob.NewEncoder(buffer)
err := enc.Encode(encoder.root)
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func (encoder *HuffmanRoot) DeserializeTree(data []byte) error {
buffer := bytes.NewBuffer(data)
dec := gob.NewDecoder(buffer)
err := dec.Decode(&encoder.root)
return err
}
func (encoder *HuffmanRoot) BuildTree(data []byte) {
frequencies := make(map[byte]int)
for _, b := range data {
frequencies[b]++
}
encoder.root = buildHuffmanTree(frequencies)
}
func buildHuffmanTree(frequencies map[byte]int) *HuffmanNode {
var nodes []*HuffmanNode
var left, right *HuffmanNode
// Create leaf nodes for each symbol
for symbol, freq := range frequencies {
nodes = append(nodes, &HuffmanNode{
Value: symbol,
Frequency: freq,
})
}
for len(nodes) > 1 {
// Sort nodes by frequency (ascending order)
sort.Slice(nodes, func(i, j int) bool {
return nodes[i].Frequency < nodes[j].Frequency
})
// Take two nodes with the lowest frequency
left = nodes[0]
right = nodes[1]
// Create a parent node with the sum of frequencies
parent := &HuffmanNode{
Frequency: left.Frequency + right.Frequency,
LeftChild: left,
RightChild: right,
}
// Remove the two nodes and add the parent node
nodes = nodes[2:]
nodes = append(nodes, parent)
}
// Return the root node
return nodes[0]
}
func generateHuffmanCodes(root *HuffmanNode) map[byte]string {
codes := make(map[byte]string, 0)
buildHuffmanCodes(root, "", codes)
return codes
}
func buildHuffmanCodes(node *HuffmanNode, code string, codes map[byte]string) {
// Recursive calls for left and right children
if node.LeftChild != nil {
buildHuffmanCodes(node.LeftChild, code+"0", codes)
}
if node.RightChild != nil {
buildHuffmanCodes(node.RightChild, code+"1", codes)
}
if node.LeftChild == nil && node.RightChild == nil {
codes[node.Value] = code
return
}
}
func EncodeLoop(data []byte, i *int8) ([]byte, error) {
var binBuffer bytes.Buffer
encoder := &HuffmanRoot{}
encoder.BuildTree(data)
compressed, err := encoder.Encode(data)
if err != nil {
return compressed, err
}
treeData, err := encoder.SerializeTree()
if err != nil {
return compressed, err
}
header := FileHeader{
TreeSize: int64(len(treeData)),
DataSize: int64(len(data)),
CompressAmount: *i,
}
err = binary.Write(&binBuffer, binary.LittleEndian, header)
if err != nil {
return compressed, err
}
err = binary.Write(&binBuffer, binary.LittleEndian, treeData)
if err != nil {
return compressed, err
}
err = binary.Write(&binBuffer, binary.LittleEndian, compressed)
if err != nil {
return compressed, err
}
if len(binBuffer.Bytes()) < len(data) {
*i++
data, err = EncodeLoop(binBuffer.Bytes(), i)
if err != nil {
return data, err
}
} else {
data = binBuffer.Bytes()
}
return data, err
}
func EncodeAndLargeFile(inputFilePath, outputFilePath string) error {
data, err := readChunks(inputFilePath, 1024)
if err != nil {
return err
}
var i int8 = 0
compressed, err := EncodeLoop(data, &i)
if err != nil {
return err
}
file, err := os.Create(outputFilePath)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(compressed)
if err != nil {
return err
}
return nil
}
func DecodeLargeFile(filePath, decodedFilePath string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
var binBuffer bytes.Buffer
_, err = binBuffer.ReadFrom(file)
if err != nil {
return err
}
for {
var header FileHeader
err = binary.Read(&binBuffer, binary.LittleEndian, &header)
if err != nil {
return err
}
treeData := make([]byte, header.TreeSize)
err = binary.Read(&binBuffer, binary.LittleEndian, &treeData)
if err != nil {
return err
}
encoder := &HuffmanRoot{}
err = encoder.DeserializeTree(treeData)
if err != nil {
return err
}
decoded := decodeData(binBuffer.Bytes(), encoder.root, header.DataSize)
binBuffer.Reset()
_, err = binBuffer.Write(decoded)
if err != nil {
return err
}
if header.CompressAmount == 0 {
break
}
}
err = os.WriteFile(decodedFilePath, binBuffer.Bytes(), 0644)
if err != nil {
return err
}
return nil
}
func decodeData(data []byte, root *HuffmanNode, size int64) []byte {
var decoded []byte
node := root
var j int64 = 0
for _, b := range data {
for i := 7; i >= 0; i-- {
bit := (b >> i) & 1
if bit == 0 {
node = node.LeftChild
} else {
node = node.RightChild
}
if node.LeftChild == nil && node.RightChild == nil {
j++
decoded = append(decoded, node.Value)
node = root
// For not used bits
if j == size {
break
}
}
}
}
return decoded
}
func main() {
compress := flag.Bool("C", false, "-C Compress")
decompress := flag.Bool("D", false, "-D Compress")
inputFilePath := flag.String("i", "", "-i filename")
outputFilePath := flag.String("o", "", "-i filename")
flag.Parse()
if *inputFilePath == "" || *outputFilePath == "" {
fmt.Println("input or output cannot be empty")
fmt.Println(*inputFilePath, *outputFilePath)
return
}
if *compress {
err := EncodeAndLargeFile(*inputFilePath, *outputFilePath)
if err != nil {
fmt.Printf("Error encoding and saving: %s\n", err.Error())
return
}
}
if *decompress {
err := DecodeLargeFile(*inputFilePath, *outputFilePath)
if err != nil {
fmt.Printf("Error decoding and saving: %s\n", err.Error())
return
}
}
}