/***** **** *** ** *  *   *    *     *       *     *   *  * ** *** **** *****\

    logresolve 2.0 - http://www.uunet.ca/~tomr/progs/logresolve/

    lr-hash.h - hashed memory cache 2.0h0

    Tom Rathborne - tomr@uunet.ca - http://www.uunet.ca/~tomr/

\***** **** *** ** *  *   *    *     *       *     *   *  * ** *** **** *****/

#include "lr-hash.h"

/*
 * hash_lookup - gets pointer to record in hash table
 */

struct nsrec *
hash_lookup(tab, ipnum)
    struct nstab *tab;
    unsigned char ipnum[4];
{
    int bucknum;
    struct nsrec *current, *prev, *bucket, *temp, *record;

    bucknum = ip_hash(ipnum, tab->size);
    current = bucket = tab->rec[bucknum];

    while (current && !ip_cmp(ipnum, current->ipnum)) {
	prev = current;
	current = current->next;
    }

    if (current) {		/*
				 * it's in the hash table 
				 */
	current->usagecount++;

	if (current != bucket) {	/*
					 * move to front of bucket if necessary 
					 */
	    temp = current->next;
	    current->next = bucket;
	    tab->rec[bucknum] = current;
	    prev->next = temp;
	}
	record = current;

    } else {			/*
				 * not in hash table 
				 */
	return (0);
    }

    return (record);
}

/*
 * hash_insert - puts record into hash table at front of bucket
 */

void
hash_insert(tab, record)
    struct nstab *tab;
    struct nsrec *record;
{
    int bucknum;
    struct nsrec *temp;

    bucknum = ip_hash(record->ipnum, tab->size);
    temp = tab->rec[bucknum];

    tab->rec[bucknum] = record;
    record->next = temp;
}

/*
 * hash_dumpto_pdbm - dumps hash table to pdbm file
 */

#ifdef LR_DBM
void
hash_dumpto_pdbm(tab, dbfname, lockname)
    struct nstab *tab;
    char *dbfname;
    char *lockname;
{
    struct nsrec *current;
    struct nsdbm *db;
    int i;

    db = pdbm_open(dbfname, lockname, LR_WRITE);

    if (db->mode == LR_WRITE) {
	for (i = 0; i < tab->size; i++) {
	    current = tab->rec[i];
	    while (current) {
		pdbm_insert(db, current);
		current = current->next;
	    }
	}

	pdbm_close(db);
    }
}
#endif

/*
 * hash_new - makes a new hash table
 */

struct nstab *
hash_new(size)
    int size;
{
    struct nstab *tab;

    tab = (struct nstab *) malloc(sizeof(struct nstab));

    tab->size = size;
    tab->rec = (struct nsrec **) calloc(1, sizeof(struct nsrec *) * size);

    for (; size; size--) {	/*
				 * because we don't trust calloc 
				 */
	tab->rec[size - 1] = 0;
    }

    return (tab);
}

/*** end of lr-hash.c ***/
