shithub: hmap

ref: 9ae12fa984b9bc0eb0a33f9c0cf5b4ebd47ecd6d
dir: /test.c/

View raw version
#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 **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 = allochmap(thash, strcmp, 1, sizeof(char*));

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

	for(i=0; i < nelem(tab); i++){
		v = hmapget(h, tab[i].key);
		assert(v);
		assert(strcmp(*v, 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++){
		v = hmapget(h, tab[i].key);
		assert(v);
		assert(strcmp(*v, tab[i].value) == 0);
	}
	print("len, cap: %d %d\n", h->len, h->cap);
	free(h);
}

uvlong
runehash(void *p)
{
	Hkey k;
	k.p = p;
	return k.v * 0xdeece66d + 0xb;
}

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;

	h = allochmap(runehash, runecmp, 16, sizeof(char*));

	k.v = 'p';
	v = "hello";
	hmapset(&h, k.p, &v);
	hmapset(&h, k.p, &v);

	p = hmapget(h, k.p);
	assert(p && *p);
	assert(*p == v);
}

void
main(int argc, char **argv)
{
	USED(argc);
	USED(argv);
	testbasic();
	testrunekey();
}