Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/common/dict.c
blob: d4cfd8e7461350f500fc0d8451ff501e9f7e5db4 (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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
   dict.c - dictionary functions
   This file is part of the nss-pam-ldapd library.

   Copyright (C) 2007, 2008, 2009, 2010, 2012, 2013 Arthur de Jong

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301 USA
*/

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif /* HAVE_STDINT_H */

#include "dict.h"

/*
   This module uses a hashtable to store its key to value mappings. The
   structure is basically as follows:

   [struct dictionary]
     \- holds an array of pointers to a linked list of [struct dict_entry]
          \- each entry has a key/value mapping

   The hashmap can be resized when the total number of elements in the hashmap
   exceeds a certain load factor.

   All the keys are copied in a separate linked list of buffers where each new
   buffer that is allocated is larger than the previous one. The first buffer
   in the linked list is always the current one.
*/

/* an entry stores one key/value pair */
struct dict_entry {
  uint32_t hash;      /* used for quick matching and rehashing */
  const char *key;    /* a reference to a copy of the key */
  void *value;        /* the stored value */
  struct dict_entry *next;
};

/* the initial size of the hashtable */
#define DICT_INITSIZE 7

/* load factor at which point to grow hashtable */
#define DICT_LOADPERCENTAGE 400

/* the dictionary is a hashtable */
struct dictionary {
  int size;                      /* size of the hashtable */
  int num;                       /* total number of keys stored */
  struct dict_entry **table;     /* the hashtable */
};

/* Simple hash function that computes the hash value of a string. */
static uint32_t stringhash(const char *str)
{
  uint32_t hash = 5381;
  uint32_t c;
  while ((c = *str++) != '\0')
    hash = 33 * hash + c;
  return hash;
}

/* Grow the hashtable. */
static void growhashtable(DICT *dict)
{
  int i;
  int newsize;
  struct dict_entry **newtable;
  struct dict_entry *entry, *tmp;
  newsize = dict->size * 3 + 1;
  /* allocate room for new hashtable */
  newtable = (struct dict_entry **)malloc(newsize * sizeof(struct dict_entry *));
  if (newtable == NULL)
    return; /* allocating memory failed continue to fill the existing table */
  /* clear new table */
  for (i = 0; i < newsize; i++)
    newtable[i] = NULL;
  /* copy old hashtable into new table */
  for (i = 0; i < dict->size; i++)
  {
    /* go over elements in linked list */
    entry = dict->table[i];
    while (entry != NULL)
    {
      tmp = entry;
      entry = entry->next;
      /* put in new position */
      tmp->next = newtable[tmp->hash % newsize];
      newtable[tmp->hash % newsize] = tmp;
    }
  }
  /* free the old hashtable */
  free(dict->table);
  /* put new hashtable in place */
  dict->size = newsize;
  dict->table = newtable;
}

DICT *dict_new(void)
{
  struct dictionary *dict;
  int i;
  /* allocate room for dictionary information */
  dict = (struct dictionary *)malloc(sizeof(struct dictionary));
  if (dict == NULL)
    return NULL;
  dict->size = DICT_INITSIZE;
  dict->num = 0;
  /* allocate initial hashtable */
  dict->table = (struct dict_entry **)malloc(DICT_INITSIZE * sizeof(struct dict_entry *));
  if (dict->table == NULL)
  {
    free(dict);
    return NULL;
  }
  /* clear the hashtable */
  for (i = 0; i < DICT_INITSIZE; i++)
    dict->table[i] = NULL;
  /* we're done */
  return dict;
}

void dict_free(DICT *dict)
{
  struct dict_entry *entry, *etmp;
  int i;
  /* free hashtable entries */
  for (i = 0; i < dict->size; i++)
  {
    entry = dict->table[i];
    while (entry != NULL)
    {
      etmp = entry;
      entry = entry->next;
      free(etmp);
    }
  }
  /* free the hashtable */
  free(dict->table);
  /* free dictionary struct itself */
  free(dict);
}

void *dict_get(DICT *dict, const char *key)
{
  uint32_t hash;
  struct dict_entry *entry;
  /* calculate the hash */
  hash = stringhash(key);
  /* loop over the linked list in the hashtable */
  for (entry = dict->table[hash % dict->size]; entry != NULL; entry = entry->next)
  {
    if ((entry->hash == hash) && (strcmp(entry->key, key) == 0))
      return entry->value;
  }
  /* no matches found */
  return NULL;
}

const char *dict_getany(DICT *dict)
{
  int i;
  /* loop over the linked list in the hashtable */
  for (i = 0; i < dict->size; i++)
    if (dict->table[i])
      return dict->table[i]->key;
  /* no matches found */
  return NULL;
}

int dict_put(DICT *dict, const char *key, void *value)
{
  uint32_t hash;
  int l;
  char *buf;
  int idx;
  struct dict_entry *entry, *prev;
  /* check if we should grow the hashtable */
  if (dict->num >= ((dict->size * DICT_LOADPERCENTAGE) / 100))
    growhashtable(dict);
  /* calculate the hash and position in the hashtable */
  hash = stringhash(key);
  idx = hash % dict->size;
  /* check if the entry is already present */
  for (entry = dict->table[idx], prev = NULL; entry != NULL; prev = entry, entry = entry->next)
  {
    if ((entry->hash == hash) && (strcmp(entry->key, key) == 0))
    {
      /* check if we should unset the entry */
      if (value == NULL)
      {
        /* remove from linked list */
        if (prev == NULL)
          dict->table[idx] = entry->next;
        else
          prev->next = entry->next;
        /* free entry memory and register removal */
        free(entry);
        dict->num--;
        return 0;
      }
      /* just set the new value */
      entry->value = value;
      return 0;
    }
  }
  /* if entry should be unset we're done */
  if (value == NULL)
    return 0;
  /* entry is not present, make new entry */
  l = strlen(key) + 1;
  buf = (char *)malloc(sizeof(struct dict_entry) + l);
  if (buf == NULL)
    return -1;
  entry = (struct dict_entry *)(void *)buf;
  buf += sizeof(struct dict_entry);
  strcpy(buf, key);
  entry->hash = hash;
  entry->key = buf;
  entry->value = value;
  /* insert into hashtable/linked list */
  entry->next = dict->table[idx];
  dict->table[idx] = entry;
  /* increment number of stored items */
  dict->num++;
  return 0;
}

const char **dict_keys(DICT *dict)
{
  int i;
  struct dict_entry *entry;
  char *buf;
  const char **values;
  size_t sz;
  int num;
  /* figure out how much memory to allocate */
  num = 0;
  sz = 0;
  for (i = 0; i < dict->size; i++)
  {
    entry = dict->table[i];
    while (entry != NULL)
    {
      num++;
      sz += strlen(entry->key) + 1;
      entry = entry->next;
    }
  }
  /* allocate the needed memory */
  buf = (char *)malloc((num + 1) * sizeof(char *) + sz);
  if (buf == NULL)
    return NULL;
  values = (const char **)(void *)buf;
  buf += (num + 1) * sizeof(char *);
  /* fill the array with the keys */
  num = 0;
  for (i = 0; i < dict->size; i++)
  {
    entry = dict->table[i];
    while (entry != NULL)
    {
      strcpy(buf, entry->key);
      values[num++] = buf;
      buf += strlen(buf) + 1;
      entry = entry->next;
    }
  }
  values[num] = NULL;
  /* done */
  return values;
}