Ed Tanous | 911ac31 | 2017-08-15 09:37:42 -0700 | [diff] [blame] | 1 | #pragma once |
| 2 | |
| 3 | #include <zlib.h> |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 4 | |
Ed Tanous | 911ac31 | 2017-08-15 09:37:42 -0700 | [diff] [blame] | 5 | #include <cstring> |
| 6 | #include <string> |
| 7 | |
Ed Tanous | 55c7b7a | 2018-05-22 15:27:24 -0700 | [diff] [blame] | 8 | inline bool gzipInflate(const std::string& compressedBytes, |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 9 | std::string& uncompressedBytes) |
| 10 | { |
| 11 | if (compressedBytes.empty()) |
| 12 | { |
| 13 | uncompressedBytes = compressedBytes; |
| 14 | return true; |
Ed Tanous | 911ac31 | 2017-08-15 09:37:42 -0700 | [diff] [blame] | 15 | } |
| 16 | |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 17 | uncompressedBytes.clear(); |
Ed Tanous | 911ac31 | 2017-08-15 09:37:42 -0700 | [diff] [blame] | 18 | |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 19 | unsigned half_length = compressedBytes.size() / 2; |
| 20 | |
| 21 | z_stream strm{}; |
| 22 | |
| 23 | // The following line is nolint because we're declaring away constness. |
| 24 | // It's not clear why the input buffers on zlib aren't const, so this is a |
| 25 | // bit of a cheat for the moment |
| 26 | strm.next_in = (Bytef*)compressedBytes.data(); // NOLINT |
| 27 | strm.avail_in = compressedBytes.size(); |
| 28 | strm.total_out = 0; |
| 29 | strm.zalloc = Z_NULL; |
| 30 | strm.zfree = Z_NULL; |
| 31 | |
| 32 | bool done = false; |
| 33 | |
| 34 | if (inflateInit2(&strm, (16 + MAX_WBITS)) != Z_OK) |
| 35 | { |
| 36 | return false; |
Ed Tanous | 911ac31 | 2017-08-15 09:37:42 -0700 | [diff] [blame] | 37 | } |
Ed Tanous | 911ac31 | 2017-08-15 09:37:42 -0700 | [diff] [blame] | 38 | |
Ed Tanous | 1abe55e | 2018-09-05 08:30:59 -0700 | [diff] [blame] | 39 | while (!done) |
| 40 | { |
| 41 | // If our output buffer is too small |
| 42 | if (strm.total_out >= uncompressedBytes.size()) |
| 43 | { |
| 44 | uncompressedBytes.resize(uncompressedBytes.size() + half_length); |
| 45 | } |
| 46 | |
| 47 | strm.next_out = |
| 48 | (Bytef*)(uncompressedBytes.data() + strm.total_out); // NOLINT |
| 49 | strm.avail_out = |
| 50 | ((uLong)uncompressedBytes.size() - strm.total_out); // NOLINT |
| 51 | |
| 52 | // Inflate another chunk. |
| 53 | int err = inflate(&strm, Z_SYNC_FLUSH); |
| 54 | if (err == Z_STREAM_END) |
| 55 | { |
| 56 | done = true; |
| 57 | } |
| 58 | else if (err != Z_OK) |
| 59 | { |
| 60 | break; |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | return inflateEnd(&strm) == Z_OK; |
Ed Tanous | 911ac31 | 2017-08-15 09:37:42 -0700 | [diff] [blame] | 65 | } |