home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume13 / ratfor / lookup.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-02-27  |  1.4 KB  |  85 lines

  1. #include <stdio.h>
  2. #include "lookup.h"
  3.  
  4. static 
  5. struct    hashlist *hashtab[HASHMAX];
  6.  
  7. /*
  8.  * from K&R "The C Programming language"
  9.  * Table lookup routines
  10.  *
  11.  * hash - for a hash value for string s
  12.  *
  13.  */
  14. hash(s)
  15. char *s;
  16. {
  17.     int    hashval;
  18.  
  19.     for (hashval = 0; *s != '\0';)
  20.         hashval += *s++;
  21.     return (hashval % HASHMAX);
  22. }
  23.  
  24. /*
  25.  * lookup - lookup for a string s in the hash table
  26.  *
  27.  */
  28. struct hashlist
  29. *lookup(s)
  30. char *s;
  31. {
  32.     struct hashlist *np;
  33.  
  34.     for (np = hashtab[hash(s)]; np != NULL; np = np->next)
  35.         if (strcmp(s, np->name) == 0)
  36.             return(np);    /* found     */
  37.     return(NULL);        /* not found */
  38. }
  39.  
  40. /*
  41.  * install - install a string name in hashtable and its value def
  42.  *
  43.  */
  44. struct hashlist
  45. *install(name,def)
  46. char *name;
  47. char *def;
  48. {
  49.     int hashval;
  50.     struct hashlist *np, *lookup();
  51.     char *strsave(), *malloc();
  52.  
  53.     if ((np = lookup(name)) == NULL) {    /* not found.. */
  54.         np = (struct hashlist *) malloc(sizeof(*np));
  55.         if (np == NULL)
  56.             return(NULL);
  57.         if ((np->name = strsave(name)) == NULL)
  58.             return(NULL);
  59.         hashval = hash(np->name);
  60.         np->next = hashtab[hashval];
  61.         hashtab[hashval] = np;
  62.     } else                    /* found..     */
  63.         free(np->def);            /* free prev.  */
  64.     if ((np->def = strsave(def)) == NULL)
  65.         return(NULL);
  66.     return(np);
  67. }
  68.  
  69. /*
  70.  * strsave - save string s somewhere
  71.  *
  72.  */
  73. char
  74. *strsave(s)
  75. char *s;
  76. {
  77.     char *p, *malloc();
  78.  
  79.     if ((p = malloc(strlen(s)+1)) != NULL)
  80.         strcpy(p, s);
  81.     return(p);
  82. }
  83.  
  84.  
  85.