使用 zlib 进行内存解压 [英] In-memory decompression with zlib

查看:39
本文介绍了使用 zlib 进行内存解压的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在内存中读取 zlib 压缩文件而不实际将其解压缩到磁盘吗?如果你能提供一个片段就好了.

Can I read a zlib compressed file in memory without actually extracting it to disk? It would be nice if you could provide a snippet.

推荐答案

这是一个 zLib 膨胀例程,它在内存中获取一个缓冲区并解压到提供的输出缓冲区中.这是一个一次性"功能,因为它会尝试一次性填充整个输入缓冲区,并假设您已经为其提供了足够的空间来容纳所有内容.也可以编写一个 multi-shot 函数,根据需要动态增长目标缓冲区.

Here's a zLib inflate routine that takes a buffer in memory and decompresses into the provided output buffer. This is a 'one-shot' function, in that it attempts to inflate the entire input buffer all at once, and assumes you've given it enough space to fit it all. It is also possible to write a multi-shot function that dynamically grows 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;
}

说明:

src:包含压缩(gzip 或 zlib)数据的源缓冲区
srcLen:源缓冲区的长度
dst:目标缓冲区,输出将写入其中
dstLen:目标缓冲区的长度

src: the source buffer containing the compressed (gzip or zlib) data
srcLen: the length of the source buffer
dst: the destination buffer, into which the output will be written
dstLen: the length of the destination buffer

返回值:

Z_BUF_ERROR:如果 dstLen 不够大以适合膨胀的数据
Z_MEM_ERROR:如果没有足够的内存来执行解压
Z_DATA_ERROR:如果输入数据已损坏

Z_BUF_ERROR: if dstLen is not large enough to fit the inflated data
Z_MEM_ERROR: if there's insufficient memory to perform the decompression
Z_DATA_ERROR: if the input data was corrupt

否则,返回值是写入 dst 的字节数.

Otherwise, the return value is the number of bytes written to dst.

这篇关于使用 zlib 进行内存解压的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆