aboutsummaryrefslogtreecommitdiffstats
path: root/src/util-hash.c
blob: 98239fa11074a89111a5681b059d7c0ec3b8e55f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "matchbox-stroke.h"

/* v.simple hash implementation */

#define HASHSIZE 101

struct UtilHash 
{
  UtilHashNode **hashtab;
  int            size;
};

struct UtilHashNode 
{
   UtilHashNode  *next;
   char          *key;
   pointer       *value;
};

UtilHash*
util_hash_new(void)
{
  UtilHash *hash;

  hash          = util_malloc0(sizeof(UtilHash));
  hash->size    = HASHSIZE;
  hash->hashtab = util_malloc0(sizeof(UtilHashNode)*HASHSIZE);

  return hash;
}

static unsigned int 
hashfunc(UtilHash *hash, char *s)
{
  unsigned int hash_val;

  for(hash_val = 0; *s != '\0'; s++)
    hash_val = *s + 21 * hash_val;

  return hash_val % hash->size;
}

UtilHashNode*
util_hash_lookup_node(UtilHash *hash, char *key)
{
   UtilHashNode *node;

   for (node = hash->hashtab[hashfunc(hash, key)]; 
	node != NULL; 
	node = node->next)
     {
       if (streq(key, node->key))
	 return node;
     }

   return NULL;
}

pointer
util_hash_lookup(UtilHash *hash, char *key)
{
  UtilHashNode *node = NULL;

  node = util_hash_lookup_node(hash, key);

  if (node) 
    return node->value;

  return NULL;
}

void
util_hash_insert(UtilHash *hash, char *key, pointer val)
{
   UtilHashNode *node;
   unsigned int  hashval;

   if ((node = util_hash_lookup_node(hash, key)) == NULL)
     {
       hashval = hashfunc(hash, key);
       
       node       = util_malloc0(sizeof(UtilHashNode));
       node->key  = strdup(key);

       /* link nodes, if any */
       node->next = hash->hashtab[hashval];
       hash->hashtab[hashval] = node;
     } 
   else  /* hmm, key already exists, reset val   */
     free(node->value);
   
   node->value = val;

}

void 
util_hash_destroy(UtilHash *hash)
{
  UtilHashNode *node = NULL, *onode = NULL;
  int           i;

  for (i=0; i<hash->size; i++)
    if (hash->hashtab[i])
      {
	node = hash->hashtab[i];
	while (node != NULL) 
	  {
	    onode = node->next;
	    if (node->key)   free(node->key);
	    /* XXX should call destroyFunc */
	    if (node->value) free(node->value);
	    free(node);
	    node = onode;
	  }
      }

  free(hash->hashtab);
  free(hash);
}