/*
 * hash.c
 */

#include "hash.h"
#include "misc.h"

static struct addressinfo *hashtable[HASHLEN] = {NULL, };

static inline int Hash(unsigned char *hwAddr);

struct addressinfo *
GetAddr(unsigned char *hwAddr)
{
	struct addressinfo *addr;
	int		hashVal;

	hashVal = Hash(hwAddr);
	addr = hashtable[hashVal];
	while(addr) {
#ifdef DEBUG
		printf("GetAddr: trying ");
		PrintHex((unsigned char *) &addr->hwAddr, 6); putchar('\n');
#endif
		if(!memcmp(&addr->hwAddr, hwAddr, ETH_ALEN))
			return addr;
		addr = addr->next;
	}
	return NULL;
}

int
InsertAddr(unsigned char *hwAddr, int locIndex)
{
	struct addressinfo	*addr = Malloc(sizeof(struct addressinfo));
	struct addressinfo	*next;
	int		hashVal;

	memcpy(&addr->hwAddr, hwAddr, ETH_ALEN);
	addr->age = 0;
	addr->locIndex = locIndex;
	hashVal = Hash(hwAddr);
	next = hashtable[hashVal];
	addr->next = next ? next->next : NULL;
	hashtable[hashVal] = addr;

	return TRUE;
}

static inline int
Hash(unsigned char *hwAddr)
{
	int val = 0, i;

	for(i = 1; i < ETH_ALEN; i++)
		val += hwAddr[i] << i;	/* Tune me */

	return val % HASHLEN;
}
