11 std::vector<unsigned char>
Compress(
const std::vector<unsigned char>& raw)
13 unsigned long size_to_compress =
static_cast<unsigned long>(raw.size());
14 unsigned long compressed_size = compressBound(size_to_compress);
16 std::vector<unsigned char> compressed_data(compressed_size);
17 int status = compress2(compressed_data.data(), &compressed_size, raw.data(), size_to_compress, Z_DEFAULT_COMPRESSION);
21 throw std::runtime_error(
"Error compressing packet");
24 compressed_data.resize(compressed_size);
25 return compressed_data;
28 std::vector<unsigned char>
Decompress(
const std::vector<unsigned char>& compressed,
const int start)
30 unsigned long size_to_decompress =
static_cast<unsigned long>(compressed.size() - start);
32 std::vector<unsigned char> decompressed_data;
33 decompressed_data.reserve(size_to_decompress);
35 std::vector<unsigned char> buffer(64 * 1024);
38 memset(&strm, 0,
sizeof(strm));
39 strm.next_in =
const_cast<unsigned char*
>(compressed.data() + start);
40 strm.avail_in = size_to_decompress;
41 strm.next_out = buffer.data();
42 strm.avail_out =
static_cast<unsigned int>(buffer.size());
44 int res = inflateInit(&strm);
47 throw std::runtime_error(
"inflateInit failed: " + std::string(strm.msg));
52 res = inflate(&strm, Z_NO_FLUSH);
56 decompressed_data.insert(decompressed_data.end(), buffer.begin(), buffer.end() - strm.avail_out);
57 strm.next_out = buffer.data();
58 strm.avail_out =
static_cast<unsigned int>(buffer.size());
59 if (strm.avail_in == 0)
62 return decompressed_data;
66 decompressed_data.insert(decompressed_data.end(), buffer.begin(), buffer.end() - strm.avail_out);
68 return decompressed_data;
72 throw std::runtime_error(
"Inflate decompression failed: " + std::string(strm.msg));