Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/Data/Encoding/Compression.cpp
3187 views
1
// Little utility functions for data compression.
2
// Taken from http://panthema.net/2007/0328-ZLibString.html
3
4
5
#include <string>
6
#include <stdexcept>
7
#include <cstring>
8
9
#include <zlib.h>
10
11
#include "Common/Log.h"
12
13
/** Compress a STL string using zlib with given compression level and return
14
* the binary data. */
15
bool compress_string(const std::string& str, std::string *dest, int compressionlevel) {
16
z_stream zs; // z_stream is zlib's control structure
17
memset(&zs, 0, sizeof(zs));
18
19
if (deflateInit(&zs, compressionlevel) != Z_OK) {
20
ERROR_LOG(Log::IO, "deflateInit failed while compressing.");
21
return false;
22
}
23
24
zs.next_in = (Bytef*)str.data();
25
zs.avail_in = (uInt)str.size(); // set the z_stream's input
26
27
int ret;
28
char outbuffer[32768];
29
std::string outstring;
30
31
// retrieve the compressed bytes blockwise
32
do {
33
zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
34
zs.avail_out = sizeof(outbuffer);
35
36
ret = deflate(&zs, Z_FINISH);
37
38
if (outstring.size() < zs.total_out) {
39
// append the block to the output string
40
outstring.append(outbuffer,
41
zs.total_out - outstring.size());
42
}
43
} while (ret == Z_OK);
44
45
deflateEnd(&zs);
46
47
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
48
ERROR_LOG(Log::IO, "Exception during zlib compression: (%d): %s", ret, zs.msg);
49
return false;
50
}
51
52
*dest = outstring;
53
return true;
54
}
55
56
/** Decompress an STL string using zlib and return the original data. */
57
bool decompress_string(const std::string& str, std::string *dest) {
58
if (!str.size())
59
return false;
60
61
z_stream zs; // z_stream is zlib's control structure
62
memset(&zs, 0, sizeof(zs));
63
64
// modification by hrydgard: inflateInit2, 16+MAXWBITS makes it read gzip data too
65
if (inflateInit2(&zs, 32+MAX_WBITS) != Z_OK) {
66
ERROR_LOG(Log::IO, "inflateInit failed while decompressing.");
67
return false;
68
}
69
70
zs.next_in = (Bytef*)str.data();
71
zs.avail_in = (uInt)str.size();
72
73
int ret;
74
char outbuffer[32768];
75
std::string outstring;
76
77
// get the decompressed bytes blockwise using repeated calls to inflate
78
do {
79
zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
80
zs.avail_out = sizeof(outbuffer);
81
82
ret = inflate(&zs, 0);
83
84
if (outstring.size() < zs.total_out) {
85
outstring.append(outbuffer,
86
zs.total_out - outstring.size());
87
}
88
89
} while (ret == Z_OK);
90
91
inflateEnd(&zs);
92
93
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
94
ERROR_LOG(Log::IO, "Exception during zlib decompression: (%i) %s", ret, zs.msg);
95
return false;
96
}
97
98
*dest = outstring;
99
return true;
100
}
101
102