-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanTree.cpp
More file actions
429 lines (352 loc) · 12.2 KB
/
HuffmanTree.cpp
File metadata and controls
429 lines (352 loc) · 12.2 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#include "HuffmanTree.h"
#include <iostream>
#include <fstream>
#include <memory>
#include <queue>
#include <bitset>
#include <string>
#include <cstring>
#include <sstream>
#include <unordered_map>
using namespace CHNJAR003;
#define PRINT(x) std::cout << x;
HuffmanTree::HuffmanTree()
{
root = nullptr;
}
HuffmanTree::~HuffmanTree()
{
root = nullptr;
}
//performs shallow copy construction using rhs HuffmanTree
HuffmanTree::HuffmanTree(const HuffmanTree &rhs) : root(rhs.root)
{
}
//move copy constructor
HuffmanTree::HuffmanTree(HuffmanTree &&rhs) : root(std::move(rhs.root))
{
rhs.root = nullptr;
}
//copy assignment operator
HuffmanTree &HuffmanTree::operator=(const HuffmanTree &rhs)
{
if (this != &rhs)
{
root = rhs.root;
}
return *this;
}
//move assignment operator
HuffmanTree &HuffmanTree::operator=(HuffmanTree &&rhs)
{
if (this != &rhs)
{
root = std::move(rhs.root);
rhs.root = nullptr;
}
return *this;
}
void HuffmanTree::buildFrequencyTable(std::string inputFileName)
{
std::ifstream ifs;
ifs.open((inputFileName + ".txt").c_str());
if (ifs.is_open())
{
char tempChar;
while (ifs.get(tempChar))
{
frequencyTable[tempChar] += 1; //increment the frequency of the character in the map
}
ifs.close();
}
/*std::cout << "FT:" << std::endl;
for (auto const &element : frequencyTable)
{
std::cout << (int)element.first << ":" << element.second << std::endl;
}*/
}
void HuffmanTree::fillPriorityQueue(std::unordered_map<char, int> ft)
{
for (std::pair<char, int> element : ft)
{
char keyChar = element.first;
int valueFreq = element.second;
//PRINT("key=" + std::string(1, keyChar) + " value=" + std::to_string(valueFreq) + "\n");
HuffmanNode tempNode = HuffmanNode();
tempNode.setCharacter(keyChar);
tempNode.setFrequency(valueFreq);
nodeQueue.push(tempNode);
//PRINT("tempNode char=" + std::string(1, tempPtr->getCharacter()) + "\n");
}
}
void HuffmanTree::buildHuffmanTree(std::unordered_map<char, int> ft)
{
fillPriorityQueue(ft);
while (nodeQueue.size() > 1)
{
HuffmanNode newTempNode = HuffmanNode();
int sumFrequency = 0;
HuffmanNode temp = nodeQueue.top(); //temporarily store the top element
sumFrequency += temp.getFrequency();
newTempNode.setLeftChild(temp);
nodeQueue.pop();
temp = nodeQueue.top(); //temporarily store the top element
sumFrequency += temp.getFrequency();
newTempNode.setRightChild(temp);
nodeQueue.pop();
newTempNode.setFrequency(sumFrequency);
nodeQueue.push(newTempNode);
}
root = std::make_shared<HuffmanNode>(nodeQueue.top());
nodeQueue.pop();
//PRINT("root frequency=" + std::to_string(root->getFrequency()) + "\n");
}
void HuffmanTree::buildCodeTable(HuffmanNode *node, std::string binaryCode)
{
if ((node->getLeftChild() == nullptr) && (node->getRightChild() == nullptr))
{ //Is at a leaf node
codeTable[node->getCharacter()] = binaryCode;
return;
}
else
{
std::string leftCode = binaryCode + "0";
std::string rightCode = binaryCode + "1";
buildCodeTable(node->getLeftChild(), leftCode);
buildCodeTable(node->getRightChild(), rightCode);
}
}
void HuffmanTree::compressData(std::string inputFileName, std::string outputFileName)
{
PRINT("Running compressData()\n");
buildFrequencyTable(inputFileName); //build the frequency table (map) of all the characters in the text file
buildHuffmanTree(frequencyTable);
buildCodeTable(root.get(), ""); //Build the code table from the tree
//Now compress the ASCII text file and write it out
std::string encodedString = encodeData(inputFileName);
std::ofstream outputFile;
outputFile.open(("outputFiles/" + outputFileName + ".txt").c_str());
if (outputFile.is_open())
{
outputFile << encodedString;
outputFile.close();
}
outputFile.open(("outputFiles/" + outputFileName + ".hdr").c_str());
if (outputFile.is_open())
{
//PRINT("About to write out the code table.\n");
for (std::pair<char, std::string> element : codeTable)
{
char keyChar = element.first;
std::string valueBitString = element.second;
//PRINT(std::string(1, keyChar) + ":" + valueBitString + "\n");
outputFile << (int)keyChar << ":" << valueBitString << std::endl;
}
outputFile.close();
//int actualFileSize = (numBitsInFile / 8) + (numBitsInFile % 8 ? 1 : 0);
//PRINT("Actual file size supposed to be: " + std::to_string(actualFileSize) + " bytes\n");
}
else
{
PRINT("Could not open file.");
}
}
std::unordered_map<char, int> HuffmanTree::getFrequencyTable() const
{
return frequencyTable;
}
std::unordered_map<char, std::string> HuffmanTree::getCodeTable() const
{
return codeTable;
}
std::priority_queue<HuffmanNode> HuffmanTree::getNodeQueue() const
{
return nodeQueue;
}
HuffmanNode *HuffmanTree::getRootNode() const
{
return root.get();
}
std::string HuffmanTree::encodeData(std::string inputFileName)
{
PRINT("Running encodeData()\n");
int numCharsInFile = 0;
int numBitsInFile = 0;
std::string encodedString = "";
std::ifstream inputFile;
inputFile.open((inputFileName + ".txt").c_str());
if (inputFile.is_open())
{
char tempChar;
while (inputFile.get(tempChar))
{
numCharsInFile++; //increment the number of characters read from the file
std::string bitString = codeTable[tempChar]; //convert the character to its corresponding string binary code
numBitsInFile += bitString.length(); //record the number of individual "bits"
encodedString += bitString; //add the bitstring for the character to the full string
//PRINT(bitString + "\n");
}
inputFile.close();
}
//int actualFileSize = (numBitsInFile / 8) + (numBitsInFile % 8 ? 1 : 0);
//PRINT("Actual file size supposed to be: " + std::to_string(actualFileSize) + " bytes\n");
return encodedString;
}
void HuffmanTree::compressToBitStream(std::string inputFileName, std::string outputFileName)
{
PRINT("Running compressToBitStream()\n");
buildFrequencyTable(inputFileName); //build the frequency table (map) of all the characters in the text file
buildHuffmanTree(frequencyTable);
buildCodeTable(root.get(), ""); //Build the code table from the tree
std::string encodedString = encodeData(inputFileName);
int processedBitsCount = 0;
std::ofstream binaryFile;
binaryFile.open(("outputFiles/" + outputFileName + ".bin").c_str(), std::ios::binary | std::ios::out);
if (binaryFile.is_open())
{
int numBits = encodedString.length();
char endlChar = '\n';
binaryFile.write(reinterpret_cast<const char *>(&numBits), sizeof(numBits));
binaryFile.write(&endlChar, 1);
while (processedBitsCount < encodedString.length())
{
std::string subBits = encodedString.substr(processedBitsCount, 8);
processedBitsCount += 8;
//std::bitset<8> tempBitset(subBits);
std::bitset<8> tempBitset;
for (int i = 0; i < subBits.length(); i++)
{
if (subBits[i] == '1')
{
tempBitset[7 - i] = 1;
}
}
char tempChar = tempBitset.to_ulong();
//PRINT("writing to binary file: " + tempBitset.to_string() + "\n");
binaryFile.write((char *)&tempChar, 1);
}
binaryFile.close();
}
else
{
PRINT("Could not open the binary file to write compressed file.\n");
}
std::ofstream outputFile;
outputFile.open(("outputFiles/" + outputFileName + ".hdr").c_str());
if (outputFile.is_open())
{
//PRINT("About to write out the code table.\n");
for (std::pair<char, std::string> element : codeTable)
{
char keyChar = element.first;
std::string valueBitString = element.second;
//PRINT(std::string(1, keyChar) + ":" + valueBitString + "\n");
outputFile << (int)keyChar << ":" << valueBitString << std::endl;
}
outputFile.close();
//int actualFileSize = (numBitsInFile / 8) + (numBitsInFile % 8 ? 1 : 0);
//PRINT("Actual file size supposed to be: " + std::to_string(actualFileSize) + " bytes\n");
}
else
{
PRINT("Could not open file.");
}
//char test = std::stoi("101", nullptr, 2);
}
void HuffmanTree::decompressFromBitStream(std::string binFileName, std::string codeTableFile)
{
std::unordered_map<std::string, char> decode_code_table;
std::ifstream inputCodeFile;
inputCodeFile.open(("outputFiles/" + codeTableFile + ".hdr").c_str());
if (inputCodeFile.is_open())
{
std::string line;
std::string token;
std::vector<std::string> tokens;
getline(inputCodeFile, line);
while (!inputCodeFile.eof())
{
std::istringstream iss(line);
while (getline(iss, token, ':'))
{
tokens.push_back(token);
}
getline(inputCodeFile, line);
}
//PRINT("About to print decompress map:\n")
//insert the codes from the header file into the code table/map
for (int i = 0; i < tokens.size(); i += 2)
{
decode_code_table[tokens[i + 1]] = (char)std::stoi(tokens[i]);
}
/*for (const auto &element : decode_code_table)
{
PRINT(element.first + ":" + std::string(1, element.second) + "\n");
}*/
inputCodeFile.close();
}
else
{
PRINT("Could not open the code table header file in order to read compressed file.\n");
}
std::ifstream inputBinaryFile;
inputBinaryFile.open(("outputFiles/" + binFileName + ".bin").c_str(), std::ios::in | std::ios::binary);
if (inputBinaryFile.is_open())
{
int totNumBits;
char tempChar;
inputBinaryFile.read(reinterpret_cast<char *>(&totNumBits), sizeof(int)); // read in the total number of bits
inputBinaryFile.read(&tempChar, 1);
int totNumBytes = totNumBits / 8 + (totNumBits % 8 ? 1 : 0);
//std::bitset<8> *bitsetByteArray = new std::bitset<8>[totNumBytes];
std::string encodedString = "";
std::string tempBit = "";
std::bitset<8> tempBitsetByte;
int bitcount = 0;
for (int byteIndex = 0; byteIndex < totNumBytes; byteIndex++)
{
inputBinaryFile.read((char *)&tempBitsetByte, 1);
//PRINT("reading from binary file: " + tempBitsetByte.to_string() + "\n");
for (int i = 7; i > -1; i--)
{
tempBit = (tempBitsetByte[i] == 1 ? '1' : '0');
if (bitcount < totNumBits)
{
encodedString += tempBit;
bitcount++;
}
}
}
//PRINT("Encoded string: " + encodedString + "\n");
std::string decodedString = decodeData(decode_code_table, encodedString);
//PRINT("Decoded string: " + decodedString + "\n");
inputBinaryFile.close();
std::ofstream decompressedFile;
decompressedFile.open(("outputFiles/" + binFileName + "_decompressed.txt").c_str());
//write it out to file
if (decompressedFile.is_open())
{
decompressedFile << decodedString;
decompressedFile.close();
}
}
else
{
PRINT("Could not open the binary file to read compressed file.\n");
}
}
std::string HuffmanTree::decodeData(std::unordered_map<std::string, char> decode_code_table, std::string encodedString)
{
std::string tempCode = "";
std::string decodedString = "";
for (int i = 0; i < encodedString.length(); i++)
{
tempCode += encodedString[i];
if (decode_code_table.count(tempCode) > 0)
{
decodedString += decode_code_table[tempCode];
tempCode = "";
}
}
return decodedString;
}