首页 > 解决方案 > C++ 从 std::vector 膨胀 zlib

问题描述

我在 std::vector 内有 zlib 格式的压缩数据

我试图找出一种方法来编写一个函数,该函数接受该数据并返回另一个带有膨胀数据的向量。该函数甚至不需要检查它是否是有效的 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;
}

pipe.c 中的示例代码假定数据是从文件中读取的。在我的情况下,数据已经过验证并存储在向量中。

谢谢

标签: c++zlib

解决方案


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

#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;
}

推荐阅读