shithub: hmap

ref: d3298a0f73f8d45249df6b45b167ae17bea22167
dir: /test.c/

View raw version
#include "hash.c"

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

int
tfmt(Fmt *f)
{
	Tnode *t;

	t = va_arg(f->args, Tnode*);
	return fmtprint(f, "%s %s\n", t->key, t->value);
}

uvlong
thash(Hnode *h)
{
	Tnode *t;
	uvlong hash;
	char *s;

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

int
tcmp(Hnode *ha, Hnode *hb)
{
	Tnode *a, *b;

	a = (Tnode*)ha;
	b = (Tnode*)hb;
	return strcmp(a->key, b->key);
}

void
main(int argc, char **argv)
{
	Hmap *h;
	Tnode a, b;
	Tnode *r;

	fmtinstall('T', tfmt);
	fmtinstall('H', hmapfmt);
	h = allochmap(thash, tcmp, 2, sizeof(Tnode));
	h->nodeverb = 'T';
	a.key = "key";
	a.value = "value";
	hmapset(h, &a);
	b.key = "key2";
	b.value = "value2";
	hmapset(h, &b);
	b.key = "key3";
	b.value = "value3";
	hmapset(h, &b);
	a.value = "";
	r = (Tnode*)hmapget(h, &a);
	assert(strcmp(r->key, a.key) == 0);
	if(strcmp(r->value, "value") != 0)
		sysfatal("fail");

	b.key = "key3";
	r = (Tnode*)hmapget(h, &b);
	assert(strcmp(r->key, b.key) == 0);
	print("%H", h);
	hmapfree(h);
	print("len, cap: %d %d\n", h->len, h->cap);
	print("pass\n");
}