1 /*-------------------------------------------------------------------------*/
6 @version $Revision: 1.27 $
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.27 2007-11-23 21:39:18 ndevilla Exp $
19 /*---------------------------------------------------------------------------
21 ---------------------------------------------------------------------------*/
22 #include "dictionary.h"
29 /** Maximum value size for integers and doubles. */
32 /** Minimal allocated number of entries in a dictionary */
35 /** Invalid key token */
36 #define DICT_INVALID_KEY ((char*)-1)
38 /*---------------------------------------------------------------------------
40 ---------------------------------------------------------------------------*/
42 /* Doubles the allocated size associated to a pointer */
43 /* 'size' is the current allocated size. */
44 static void * mem_double(void * ptr, int size)
48 newptr = calloc(2*size, 1);
52 memcpy(newptr, ptr, size);
57 /*-------------------------------------------------------------------------*/
59 @brief Duplicate a string
60 @param s String to duplicate
61 @return Pointer to a newly allocated string, to be freed with free()
63 This is a replacement for strdup(). This implementation is provided
64 for systems that do not have it.
66 /*--------------------------------------------------------------------------*/
67 static char * xstrdup(char * s)
72 t = malloc(strlen(s)+1) ;
79 /*---------------------------------------------------------------------------
81 ---------------------------------------------------------------------------*/
82 /*-------------------------------------------------------------------------*/
84 @brief Compute the hash key for a string.
85 @param key Character string to use for key.
86 @return 1 unsigned int on at least 32 bits.
88 This hash function has been taken from an Article in Dr Dobbs Journal.
89 This is normally a collision-free function, distributing keys evenly.
90 The key is stored anyway in the struct so that collision can be avoided
91 by comparing the key itself in last resort.
93 /*--------------------------------------------------------------------------*/
94 unsigned dictionary_hash(char * key)
101 for (hash=0, i=0 ; i<len ; i++) {
102 hash += (unsigned)key[i] ;
112 /*-------------------------------------------------------------------------*/
114 @brief Create a new dictionary object.
115 @param size Optional initial size of the dictionary.
116 @return 1 newly allocated dictionary objet.
118 This function allocates a new dictionary object of given size and returns
119 it. If you do not know in advance (roughly) the number of entries in the
120 dictionary, give size=0.
122 /*--------------------------------------------------------------------------*/
123 dictionary * dictionary_new(int size)
127 /* If no size was specified, allocate space for DICTMINSZ */
128 if (size<DICTMINSZ) size=DICTMINSZ ;
130 if (!(d = (dictionary *)calloc(1, sizeof(dictionary)))) {
134 d->val = (char **)calloc(size, sizeof(char*));
135 d->key = (char **)calloc(size, sizeof(char*));
136 d->hash = (unsigned int *)calloc(size, sizeof(unsigned));
140 /*-------------------------------------------------------------------------*/
142 @brief Delete a dictionary object
143 @param d dictionary object to deallocate.
146 Deallocate a dictionary object and all memory associated to it.
148 /*--------------------------------------------------------------------------*/
149 void dictionary_del(dictionary * d)
153 if (d==NULL) return ;
154 for (i=0 ; i<d->size ; i++) {
167 /*-------------------------------------------------------------------------*/
169 @brief Get a value from a dictionary.
170 @param d dictionary object to search.
171 @param key Key to look for in the dictionary.
172 @param def Default value to return if key not found.
173 @return 1 pointer to internally allocated character string.
175 This function locates a key in a dictionary and returns a pointer to its
176 value, or the passed 'def' pointer if no such key can be found in
177 dictionary. The returned character pointer points to data internal to the
178 dictionary object, you should not try to free it or modify it.
180 /*--------------------------------------------------------------------------*/
181 char * dictionary_get(dictionary * d, char * key, char * def)
186 hash = dictionary_hash(key);
187 for (i=0 ; i<d->size ; i++) {
191 if (hash==d->hash[i]) {
192 /* Compare string, to avoid hash collisions */
193 if (!strcmp(key, d->key[i])) {
201 /*-------------------------------------------------------------------------*/
203 @brief Set a value in a dictionary.
204 @param d dictionary object to modify.
205 @param key Key to modify or add.
206 @param val Value to add.
207 @return int 0 if Ok, anything else otherwise
209 If the given key is found in the dictionary, the associated value is
210 replaced by the provided one. If the key cannot be found in the
211 dictionary, it is added to it.
213 It is Ok to provide a NULL value for val, but NULL values for the dictionary
214 or the key are considered as errors: the function will return immediately
217 Notice that if you dictionary_set a variable to NULL, a call to
218 dictionary_get will return a NULL value: the variable will be found, and
219 its value (NULL) is returned. In other words, setting the variable
220 content to NULL is equivalent to deleting the variable from the
221 dictionary. It is not possible (in this implementation) to have a key in
222 the dictionary without value.
224 This function returns non-zero in case of failure.
226 /*--------------------------------------------------------------------------*/
227 int dictionary_set(dictionary * d, char * key, char * val)
232 if (d==NULL || key==NULL) return -1 ;
234 /* Compute hash for this key */
235 hash = dictionary_hash(key) ;
236 /* Find if value is already in dictionary */
238 for (i=0 ; i<d->size ; i++) {
241 if (hash==d->hash[i]) { /* Same hash value */
242 if (!strcmp(key, d->key[i])) { /* Same key */
243 /* Found a value: modify and return */
246 d->val[i] = val ? xstrdup(val) : NULL ;
247 /* Value has been modified: return */
253 /* Add a new value */
254 /* See if dictionary needs to grow */
257 /* Reached maximum size: reallocate dictionary */
258 d->val = (char **)mem_double(d->val, d->size * sizeof(char*)) ;
259 d->key = (char **)mem_double(d->key, d->size * sizeof(char*)) ;
260 d->hash = (unsigned int *)mem_double(d->hash, d->size * sizeof(unsigned)) ;
261 if ((d->val==NULL) || (d->key==NULL) || (d->hash==NULL)) {
262 /* Cannot grow dictionary */
269 /* Insert key in the first empty slot */
270 for (i=0 ; i<d->size ; i++) {
271 if (d->key[i]==NULL) {
277 d->key[i] = xstrdup(key);
278 d->val[i] = val ? xstrdup(val) : NULL ;
284 /*-------------------------------------------------------------------------*/
286 @brief Delete a key in a dictionary
287 @param d dictionary object to modify.
288 @param key Key to remove.
291 This function deletes a key in a dictionary. Nothing is done if the
294 /*--------------------------------------------------------------------------*/
295 void dictionary_unset(dictionary * d, char * key)
304 hash = dictionary_hash(key);
305 for (i=0 ; i<d->size ; i++) {
309 if (hash==d->hash[i]) {
310 /* Compare string, to avoid hash collisions */
311 if (!strcmp(key, d->key[i])) {
323 if (d->val[i]!=NULL) {
332 /*-------------------------------------------------------------------------*/
334 @brief Dump a dictionary to an opened file pointer.
335 @param d Dictionary to dump
336 @param f Opened file pointer.
339 Dumps a dictionary onto an opened file pointer. Key pairs are printed out
340 as @c [Key]=[Value], one per line. It is Ok to provide stdout or stderr as
341 output file pointers.
343 /*--------------------------------------------------------------------------*/
344 void dictionary_dump(dictionary * d, FILE * out)
348 if (d==NULL || out==NULL) return ;
350 fprintf(out, "empty dictionary\n");
353 for (i=0 ; i<d->size ; i++) {
355 fprintf(out, "%20s\t[%s]\n",
357 d->val[i] ? d->val[i] : "UNDEF");
367 int main(int argc, char *argv[])
374 /* Allocate dictionary */
375 printf("allocating...\n");
376 d = dictionary_new(0);
378 /* Set values in dictionary */
379 printf("setting %d values...\n", NVALS);
380 for (i=0 ; i<NVALS ; i++) {
381 sprintf(cval, "%04d", i);
382 dictionary_set(d, cval, "salut");
384 printf("getting %d values...\n", NVALS);
385 for (i=0 ; i<NVALS ; i++) {
386 sprintf(cval, "%04d", i);
387 val = dictionary_get(d, cval, DICT_INVALID_KEY);
388 if (val==DICT_INVALID_KEY) {
389 printf("cannot get value for key [%s]\n", cval);
392 printf("unsetting %d values...\n", NVALS);
393 for (i=0 ; i<NVALS ; i++) {
394 sprintf(cval, "%04d", i);
395 dictionary_unset(d, cval);
398 printf("error deleting values\n");
400 printf("deallocating...\n");
405 /* vim: set ts=4 et sw=4 tw=75 */