#include <string>
#include <stdexcept>
#include <cstring>
#include <zlib.h>
#include "Common/Log.h"
bool compress_string(const std::string& str, std::string *dest, int compressionlevel) {
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (deflateInit(&zs, compressionlevel) != Z_OK) {
ERROR_LOG(Log::IO, "deflateInit failed while compressing.");
return false;
}
zs.next_in = (Bytef*)str.data();
zs.avail_in = (uInt)str.size();
int ret;
char outbuffer[32768];
std::string outstring;
do {
zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
zs.avail_out = sizeof(outbuffer);
ret = deflate(&zs, Z_FINISH);
if (outstring.size() < zs.total_out) {
outstring.append(outbuffer,
zs.total_out - outstring.size());
}
} while (ret == Z_OK);
deflateEnd(&zs);
if (ret != Z_STREAM_END) {
ERROR_LOG(Log::IO, "Exception during zlib compression: (%d): %s", ret, zs.msg);
return false;
}
*dest = outstring;
return true;
}
bool decompress_string(const std::string& str, std::string *dest) {
if (!str.size())
return false;
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (inflateInit2(&zs, 32+MAX_WBITS) != Z_OK) {
ERROR_LOG(Log::IO, "inflateInit failed while decompressing.");
return false;
}
zs.next_in = (Bytef*)str.data();
zs.avail_in = (uInt)str.size();
int ret;
char outbuffer[32768];
std::string outstring;
do {
zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
zs.avail_out = sizeof(outbuffer);
ret = inflate(&zs, 0);
if (outstring.size() < zs.total_out) {
outstring.append(outbuffer,
zs.total_out - outstring.size());
}
} while (ret == Z_OK);
inflateEnd(&zs);
if (ret != Z_STREAM_END) {
ERROR_LOG(Log::IO, "Exception during zlib decompression: (%i) %s", ret, zs.msg);
return false;
}
*dest = outstring;
return true;
}