Chunk data decompressing (Zlib)

From wiki.vg
Jump to: navigation, search

This snippet shows how to decompress chunk data sent by 0x33 packet, using Zlib deflate.

Add the Zlib library by "#include <zlib.h>" and link to it by adding -lz to the linking stage.

To use it to decompress the chunk data, you can use the following snippet:

int len = net.recvInt();
char *in = new char[len];
net.recvByteArray(in, len);
	
//Output memory is at most 16*16*128*2.5 bytes
char *out = new char[100000];

int ret;
z_stream strm;
    
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm);

if (ret != Z_OK){
   cerr << "Zlib error: inflateInit() failed" << endl;
   return -1;
}

strm.avail_in = len;
strm.next_in = (Bytef*)in; 
strm.avail_out = 100000;
strm.next_out = (Bytef*)out; 

ret = inflate(&strm, Z_NO_FLUSH);
            
switch (ret) {
   case Z_NEED_DICT:
      ret = Z_DATA_ERROR;   
   case Z_DATA_ERROR:
   case Z_MEM_ERROR:
      cerr << "Zlib error: inflate()" << endl;
      return ret;
}               
inflateEnd(&strm);    
delete []in;
//Data is now in "out" buffer

You could also decompress the data as you get it (instead of doing it after getting the whole packet).