-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
395 lines (334 loc) · 13.2 KB
/
main.cpp
File metadata and controls
395 lines (334 loc) · 13.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
#include <bits/stdc++.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <fstream>
#include <unordered_map>
#include <chrono>
#include <filesystem>
using namespace std;
using namespace std::chrono;
namespace fs = std::filesystem;
// --------------------- PATH HANDLING ---------------------
string normalizePath(string path) {
// Trim surrounding quotes (handles both single and double)
if (!path.empty() &&
((path.front() == '"' && path.back() == '"') ||
(path.front() == '\'' && path.back() == '\''))) {
path = path.substr(1, path.size() - 2);
}
// Replace backslashes with forward slashes for consistency
std::replace(path.begin(), path.end(), '\\', '/');
// Remove trailing slashes (except if root)
while (path.size() > 1 && (path.back() == '/' || path.back() == '\\')) {
path.pop_back();
}
// Convert to absolute and canonical form
try {
fs::path p = fs::absolute(path);
p = fs::weakly_canonical(p); // safer than canonical, tolerates missing dirs
path = p.generic_string(); // uses forward slashes consistently
} catch (const fs::filesystem_error&) {
// In case path doesn’t exist or something goes wrong, keep fallback
path = fs::absolute(fs::path(path)).generic_string();
}
return path;
}
// --------------------- THREAD-SAFE QUEUE ---------------------
template<typename T>
class SafeQueue {
private:
queue<T> q;
mutex mtx;
condition_variable cv;
public:
void push(T item) {
unique_lock<mutex> lock(mtx);
q.push(item);
cv.notify_one();
}
T pop() {
unique_lock<mutex> lock(mtx);
cv.wait(lock, [this]{ return !q.empty(); });
T item = q.front();
q.pop();
return item;
}
bool empty() {
unique_lock<mutex> lock(mtx);
return q.empty();
}
};
// --------------------- HUFFMAN TREE ---------------------
struct HuffmanNode {
char ch;
int freq;
HuffmanNode *left, *right;
HuffmanNode(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
struct Compare {
bool operator()(HuffmanNode* a, HuffmanNode* b) {
return a->freq > b->freq;
}
};
// Build Huffman Tree
HuffmanNode* buildHuffmanTree(const unordered_map<char,int> &freqMap) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (auto &[c,f] : freqMap) pq.push(new HuffmanNode(c,f));
while (pq.size() > 1) {
HuffmanNode* left = pq.top(); pq.pop();
HuffmanNode* right = pq.top(); pq.pop();
HuffmanNode* parent = new HuffmanNode('\0', left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// Generate Huffman Codes
void generateCodes(HuffmanNode* root, string code, unordered_map<char,string> &codes) {
if (!root) return;
if (!root->left && !root->right) {
codes[root->ch] = code;
}
generateCodes(root->left, code+"0", codes);
generateCodes(root->right, code+"1", codes);
}
// Compress a chunk
vector<char> compressChunk(const vector<char> &chunk, unordered_map<char,string> &outCodes) {
unordered_map<char,int> freqMap;
for (char c : chunk) freqMap[c]++;
HuffmanNode* root = buildHuffmanTree(freqMap);
unordered_map<char,string> codes;
generateCodes(root, "", codes);
outCodes = codes;
string bitString = "";
for (char c : chunk) bitString += codes[c];
// Convert bit string to bytes
vector<char> compressed;
for (size_t i=0; i<bitString.size(); i+=8) {
string byteStr = bitString.substr(i, min((size_t)8, bitString.size()-i));
while (byteStr.size() < 8) byteStr += '0';
compressed.push_back(stoi(byteStr, nullptr, 2));
}
return compressed;
}
// --------------------- WORKER THREAD ---------------------
void worker(SafeQueue<pair<int, vector<char>>> &inputQueue,
SafeQueue<pair<int, pair<vector<char>, unordered_map<char,string>>>> &outputQueue) {
while (true) {
auto chunkPair = inputQueue.pop();
if (chunkPair.second.empty()) break; // termination signal
unordered_map<char,string> codes;
auto compressed = compressChunk(chunkPair.second, codes);
outputQueue.push({chunkPair.first, {compressed, codes}});
}
}
// --------------------- FILE IO ---------------------
vector<char> readFileChunk(ifstream &file, size_t chunkSize) {
vector<char> buffer(chunkSize);
file.read(buffer.data(), chunkSize);
buffer.resize(file.gcount());
return buffer;
}
// Write Huffman metadata to file
void writeMetadata(ofstream &outFile, unordered_map<char,string> &codes) {
uint32_t mapSize = codes.size();
outFile.write(reinterpret_cast<char*>(&mapSize), sizeof(mapSize));
for (auto &[c, code] : codes) {
outFile.write(&c, 1);
uint32_t codeLen = code.size();
outFile.write(reinterpret_cast<char*>(&codeLen), sizeof(codeLen));
outFile.write(code.c_str(), codeLen);
}
}
// --------------------- DECOMPRESSION ---------------------
// Read Huffman metadata from file
unordered_map<string,char> readMetadata(ifstream &inFile) {
unordered_map<string,char> codes;
uint32_t mapSize;
inFile.read(reinterpret_cast<char*>(&mapSize), sizeof(mapSize));
for (uint32_t i = 0; i < mapSize; i++) {
char c;
uint32_t codeLen;
inFile.read(&c, 1);
inFile.read(reinterpret_cast<char*>(&codeLen), sizeof(codeLen));
string code(codeLen, '\0');
inFile.read(&code[0], codeLen);
codes[code] = c;
}
return codes;
}
// Convert bytes to bit string
string bytesToBitString(const vector<char>& bytes) {
string bits;
for (unsigned char byte : bytes) {
for (int i = 7; i >= 0; i--) {
bits += ((byte >> i) & 1) ? '1' : '0';
}
}
return bits;
}
// Decompress a chunk
vector<char> decompressChunk(const vector<char>& compressedChunk, const unordered_map<string,char>& codes) {
string bitString = bytesToBitString(compressedChunk);
vector<char> decompressed;
string currentCode;
for (char bit : bitString) {
currentCode += bit;
if (codes.count(currentCode)) {
decompressed.push_back(codes.at(currentCode));
currentCode.clear();
}
}
return decompressed;
}
// Worker thread for decompression
void decompressWorker(SafeQueue<pair<int, pair<vector<char>, unordered_map<string,char>>>>& inputQueue,
SafeQueue<pair<int, vector<char>>>& outputQueue) {
while (true) {
auto chunk = inputQueue.pop();
if (chunk.second.first.empty()) break; // termination signal
auto decompressed = decompressChunk(chunk.second.first, chunk.second.second);
outputQueue.push({chunk.first, decompressed});
}
}
// --------------------- MAIN ---------------------
int main() {
string inputFile, outputFile;
string mode;
int NUM_THREADS = 4;
size_t CHUNK_SIZE = 1024 * 1024; // 1 MB default
// ------------------ TERMINAL INPUT ------------------
cout << "Enter mode (c for compress, d for decompress): ";
getline(cin, mode);
if (mode != "c" && mode != "d") {
cerr << "Invalid mode. Use 'c' for compress or 'd' for decompress.\n";
return 1;
}
cout << "Enter input file path: ";
getline(cin, inputFile);
inputFile = normalizePath(inputFile);
cout << "Enter output file path: ";
getline(cin, outputFile);
outputFile = normalizePath(outputFile);
// Validate input file exists
if (!fs::exists(inputFile)) {
cerr << "Input file does not exist.\n";
return 1;
}
// Check if input is a directory
if (fs::is_directory(inputFile)) {
cerr << "Input path is a directory. Please provide a file path.\n";
return 1;
}
cout << "Enter number of threads (default 4): ";
string threadsInput;
getline(cin, threadsInput);
if (!threadsInput.empty()) NUM_THREADS = stoi(threadsInput);
cout << "Enter chunk size in MB (default 1): ";
string chunkInput;
getline(cin, chunkInput);
if (!chunkInput.empty()) CHUNK_SIZE = stoi(chunkInput) * 1024 * 1024;
// Get input file size for statistics
uintmax_t inputFileSize = fs::file_size(inputFile);
// ------------------ VALIDATE FILES ------------------
ifstream inFile(inputFile, ios::binary);
if (!inFile.is_open()) { cerr << "Cannot open input file\n"; return 1; }
ofstream outFile(outputFile, ios::binary);
if (!outFile.is_open()) { cerr << "Cannot open output file\n"; return 1; }
// Start timing
auto startTime = high_resolution_clock::now();
if (mode == "c") {
cout << "\nStarting compression with " << NUM_THREADS
<< " threads and chunk size " << CHUNK_SIZE/(1024*1024) << " MB...\n";
SafeQueue<pair<int, vector<char>>> inputQueue;
SafeQueue<pair<int, pair<vector<char>, unordered_map<char,string>>>> outputQueue;
// ------------------ START WORKER THREADS ------------------
vector<thread> threads;
for (int i=0; i<NUM_THREADS; i++)
threads.emplace_back(worker, ref(inputQueue), ref(outputQueue));
// ------------------ READ FILE AND PUSH CHUNKS ------------------
int chunkId = 0;
while (!inFile.eof()) {
vector<char> chunk = readFileChunk(inFile, CHUNK_SIZE);
if (!chunk.empty()) {
inputQueue.push({chunkId, chunk});
cout << "Processing chunk " << chunkId << " ("
<< (float)inFile.tellg() / inputFileSize * 100 << "% complete)\n";
chunkId++;
}
}
// ------------------ TERMINATE THREADS ------------------
for (int i=0; i<NUM_THREADS; i++) inputQueue.push({-1, {}});
// ------------------ JOIN THREADS ------------------
for (auto &t : threads) t.join();
// ------------------ WRITE COMPRESSED FILE ------------------
vector<pair<vector<char>, unordered_map<char,string>>> compressedChunks(chunkId);
while (!outputQueue.empty()) {
auto [id, data] = outputQueue.pop();
compressedChunks[id] = data;
}
for (auto &[chunk, codes] : compressedChunks) {
writeMetadata(outFile, codes);
uint32_t size = chunk.size();
outFile.write(reinterpret_cast<char*>(&size), sizeof(size));
outFile.write(chunk.data(), chunk.size());
}
} else { // Decompression mode
cout << "\nStarting decompression with " << NUM_THREADS << " threads...\n";
SafeQueue<pair<int, pair<vector<char>, unordered_map<string,char>>>> inputQueue;
SafeQueue<pair<int, vector<char>>> outputQueue;
// Start decompression threads
vector<thread> threads;
for (int i=0; i<NUM_THREADS; i++)
threads.emplace_back(decompressWorker, ref(inputQueue), ref(outputQueue));
// Read and process chunks
int chunkId = 0;
while (inFile.peek() != EOF) {
// Read metadata for this chunk
auto codes = readMetadata(inFile);
// Read compressed chunk
uint32_t chunkSize;
inFile.read(reinterpret_cast<char*>(&chunkSize), sizeof(chunkSize));
vector<char> compressedChunk(chunkSize);
inFile.read(compressedChunk.data(), chunkSize);
cout << "Decompressing chunk " << chunkId << " ("
<< (float)inFile.tellg() / inputFileSize * 100 << "% complete)\n";
inputQueue.push({chunkId++, {compressedChunk, codes}});
}
// Signal threads to terminate
for (int i=0; i<NUM_THREADS; i++)
inputQueue.push({-1, {{}, {}}});
// Wait for threads to finish
for (auto &t : threads) t.join();
// Write decompressed chunks in order
vector<vector<char>> decompressedChunks(chunkId);
while (!outputQueue.empty()) {
auto [id, chunk] = outputQueue.pop();
decompressedChunks[id] = chunk;
}
for (const auto &chunk : decompressedChunks) {
outFile.write(chunk.data(), chunk.size());
}
}
// Calculate and display statistics
auto endTime = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(endTime - startTime);
uintmax_t outputFileSize = fs::file_size(outputFile);
cout << "\n-------- Operation Statistics --------\n";
cout << "Operation: " << (mode == "c" ? "Compression" : "Decompression") << "\n";
cout << "Input file size: " << inputFileSize << " bytes\n";
cout << "Output file size: " << outputFileSize << " bytes\n";
if (mode == "c") {
double ratio = (1.0 - static_cast<double>(outputFileSize) / inputFileSize) * 100;
cout << "Compression ratio: " << fixed << setprecision(2) << ratio << "%\n";
}
cout << "Processing time: " << duration.count() / 1000.0 << " seconds\n";
cout << "Threads used: " << NUM_THREADS << "\n";
cout << "Chunk size: " << CHUNK_SIZE / (1024 * 1024) << " MB\n";
cout << "----------------------------------\n\n";
cout << "Operation completed successfully! Output file: " << outputFile << endl;
return 0;
}