-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
195 lines (160 loc) · 3.45 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
package main
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"math/bits"
"os"
"strings"
"github.com/fr3fou/depressor/huffman"
)
func main() {
if err := run(); err != nil {
log.Fatalln(err)
}
}
func usage() {
fmt.Println("usage: ")
fmt.Println(" depressor -c file.txt")
fmt.Println(" depressor -d file.txt.mkti")
fmt.Println(" depressor -help")
}
func run() error {
if len(os.Args) < 3 {
usage()
return nil
}
cmd := os.Args[1]
fileName := os.Args[2]
input, err := os.Open(fileName)
if err != nil {
return fmt.Errorf("failed opening file for reading: %w", err)
}
defer input.Close()
if cmd == "-c" {
return compress(fileName, input)
}
if cmd == "-d" {
return decompress(fileName, input)
}
usage()
return nil
}
func compress(fileName string, reader io.Reader) error {
sb := &strings.Builder{}
io.Copy(sb, reader)
text := sb.String()
tree := huffman.BuildTree(text)
dictionary := huffman.BuildDictionary(tree)
output, err := os.Create(fmt.Sprintf("%s.mkti", fileName))
if err != nil {
return err
}
defer output.Close()
writer := bufio.NewWriter(output)
if err := huffman.EncodeTree(writer, &tree); err != nil {
return nil
}
if err := binary.Write(writer, binary.BigEndian, byte(0)); err != nil {
return nil
}
buf := []byte{}
buf = binary.AppendUvarint(buf, uint64(len(text)))
_, err = writer.Write(buf)
if err != nil {
return err
}
var overflow int8
buf = []byte{}
for _, r := range text {
code := dictionary[r]
buf, overflow = encode(buf, overflow, code)
}
_, err = writer.Write(buf)
if err != nil {
return nil
}
if err := writer.Flush(); err != nil {
return nil
}
return nil
}
func decompress(fileName string, reader io.Reader) error {
br := bufio.NewReader(reader)
root, err := huffman.Decode(br)
if err != nil {
return err
}
textLength, err := binary.ReadUvarint(br)
if err != nil {
return err
}
output, err := os.Create(strings.ReplaceAll(fileName, ".mkti", ""))
if err != nil {
return fmt.Errorf("failed opening file for writing: %w", err)
}
defer output.Close()
sb := &strings.Builder{}
node := root
for sb.Len() < int(textLength) {
b, err := br.ReadByte()
if err != nil && !errors.Is(err, io.EOF) {
return err
}
p := 7
for p >= 0 && sb.Len() < int(textLength) {
if (b & (1 << p)) == 0 {
node = *node.Data.Left
} else {
node = *node.Data.Right
}
if node.Data.Rune != 0 {
sb.WriteRune(node.Data.Rune)
node = root
}
p--
}
if err != nil {
break
}
}
_, err = output.WriteString(sb.String())
return err
}
// shoutout tsetso
func encode(buf []byte, overflow int8, code uint32) ([]byte, int8) {
acc := buf
l := bits.Len32(code)
// Keep track of two "pointers":
// `read` is the current bit we're reading from `code` -> [0..l-2]
// `write` is the current bit we're writing into `acc` -> [7..0]
read := 0
write := overflow - 1
// Helper for appending a new byte and resetting the write pointer
newByte := func() {
acc = append(acc, 0)
write = 7
}
// If there's no space left over from a previous serialization, start by
// appending a new byte.
if overflow == 0 {
newByte()
}
for read < l-1 {
// If the current bit is set in `code`, set it in `acc`:
if code&(1<<read) != 0 {
acc[len(acc)-1] |= 1 << write
}
// Move the pointers
read++
write--
// If we're not done and we're out of writing space, append a new byte
if read != l-1 && write < 0 {
newByte()
}
}
return acc, write + 1
}