aboutsummaryrefslogtreecommitdiff
path: root/common.c
diff options
context:
space:
mode:
authorDeterminant <[email protected]>2015-06-05 10:58:57 +0800
committerDeterminant <[email protected]>2015-06-05 10:58:57 +0800
commitdf737041e4a9f3f55978cc74db9a9cea27fa9fa0 (patch)
treed656820be286550bc548f7c5ed4b1dcfecf3691c /common.c
parentea6f2990f99dd9ded6a0e74d75a3ec84900a2518 (diff)
add profiling; add ce accurarcy; several other changes
Diffstat (limited to 'common.c')
-rw-r--r--common.c55
1 files changed, 52 insertions, 3 deletions
diff --git a/common.c b/common.c
index c60c1ec..355d7ff 100644
--- a/common.c
+++ b/common.c
@@ -1,5 +1,3 @@
-#ifndef NERV_COMMON_H
-#define NERV_COMMON_H
#include "common.h"
#include <stdarg.h>
int nerv_error(lua_State *L, const char *err_mesg_fmt, ...) {
@@ -24,4 +22,55 @@ void luaN_append_methods(lua_State *L, const luaL_Reg *mlist) {
lua_setfield(L, -2, mlist->name);
}
}
-#endif
+
+HashMap *hashmap_create(size_t size, HashKey_t hfunc, HashMapCmp_t cmp) {
+ HashMap *res = (HashMap *)malloc(sizeof(HashMap));
+ res->bucket = calloc(size, sizeof(HashNode));
+ res->cmp = cmp;
+ res->hfunc = hfunc;
+ res->size = size;
+ return res;
+}
+
+void *hashmap_getval(HashMap *h, const char *key) {
+ size_t idx = h->hfunc(key) % h->size;
+ HashNode *ptr;
+ for (ptr = h->bucket[idx]; ptr; ptr = ptr->next)
+ {
+ if (!h->cmp(ptr->key, key))
+ return ptr->val;
+ }
+ return NULL;
+}
+
+void hashmap_setval(HashMap *h, const char *key, void *val) {
+ size_t idx = h->hfunc(key) % h->size;
+ HashNode *ptr = malloc(sizeof(HashNode));
+ ptr->next = h->bucket[idx];
+ h->bucket[idx] = ptr;
+ ptr->key = key;
+ ptr->val = val;
+}
+
+void hashmap_clear(HashMap *h) {
+ size_t i;
+ for (i = 0; i < h->size; i++)
+ {
+ HashNode *ptr, *nptr;
+ for (ptr = h->bucket[i]; ptr; ptr = nptr)
+ {
+ nptr = ptr->next;
+ free(ptr->val);
+ free(ptr);
+ }
+ h->bucket[i] = NULL;
+ }
+}
+
+size_t bkdr_hash(const char *key) {
+ unsigned int seed = 131;
+ unsigned int res = 0;
+ while (*key)
+ res = res * seed + *key++;
+ return res;
+}