-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompression.cpp
More file actions
58 lines (42 loc) · 1.14 KB
/
Copy pathCompression.cpp
File metadata and controls
58 lines (42 loc) · 1.14 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
#include "Compression.h"
#include "Logger.h"
#include <zlib.h>
#include <stdexcept>
using namespace std;
string Compression::gzip(const string& data)
{
z_stream zs{};
if (deflateInit2(
&zs,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
15 + 16, // gzip header
8,
Z_DEFAULT_STRATEGY) != Z_OK)
{
Logger::error("Compression failed");
throw runtime_error("deflateInit2 failed");
}
zs.next_in = (Bytef*)data.data();
zs.avail_in = data.size();
string output;
char buffer[32768];
int ret;
do
{
zs.next_out = (Bytef*)buffer;
zs.avail_out = sizeof(buffer);
ret = deflate(&zs, Z_FINISH);
output.append(
buffer,
sizeof(buffer) - zs.avail_out);
} while(ret == Z_OK);
deflateEnd(&zs);
if(ret != Z_STREAM_END)
{
Logger::error("Compression failed");
throw runtime_error("gzip failed");
}
Logger::debug("Compression statistics: original size=" + to_string(data.size()) + ", compressed size=" + to_string(output.size()));
return output;
}