diff --git a/src/lua/LuaScriptInterface.cpp b/src/lua/LuaScriptInterface.cpp index ea37d4c37..c3d2a16f4 100644 --- a/src/lua/LuaScriptInterface.cpp +++ b/src/lua/LuaScriptInterface.cpp @@ -2,6 +2,7 @@ #ifdef LUACONSOLE #include "client/http/Request.h" // includes curl.h, needs to come first to silence a warning on windows +#include "bzip2/bz2wrap.h" #include "LuaScriptInterface.h" @@ -113,6 +114,68 @@ int TptNewindexClosure(lua_State *l) return lsi->tpt_newIndex(l); } +static int bz2_compress_wrapper(lua_State *L) +{ + auto src = tpt_lua_checkByteString(L, 1); + auto maxSize = size_t(luaL_optinteger(L, 2, 0)); + std::vector dest; + auto result = BZ2WCompress(dest, src.data(), src.size(), maxSize); +#define RETURN_ERR(str) lua_pushnil(L); lua_pushinteger(L, int(result)); lua_pushliteral(L, str); return 3 + switch (result) + { + case BZ2WCompressOk: break; + case BZ2WCompressNomem: RETURN_ERR("out of memory"); + case BZ2WCompressLimit: RETURN_ERR("size limit exceeded"); + } +#undef RETURN_ERR + tpt_lua_pushByteString(L, ByteString(dest.begin(), dest.end())); + return 1; +} + +static int bz2_decompress_wrapper(lua_State *L) +{ + auto src = tpt_lua_checkByteString(L, 1); + auto maxSize = size_t(luaL_optinteger(L, 2, 0)); + std::vector dest; + auto result = BZ2WDecompress(dest, src.data(), src.size(), maxSize); +#define RETURN_ERR(str) lua_pushnil(L); lua_pushinteger(L, int(result)); lua_pushliteral(L, str); return 3 + switch (result) + { + case BZ2WDecompressOk: break; + case BZ2WDecompressNomem: RETURN_ERR("out of memory"); + case BZ2WDecompressLimit: RETURN_ERR("size limit exceeded"); + case BZ2WDecompressType: + case BZ2WDecompressBad: + case BZ2WDecompressEof: RETURN_ERR("corrupted stream"); + } +#undef RETURN_ERR + tpt_lua_pushByteString(L, ByteString(dest.begin(), dest.end())); + return 1; +} + +static void initBZ2API(lua_State *L) +{ + luaL_Reg reg[] = { + { "compress", bz2_compress_wrapper }, + { "decompress", bz2_decompress_wrapper }, + { NULL, NULL }, + }; + lua_newtable(L); + luaL_register(L, NULL, reg); +#define BZ2_CONST(k, v) lua_pushinteger(L, int(v)); lua_setfield(L, -2, k) + BZ2_CONST("compressOk", BZ2WCompressOk); + BZ2_CONST("compressNomem", BZ2WCompressNomem); + BZ2_CONST("compressLimit", BZ2WCompressLimit); + BZ2_CONST("decompressOk", BZ2WDecompressOk); + BZ2_CONST("decompressNomem", BZ2WDecompressNomem); + BZ2_CONST("decompressLimit", BZ2WDecompressLimit); + BZ2_CONST("decompressType", BZ2WDecompressType); + BZ2_CONST("decompressBad", BZ2WDecompressBad); + BZ2_CONST("decompressEof", BZ2WDecompressEof); +#undef BZ2_CONST + lua_setglobal(L, "bz2"); +} + LuaScriptInterface::LuaScriptInterface(GameController * c, GameModel * m): CommandInterface(c, m), luacon_mousex(0), @@ -167,6 +230,8 @@ LuaScriptInterface::LuaScriptInterface(GameController * c, GameModel * m): initSocketAPI(); #endif + initBZ2API(l); + //Old TPT API int currentElementMeta, currentElement; const static struct luaL_Reg tptluaapi [] = {