summaryrefslogblamecommitdiffstats
path: root/tests/hashmap_tests.c
blob: 13e945b899992ed1a870200e08211e1f85bc2710 (plain) (tree)



























































































                                                                
/* compat functions */
struct rwlock;
#define rw_init(a, b)
#define rw_enter_read(a)
#define rw_exit_read(a)
#define rw_enter_write(a)
#define rw_exit_write(a)

#include "../src/hashmap.h"

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <strings.h>


size_t alert_malloc(size_t a) { printf("malloc!\n"); return a; }
void * alert_free(void *a) { printf("free!\n"); return a; }
#define mallocarray(a, b, c, d) calloc(alert_malloc(a), b)
#define free(p, a, b) free(alert_free(p))

/* test cases */
struct entry {
	u_int32_t key;
	u_int32_t value;
};

int
entry_cmp(struct entry *a, struct entry *b)
{
	return a->key == b->key;
}

u_int64_t
entry_hash(struct entry *e)
{
	return e->key;
}

#define PRIME 31337

int
main(int argc, char *argv[])
{
	struct entry entry;
	HASHMAP_HEAD(test_hashmap, entry) hashmap;
	HASHMAP_INIT(&hashmap, 1, entry_cmp, entry_hash);


	/* Load up hashmap */
	for(int i = 0; i < 1024; i++) {
		int x = i * PRIME;
		entry.key = x;
		entry.value = x + 1;
		HASHMAP_RESIZE(&hashmap, test_hashmap, i);
		printf("Inserting: %d\n", i);
		HASHMAP_SET(&hashmap, entry);
	}

	/* Test stored values */
	for(int i = 0; i < 1024; i++) {
		int x = i * PRIME;
		entry.key = x;
		printf("Verifying: %d\n", i);
		HASHMAP_LOOKUP(&hashmap, entry);
		assert(entry.value == x + 1);
	}

	/* Delete values */
	for(int i = 1023; i >= 0; i--) {
		int x = i * PRIME;
		entry.key = x;
		printf("Removing: %d\n", i);
		HASHMAP_REMOVE(&hashmap, entry);
		HASHMAP_RESIZE(&hashmap, test_hashmap, i);
	}

	printf("Checking empty\n");
	assert(HASHMAP_NUM(&hashmap) == 0);

	printf("Should fail assertion!\n");
	HASHMAP_RESIZE(&hashmap, test_hashmap, 3);
	for(int i = 0; i < 8; i++) {
		int x = i * PRIME;
		entry.key = x;
		entry.value = x + 1;
		printf("Inserting: %d, size 3\n", i);
		HASHMAP_SET(&hashmap, entry);
	}

	HASHMAP_DEINIT(&hashmap);
}