10string compress_string(
const string& str,
int compressionlevel = Z_BEST_COMPRESSION)
13 memset(&zs, 0,
sizeof(zs));
15 if (deflateInit(&zs, compressionlevel) != Z_OK)
16 throw(std::runtime_error(
"deflateInit failed while compressing."));
18 zs.next_in = (Bytef*)str.data();
19 zs.avail_in = str.size();
22 char outbuffer[32768];
23 std::string outstring;
27 zs.next_out =
reinterpret_cast<Bytef*
>(outbuffer);
28 zs.avail_out =
sizeof(outbuffer);
30 ret = deflate(&zs, Z_FINISH);
32 if (outstring.size() < zs.total_out) {
34 outstring.append(outbuffer,
35 zs.total_out - outstring.size());
37 }
while (ret == Z_OK);
41 if (ret != Z_STREAM_END) {
43 oss <<
"Exception during zlib compression: (" << ret <<
") " << zs.msg;
44 throw(runtime_error(oss.str()));
55 memset(&zs, 0,
sizeof(zs));
57 if (inflateInit(&zs) != Z_OK)
58 throw(std::runtime_error(
"inflateInit failed while decompressing."));
60 zs.next_in = (Bytef*)str.data();
61 zs.avail_in = str.size();
64 char outbuffer[32768];
65 std::string outstring;
69 zs.next_out =
reinterpret_cast<Bytef*
>(outbuffer);
70 zs.avail_out =
sizeof(outbuffer);
72 ret = inflate(&zs, 0);
74 if (outstring.size() < zs.total_out) {
75 outstring.append(outbuffer,
76 zs.total_out - outstring.size());
79 }
while (ret == Z_OK);
83 if (ret != Z_STREAM_END) {
84 std::ostringstream oss;
85 oss <<
"Exception during zlib decompression: (" << ret <<
") "
87 throw(std::runtime_error(oss.str()));