c++ - 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 中的示例代码假定数据是从文件中读取的。在我的情况下,数据已经过验证并存储在向量中。
谢谢
解决方案
像这样的东西应该可以工作,虽然我还没有测试过:
#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;
}
推荐阅读
- php - 如何在没有用户干预的情况下在某些条件下从 php 发送电子邮件?
- file - 文件格式 GRP
- sql - plsql 函数必须声明
- python - 如何通过 field_id 在flask-mongoengine 中保存文档?
- asp.net-mvc - IIS 提供 https GET,但 POST 失败
- postgresql - Postgresql 连续时间之间的平均间隔——按星期几
- python - 如何使用 Python 在 3D 平面上绘制椭圆?
- mysql - 无法从 Ubuntu 20.10 安装或清除 mariadb
- android - Flutter:如何将多张照片或图标内的一张照片链接到地理位置标记?
- flutter - MissingPluginException - shared_preferences、image_picker 等。在删除 flutter_branch_sdk 时有效