From df737041e4a9f3f55978cc74db9a9cea27fa9fa0 Mon Sep 17 00:00:00 2001 From: Determinant Date: Fri, 5 Jun 2015 10:58:57 +0800 Subject: add profiling; add ce accurarcy; several other changes --- common.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) (limited to 'common.c') 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 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; +} -- cgit v1.2.3-70-g09d2