lua-hash: introduce a lua hashing library using libubox.

This commit is contained in:
lemoer 2016-04-08 02:56:23 +02:00
parent fea8f67d5d
commit b41132b593
4 changed files with 92 additions and 0 deletions

36
libs/lua-hash/Makefile Normal file
View File

@ -0,0 +1,36 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=lua-hash
PKG_VERSION:=1
PKG_BUILD_DIR := $(BUILD_DIR)/$(PKG_NAME)
include $(INCLUDE_DIR)/package.mk
define Package/lua-hash
SECTION:=libs
CATEGORY:=Libraries
TITLE:=Lua hash library
DEPENDS:=+lua +libubox
endef
define Build/Prepare
mkdir -p $(PKG_BUILD_DIR)
$(CP) ./src/* $(PKG_BUILD_DIR)/
endef
define Build/Configure
endef
define Build/Compile
CFLAGS="$(TARGET_CFLAGS)" \
CPPFLAGS="$(TARGET_CPPFLAGS)" \
$(MAKE) -C $(PKG_BUILD_DIR) $(TARGET_CONFIGURE_OPTS)
endef
define Package/lua-hash/install
$(INSTALL_DIR) $(1)/usr/lib/lua
$(CP) $(PKG_BUILD_DIR)/hash.so $(1)/usr/lib/lua/
endef
$(eval $(call BuildPackage,lua-hash))

View File

@ -0,0 +1,6 @@
all: hash.so
CFLAGS += -Wall
hash.so: hash.c
$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -shared -fPIC -o $@ $^ $(LDLIBS) -llua -lubox

47
libs/lua-hash/src/hash.c Normal file
View File

@ -0,0 +1,47 @@
#include <libubox/md5.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <stdlib.h>
#include <string.h>
#define MD5_DIGEST_LEN 16
#define MD5_STRLEN (2*MD5_DIGEST_LEN+1)
static int md5(lua_State *L) {
size_t len;
const char *input = lua_tolstring(L, 1, &len);
if (input == NULL) {
lua_pushstring(L, "first argument: should be the input string");
lua_error(L);
__builtin_unreachable();
}
unsigned char digest[MD5_DIGEST_LEN];
char output[MD5_STRLEN];
struct md5_ctx ctx;
md5_begin(&ctx);
md5_hash(input, len, &ctx);
md5_end(digest, &ctx);
// fill the digest bytewise in the output string
int i;
for (i = 0; i < MD5_DIGEST_LEN; i++) {
sprintf(output + 2*i, "%02x", digest[i]);
}
lua_pushstring(L, output);
return 1;
}
static const luaL_Reg R[] = {
{"md5", md5},
{NULL, NULL },
};
LUALIB_API int luaopen_hash(lua_State *L) {
luaL_register(L, "hash", R);
return 1;
}

View File

@ -0,0 +1,3 @@
#!/usr/bin/lua
hash = require "hash"
assert(hash.md5('testing') == 'ae2b1fca515949e5d54fb22b8ed95575')