ref: 8e631b19c4bf009a69489fcdd2e0b8c84a104a15
dir: /test.c/
#include "hash.c" uvlong thash(char *s) { uvlong hash; hash = 7; for(; *s; s++) hash = hash*31 + *s; return hash; } void testbasic(void) { int i; Hmap *h; char *p; char **v; struct { char *key; char *value; } tab[] = { {.key "key1", .value "value1" }, {.key "key2", .value "value2" }, {.key "key3", .value "value3" }, {.key "key4", .value "value4" }, {.key "key5", .value "value5" }, {.key "key6", .value "value6" }, }; h = hmapalloc(thash, strcmp, 1, sizeof(char*)); for(i=0; i < nelem(tab); i++) hmapset(&h, tab[i].key, &tab[i].value, nil); for(i=0; i < nelem(tab); i++){ hmapget(h, tab[i].key, &p); assert(p); assert(strcmp(p, tab[i].value) == 0); } print("len, cap: %d %d\n", h->len, h->cap); v = mallocz(nelem(tab)*sizeof(char*), 1); assert(hmapvals(h, v, nelem(tab)) == nelem(tab)); for(i=0; i < nelem(tab); i++) print("%s\n", v[i]); h = hmaprehash(h, 0); for(i=0; i < nelem(tab); i++){ hmapget(h, tab[i].key, &p); assert(p); assert(strcmp(p, tab[i].value) == 0); } print("len, cap: %d %d\n", h->len, h->cap); free(h); } uvlong runehash(void *p) { uvlong s; Hkey k; k.p = p; s = 2654435761L; s *= 1<<sizeof(p); s *= k.v; return s>>sizeof(p); } int runecmp(void *_a, void *_b) { Hkey a, b; a.p = _a, b.p = _b; return !(a.v == b.v); } void testrunekey(void) { Hkey k; Hmap *h; char *v; char *p, *p2; char keys[] = "abcdefghijklmnopqrstuvwxyz"; int i; h = hmapalloc(runehash, runecmp, 16, sizeof(char*)); k.v = 'p'; v = "hello"; assert(hmapset(&h, k.p, &v, nil) == 0); assert(hmapset(&h, k.p, &v, &p2) == 1); assert(p2 == v); for(i=0; i < sizeof keys - 1; i++){ k.v = keys[i]; hmapset(&h, k.p, &v, nil); } assert(hmapget(h, k.p, &p) == 0); assert(p && *p); assert(p == v); free(h); } void main(int argc, char **argv) { USED(argc); USED(argv); testbasic(); testrunekey(); }