hash.c 1.22 KB
#include "ic.h"

/*
 * A simple and mediocre hash table implementation.  This will go into
 * an infinite loop when the hash table fills up.
 */

#define	TABLESIZE	1024		/* must be a power of 2 */
#define M1		71
#define M2		578393
#define M3		358723

struct id *hashtable[TABLESIZE];

/* This returns an integer hash value for a string. */
int hash(char *str)
{
    char c;
    int h = 0;
    while ((c = *str++) != '\0')
        h = (h * M1 + (int) c);
    return(h);
}

/*
 * If hash location is already full, this computes a new hash address
 * to try.
 */
int rehash(int h)
{
    return(h +1);
}

struct id *enter(int lextype, char *str, int len)
{
    int h = hash(str);
    while (1) {
        int i = (h & TABLESIZE-1);
        struct id *entry = hashtable[i];
        if (entry == NULL) {
            /* enter it and return */
            hashtable[i] = entry = (struct id *) calloc(1, sizeof(struct id));
            entry->name = (char *) calloc(1, (unsigned) len+1);
            strcpy(entry->name, str);
            entry->lextype = lextype;
            return(entry);
        } else if (strcmp(entry->name, str) == 0) {
            return(entry);
        } else {
            /* try again */
            h = rehash(h);
        }
    }
}