shithub: hmap

ref: 1edcce3e14962a3642ff07d95770128cee95c5b5
dir: /test.c/

View raw version
#include "hash.c"

typedef struct Tnode {
	char *key;
	char *value;
} Tnode;

uvlong
thash(void *n)
{
	Tnode *t;
	uvlong hash;
	char *s;

	t = n;
	hash = 7;
	s = t->key;
	for(; *s; s++)
		hash = hash*31  + *s;
	return hash;
}

int
tcmp(void *_a, void *_b)
{
	Tnode *a, *b;

	a = _a;
	b = _b;
	return strcmp(a->key, b->key);
}

void
main(int argc, char **argv)
{
	int i;
	Hmap *h;
	Tnode t, *r;
	Tnode 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 = allochmap(thash, tcmp, 2, sizeof(Tnode));

	for(i=0; i < nelem(tab); i++)
		hmapset(&h, &tab[i]);

	for(i=0; i < nelem(tab); i++){
		t = tab[i];
		t.value = "";
		r = hmapget(h, &t);
		assert(r);
		assert(strcmp(r->key, tab[i].key) == 0);
		assert(strcmp(r->value, tab[i].value) == 0);
	}

	print("len, cap: %d %d\n", h->len, h->cap);
	r = mallocz(sizeof tab, 1);
	assert(hmapvals(h, r, nelem(tab)) == nelem(tab));
	for(i=0; i < nelem(tab); i++){
		print("%s %s\n", r[i].key, r[i].value);
	}

	h = hmaprehash(h, 0);
	for(i=0; i < nelem(tab); i++){
		t = tab[i];
		t.value = "";
		r = hmapget(h, &t);
		assert(r);
		assert(strcmp(r->key, tab[i].key) == 0);
		assert(strcmp(r->value, tab[i].value) == 0);
	}
	print("len, cap: %d %d\n", h->len, h->cap);
}