1 /*-------------------------------------------------------------------------*/
6 @version $Revision: 1.1.2.1 $
7 @brief Implements a dictionary for string variables.
9 This module implements a simple dictionary object, i.e. a list
10 of string/string associations. This object is useful to store e.g.
11 informations retrieved from a configuration file (ini files).
13 /*--------------------------------------------------------------------------*/
16 $Id: dictionary.c,v 1.1.2.1 2010-02-12 10:19:23 kleplat Exp $
19 /*---------------------------------------------------------------------------
21 ---------------------------------------------------------------------------*/
22 #include "dictionary.h"
31 /** Maximum value size for integers and doubles. */
34 /** Minimal allocated number of entries in a dictionary */
37 /** Invalid key token */
38 #define DICT_INVALID_KEY ((char*)-1)
40 /*---------------------------------------------------------------------------
42 ---------------------------------------------------------------------------*/
44 /* Doubles the allocated size associated to a pointer */
45 /* 'size' is the current allocated size. */
46 static void * mem_double(void * ptr, int size)
50 newptr = calloc(2*size, 1);
54 memcpy(newptr, ptr, size);
59 /*-------------------------------------------------------------------------*/
61 @brief Duplicate a string
62 @param s String to duplicate
63 @return Pointer to a newly allocated string, to be freed with free()
65 This is a replacement for strdup(). This implementation is provided
66 for systems that do not have it.
68 /*--------------------------------------------------------------------------*/
69 static char * xstrdup(const char * s)
74 t = malloc(strlen(s)+1) ;
81 /*---------------------------------------------------------------------------
83 ---------------------------------------------------------------------------*/
84 /*-------------------------------------------------------------------------*/
86 @brief Compute the hash key for a string.
87 @param key Character string to use for key.
88 @return 1 unsigned int on at least 32 bits.
90 This hash function has been taken from an Article in Dr Dobbs Journal.
91 This is normally a collision-free function, distributing keys evenly.
92 The key is stored anyway in the struct so that collision can be avoided
93 by comparing the key itself in last resort.
95 /*--------------------------------------------------------------------------*/
96 unsigned dictionary_hash(const char * key)
103 for (hash=0, i=0 ; i<len ; i++) {
104 hash += (unsigned)key[i] ;
114 /*-------------------------------------------------------------------------*/
116 @brief Create a new dictionary object.
117 @param size Optional initial size of the dictionary.
118 @return 1 newly allocated dictionary objet.
120 This function allocates a new dictionary object of given size and returns
121 it. If you do not know in advance (roughly) the number of entries in the
122 dictionary, give size=0.
124 /*--------------------------------------------------------------------------*/
125 dictionary * dictionary_new(int size)
129 /* If no size was specified, allocate space for DICTMINSZ */
130 if (size<DICTMINSZ) size=DICTMINSZ ;
132 if (!(d = (dictionary *)calloc(1, sizeof(dictionary))))
136 d->values = (dictionary_value *)calloc(size, sizeof(dictionary_value));
137 d->key = (char **)calloc(size, sizeof(char*));
138 d->hash = (unsigned int *)calloc(size, sizeof(unsigned));
140 memset(d->values, 0, size*sizeof(dictionary_value));
141 memset(d->key, 0, size*sizeof(char*));
142 memset(d->hash, 0, size*sizeof(unsigned));
147 /*-------------------------------------------------------------------------*/
149 @brief Delete a dictionary object
150 @param d dictionary object to deallocate.
153 Deallocate a dictionary object and all memory associated to it.
155 /*--------------------------------------------------------------------------*/
156 void dictionary_del(dictionary * d)
160 if (d==NULL) return ;
161 for (i=0 ; i<d->size ; i++) {
164 if (d->values[i].val!=NULL)
165 free(d->values[i].val);
174 /*-------------------------------------------------------------------------*/
176 @brief Get a value from a dictionary.
177 @param d dictionary object to search.
178 @param key Key to look for in the dictionary.
179 @return 1 pointer to internally allocated character string.
181 This function locates a key in a dictionary and returns a pointer to its
182 value, or the passed 'def' pointer if no such key can be found in
183 dictionary. The returned character pointer points to data internal to the
184 dictionary object, you should not try to free it or modify it.
186 /*--------------------------------------------------------------------------*/
187 dictionary_value* dictionary_get(dictionary * d, const char * key)
192 hash = dictionary_hash(key);
193 for (i=0 ; i<d->size ; i++) {
197 if (hash==d->hash[i]) {
198 /* Compare string, to avoid hash collisions */
199 if (!strcmp(key, d->key[i])) {
200 return &d->values[i];
207 /*-------------------------------------------------------------------------*/
209 @brief Set a value in a dictionary.
210 @param d dictionary object to modify.
211 @param key Key to modify or add.
212 @param val Value to add.
213 @return int 0 if Ok, anything else otherwise
215 If the given key is found in the dictionary, the associated value is
216 replaced by the provided one. If the key cannot be found in the
217 dictionary, it is added to it.
219 It is Ok to provide a NULL value for val, but NULL values for the dictionary
220 or the key are considered as errors: the function will return immediately
223 Notice that if you dictionary_set a variable to NULL, a call to
224 dictionary_get will return a NULL value: the variable will be found, and
225 its value (NULL) is returned. In other words, setting the variable
226 content to NULL is equivalent to deleting the variable from the
227 dictionary. It is not possible (in this implementation) to have a key in
228 the dictionary without value.
230 This function returns non-zero in case of failure.
232 /*--------------------------------------------------------------------------*/
233 dictionary_value* dictionary_set(dictionary * d, const char * key, char * val, int type, void* ptr,void (*cb)(void))
238 if (d==NULL || key==NULL)
241 /* Compute hash for this key */
242 hash = dictionary_hash(key) ;
243 /* Find if value is already in dictionary */
245 for (i=0 ; i<d->size ; i++) {
248 if (hash==d->hash[i]) { /* Same hash value */
249 if (!strcmp(key, d->key[i])) { /* Same key */
250 /* Found a value: modify and return */
251 if (d->values[i].val!=NULL)
252 free(d->values[i].val);
254 d->values[i].val = (val != NULL) ? xstrdup(val) : NULL ;
255 /* Value has been modified: return */
256 return &d->values[i];
262 /* Add a new value */
263 /* See if dictionary needs to grow */
265 /* Reached maximum size: reallocate dictionary */
266 d->values = (dictionary_value *)mem_double(d->values, d->size * sizeof(dictionary_value*)) ;
267 d->key = (char **)mem_double(d->key, d->size * sizeof(char*)) ;
268 d->hash = (unsigned int *)mem_double(d->hash, d->size * sizeof(unsigned)) ;
269 if ((d->values==NULL) || (d->key==NULL) || (d->hash==NULL)) {
270 /* Cannot grow dictionary */
277 /* Insert key in the first empty slot */
278 for (i=0 ; i<d->size ; i++) {
279 if (d->key[i]==NULL) {
285 d->key[i] = xstrdup(key);
286 d->values[i].val = (val != NULL) ? xstrdup(val) : NULL;
287 d->values[i].type = type;
288 d->values[i].callback = NULL;
290 d->values[i].scope = -1;
291 d->values[i].ptr = ptr;
295 return &d->values[i] ;
298 /*-------------------------------------------------------------------------*/
300 @brief Delete a key in a dictionary
301 @param d dictionary object to modify.
302 @param key Key to remove.
305 This function deletes a key in a dictionary. Nothing is done if the
308 /*--------------------------------------------------------------------------*/
309 void dictionary_unset(dictionary * d, const char * key)
318 hash = dictionary_hash(key);
319 for (i=0 ; i<d->size ; i++) {
323 if (hash==d->hash[i]) {
324 /* Compare string, to avoid hash collisions */
325 if (!strcmp(key, d->key[i])) {
338 if (d->values[i].val!=NULL) {
339 free(d->values[i].val);
340 d->values[i].val = NULL ;
347 /*-------------------------------------------------------------------------*/
349 @brief Dump a dictionary to an opened file pointer.
350 @param d Dictionary to dump
351 @param f Opened file pointer.
354 Dumps a dictionary onto an opened file pointer. Key pairs are printed out
355 as @c [Key]=[Value], one per line. It is Ok to provide stdout or stderr as
356 output file pointers.
358 /*--------------------------------------------------------------------------*/
359 void dictionary_dump(dictionary * d, FILE * out)
363 if (d==NULL || out==NULL) return ;
365 fprintf(out, "empty dictionary\n");
368 for (i=0 ; i<d->size ; i++) {
370 fprintf(out, "%20s\t[%s]\n", d->key[i], (d->values[i].val != NULL) ? d->values[i].val : "UNDEF");
380 int main(int argc, char *argv[])
387 /* Allocate dictionary */
388 printf("allocating...\n");
389 d = dictionary_new(0);
391 /* Set values in dictionary */
392 printf("setting %d values...\n", NVALS);
393 for (i=0 ; i<NVALS ; i++) {
394 sprintf(cval, "%04d", i);
395 dictionary_set(d, cval, "salut");
397 printf("getting %d values...\n", NVALS);
398 for (i=0 ; i<NVALS ; i++) {
399 sprintf(cval, "%04d", i);
400 val = dictionary_get(d, cval, DICT_INVALID_KEY);
401 if (val==DICT_INVALID_KEY) {
402 printf("cannot get value for key [%s]\n", cval);
405 printf("unsetting %d values...\n", NVALS);
406 for (i=0 ; i<NVALS ; i++) {
407 sprintf(cval, "%04d", i);
408 dictionary_unset(d, cval);
411 printf("error deleting values\n");
413 printf("deallocating...\n");
418 /* vim: set ts=4 et sw=4 tw=75 */