Repository navigation
Expand file tree
/
Copy pathDecoder.cpp
More file actions
97 lines (90 loc) · 2.24 KB
/
Copy pathDecoder.cpp
File metadata and controls
97 lines (90 loc) · 2.24 KB
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
#include <iostream>
#include <set>
#include <utility>
#include <vector>
#include <cstdint>
#include "Decoder.h"
void HuffmanDecoder::add(unsigned int freq, uint8_t symbol, Node* left, Node* right) {
Node* curr = new Node();
curr->symbol = symbol;
curr->left = left;
curr->right = right;
s.insert({freq, curr});
}
void HuffmanDecoder::remTree(Node* curr) {
if(curr == nullptr) return;
remTree(curr->left);
remTree(curr->right);
delete curr;
}
void HuffmanDecoder::buildTree() {
for(int i = 0; i < 256; i++) {
if(freq[i] > 0) {
add(freq[i], i);
}
}
if(s.size() == 0) {
root = nullptr;
return;
}
if(s.size() == 1){
add(0,0);
}
while(s.size() > 1) {
auto it1 = s.begin();
auto it2 = std::next(it1);
add(it1->first + it2->first, 0, it1->second, it2->second);
s.erase(it1);
s.erase(it2);
}
root = s.begin()->second;
}
void HuffmanDecoder::readData() {
uint8_t* bytes_tot_len = (uint8_t*)&tot_len;
int wsk = 0;
for(int i = 0; i < 4; i++) {
bytes_tot_len[i] = compressed[wsk++];
}
for(int i = 0; i < 256; i++) {
uint8_t* bytes_freq = (uint8_t*)&freq[i];
for(int j = 0; j < 4; j++) {
bytes_freq[j] = compressed[wsk++];
}
}
}
HuffmanDecoder::HuffmanDecoder(std::vector<uint8_t> inp) {
compressed = inp;
root = nullptr;
tot_len = 0;
for(int i = 0; i < 256; i++) {
freq[i] = 0;
}
}
HuffmanDecoder::~HuffmanDecoder() {
remTree(root);
}
std::vector<uint8_t> HuffmanDecoder::decompress() {
readData();
buildTree();
std::vector<uint8_t> res;
Node* curr = root;
int rem = 0;
for(int i = 4 + 256 * 4; i < compressed.size(); i++) {
for(int j = 7; j >= 0; j--) {
if(compressed[i] & (1<<j)) {
curr = curr->right;
}else {
curr = curr->left;
}
if(curr->left == nullptr && curr->right == nullptr) {
res.push_back(curr->symbol);
curr = root;
rem++;
if(rem == tot_len) {
return res;
}
}
}
}
return res;
}