gpt4 book ai didi

C++ 从 std::vector 膨胀 zlib

转载 作者:行者123 更新时间:2023-11-28 04:12:36 29 4
gpt4 key购买 nike

我在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com