Here zLib inflates a routine that takes a buffer in memory and decompresses into the provided output buffer. This is a one-shot function because it tries to inflate the entire input buffer at the same time and assumes that you have given it enough space to fit all of this. It is also possible to write a multi-shot function that dynamically increases the destination buffer as needed.
int inflate(const void *src, int srcLen, void *dst, int dstLen) { z_stream strm = {0}; strm.total_in = strm.avail_in = srcLen; strm.total_out = strm.avail_out = dstLen; strm.next_in = (Bytef *) src; strm.next_out = (Bytef *) dst; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; int err = -1; int ret = -1; err = inflateInit2(&strm, (15 + 32)); //15 window bits, and the +32 tells zlib to to detect if using gzip or zlib if (err == Z_OK) { err = inflate(&strm, Z_FINISH); if (err == Z_STREAM_END) { ret = strm.total_out; } else { inflateEnd(&strm); return err; } } else { inflateEnd(&strm); return err; } inflateEnd(&strm); return ret; }
Explanation:
src : source buffer containing compressed (gzip or zlib) data
srcLen : source buffer length
dst : destination buffer to write output to
dstLen : destination buffer length
Return Values:
Z_BUF_ERROR: if dstLen is not large enough to match the inflated data
Z_MEM_ERROR: if there is not enough memory to perform decompression Z_DATA_ERROR: if the input data was damaged,
Otherwise, the return value is the number of bytes written to dst.
source share