Botcraft 1.21.4
Loading...
Searching...
No Matches
Compression.cpp
Go to the documentation of this file.
2
3#ifdef USE_COMPRESSION
4#include <zlib.h>
5#include <string>
6#include <cstring>
7#include <stdexcept>
8
9namespace Botcraft
10{
11 std::vector<unsigned char> Compress(const std::vector<unsigned char>& raw)
12 {
13 unsigned long size_to_compress = static_cast<unsigned long>(raw.size());
14 unsigned long compressed_size = compressBound(size_to_compress);
15
16 std::vector<unsigned char> compressed_data(compressed_size);
17 int status = compress2(compressed_data.data(), &compressed_size, raw.data(), size_to_compress, Z_DEFAULT_COMPRESSION);
18
19 if (status != Z_OK)
20 {
21 throw std::runtime_error("Error compressing packet");
22 }
23
24 compressed_data.resize(compressed_size);
25 return compressed_data;
26 }
27
28 std::vector<unsigned char> Decompress(const std::vector<unsigned char>& compressed, const int start)
29 {
30 unsigned long size_to_decompress = static_cast<unsigned long>(compressed.size() - start);
31
32 std::vector<unsigned char> decompressed_data;
33 decompressed_data.reserve(size_to_decompress);
34
35 std::vector<unsigned char> buffer(64 * 1024);
36
37 z_stream strm;
38 memset(&strm, 0, sizeof(strm));
39 strm.next_in = const_cast<unsigned char*>(compressed.data() + start);
40 strm.avail_in = size_to_decompress;
41 strm.next_out = buffer.data();
42 strm.avail_out = static_cast<unsigned int>(buffer.size());
43
44 int res = inflateInit(&strm);
45 if (res != Z_OK)
46 {
47 throw std::runtime_error("inflateInit failed: " + std::string(strm.msg));
48 }
49
50 for (;;)
51 {
52 res = inflate(&strm, Z_NO_FLUSH);
53 switch (res)
54 {
55 case Z_OK:
56 decompressed_data.insert(decompressed_data.end(), buffer.begin(), buffer.end() - strm.avail_out);
57 strm.next_out = buffer.data();
58 strm.avail_out = static_cast<unsigned int>(buffer.size());
59 if (strm.avail_in == 0)
60 {
61 inflateEnd(&strm);
62 return decompressed_data;
63 }
64 break;
65 case Z_STREAM_END:
66 decompressed_data.insert(decompressed_data.end(), buffer.begin(), buffer.end() - strm.avail_out);
67 inflateEnd(&strm);
68 return decompressed_data;
69 break;
70 default:
71 inflateEnd(&strm);
72 throw std::runtime_error("Inflate decompression failed: " + std::string(strm.msg));
73 break;
74 }
75 }
76 }
77} //Botcraft
78#endif
std::vector< unsigned char > Decompress(const std::vector< unsigned char > &compressed, const int start=0)
std::vector< unsigned char > Compress(const std::vector< unsigned char > &raw)