DarkflameServer/dCommon/ZCompression.cpp

51 lines
1.5 KiB
C++
Raw Permalink Normal View History

2022-08-06 03:01:59 +00:00
#include "ZCompression.h"
#include "zlib-ng.h"
2022-07-28 13:39:57 +00:00
namespace ZCompression {
int32_t GetMaxCompressedLength(int32_t nLenSrc) {
int32_t n16kBlocks = (nLenSrc + 16383) / 16384; // round up any fraction of a block
return (nLenSrc + 6 + (n16kBlocks * 5));
}
2022-07-28 13:39:57 +00:00
int32_t Compress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst) {
zng_stream zInfo = { 0 };
2022-07-28 13:39:57 +00:00
zInfo.total_in = zInfo.avail_in = nLenSrc;
zInfo.total_out = zInfo.avail_out = nLenDst;
zInfo.next_in = const_cast<Bytef*>(abSrc);
zInfo.next_out = abDst;
2022-07-28 13:39:57 +00:00
int nErr, nRet = -1;
nErr = zng_deflateInit(&zInfo, Z_DEFAULT_COMPRESSION); // zlib function
2022-07-28 13:39:57 +00:00
if (nErr == Z_OK) {
nErr = zng_deflate(&zInfo, Z_FINISH); // zlib function
2022-07-28 13:39:57 +00:00
if (nErr == Z_STREAM_END) {
nRet = zInfo.total_out;
}
}
zng_deflateEnd(&zInfo); // zlib function
2022-07-28 13:39:57 +00:00
return(nRet);
}
2022-07-28 13:39:57 +00:00
int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr) {
// Get the size of the decompressed data
zng_stream zInfo = { 0 };
2022-07-28 13:39:57 +00:00
zInfo.total_in = zInfo.avail_in = nLenSrc;
zInfo.total_out = zInfo.avail_out = nLenDst;
zInfo.next_in = const_cast<Bytef*>(abSrc);
zInfo.next_out = abDst;
2022-07-28 13:39:57 +00:00
int nRet = -1;
nErr = zng_inflateInit(&zInfo); // zlib function
2022-07-28 13:39:57 +00:00
if (nErr == Z_OK) {
nErr = zng_inflate(&zInfo, Z_FINISH); // zlib function
2022-07-28 13:39:57 +00:00
if (nErr == Z_STREAM_END) {
nRet = zInfo.total_out;
}
}
zng_inflateEnd(&zInfo); // zlib function
2022-07-28 13:39:57 +00:00
return(nRet);
}
}