SHARE
TWEET

string hash code

quixadhal Jun 13th, 2014 248 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <ctype.h>
  5. #include <string.h>
  6.  
  7. #define BUCKETS 100
  8.  
  9. struct s_stringMap;
  10.  
  11. typedef struct s_stringMap {
  12.     const char *key;
  13.     const char *value;
  14.     struct s_stringMap *next;
  15. } stringMap;
  16.  
  17. unsigned int hashmap( const char *s );
  18. void hash_init( stringMap *map );
  19. void hash_add( stringMap *map, const char *k, const char *v );
  20. const char * hash_find(stringMap *map, const char *k);
  21.  
  22. unsigned int hashmap( const char *s )
  23. {
  24.     unsigned int hash = 0;
  25.  
  26.     if(!s || !*s) return 0;
  27.     do {
  28.         hash += *s;
  29.         hash *= 13;
  30.         s++;
  31.     } while (*s);
  32.  
  33.     return hash % BUCKETS;
  34. }
  35.  
  36. void hash_init( stringMap *map )
  37. {
  38.     int i;
  39.  
  40.     for(i = 0; i < BUCKETS; i++)
  41.     {
  42.         map[i].key = NULL;
  43.         map[i].value = NULL;
  44.         map[i].next = NULL;
  45.     }
  46. }
  47.  
  48. void hash_add( stringMap *map, const char *k, const char *v )
  49. {
  50.     unsigned int hashcode;
  51.     stringMap *p;
  52.  
  53.     hashcode = hashmap(k);
  54.     p = &map[hashcode];
  55.     while(p->key && strcmp(p->key, k) && p->next)
  56.         p = p->next;
  57.  
  58.     if(!p->key) {
  59.         /* First node? */
  60.         p->key = (const char *)strdup(k);
  61.         p->value = (const char *)strdup(v);
  62.         p->next = NULL;
  63.     } else if(!strcmp(p->key, k)) {
  64.         /* Found our match! */
  65.         if(p->value)
  66.             free((void *)p->value);
  67.         p->value = (const char *)strdup(v);
  68.     } else {
  69.         /* New key */
  70.         p->next = (stringMap *)calloc(1, sizeof(stringMap));
  71.         p = p->next;
  72.         p->key = (const char *)strdup(k);
  73.         p->value = (const char *)strdup(v);
  74.         p->next = NULL;
  75.     }
  76. }
  77.  
  78. const char * hash_find(stringMap *map, const char *k)
  79. {
  80.     unsigned int hashcode;
  81.     stringMap *p;
  82.  
  83.     hashcode = hashmap(k);
  84.     p = &map[hashcode];
  85.     while(p->key && strcmp(p->key, k) && p->next)
  86.         p = p->next;
  87.  
  88.     if(!p->key)
  89.         return NULL;
  90.  
  91.     if(!strcmp(p->key, k))
  92.         return p->value;
  93.  
  94.     return NULL;
  95. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top