26 template <
typename InputType>
void compress(InputType&
output,
const char*
data, std::size_t size)
const
31 if (size > std::numeric_limits<unsigned int>::max())
33 throw std::runtime_error(
"size arg is too large to fit into unsigned int type");
38 throw std::runtime_error(
"size may use more memory than intended when decompressing");
42 deflate_s.zalloc = Z_NULL;
43 deflate_s.zfree = Z_NULL;
44 deflate_s.opaque = Z_NULL;
45 deflate_s.avail_in = 0;
46 deflate_s.next_in = Z_NULL;
56 constexpr int window_bits = 15 + 16;
58 constexpr int mem_level = 8;
64#pragma GCC diagnostic push
65#pragma GCC diagnostic ignored "-Wold-style-cast"
66 if (deflateInit2(&deflate_s,
level_, Z_DEFLATED, window_bits, mem_level, Z_DEFAULT_STRATEGY) != Z_OK)
68 throw std::runtime_error(
"deflate init failed");
70#pragma GCC diagnostic pop
72 deflate_s.next_in =
reinterpret_cast<z_const Bytef*
>(
data);
73 deflate_s.avail_in =
static_cast<unsigned int>(size);
75 std::size_t size_compressed = 0;
78 size_t increase = size / 2 + 1024;
79 if (
output.size() < (size_compressed + increase))
81 output.resize(size_compressed + increase);
85 deflate_s.avail_out =
static_cast<unsigned int>(increase);
86 deflate_s.next_out =
reinterpret_cast<Bytef*
>((&
output[0] + size_compressed));
91 deflate(&deflate_s, Z_FINISH);
92 size_compressed += (increase - deflate_s.avail_out);
93 }
while (deflate_s.avail_out == 0);
95 deflateEnd(&deflate_s);
96 output.resize(size_compressed);