minetestmapper/ZlibDecompressor.cpp

70 lines
1.3 KiB
C++
Raw Permalink Normal View History

2012-09-18 10:43:34 +02:00
#include <zlib.h>
2012-09-18 12:46:15 +02:00
#include <stdint.h>
2012-09-18 10:43:34 +02:00
#include "ZlibDecompressor.h"
2022-02-09 22:46:07 +01:00
ZlibDecompressor::ZlibDecompressor(const u8 *data, size_t size):
2012-09-18 10:43:34 +02:00
m_data(data),
m_seekPos(0),
m_size(size)
{
}
ZlibDecompressor::~ZlibDecompressor()
{
}
2022-02-09 22:46:07 +01:00
void ZlibDecompressor::setSeekPos(size_t seekPos)
2012-09-18 10:43:34 +02:00
{
m_seekPos = seekPos;
}
2022-02-09 22:46:07 +01:00
size_t ZlibDecompressor::seekPos() const
2012-09-18 10:43:34 +02:00
{
return m_seekPos;
}
ustring ZlibDecompressor::decompress()
2012-09-18 10:43:34 +02:00
{
const unsigned char *data = m_data + m_seekPos;
2022-02-09 22:46:07 +01:00
const size_t size = m_size - m_seekPos;
2012-09-18 10:43:34 +02:00
ustring buffer;
2024-04-20 21:38:05 +02:00
constexpr size_t BUFSIZE = 32 * 1024;
2012-09-18 10:43:34 +02:00
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = Z_NULL;
2024-04-20 21:38:05 +02:00
strm.avail_in = 0;
2012-09-18 10:43:34 +02:00
if (inflateInit(&strm) != Z_OK)
2012-09-18 10:43:34 +02:00
throw DecompressError();
strm.next_in = const_cast<unsigned char *>(data);
2024-04-20 21:38:05 +02:00
strm.avail_in = size;
buffer.resize(BUFSIZE);
strm.next_out = &buffer[0];
strm.avail_out = BUFSIZE;
2012-09-18 10:43:34 +02:00
int ret = 0;
do {
ret = inflate(&strm, Z_NO_FLUSH);
2024-04-20 21:38:05 +02:00
if (strm.avail_out == 0) {
const auto off = buffer.size();
buffer.reserve(off + BUFSIZE);
strm.next_out = &buffer[off];
strm.avail_out = BUFSIZE;
}
2012-09-18 10:43:34 +02:00
} while (ret == Z_OK);
if (ret != Z_STREAM_END)
2012-09-18 10:43:34 +02:00
throw DecompressError();
2012-09-18 10:43:34 +02:00
m_seekPos += strm.next_in - data;
2024-04-20 21:38:05 +02:00
buffer.resize(buffer.size() - strm.avail_out);
2022-02-09 22:46:07 +01:00
(void) inflateEnd(&strm);
2012-09-18 10:43:34 +02:00
return buffer;
}