-
Notifications
You must be signed in to change notification settings - Fork 0
/
huffman.cpp
618 lines (483 loc) · 13.6 KB
/
huffman.cpp
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <queue>
#include <windows.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int characterMax = 256 + 5;
const int nodeMax = characterMax * 2 + 50;
enum opTypeEnum {
COMPRESSION = 1,
DECOMPRESSION
};
struct nodeType {
ull occ;
char ch;
int st,dr;
nodeType(ull _occ = 0,char _ch = '\0',int _st = 0,int _dr = 0) {
occ = _occ;
ch = _ch;
st = _st;
dr = _dr;
}
};
class dataCompressionClass {
private:
ifstream in;
string *code;
ofstream *out;
char currentCharacter;
ll codeIndex,fileEnd;
bool nextBit;
public:
dataCompressionClass(char* name,string* _code,ofstream *_out);
~dataCompressionClass();
void writeData();
private:
bool getNext8Bit(char& ch);
bool checkNextBit();
char getNextBit();
};
struct trieNode {
char ch;
trieNode *st,*dr;
trieNode(char _ch = 0,trieNode* _st = 0,trieNode* _dr = 0): ch(_ch), st(_st), dr(_dr) {}
};
class dataDecompressionClass {
private:
ifstream *in;
ofstream out;
const ull nrBits;
int currentIndex;
char current8Bit;
trieNode * const root;
trieNode *currentNode;
bool fail;
public:
dataDecompressionClass(ifstream *_in,char* outputFileName,ull _nrBits,trieNode* _root);
~dataDecompressionClass();
void writeData();
bool hasFailed();
private:
char getNextBit();
char walkTrie(char);
};
bool checkInput(int,char**,opTypeEnum&);
void printMessage(char*);
void buildFreq(char*,ull*);
void getNodes(nodeType*,int&,ull*);
void buildHuffman(nodeType*,int&,ull&);
void dfs(int,string,nodeType*,string*);
void writeI64(ull,ofstream&);
void writeI8(char,ofstream&);
void writeInfo(nodeType*,int,string*,ofstream&);
void compress(char*,char*);
void decompress(char*,char*);
ull readI64(ifstream&);
char readI8(ifstream&);
void add(trieNode*,char,const string&,int);
int main(int argc,char **argv)
{
printf("\n");
opTypeEnum operationType;
if (checkInput(argc,argv,operationType) == false) {
printMessage(argv[0]);
return 0;
}
if (operationType == COMPRESSION) {
compress(argv[2],argv[3]);
}
else {
decompress(argv[2],argv[3]);
}
return 0;
}
bool checkInput(int argc,char** argv,opTypeEnum& operationType) {
if (argc != 4) {
printf("Invalid number of arguments!\n");
return false;
}
if (argv[1][1] != '\0' || !(argv[1][0] == '1' || argv[1][0] == '2')) {
printf("Invalid operation!\n");
return false;
}
if (argv[1][0] == '1') {
operationType = COMPRESSION;
}
else {
operationType = DECOMPRESSION;
}
if (operationType == COMPRESSION) {
int sz = strlen(argv[2]);
if (strcmp(argv[2] + sz - 4,".txt") != 0) {
printf("Invalid input file type!\n");
return false;
}
FILE *f = fopen(argv[2],"r");
if (f == NULL) {
printf("Input file doesn't exist!\n");
fclose(f);
return false;
}
fseek(f,0,SEEK_END);
int len = ftell(f);
if (len == 0) {
printf("Input file is empty!\n");
fclose(f);
return false;
}
fclose(f);
sz = strlen(argv[3]);
if (strcmp(argv[3] + sz - 4,".huf") != 0) {
printf("Invalid output file type!\n");
return false;
}
f = fopen(argv[3],"r");
/*
if (f != NULL) {
printf("File already exists!\n");
fclose(f);
return false;
}
//*/
fclose(f);
}
else {
int sz = strlen(argv[2]);
if (strcmp(argv[2] + sz - 4,".huf") != 0) {
printf("Invalid input file type!\n");
return false;
}
FILE *f = fopen(argv[2],"r");
if (f == NULL) {
printf("Input file doesn't exist!\n");
fclose(f);
return false;
}
fseek(f,0,SEEK_END);
int len = ftell(f);
if (len == 0) {
printf("Input file is empty!\n");
fclose(f);
return false;
}
fclose(f);
sz = strlen(argv[3]);
if (strcmp(argv[3] + sz - 4,".txt") != 0) {
printf("Invalid output file type!\n");
return false;
}
f = fopen(argv[3],"r");
/*
if (f != NULL) {
printf("File already exists!\n");
fclose(f);
return false;
}
fclose(f);
//*/
}
return true;
}
void printMessage(char *name) {
printf("Usage: %s <operation type> <if> <of>\n\n",name);
printf("- operation type = 1 if compression is desired;\n");
printf("<if> - full name of a local .txt file that is to be compressed.\n");
printf("<of> - full name of a local .huf file to store output.\n");
printf("E.g.: %s 1 localInput.txt localOutput.huf\n\n",name);
printf("- operation type = 2 if decompression is desired;\n");
printf("<if> - full name of a local .huf file that is to be decompressed.\n");
printf("<of> - full name of a local .txt file to store output.\n");
printf("E.g.: %s 1 localInput.huf localOutput.txt\n\n",name);
}
void compress(char* inputFileName,char* outputFileName) {
ull freq[characterMax] = {};
nodeType node[nodeMax];
int nrNodes;
string code[characterMax];
buildFreq(inputFileName,freq);
getNodes(node,nrNodes,freq);
int lastLeafIndex = nrNodes;
ull textLength;
buildHuffman(node,nrNodes,textLength);
int rootIndex = nrNodes;
dfs(rootIndex,"",node,code);
ofstream out(outputFileName,ios::binary);
writeInfo(node,lastLeafIndex,code,out);
writeI64(textLength,out);
dataCompressionClass writerObject(inputFileName,code,&out);
writerObject.writeData();
printf("Compression was successful!\n");
}
void buildFreq(char* fileName,ull* freq) {
FILE *in = fopen(fileName,"r");
char c;
while (true) {
c = getc(in);
if (feof(in) != 0) {
break;
}
++freq[c];
}
}
void getNodes(nodeType* node,int& nrNodes,ull* freq) {
nrNodes = 0;
for (int i=0;i <= 127;++i) {
if (freq[i] == 0) {
continue;
}
node[++nrNodes] = nodeType(freq[i],(char)i);
}
if (nrNodes == 1) {
node[++nrNodes] = nodeType(0,'\0');
}
}
void buildHuffman(nodeType* node,int& nrNodes,ull& textLength) {
class comp {
private:
nodeType *arr;
public:
comp(nodeType* _arr): arr(_arr) {}
bool operator() (const int idx1,const int idx2) {
return arr[idx1].occ > arr[idx2].occ;
}
};
priority_queue< int,vector<int>,comp > pq(node);
for (int i=1;i <= nrNodes;++i) {
pq.push(i);
}
textLength = 0;
while (pq.size() > 1) {
int st = pq.top(); pq.pop();
int dr = pq.top(); pq.pop();
node[++nrNodes] = nodeType(node[st].occ + node[dr].occ,'\0',st,dr);
textLength += node[nrNodes].occ;
pq.push(nrNodes);
}
}
void dfs(int nodeIndex,string nodeCode,nodeType* node,string* code) {
if (node[nodeIndex].st == 0) {
code[ node[nodeIndex].ch ] = nodeCode;
return;
}
dfs(node[nodeIndex].st,nodeCode + "0",node,code);
dfs(node[nodeIndex].dr,nodeCode + "1",node,code);
}
void writeI64(ull number,ofstream& out) {
char aux[10] = {};
ull mask = (1<<8) - 1;
int shiftAmount = 56;
for (int i=0;i < 8;++i) {
aux[i] = (number>>shiftAmount) & mask;
shiftAmount -= 8;
}
out.write(aux,8);
}
void writeI8(char number,ofstream& out) {
out.write(&number,1);
}
void writeInfo(nodeType* node,int lastLeafIndex,string* code,ofstream& out) {
writeI64(lastLeafIndex,out);
for (int i=1;i <= lastLeafIndex;++i) {
char ch = node[i].ch;
char len = (char)code[ch].size();
writeI8(ch,out);
writeI8(len,out);
string tempCode = code[ch];
while (tempCode.size() % 8 != 0) {
tempCode += "0";
}
int numberCode = 0;
for (int j=0;j < (int)tempCode.size();++j) {
numberCode <<= 1;
numberCode += tempCode[j] - '0';
if ((j+1) % 8 == 0) {
writeI8(numberCode,out);
}
}
}
}
dataCompressionClass::dataCompressionClass(char* name,string* _code,ofstream *_out) {
in.open(name);
in.seekg(0,in.end);
fileEnd = in.tellg();
in.seekg(0,in.beg);
code = _code;
out = _out;
currentCharacter = in.get();
codeIndex = 0;
nextBit = true;
}
dataCompressionClass::~dataCompressionClass() {
in.close();
}
void dataCompressionClass::writeData() {
while (true) {
char ch;
if (getNext8Bit(ch) == false) {
break;
}
writeI8(ch,*out);
}
}
bool dataCompressionClass::getNext8Bit(char& ch) {
if (checkNextBit() == false) {
return false;
}
ch = 0;
int nr = 0;
while (checkNextBit() && nr < 8) {
ch <<= 1;
char aux = getNextBit();
ch += aux;
++nr;
}
while (nr < 8) {
ch <<= 1;
++nr;
}
return true;
}
bool dataCompressionClass::checkNextBit() {
return nextBit;
}
char dataCompressionClass::getNextBit() {
char ret = code[currentCharacter][codeIndex++] - '0';
if (codeIndex == code[currentCharacter].size()) {
if (in.tellg() == fileEnd) {
nextBit = false;
}
else {
currentCharacter = in.get();
codeIndex = 0;
}
}
return ret;
}
void decompress(char* inputFileName,char* outputFileName) {
ifstream in(inputFileName,ios::binary);
trieNode root;
ull nrChar = readI64(in);
for (ull i=0;i < nrChar;++i) {
char currentCharacter = readI8(in);
unsigned char codeLength = readI8(in);
int inputLength = codeLength;
while (inputLength % 8 != 0) {
++inputLength;
}
int byteNumber = inputLength / 8;
char aux[300];
in.read(aux,byteNumber);
string code = "";
for (int idx=0;idx < codeLength;++idx) {
int i = idx/8, j = idx - 8*i;
j = 7-j;
char temp = (aux[i]>>j) & 1;
code += temp + '0';
}
add(&root,currentCharacter,code,0);
}
ull nrBits = readI64(in);
dataDecompressionClass writerObject(&in,outputFileName,nrBits,&root);
writerObject.writeData();
if (writerObject.hasFailed()) {
printf("Failed to compress!\n");
}
else {
printf("Data decompression successful!\n");
}
}
ull readI64(ifstream& in) {
char aux[10];
in.read(aux,8);
ull ret = 0;
for (int i=0;i < 8;++i) {
ret <<= 8;
ret += (unsigned char)aux[i];
}
return ret;
}
char readI8(ifstream& in) {
char ret;
in.read(&ret,1);
return ret;
}
void add(trieNode* node,char character,const string& code,int pos) {
if ((int)code.size() == pos) {
node->ch = character;
return;
}
if (code[pos] == '0') {
if (node->st == NULL) {
node->st = new trieNode;
}
add(node->st,character,code,pos+1);
}
else {
if (node->dr == NULL) {
node->dr = new trieNode;
}
add(node->dr,character,code,pos+1);
}
}
dataDecompressionClass::dataDecompressionClass(ifstream *_in,char* outputFileName,ull _nrBits,trieNode* _root): nrBits(_nrBits),root(_root) {
in = _in;
out.open(outputFileName);
currentNode = root;
in->read(¤t8Bit,1);
currentIndex = 0;
fail = false;
}
dataDecompressionClass::~dataDecompressionClass() {
out.close();
}
bool dataDecompressionClass::hasFailed() {
return fail;
}
void dataDecompressionClass::writeData() {
for (ull i=0;i < nrBits;++i) {
char bit = getNextBit();
char outCh = walkTrie(bit);
if (fail) {
return;
}
if (outCh != '\0') {
out<<outCh;
}
}
}
char dataDecompressionClass::getNextBit() {
if (currentIndex == 8) {
currentIndex = 0;
in->read(¤t8Bit,1);
}
char bit = ((unsigned char)current8Bit>>(7-currentIndex)) & 1;
bit += '0';
++currentIndex;
return bit;
}
char dataDecompressionClass::walkTrie(char bit) {
if (bit == '0') {
if (currentNode->st == NULL) {
printf("Error going left on trie while decompressing. Input file could be corrupt.\n");
fail = true;
return '\0';
}
currentNode = currentNode->st;
}
else {
if (currentNode->dr == NULL) {
printf("Error going right on trie while decompressing. Input file could be corrupt.\n");
fail = true;
return '\0';
}
currentNode = currentNode->dr;
}
char ret = currentNode->ch;
if (ret != '\0') {
currentNode = root;
}
return ret;
}