/** * hash.c * An implementation of hash tables, based loosely on code from K&R 2nd, * pp. 143-145. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include // For malloc #include "hash.h" #include "hashfun.h" // +-------+---------------------------------------------------------- // | Types | // +-------+ /** * Nodes in a list in one element of the hash table. */ struct nlist { struct nlist *next; // Next entry in the list char *key; // The key char *value; // The value }; // struct nlist // +-----------------+------------------------------------------------ // | Local Functions | // +-----------------+ /** * Find an nlist element in a hash table. (Based on lookup in K&R.) */ struct nlist * lookup (struct hash *hashtab, char *str) { unsigned pos = hash (str) % hashtab->size; struct nlist *np; for (np = hashtab->contents[pos]; np != NULL; np = np->next) if (strcmp (str, np->key) == 0) return np; // found return NULL; // not found } // lookup // +--------------------+--------------------------------------------- // | Exported Functions | // +--------------------+ char * find (struct hash *hashtab, char *key) { struct nlist *np = lookup (hashtab, key); if (np == NULL) return NULL; else return np->value; } // find struct hash * new_hash (int size) { struct hash *hashtab = malloc (sizeof (struct hash)); // Allocate space for the hash table. if (hash == NULL) return NULL; hashtab->size = size; // Allocate space for the real part of the hash table. hashtab->contents = malloc (size * sizeof (struct nlist *)); // If we fail, clean up. if (hashtab->contents == NULL) { free (hashtab) return NULL; } // And we're done. return hashtab; } // new_hash (int)