-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncoder.cpp
54 lines (41 loc) · 1.72 KB
/
Encoder.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
#include "Encoder.h"
Encoder::~Encoder(){
if (inputFile.is_open()) inputFile.close();
}
void Encoder::encode(const std::string& inputFilePath, const std::string& outputFilePath) {
inputFile.open(inputFilePath, std::ios::binary);
if (!inputFile) {
throw std::runtime_error("Failed to open input file: " + inputFilePath);
}
writer.initWriter(outputFilePath, inputFilePath);
char nextChar; //next
std::string currentStr =""; //curent sequence we are looking at
while (inputFile.get(nextChar)) {
currentStr += nextChar;
if (!dictionary.includes(currentStr)) {
// without the last char
currentStr = currentStr.substr(0, currentStr.length() - 1);
//output
// represents the encoded representation of the previous sequence.
packCode(dictionary.getCode(currentStr));
//dict entry
// add to dictionary including the current character
dictionary.addCode(currentStr+nextChar);
currentStr = nextChar; //currentStr = last char added
if (dictionary.isFull()) { //reset dictionary
dictionary.clear();
currentStr = "";
}
}
}// Process the last character sequence with prev str now
if (!currentStr.empty()) {
packCode(dictionary.getCode(currentStr));
}
writer.writeLast();
writer.closeStream(); // Close the output file
inputFile.close(); // Close the input file
};
void Encoder::packCode(uint16_t code) {
// pass the current bit-size of code (9-..)
writer.packBits(code, dictionary.getCurrentSize());
}