iw4x-client/src/Utils/Compression.cpp

73 lines
1.5 KiB
C++
Raw Normal View History

2016-01-04 18:49:34 -05:00
#include "STDInclude.hpp"
namespace Utils
{
namespace Compression
{
std::string ZLib::Compress(std::string data)
{
2016-01-12 13:08:26 -05:00
unsigned long length = (data.size() * 2);
char* buffer = Utils::Memory::AllocateArray<char>(length);
2016-01-04 18:49:34 -05:00
if (compress2(reinterpret_cast<Bytef*>(buffer), &length, reinterpret_cast<Bytef*>(const_cast<char*>(data.data())), data.size(), Z_BEST_COMPRESSION) != Z_OK)
2016-01-04 18:49:34 -05:00
{
2016-01-12 13:08:26 -05:00
Utils::Memory::Free(buffer);
2016-01-04 18:49:34 -05:00
return "";
}
data.clear();
2016-01-12 13:08:26 -05:00
data.append(buffer, length);
2016-01-04 18:49:34 -05:00
2016-01-12 13:08:26 -05:00
Utils::Memory::Free(buffer);
2016-01-04 18:49:34 -05:00
return data;
}
std::string ZLib::Decompress(std::string data)
{
2016-01-09 09:30:13 -05:00
z_stream stream;
ZeroMemory(&stream, sizeof(stream));
std::string buffer;
if (inflateInit(&stream) != Z_OK)
{
return "";
2016-01-09 09:30:13 -05:00
}
int ret = 0;
2016-01-12 13:08:26 -05:00
uint8_t* dest = Utils::Memory::AllocateArray<uint8_t>(CHUNK);
2016-01-09 09:30:13 -05:00
const char* dataPtr = data.data();
do
{
stream.avail_in = min(CHUNK, data.size() - (dataPtr - data.data()));
stream.next_in = reinterpret_cast<const uint8_t*>(dataPtr);
do
{
stream.avail_out = CHUNK;
stream.next_out = dest;
ret = inflate(&stream, Z_NO_FLUSH);
if (ret == Z_STREAM_ERROR)
{
inflateEnd(&stream);
2016-01-12 13:08:26 -05:00
Utils::Memory::Free(dest);
return "";
2016-01-09 09:30:13 -05:00
}
buffer.append(reinterpret_cast<const char*>(dest), CHUNK - stream.avail_out);
} while (stream.avail_out == 0);
} while (ret != Z_STREAM_END);
inflateEnd(&stream);
2016-01-12 13:08:26 -05:00
Utils::Memory::Free(dest);
2016-01-09 09:30:13 -05:00
return buffer;
2016-01-04 18:49:34 -05:00
}
};
}