blob: be138092369109679f07863bd4d9a74dcd1e8677 [file] [log] [blame]
Ed Tanous911ac312017-08-15 09:37:42 -07001#pragma once
2
3#include <zlib.h>
Ed Tanous1abe55e2018-09-05 08:30:59 -07004
Ed Tanous911ac312017-08-15 09:37:42 -07005#include <cstring>
6#include <string>
7
Ed Tanous55c7b7a2018-05-22 15:27:24 -07008inline bool gzipInflate(const std::string& compressedBytes,
Ed Tanous1abe55e2018-09-05 08:30:59 -07009 std::string& uncompressedBytes)
10{
11 if (compressedBytes.empty())
12 {
13 uncompressedBytes = compressedBytes;
14 return true;
Ed Tanous911ac312017-08-15 09:37:42 -070015 }
16
Ed Tanous1abe55e2018-09-05 08:30:59 -070017 uncompressedBytes.clear();
Ed Tanous911ac312017-08-15 09:37:42 -070018
Ed Tanous1abe55e2018-09-05 08:30:59 -070019 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 Tanous911ac312017-08-15 09:37:42 -070037 }
Ed Tanous911ac312017-08-15 09:37:42 -070038
Ed Tanous1abe55e2018-09-05 08:30:59 -070039 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 Tanous911ac312017-08-15 09:37:42 -070065}