Last active
September 7, 2019 10:20
-
-
Save starwing/bd04a4a1d5e9d9a3e55ed1d75ecc7ea5 to your computer and use it in GitHub Desktop.
Lua FastLZ binding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define LUA_LIB | |
#include <lua.h> | |
#include <lauxlib.h> | |
#include "fastlz.h" | |
#include "fastlz.c" | |
#include <stdlib.h> | |
static int Lcompress(lua_State *L) { | |
size_t len; | |
const char *s = luaL_checklstring(L, 1, &len); | |
int r, level = luaL_optinteger(L, 2, 0); | |
char init_out[LUAL_BUFFERSIZE], *out = init_out; | |
if (level != 0 && (level < 1 || level > 2)) | |
luaL_error(L, "level range error (0-2): %d", level); | |
if ((size_t)(len*1.05+4) > LUAL_BUFFERSIZE) | |
out = lua_newuserdata(L, (size_t)(len*1.05 + 4)); | |
out[0] = (len >> 24) & 0xFF; | |
out[1] = (len >> 16) & 0xFF; | |
out[2] = (len >> 8) & 0xFF; | |
out[3] = (len >> 0) & 0xFF; | |
r = level ? | |
fastlz_compress_level(level, s, len, out+4) : | |
fastlz_compress(s, len, out+4); | |
lua_pushlstring(L, out, r+4); | |
return 1; | |
} | |
static int Ldecompress(lua_State *L) { | |
size_t len, size; | |
const char *s = luaL_checklstring(L, 1, &len); | |
char init_out[LUAL_BUFFERSIZE], *out = init_out; | |
int r; | |
if (len < 4) return luaL_error(L, "decompress error"); | |
size = ((s[0] & 0xFF) << 24) | | |
((s[1] & 0xFF) << 16) | | |
((s[2] & 0xFF) << 8) | | |
((s[3] & 0xFF) << 0); | |
if (size > LUAL_BUFFERSIZE) | |
out = lua_newuserdata(L, size); | |
r = fastlz_decompress(s+4, len-4, out, size); | |
if (r == 0) return luaL_error(L, "decompress error"); | |
lua_pushlstring(L, out, r); | |
return 1; | |
} | |
LUALIB_API int luaopen_fastlz(lua_State *L) { | |
luaL_Reg libs[] = { | |
#define ENTRY(name) { #name, L##name } | |
ENTRY(compress), | |
ENTRY(decompress), | |
#undef ENTRY | |
{ NULL, NULL } | |
}; | |
luaL_newlib(L, libs); | |
return 1; | |
} | |
/* unixcc: flags+='-shared -fpic -undefined dynamic_lookup' | |
* unixcc: output='fastlz.so' | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment