]> git.lizzy.rs Git - minetest.git/blobdiff - src/script/lua_api/l_util.cpp
Add compression API
[minetest.git] / src / script / lua_api / l_util.cpp
index b30bab292ae7382fd7e5212dd85cff7a29efc31e..dda5b5abfca4c1ffbd0efbce57c3c611066de817 100644 (file)
@@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "common/c_converter.h"
 #include "common/c_content.h"
 #include "cpp_api/s_async.h"
+#include "serialization.h"
 #include "debug.h"
 #include "porting.h"
 #include "log.h"
@@ -47,11 +48,12 @@ int ModApiUtil::l_debug(lua_State *L)
                lua_pushvalue(L, -1);  /* function to be called */
                lua_pushvalue(L, i);   /* value to print */
                lua_call(L, 1, 1);
-               const char *s = lua_tostring(L, -1);
-               if (i>1)
+               size_t len;
+               const char *s = lua_tolstring(L, -1, &len);
+               if (i > 1)
                        dstream << "\t";
                if (s)
-                       dstream << s;
+                       dstream << std::string(s, len);
                lua_pop(L, 1);
        }
        dstream << std::endl;
@@ -282,6 +284,40 @@ int ModApiUtil::l_get_builtin_path(lua_State *L)
        return 1;
 }
 
+// compress(data, method, level)
+int ModApiUtil::l_compress(lua_State *L)
+{
+       size_t size;
+       const char *data = luaL_checklstring(L, 1, &size);
+
+       int level = -1;
+       if (!lua_isnone(L, 3) && !lua_isnil(L, 3))
+               level = luaL_checknumber(L, 3);
+
+       std::ostringstream os;
+       compressZlib(std::string(data, size), os, level);
+
+       std::string out = os.str();
+
+       lua_pushlstring(L, out.data(), out.size());
+       return 1;
+}
+
+// decompress(data, method)
+int ModApiUtil::l_decompress(lua_State *L)
+{
+       size_t size;
+       const char * data = luaL_checklstring(L, 1, &size);
+
+       std::istringstream is(std::string(data, size));
+       std::ostringstream os;
+       decompressZlib(is, os);
+
+       std::string out = os.str();
+
+       lua_pushlstring(L, out.data(), out.size());
+       return 1;
+}
 
 void ModApiUtil::Initialize(lua_State *L, int top)
 {
@@ -305,6 +341,9 @@ void ModApiUtil::Initialize(lua_State *L, int top)
        API_FCT(is_yes);
 
        API_FCT(get_builtin_path);
+
+       API_FCT(compress);
+       API_FCT(decompress);
 }
 
 void ModApiUtil::InitializeAsync(AsyncEngine& engine)
@@ -324,5 +363,8 @@ void ModApiUtil::InitializeAsync(AsyncEngine& engine)
        ASYNC_API_FCT(is_yes);
 
        ASYNC_API_FCT(get_builtin_path);
+
+       ASYNC_API_FCT(compress);
+       ASYNC_API_FCT(decompress);
 }