// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute // SPDX-License-Identifier: GPL-3.0-only #include "JFJochGzip.h" #include #include std::string Gzip(const std::string &text) { z_stream s{}; // 15 + 16: the largest window, with a gzip header and trailer if (deflateInit2(&s, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY) != Z_OK) throw std::runtime_error("cannot start zlib"); std::string out(deflateBound(&s, text.size()), '\0'); s.next_in = reinterpret_cast(const_cast(text.data())); s.avail_in = static_cast(text.size()); s.next_out = reinterpret_cast(out.data()); s.avail_out = static_cast(out.size()); const int ret = deflate(&s, Z_FINISH); out.resize(s.total_out); deflateEnd(&s); if (ret != Z_STREAM_END) throw std::runtime_error("gzip compression failed"); return out; } std::string Gunzip(const uint8_t *data, size_t size) { z_stream s{}; if (inflateInit2(&s, 15 + 32) != Z_OK) throw std::runtime_error("cannot start zlib"); std::string out; char buf[1 << 16]; s.next_in = const_cast(data); s.avail_in = static_cast(size); int ret = Z_OK; while (ret != Z_STREAM_END || s.avail_in > 0) { if (ret == Z_STREAM_END) inflateReset(&s); s.next_out = reinterpret_cast(buf); s.avail_out = sizeof buf; ret = inflate(&s, Z_NO_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { inflateEnd(&s); throw std::runtime_error("the gzip stream is damaged"); } out.append(buf, sizeof buf - s.avail_out); if (ret == Z_OK && s.avail_in == 0 && s.avail_out != 0) { inflateEnd(&s); throw std::runtime_error("the gzip stream is cut short"); } } inflateEnd(&s); return out; }