1
0
Fork 0
mirror of https://github.com/luanti-org/luanti.git synced 2025-06-27 16:36:03 +00:00

Add zstd compression support (#12515)

This commit is contained in:
20kdc 2022-09-28 14:06:14 +01:00 committed by GitHub
parent 0251b01da6
commit b1233056b7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 95 additions and 13 deletions

View file

@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "cpp_api/s_async.h"
#include "serialization.h"
#include <json/json.h>
#include <zstd.h>
#include "cpp_api/s_security.h"
#include "porting.h"
#include "convert_json.h"
@ -278,6 +279,34 @@ int ModApiUtil::l_get_user_path(lua_State *L)
return 1;
}
enum LuaCompressMethod
{
LUA_COMPRESS_METHOD_DEFLATE,
LUA_COMPRESS_METHOD_ZSTD,
};
static const struct EnumString es_LuaCompressMethod[] =
{
{LUA_COMPRESS_METHOD_DEFLATE, "deflate"},
{LUA_COMPRESS_METHOD_ZSTD, "zstd"},
{0, nullptr},
};
static LuaCompressMethod get_compress_method(lua_State *L, int index)
{
if (lua_isnoneornil(L, index))
return LUA_COMPRESS_METHOD_DEFLATE;
const char *name = luaL_checkstring(L, index);
int value;
if (!string_to_enum(es_LuaCompressMethod, value, name)) {
// Pretend it's deflate if we don't know, for compatibility reasons.
log_deprecated(L, "Unknown compression method \"" + std::string(name)
+ "\", defaulting to \"deflate\". You should pass a valid value.");
return LUA_COMPRESS_METHOD_DEFLATE;
}
return (LuaCompressMethod) value;
}
// compress(data, method, level)
int ModApiUtil::l_compress(lua_State *L)
{
@ -286,12 +315,23 @@ int ModApiUtil::l_compress(lua_State *L)
size_t size;
const char *data = luaL_checklstring(L, 1, &size);
int level = -1;
if (!lua_isnoneornil(L, 3))
level = readParam<int>(L, 3);
LuaCompressMethod method = get_compress_method(L, 2);
std::ostringstream os(std::ios_base::binary);
compressZlib(reinterpret_cast<const u8 *>(data), size, os, level);
if (method == LUA_COMPRESS_METHOD_DEFLATE) {
int level = -1;
if (!lua_isnoneornil(L, 3))
level = readParam<int>(L, 3);
compressZlib(reinterpret_cast<const u8 *>(data), size, os, level);
} else if (method == LUA_COMPRESS_METHOD_ZSTD) {
int level = ZSTD_CLEVEL_DEFAULT;
if (!lua_isnoneornil(L, 3))
level = readParam<int>(L, 3);
compressZstd(reinterpret_cast<const u8 *>(data), size, os, level);
}
std::string out = os.str();
@ -307,9 +347,16 @@ int ModApiUtil::l_decompress(lua_State *L)
size_t size;
const char *data = luaL_checklstring(L, 1, &size);
LuaCompressMethod method = get_compress_method(L, 2);
std::istringstream is(std::string(data, size), std::ios_base::binary);
std::ostringstream os(std::ios_base::binary);
decompressZlib(is, os);
if (method == LUA_COMPRESS_METHOD_DEFLATE) {
decompressZlib(is, os);
} else if (method == LUA_COMPRESS_METHOD_ZSTD) {
decompressZstd(is, os);
}
std::string out = os.str();