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

    logresolve 2.0 - http://www.net/~tomr/progs/logresolve/

    lr-hash.c - hashed memory cache 2.0h2

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

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

#include <stdlib.h>

#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 *prev = 0, *bucket, *temp, *record;

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

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

    if (record && (record != bucket)) {		/* it's in the hash table and we need to move it to the front of the bucket */
	temp = record->next;
	record->next = bucket;
	tab->rec[bucknum] = record;
	prev->next = temp;
    }
    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, keep)
    struct nstab *tab;
    char *dbfname;
    char *lockname;
    int keep;
{
    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) {
		if (keep || !current->status)
		    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 ***/
