Botcraft 1.21.4
Loading...
Searching...
No Matches
GZip.cpp
Go to the documentation of this file.
3
4#include <stdexcept>
5
6#if USE_COMPRESSION
7#include <zlib.h>
8#endif
9
10namespace ProtocolCraft
11{
12 std::vector<unsigned char> ExtractGZip(ReadIterator& iter, size_t& length)
13 {
14#if USE_COMPRESSION
15 unsigned long size_to_decompress = static_cast<unsigned long>(length);
16
17 std::vector<unsigned char> decompressed_data(size_to_decompress);
18 decompressed_data.reserve(size_to_decompress);
19
20 z_stream strm;
21 memset(&strm, 0, sizeof(strm));
22 strm.next_in = const_cast<unsigned char*>(&(*iter));
23 strm.avail_in = size_to_decompress;
24 strm.next_out = decompressed_data.data();
25 strm.avail_out = static_cast<unsigned int>(decompressed_data.size());
26
27 int res = inflateInit2(&strm, 16 + MAX_WBITS); // 16 + MAX_WBITS to set zlib to gzip mode
28 if (res != Z_OK)
29 {
30 throw std::runtime_error("inflateInit failed: " + std::string(strm.msg));
31 }
32
33 while (true)
34 {
35 if (strm.total_out >= decompressed_data.size())
36 {
37 decompressed_data.resize(decompressed_data.size() + length / 2);
38 }
39 strm.next_out = decompressed_data.data() + strm.total_out;
40 strm.avail_out = static_cast<unsigned long>(decompressed_data.size()) - strm.total_out;
41
42 res = inflate(&strm, Z_SYNC_FLUSH);
43 if (res == Z_STREAM_END)
44 {
45 break;
46 }
47 else if (res != Z_OK)
48 {
49 inflateEnd(&strm);
50 throw std::runtime_error("Inflate decompression failed: " + std::string(strm.msg));
51 }
52 }
53
54 if (inflateEnd(&strm) != Z_OK)
55 {
56 throw std::runtime_error("inflateEnd failed: " + std::string(strm.msg));
57 }
58
59 iter += strm.total_in;
60 length -= strm.total_in;
61 decompressed_data.resize(strm.total_out);
62
63 return decompressed_data;
64#else
65 throw std::runtime_error("ProtocolCraft compiled without GZIP support");
66#endif
67 }
68}
std::vector< unsigned char > ExtractGZip(std::vector< unsigned char >::const_iterator &iter, std::size_t &length)
std::vector< unsigned char >::const_iterator ReadIterator