compression.c (934B)
1 #include <stdlib.h> 2 3 #include "zlib.h" 4 5 char* zlib_compress(char* buf, size_t* bufsize) { 6 size_t clen = compressBound(*bufsize); 7 char* cbuf = malloc(clen); 8 compress((Bytef*)cbuf, &clen, (Bytef*)buf, *bufsize); 9 *bufsize = clen; 10 return cbuf; 11 } 12 13 char* gzip_compress(char* buf, size_t* bufsize) { 14 size_t clen = compressBound(*bufsize); 15 char* cbuf = malloc(clen); 16 z_stream zs; 17 zs.zalloc = Z_NULL; 18 zs.zfree = Z_NULL; 19 zs.opaque = Z_NULL; 20 zs.avail_in = (uInt)*bufsize; 21 zs.next_in = (Bytef *)buf; 22 zs.avail_out = (uInt)clen; 23 zs.next_out = (Bytef *)cbuf; 24 *bufsize = clen; 25 26 // "Add 16 to windowBits to write a simple gzip header and trailer 27 // around the compressed data instead of a zlib wrapper" 28 deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 29 15 | 16, 8, Z_DEFAULT_STRATEGY); 30 deflate(&zs, Z_FINISH); 31 deflateEnd(&zs); 32 33 return cbuf; 34 }