C++ 从 std::vector 膨胀 zlib

标签 c++ zlib

我在 std::vector 中压缩了 zlib 格式的数据

我正在尝试找出一种方法来编写一个函数,该函数获取该数据并返回另一个包含膨胀数据的 vector 。 该函数甚至不需要检查它是否是有效的 zlib 数据等。 只是这些行中的内容:

// infalte compressed zlib data.
 std::vector<unsigned char> decompress_zlib(std::vector<unsigned char> data)
{
    std::vector<unsigned char> ret;
    // magic happens here
    return ret;
}

pipes.c 中的示例代码假定数据是从文件中读取的。在我的例子中,数据已经过验证并存储在 vector 中。

谢谢

最佳答案

虽然我还没有测试过,但这样的东西应该可以工作:

#include <algorithm>
#include <assert.h>
#include <vector>
#include <zlib.h>

#define CHUNK (1024 * 256)

typedef std::vector<unsigned char> vucarr;

void vucarrWrite(vucarr& out, const unsigned char* buf, size_t bufLen)
{
    out.insert(out.end(), buf, buf + bufLen);
}

size_t vucarrRead(const vucarr &in, unsigned char *&inBuf, size_t &inPosition)
{
    size_t from = inPosition;
    inBuf = const_cast<unsigned char*>(in.data()) + inPosition;
    inPosition += std::min(CHUNK, in.size() - from);
    return inPosition - from;
}

int inf(const vucarr &in, vucarr &out)
{
    int ret;
    unsigned have;
    z_stream strm = {};
    unsigned char *inBuf;
    unsigned char outBuf[CHUNK];

    size_t inPosition = 0; /* position indicator of "in" */

    /* allocate inflate state */
    ret = inflateInit(&strm);
    if (ret != Z_OK)
        return ret;

    /* decompress until deflate stream ends or end of file */
    do {
        strm.avail_in = vucarrRead(in, inBuf, inPosition);

        if (strm.avail_in == 0)
            break;
        strm.next_in = inBuf;

        /* run inflate() on input until output buffer not full */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = outBuf;
            ret = inflate(&strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR); /* state not clobbered */
            switch (ret) {
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR; /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                (void)inflateEnd(&strm);
                return ret;
            }
            have = CHUNK - strm.avail_out;
            vucarrWrite(out, outBuf, have);
        } while (strm.avail_out == 0);

        /* done when inflate() says it's done */
    } while (ret != Z_STREAM_END);

    /* clean up and return */
    (void)inflateEnd(&strm);
    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

关于C++ 从 std::vector 膨胀 zlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57338292/

相关文章:

c# - zlib 压缩字节数组?

node.js - 如何在nodejs中压缩流?

c++ - 从 Point2f 中提取数据

c++ - 使用即时计算的临时值为 ForwardIterator 实现成员访问运算符->

javascript - 如何遍历Cheerp/js中的动态命名对象?

C++ 使用线程作为定时器

javascript - 文件内容上的 NodeJS : zlib. Gunzip() 返回错误: header 检查不正确

c++ - 我可以执行 gzseek 来更新使用 gzwrite (CPP) 压缩的文件吗?

c++ - boost::iostream zlib 将多个文件压缩到一个存档中

java - 如何在Python中膨胀相同的数据