COMBINATORIAL_BLAS 1.6
 
Loading...
Searching...
No Matches
compress_string.h
Go to the documentation of this file.
1#ifndef _COMPRESS_STRING_H
2#define _COMPRESS_STRING_H
3
4#include <string>
5#include <zlib.h>
6using namespace std;
7
10string compress_string(const string& str, int compressionlevel = Z_BEST_COMPRESSION)
11{
12 z_stream zs; // z_stream is zlib's control structure
13 memset(&zs, 0, sizeof(zs));
14
15 if (deflateInit(&zs, compressionlevel) != Z_OK)
16 throw(std::runtime_error("deflateInit failed while compressing."));
17
18 zs.next_in = (Bytef*)str.data();
19 zs.avail_in = str.size(); // set the z_stream's input
20
21 int ret;
22 char outbuffer[32768];
23 std::string outstring;
24
25 // retrieve the compressed bytes blockwise
26 do {
27 zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
28 zs.avail_out = sizeof(outbuffer);
29
30 ret = deflate(&zs, Z_FINISH);
31
32 if (outstring.size() < zs.total_out) {
33 // append the block to the output string
34 outstring.append(outbuffer,
35 zs.total_out - outstring.size());
36 }
37 } while (ret == Z_OK);
38
39 deflateEnd(&zs);
40
41 if (ret != Z_STREAM_END) { // an error occurred that was not EOF
42 ostringstream oss;
43 oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
44 throw(runtime_error(oss.str()));
45 }
46
47 return outstring;
48}
49
50
52string decompress_string(const string& str)
53{
54 z_stream zs; // z_stream is zlib's control structure
55 memset(&zs, 0, sizeof(zs));
56
57 if (inflateInit(&zs) != Z_OK)
58 throw(std::runtime_error("inflateInit failed while decompressing."));
59
60 zs.next_in = (Bytef*)str.data();
61 zs.avail_in = str.size();
62
63 int ret;
64 char outbuffer[32768];
65 std::string outstring;
66
67 // get the decompressed bytes blockwise using repeated calls to inflate
68 do {
69 zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
70 zs.avail_out = sizeof(outbuffer);
71
72 ret = inflate(&zs, 0);
73
74 if (outstring.size() < zs.total_out) {
75 outstring.append(outbuffer,
76 zs.total_out - outstring.size());
77 }
78
79 } while (ret == Z_OK);
80
81 inflateEnd(&zs);
82
83 if (ret != Z_STREAM_END) { // an error occurred that was not EOF
84 std::ostringstream oss;
85 oss << "Exception during zlib decompression: (" << ret << ") "
86 << zs.msg;
87 throw(std::runtime_error(oss.str()));
88 }
89
90 return outstring;
91}
92
93#endif
string decompress_string(const string &str)
string compress_string(const string &str, int compressionlevel=Z_BEST_COMPRESSION)