繁体   English   中英

使用zlib将GZIP压缩到缓冲区中

[英]GZIP compression using zlib into buffer

我想使用gzip压缩内存缓冲区,然后将压缩后的字节放入另一个内存缓冲区。 我想使用Content-Encoding: gzip在HTTP数据包的有效负载中发送压缩缓冲区。 我可以使用zlib轻松进行压缩压缩( compress()函数)。 但是,没有我需要的API( gzip )。 zlib API将压缩并写入文件( gzwrite() )。 但是,我想压缩并写入缓冲区。

有任何想法吗?

我在Linux上使用C语言。

不,zlib API实际上确实通过deflate函数在内存中提供gzip压缩。 您实际上需要阅读zlib.h中的文档。

Gzip是一种文件格式,这就是为什么提供的实用程序功能可以在fd上运行的原因,请使用shm_open()创建具有足够内存的fd mmap() 重要的是要写入的数据不要扩展映射区域的大小,否则写入将失败。 这是映射区域的限制。

将fd传递给gzdopen()

但正如Mark在其答案中所建议的那样,使用Basic API接口是一种更好的方法。

deflate()默认情况下以zlib格式工作,要启用gzip压缩,您需要使用deflateInit2()向windowBits“添加16”,如以下代码所示,windowBits是切换为gzip格式的关键

// hope this would help  
int compressToGzip(const char* input, int inputSize, char* output, int outputSize)
{
    z_stream zs;
    zs.zalloc = Z_NULL;
    zs.zfree = Z_NULL;
    zs.opaque = Z_NULL;
    zs.avail_in = (uInt)inputSize;
    zs.next_in = (Bytef *)input;
    zs.avail_out = (uInt)outputSize;
    zs.next_out = (Bytef *)output;

    // hard to believe they don't have a macro for gzip encoding, "Add 16" is the best thing zlib can do:
    // "Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper"
    deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY);
    deflate(&zs, Z_FINISH);
    deflateEnd(&zs);
    return zs.total_out;
}

标头中的一些相关内容:

“该库还可以选择在内存中读写gzip和原始deflate流。”

“在windowBits中添加16,以围绕压缩数据而不是zlib包装器编写简单的gzip标头和标尾”

deflateInit2()的有趣文档距其定义还有1000多行,除非必须,否则我不会再准备文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM