AuroraRuntime/Source/Compression/Compression.cpp
2021-09-06 11:58:08 +01:00

87 lines
2.2 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: Compression.cpp
Date: 2021-6-17
Author: Reece
***/
#include <RuntimeInternal.hpp>
#include "Compression.hpp"
#include "zstd.h"
namespace Aurora::Compression
{
AUKN_SYM bool Compress(const void *buffer, AuUInt32 length, AuList<AuUInt8> &out, int compressionLevel )
{
if (!AuTryResize(out, length))
{
return false;
}
auto ret = ZSTD_compress(&out[0], out.size(), buffer, length, compressionLevel);
if (ZSTD_isError(ret))
{
return false;
}
out.resize(ret);
return true;
}
AUKN_SYM bool Compress(const AuList<AuUInt8> &in, AuList<AuUInt8> &out, int compressionLevel)
{
return Compress(in.data(), in.size(), out, compressionLevel);
}
AUKN_SYM bool Decompress(const void *buffer, AuUInt32 length, AuList<AuUInt8> &out)
{
AuUInt32 read = 0;
while (read != length)
{
auto startPtr = reinterpret_cast<const AuUInt8 *>(buffer) + read;
auto deflatedLength = ZSTD_findFrameCompressedSize(startPtr, length - read);
auto inflatedLength = ZSTD_getFrameContentSize(startPtr, length - read);
if (inflatedLength == ZSTD_CONTENTSIZE_ERROR)
{
return false;
}
if (inflatedLength == ZSTD_CONTENTSIZE_UNKNOWN)
{
return false;
}
if (ZSTD_isError(inflatedLength))
{
return false;
}
auto startingSize = out.size();
if (!AuTryResize(out, inflatedLength))
{
return false;
}
auto ret = ZSTD_decompress(&out[0], out.size(), buffer, length);
if (ZSTD_isError(ret))
{
return false;
}
out.resize(startingSize + ret);
read += deflatedLength;
}
return true;
}
AUKN_SYM bool Decompress(const AuList<AuUInt8> &in, AuList<AuUInt8> &out)
{
return Decompress(in.data(), in.size(), out);
}
}