AuroraRuntime/Source/Compression/Compression.cpp

87 lines
2.2 KiB
C++
Raw Normal View History

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