Skip to content

Instantly share code, notes, and snippets.

@qi7chen
Last active December 19, 2015 13:38
Show Gist options
  • Select an option

  • Save qi7chen/5963255 to your computer and use it in GitHub Desktop.

Select an option

Save qi7chen/5963255 to your computer and use it in GitHub Desktop.
zlib api usage
// The maximum size needed for the compressed output.
int GetMaxCompressedLen(int souceLen)
{
// round up any fraction of a block
int n16kBlocks = (souceLen + 16383) / 16384;
return ( souceLen + 6 + (n16kBlocks * 5) );
}
int ZlibCompress(const BYTE* input, int inlen, BYTE* output, int outlen)
{
assert(input && output);
/* allocate deflate state */
z_stream strm;
strm.total_in = strm.avail_in = inlen;
strm.total_out = strm.avail_out = outlen;
strm.next_in = (Bytef*)input;
strm.next_out = (Bytef*)output;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
int ret = -1;
int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
if (err == Z_OK)
{
err = deflate(&strm, Z_FINISH);
if (err == Z_STREAM_END)
{
ret = strm.total_out;
}
}
deflateEnd(&strm);
return ret;
}
int ZlibUnCompress(const BYTE* input, int inlen, BYTE* output, int outlen)
{
assert(input && output);
z_stream strm;
strm.total_in = strm.avail_in = inlen;
strm.total_out = strm.avail_out = outlen;
strm.next_in = (Bytef*)input;
strm.next_out = (Bytef*)output;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
int ret = -1;
int err = inflateInit(&strm);
if (err == Z_OK)
{
err = inflate(&strm, Z_FINISH);
if (err == Z_STREAM_END)
{
ret = strm.total_out;
}
}
inflateEnd(&strm);
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
FILE* fp = fopen("main.cpp", "r");
if (fp == NULL)
{
return 1;
}
const int MAX_BUF_SIZE = 1024 * 32;
BYTE buf[MAX_BUF_SIZE];
int bytes = fread(buf, sizeof(char), MAX_BUF_SIZE, fp);
if (bytes <= 0)
{
fclose(fp);
return 1;
}
fclose(fp);
int comp_len = GetMaxCompressedLen(bytes);
BYTE* compbuffer = new BYTE[comp_len];
int complen = ZlibCompress(buf, bytes, compbuffer, comp_len);
if (complen < 0)
{
delete compbuffer;
return 1;
}
BYTE* uncompbuf = new BYTE[bytes];
int uncomplen = ZlibUnCompress(compbuffer, complen, uncompbuf, bytes);
int result = memcmp(buf, uncompbuf, bytes);
delete uncompbuf;
if (result == 0)
{
printf("OK.\n");
}
else
{
printf("Failed.\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment