Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Define xbt_dictelm_set_data, to reduce code duplication.
[simgrid.git] / src / xbt / dict.c
1 /* dict - a generic dictionary, variation over hash table                   */
2
3 /* Copyright (c) 2004-2011. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #define DJB2_HASH_FUNCTION
10 //#define FNV_HASH_FUNCTION
11
12 #include <string.h>
13 #include <stdio.h>
14 #include "xbt/ex.h"
15 #include "xbt/log.h"
16 #include "xbt/mallocator.h"
17 #include "xbt_modinter.h"
18 #include "dict_private.h"
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict, xbt,
21                                 "Dictionaries provide the same functionalities than hash tables");
22
23 /**
24  * \brief Constructor
25  * \return pointer to the destination
26  * \see xbt_dict_free()
27  *
28  * Creates and initialize a new dictionary with a default hashtable size.
29  */
30 xbt_dict_t xbt_dict_new(void)
31 {
32   xbt_dict_t dict;
33
34   dict = xbt_new(s_xbt_dict_t, 1);
35   dict->free_f = NULL;
36   dict->table_size = 127;
37   dict->table = xbt_new0(xbt_dictelm_t, dict->table_size + 1);
38   dict->count = 0;
39   dict->fill = 0;
40   dict->homogeneous = 0;
41
42   return dict;
43 }
44
45 /**
46  * \brief Destructor
47  * \param dict the dictionary to be freed
48  *
49  * Frees a dictionary with all the data
50  */
51 void xbt_dict_free(xbt_dict_t * dict)
52 {
53   int i;
54   xbt_dictelm_t current, previous;
55   int table_size;
56   xbt_dictelm_t *table;
57
58   //  if ( *dict )  xbt_dict_dump_sizes(*dict);
59
60   if (dict != NULL && *dict != NULL) {
61     table_size = (*dict)->table_size;
62     table = (*dict)->table;
63     /* Warning: the size of the table is 'table_size+1'...
64      * This is because table_size is used as a binary mask in xbt_dict_rehash */
65     for (i = 0; (*dict)->count && i <= table_size; i++) {
66       current = table[i];
67       while (current != NULL) {
68         previous = current;
69         current = current->next;
70         xbt_dictelm_free(*dict, previous);
71         (*dict)->count--;
72       }
73     }
74     xbt_free(table);
75     xbt_free(*dict);
76     *dict = NULL;
77   }
78 }
79
80 /**
81  * Returns the amount of elements in the dict
82  */
83 XBT_INLINE unsigned int xbt_dict_size(xbt_dict_t dict)
84 {
85   return (dict ? (unsigned int) dict->count : (unsigned int) 0);
86 }
87
88 /**
89  * Returns the hash code of a string.
90  */
91 static XBT_INLINE unsigned int xbt_dict_hash_ext(const char *str,
92                                                  int str_len)
93 {
94
95
96 #ifdef DJB2_HASH_FUNCTION
97   /* fast implementation of djb2 algorithm */
98   int c;
99   register unsigned int hash = 5381;
100
101   while (str_len--) {
102     c = *str++;
103     hash = ((hash << 5) + hash) + c;    /* hash * 33 + c */
104   }
105 # elif defined(FNV_HASH_FUNCTION)
106   register unsigned int hash = 0x811c9dc5;
107   unsigned char *bp = (unsigned char *) str;    /* start of buffer */
108   unsigned char *be = bp + str_len;     /* beyond end of buffer */
109
110   while (bp < be) {
111     /* multiply by the 32 bit FNV magic prime mod 2^32 */
112     hash +=
113         (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) +
114         (hash << 24);
115
116     /* xor the bottom with the current octet */
117     hash ^= (unsigned int) *bp++;
118   }
119
120 # else
121   register unsigned int hash = 0;
122
123   while (str_len--) {
124     hash += (*str) * (*str);
125     str++;
126   }
127 #endif
128
129   return hash;
130 }
131
132 static XBT_INLINE unsigned int xbt_dict_hash(const char *str)
133 {
134 #ifdef DJB2_HASH_FUNCTION
135   /* fast implementation of djb2 algorithm */
136   int c;
137   register unsigned int hash = 5381;
138
139   while ((c = *str++)) {
140     hash = ((hash << 5) + hash) + c;    /* hash * 33 + c */
141   }
142
143 # elif defined(FNV_HASH_FUNCTION)
144   register unsigned int hash = 0x811c9dc5;
145
146   while (*str) {
147     /* multiply by the 32 bit FNV magic prime mod 2^32 */
148     hash +=
149         (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) +
150         (hash << 24);
151
152     /* xor the bottom with the current byte */
153     hash ^= (unsigned int) *str++;
154   }
155
156 # else
157   register unsigned int hash = 0;
158
159   while (*str) {
160     hash += (*str) * (*str);
161     str++;
162   }
163 #endif
164   return hash;
165 }
166
167 /* Expend the size of the dict */
168 static void xbt_dict_rehash(xbt_dict_t dict)
169 {
170   const int oldsize = dict->table_size + 1;
171   register int newsize = oldsize * 2;
172   register int i;
173   register xbt_dictelm_t *currcell;
174   register xbt_dictelm_t *twincell;
175   register xbt_dictelm_t bucklet;
176   register xbt_dictelm_t *pprev;
177
178   currcell =
179       (xbt_dictelm_t *) xbt_realloc((char *) dict->table,
180                                     newsize * sizeof(xbt_dictelm_t));
181   memset(&currcell[oldsize], 0, oldsize * sizeof(xbt_dictelm_t));       /* zero second half */
182   dict->table_size = --newsize;
183   dict->table = currcell;
184   XBT_DEBUG("REHASH (%d->%d)", oldsize, newsize);
185
186   for (i = 0; i < oldsize; i++, currcell++) {
187     if (!*currcell)             /* empty cell */
188       continue;
189     twincell = currcell + oldsize;
190     for (pprev = currcell, bucklet = *currcell; bucklet; bucklet = *pprev) {
191       /* Since we use "& size" instead of "%size" and since the size was doubled,
192          each bucklet of this cell must either :
193          - stay  in  cell i (ie, currcell)
194          - go to the cell i+oldsize (ie, twincell) */
195       if ((bucklet->hash_code & newsize) != i) {        /* Move to b */
196         *pprev = bucklet->next;
197         bucklet->next = *twincell;
198         if (!*twincell)
199           dict->fill++;
200         *twincell = bucklet;
201         continue;
202       } else {
203         pprev = &bucklet->next;
204       }
205
206     }
207
208     if (!*currcell)             /* everything moved */
209       dict->fill--;
210   }
211 }
212
213 /**
214  * \brief Add data to the dict (arbitrary key)
215  * \param dict the container
216  * \param key the key to set the new data
217  * \param key_len the size of the \a key
218  * \param data the data to add in the dict
219  * \param free_ctn function to call with (\a data as argument) when
220  *        \a data is removed from the dictionary
221  *
222  * Set the \a data in the structure under the \a key, which can be any kind
223  * of data, as long as its length is provided in \a key_len.
224  */
225 XBT_INLINE void xbt_dict_set_ext(xbt_dict_t dict,
226                                  const char *key, int key_len,
227                                  void *data, void_f_pvoid_t free_ctn)
228 {
229
230   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
231
232   xbt_dictelm_t current, previous = NULL;
233   xbt_assert(dict);
234
235   XBT_DEBUG("ADD %.*s hash = %d, size = %d, & = %d", key_len, key, hash_code,
236          dict->table_size, hash_code & dict->table_size);
237   current = dict->table[hash_code & dict->table_size];
238   while (current != NULL &&
239          (hash_code != current->hash_code || key_len != current->key_len
240           || memcmp(key, current->key, key_len))) {
241     previous = current;
242     current = current->next;
243   }
244
245   if (current == NULL) {
246     /* this key doesn't exist yet */
247     current = xbt_dictelm_new(dict, key, key_len, hash_code, data, free_ctn);
248     dict->count++;
249     if (previous == NULL) {
250       dict->table[hash_code & dict->table_size] = current;
251       dict->fill++;
252       if ((dict->fill * 100) / (dict->table_size + 1) > MAX_FILL_PERCENT)
253         xbt_dict_rehash(dict);
254     } else {
255       previous->next = current;
256     }
257   } else {
258     XBT_DEBUG("Replace %.*s by %.*s under key %.*s",
259            key_len, (char *) current->content,
260            key_len, (char *) data, key_len, (char *) key);
261     /* there is already an element with the same key: overwrite it */
262     xbt_dictelm_set_data(dict, current, data, free_ctn);
263   }
264 }
265
266 /**
267  * \brief Add data to the dict (null-terminated key)
268  *
269  * \param dict the dict
270  * \param key the key to set the new data
271  * \param data the data to add in the dict
272  * \param free_ctn function to call with (\a data as argument) when
273  *        \a data is removed from the dictionary
274  *
275  * set the \a data in the structure under the \a key, which is a
276  * null terminated string.
277  */
278 XBT_INLINE void xbt_dict_set(xbt_dict_t dict,
279                              const char *key, void *data,
280                              void_f_pvoid_t free_ctn)
281 {
282
283   xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
284 }
285
286 /**
287  * \brief Retrieve data from the dict (arbitrary key)
288  *
289  * \param dict the dealer of data
290  * \param key the key to find data
291  * \param key_len the size of the \a key
292  * \return the data that we are looking for
293  *
294  * Search the given \a key. Throws not_found_error when not found.
295  */
296 XBT_INLINE void *xbt_dict_get_ext(xbt_dict_t dict, const char *key,
297                                   int key_len)
298 {
299
300
301   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
302   xbt_dictelm_t current;
303
304   xbt_assert(dict);
305
306   current = dict->table[hash_code & dict->table_size];
307   while (current != NULL &&
308          (hash_code != current->hash_code || key_len != current->key_len
309           || memcmp(key, current->key, key_len))) {
310     current = current->next;
311   }
312
313   if (current == NULL)
314     THROWF(not_found_error, 0, "key %.*s not found", key_len, key);
315
316   return current->content;
317 }
318
319 /**
320  * \brief like xbt_dict_get_ext(), but returning NULL when not found
321  */
322 void *xbt_dict_get_or_null_ext(xbt_dict_t dict, const char *key,
323                                int key_len)
324 {
325
326   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
327   xbt_dictelm_t current;
328
329   xbt_assert(dict);
330
331   current = dict->table[hash_code & dict->table_size];
332   while (current != NULL &&
333          (hash_code != current->hash_code || key_len != current->key_len
334           || memcmp(key, current->key, key_len))) {
335     current = current->next;
336   }
337
338   if (current == NULL)
339     return NULL;
340
341   return current->content;
342 }
343
344 /**
345  * @brief retrieve the key associated to that object. Warning, that's a linear search
346  *
347  * Returns NULL if the object cannot be found
348  */
349 char *xbt_dict_get_key(xbt_dict_t dict, const void *data)
350 {
351   int i;
352   xbt_dictelm_t current;
353
354
355   for (i = 0; i <= dict->table_size; i++) {
356     current = dict->table[i];
357     while (current != NULL) {
358       if (current->content == data)
359         return current->key;
360       current = current->next;
361     }
362   }
363
364   return NULL;
365 }
366
367 /**
368  * \brief Retrieve data from the dict (null-terminated key)
369  *
370  * \param dict the dealer of data
371  * \param key the key to find data
372  * \return the data that we are looking for
373  *
374  * Search the given \a key. Throws not_found_error when not found.
375  * Check xbt_dict_get_or_null() for a version returning NULL without exception when
376  * not found.
377  */
378 XBT_INLINE void *xbt_dict_get(xbt_dict_t dict, const char *key)
379 {
380
381   unsigned int hash_code = xbt_dict_hash(key);
382   xbt_dictelm_t current;
383
384   xbt_assert(dict);
385
386   current = dict->table[hash_code & dict->table_size];
387   while (current != NULL
388          && (hash_code != current->hash_code || strcmp(key, current->key)))
389     current = current->next;
390
391   if (current == NULL)
392     THROWF(not_found_error, 0, "key %s not found", key);
393
394   return current->content;
395 }
396
397 /**
398  * \brief like xbt_dict_get(), but returning NULL when not found
399  */
400 XBT_INLINE void *xbt_dict_get_or_null(xbt_dict_t dict, const char *key)
401 {
402   unsigned int hash_code = xbt_dict_hash(key);
403   xbt_dictelm_t current;
404
405   xbt_assert(dict);
406
407   current = dict->table[hash_code & dict->table_size];
408   while (current != NULL &&
409          (hash_code != current->hash_code || strcmp(key, current->key)))
410     current = current->next;
411
412   if (current == NULL)
413     return NULL;
414
415   return current->content;
416 }
417
418
419 /**
420  * \brief Remove data from the dict (arbitrary key)
421  *
422  * \param dict the trash can
423  * \param key the key of the data to be removed
424  * \param key_len the size of the \a key
425  *
426  * Remove the entry associated with the given \a key (throws not_found)
427  */
428 XBT_INLINE void xbt_dict_remove_ext(xbt_dict_t dict, const char *key,
429                                     int key_len)
430 {
431
432
433   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
434   xbt_dictelm_t current, previous = NULL;
435
436   xbt_assert(dict);
437
438   //  fprintf(stderr,"RM %.*s hash = %d, size = %d, & = %d\n",key_len,key,hash_code, dict->table_size, hash_code & dict->table_size);
439   current = dict->table[hash_code & dict->table_size];
440   while (current != NULL &&
441          (hash_code != current->hash_code || key_len != current->key_len
442           || strncmp(key, current->key, key_len))) {
443     previous = current;         /* save the previous node */
444     current = current->next;
445   }
446
447   if (current == NULL)
448     THROWF(not_found_error, 0, "key %.*s not found", key_len, key);
449
450   if (previous != NULL) {
451     previous->next = current->next;
452   } else {
453     dict->table[hash_code & dict->table_size] = current->next;
454   }
455
456   if (!dict->table[hash_code & dict->table_size])
457     dict->fill--;
458
459   xbt_dictelm_free(dict, current);
460   dict->count--;
461 }
462
463
464
465 /**
466  * \brief Remove data from the dict (null-terminated key)
467  *
468  * \param dict the dict
469  * \param key the key of the data to be removed
470  *
471  * Remove the entry associated with the given \a key
472  */
473 XBT_INLINE void xbt_dict_remove(xbt_dict_t dict, const char *key)
474 {
475   xbt_dict_remove_ext(dict, key, strlen(key));
476 }
477
478 /**
479  * \brief Add data to the dict (arbitrary key)
480  * \param dict the container
481  * \param key the key to set the new data
482  * \param data the data to add in the dict
483  *
484  * Set the \a data in the structure under the \a key.
485  * Both \a data and \a key are considered as uintptr_t.
486  */
487 XBT_INLINE void xbt_dicti_set(xbt_dict_t dict,
488                               uintptr_t key, uintptr_t data)
489 {
490   xbt_dict_set_ext(dict, (void *)&key, sizeof key, (void*)data, NULL);
491 }
492
493 /**
494  * \brief Retrieve data from the dict (key considered as a uintptr_t)
495  *
496  * \param dict the dealer of data
497  * \param key the key to find data
498  * \return the data that we are looking for (or 0 if not found)
499  *
500  * Mixing uintptr_t keys with regular keys in the same dict is discouraged
501  */
502 XBT_INLINE uintptr_t xbt_dicti_get(xbt_dict_t dict, uintptr_t key)
503 {
504   return (uintptr_t)xbt_dict_get_or_null_ext(dict, (void *)&key, sizeof key);
505 }
506
507 /** Remove a uintptr_t key from the dict */
508 XBT_INLINE void xbt_dicti_remove(xbt_dict_t dict, uintptr_t key)
509 {
510   xbt_dict_remove_ext(dict, (void *)&key, sizeof key);
511 }
512
513
514 /**
515  * \brief Remove all data from the dict
516  * \param dict the dict
517  */
518 void xbt_dict_reset(xbt_dict_t dict)
519 {
520
521   int i;
522   xbt_dictelm_t current, previous = NULL;
523
524   xbt_assert(dict);
525
526   if (dict->count == 0)
527     return;
528
529   for (i = 0; i <= dict->table_size; i++) {
530     current = dict->table[i];
531     while (current != NULL) {
532       previous = current;
533       current = current->next;
534       xbt_dictelm_free(dict, previous);
535     }
536     dict->table[i] = NULL;
537   }
538
539   dict->count = 0;
540   dict->fill = 0;
541 }
542
543 /**
544  * \brief Return the number of elements in the dict.
545  * \param dict a dictionary
546  */
547 XBT_INLINE int xbt_dict_length(xbt_dict_t dict)
548 {
549   xbt_assert(dict);
550
551   return dict->count;
552 }
553
554 /** @brief function to be used in xbt_dict_dump as long as the stored values are strings */
555 void xbt_dict_dump_output_string(void *s)
556 {
557   fputs(s, stdout);
558 }
559
560 /**
561  * \brief test if the dict is empty or not
562  */
563 XBT_INLINE int xbt_dict_is_empty(xbt_dict_t dict)
564 {
565   return !dict || (xbt_dict_length(dict) == 0);
566 }
567
568 /**
569  * \brief Outputs the content of the structure (debugging purpose)
570  *
571  * \param dict the exibitionist
572  * \param output a function to dump each data in the tree (check @ref xbt_dict_dump_output_string)
573  *
574  * Outputs the content of the structure. (for debugging purpose). \a output is a
575  * function to output the data. If NULL, data won't be displayed.
576  */
577
578 void xbt_dict_dump(xbt_dict_t dict, void_f_pvoid_t output)
579 {
580   int i;
581   xbt_dictelm_t element;
582   printf("Dict %p:\n", dict);
583   if (dict != NULL) {
584     for (i = 0; i < dict->table_size; i++) {
585       element = dict->table[i];
586       if (element) {
587         printf("[\n");
588         while (element != NULL) {
589           printf(" %s -> '", element->key);
590           if (output != NULL) {
591             output(element->content);
592           }
593           printf("'\n");
594           element = element->next;
595         }
596         printf("]\n");
597       } else {
598         printf("[]\n");
599       }
600     }
601   }
602 }
603
604 xbt_dynar_t all_sizes = NULL;
605 /** @brief shows some debugging info about the bucklet repartition */
606 void xbt_dict_dump_sizes(xbt_dict_t dict)
607 {
608
609   int i;
610   unsigned int count;
611   unsigned int size;
612   xbt_dictelm_t element;
613   xbt_dynar_t sizes = xbt_dynar_new(sizeof(int), NULL);
614
615   printf("Dict %p: %d bucklets, %d used cells (of %d) ", dict, dict->count,
616          dict->fill, dict->table_size);
617   if (dict != NULL) {
618     for (i = 0; i < dict->table_size; i++) {
619       element = dict->table[i];
620       size = 0;
621       if (element) {
622         while (element != NULL) {
623           size++;
624           element = element->next;
625         }
626       }
627       if (xbt_dynar_length(sizes) <= size) {
628         int prevsize = 1;
629         xbt_dynar_set(sizes, size, &prevsize);
630       } else {
631         int prevsize;
632         xbt_dynar_get_cpy(sizes, size, &prevsize);
633         prevsize++;
634         xbt_dynar_set(sizes, size, &prevsize);
635       }
636     }
637     if (!all_sizes)
638       all_sizes = xbt_dynar_new(sizeof(int), NULL);
639
640     xbt_dynar_foreach(sizes, count, size) {
641       /* Copy values of this one into all_sizes */
642       int prevcount;
643       if (xbt_dynar_length(all_sizes) <= count) {
644         prevcount = size;
645         xbt_dynar_set(all_sizes, count, &prevcount);
646       } else {
647         xbt_dynar_get_cpy(all_sizes, count, &prevcount);
648         prevcount += size;
649         xbt_dynar_set(all_sizes, count, &prevcount);
650       }
651
652       /* Report current sizes */
653       if (count == 0)
654         continue;
655       if (size == 0)
656         continue;
657       printf("%delm x %u cells; ", count, size);
658     }
659   }
660   printf("\n");
661   xbt_dynar_free(&sizes);
662 }
663
664 /**
665  * Create the dict mallocators.
666  * This is an internal XBT function called during the lib initialization.
667  * It can be used several times to recreate the mallocator, for example when you switch to MC mode
668  */
669 void xbt_dict_preinit(void)
670 {
671   if (dict_elm_mallocator != NULL) {
672     /* Already created. I guess we want to switch to MC mode, so kill the previously created mallocator */
673     xbt_mallocator_free(dict_elm_mallocator);
674   }
675
676   dict_elm_mallocator = xbt_mallocator_new(256,
677                                            dict_elm_mallocator_new_f,
678                                            dict_elm_mallocator_free_f,
679                                            dict_elm_mallocator_reset_f);
680 }
681
682 /**
683  * Destroy the dict mallocators.
684  * This is an internal XBT function during the lib initialization
685  */
686 void xbt_dict_postexit(void)
687 {
688   if (dict_elm_mallocator != NULL) {
689     xbt_mallocator_free(dict_elm_mallocator);
690     dict_elm_mallocator = NULL;
691   }
692   if (all_sizes) {
693     unsigned int count;
694     int size;
695     double avg = 0;
696     int total_count = 0;
697     printf("Overall stats:");
698     xbt_dynar_foreach(all_sizes, count, size) {
699       if (count == 0)
700         continue;
701       if (size == 0)
702         continue;
703       printf("%delm x %d cells; ", count, size);
704       avg += count * size;
705       total_count += size;
706     }
707     printf("; %f elm per cell\n", avg / (double) total_count);
708   }
709 }
710
711 #ifdef SIMGRID_TEST
712 #include "xbt.h"
713 #include "xbt/ex.h"
714 #include "portable.h"
715
716 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
717 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
718
719 XBT_TEST_SUITE("dict", "Dict data container");
720
721 static void print_str(void *str)
722 {
723   printf("%s", (char *) PRINTF_STR(str));
724 }
725
726 static void debuged_add_ext(xbt_dict_t head, const char *key,
727                             const char *data_to_fill)
728 {
729   char *data = xbt_strdup(data_to_fill);
730
731   xbt_test_log("Add %s under %s", PRINTF_STR(data_to_fill),
732                 PRINTF_STR(key));
733
734   xbt_dict_set(head, key, data, &free);
735   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
736     xbt_dict_dump(head, (void (*)(void *)) &printf);
737     fflush(stdout);
738   }
739 }
740
741 static void debuged_add(xbt_dict_t head, const char *key)
742 {
743   debuged_add_ext(head, key, key);
744 }
745
746 static void fill(xbt_dict_t * head)
747 {
748   xbt_test_add("Fill in the dictionnary");
749
750   *head = xbt_dict_new();
751   debuged_add(*head, "12");
752   debuged_add(*head, "12a");
753   debuged_add(*head, "12b");
754   debuged_add(*head, "123");
755   debuged_add(*head, "123456");
756   /* Child becomes child of what to add */
757   debuged_add(*head, "1234");
758   /* Need of common ancestor */
759   debuged_add(*head, "123457");
760 }
761
762
763 static void search_ext(xbt_dict_t head, const char *key, const char *data)
764 {
765   void *found;
766
767   xbt_test_add("Search %s", key);
768   found = xbt_dict_get(head, key);
769   xbt_test_log("Found %s", (char *) found);
770   if (data)
771     xbt_test_assert(found,
772                      "data do not match expectations: found NULL while searching for %s",
773                      data);
774   if (found)
775     xbt_test_assert(!strcmp((char *) data, found),
776                      "data do not match expectations: found %s while searching for %s",
777                      (char *) found, data);
778 }
779
780 static void search(xbt_dict_t head, const char *key)
781 {
782   search_ext(head, key, key);
783 }
784
785 static void debuged_remove(xbt_dict_t head, const char *key)
786 {
787
788   xbt_test_add("Remove '%s'", PRINTF_STR(key));
789   xbt_dict_remove(head, key);
790   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
791 }
792
793
794 static void traverse(xbt_dict_t head)
795 {
796   xbt_dict_cursor_t cursor = NULL;
797   char *key;
798   char *data;
799   int i = 0;
800
801   xbt_dict_foreach(head, cursor, key, data) {
802     if (!key || !data || strcmp(key, data)) {
803       xbt_test_log("Seen #%d:  %s->%s", ++i, PRINTF_STR(key),
804                     PRINTF_STR(data));
805     } else {
806       xbt_test_log("Seen #%d:  %s", ++i, PRINTF_STR(key));
807     }
808     xbt_test_assert(!data || !strcmp(key, data),
809                      "Key(%s) != value(%s). Aborting", key, data);
810   }
811 }
812
813 static void search_not_found(xbt_dict_t head, const char *data)
814 {
815   int ok = 0;
816   xbt_ex_t e;
817
818   xbt_test_add("Search %s (expected not to be found)", data);
819
820   TRY {
821     data = xbt_dict_get(head, data);
822     THROWF(unknown_error, 0,
823            "Found something which shouldn't be there (%s)", data);
824   }
825   CATCH(e) {
826     if (e.category != not_found_error)
827       xbt_test_exception(e);
828     xbt_ex_free(e);
829     ok = 1;
830   }
831   xbt_test_assert(ok, "Exception not raised");
832 }
833
834 static void count(xbt_dict_t dict, int length)
835 {
836   xbt_dict_cursor_t cursor;
837   char *key;
838   void *data;
839   int effective = 0;
840
841
842   xbt_test_add("Count elements (expecting %d)", length);
843   xbt_test_assert(xbt_dict_length(dict) == length,
844                    "Announced length(%d) != %d.", xbt_dict_length(dict),
845                    length);
846
847   xbt_dict_foreach(dict, cursor, key, data)
848       effective++;
849
850   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
851                    effective, length);
852
853 }
854
855 static void count_check_get_key(xbt_dict_t dict, int length)
856 {
857   xbt_dict_cursor_t cursor;
858   char *key;
859   _XBT_GNUC_UNUSED char *key2;
860   void *data;
861   int effective = 0;
862
863
864   xbt_test_add
865       ("Count elements (expecting %d), and test the getkey function",
866        length);
867   xbt_test_assert(xbt_dict_length(dict) == length,
868                    "Announced length(%d) != %d.", xbt_dict_length(dict),
869                    length);
870
871   xbt_dict_foreach(dict, cursor, key, data) {
872     effective++;
873     key2 = xbt_dict_get_key(dict, data);
874     xbt_assert(!strcmp(key, key2),
875                 "The data was registered under %s instead of %s as expected",
876                 key2, key);
877   }
878
879   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
880                    effective, length);
881
882 }
883
884 xbt_ex_t e;
885 xbt_dict_t head = NULL;
886 char *data;
887
888
889 XBT_TEST_UNIT("basic", test_dict_basic, "Basic usage: change, retrieve, traverse")
890 {
891   xbt_test_add("Traversal the null dictionary");
892   traverse(head);
893
894   xbt_test_add("Traversal and search the empty dictionary");
895   head = xbt_dict_new();
896   traverse(head);
897   TRY {
898     debuged_remove(head, "12346");
899   }
900   CATCH(e) {
901     if (e.category != not_found_error)
902       xbt_test_exception(e);
903     xbt_ex_free(e);
904   }
905   xbt_dict_free(&head);
906
907   xbt_test_add("Traverse the full dictionary");
908   fill(&head);
909   count_check_get_key(head, 7);
910
911   debuged_add_ext(head, "toto", "tutu");
912   search_ext(head, "toto", "tutu");
913   debuged_remove(head, "toto");
914
915   search(head, "12a");
916   traverse(head);
917
918   xbt_test_add("Free the dictionary (twice)");
919   xbt_dict_free(&head);
920   xbt_dict_free(&head);
921
922   /* CHANGING */
923   fill(&head);
924   count_check_get_key(head, 7);
925   xbt_test_add("Change 123 to 'Changed 123'");
926   xbt_dict_set(head, "123", strdup("Changed 123"), &free);
927   count_check_get_key(head, 7);
928
929   xbt_test_add("Change 123 back to '123'");
930   xbt_dict_set(head, "123", strdup("123"), &free);
931   count_check_get_key(head, 7);
932
933   xbt_test_add("Change 12a to 'Dummy 12a'");
934   xbt_dict_set(head, "12a", strdup("Dummy 12a"), &free);
935   count_check_get_key(head, 7);
936
937   xbt_test_add("Change 12a to '12a'");
938   xbt_dict_set(head, "12a", strdup("12a"), &free);
939   count_check_get_key(head, 7);
940
941   xbt_test_add("Traverse the resulting dictionary");
942   traverse(head);
943
944   /* RETRIEVE */
945   xbt_test_add("Search 123");
946   data = xbt_dict_get(head, "123");
947   xbt_test_assert(data);
948   xbt_test_assert(!strcmp("123", data));
949
950   search_not_found(head, "Can't be found");
951   search_not_found(head, "123 Can't be found");
952   search_not_found(head, "12345678 NOT");
953
954   search(head, "12a");
955   search(head, "12b");
956   search(head, "12");
957   search(head, "123456");
958   search(head, "1234");
959   search(head, "123457");
960
961   xbt_test_add("Traverse the resulting dictionary");
962   traverse(head);
963
964   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
965
966   xbt_test_add("Free the dictionary twice");
967   xbt_dict_free(&head);
968   xbt_dict_free(&head);
969
970   xbt_test_add("Traverse the resulting dictionary");
971   traverse(head);
972 }
973
974 XBT_TEST_UNIT("remove", test_dict_remove, "Removing some values")
975 {
976   fill(&head);
977   count(head, 7);
978   xbt_test_add("Remove non existing data");
979   TRY {
980     debuged_remove(head, "Does not exist");
981   }
982   CATCH(e) {
983     if (e.category != not_found_error)
984       xbt_test_exception(e);
985     xbt_ex_free(e);
986   }
987   traverse(head);
988
989   xbt_dict_free(&head);
990
991   xbt_test_add
992       ("Remove each data manually (traversing the resulting dictionary each time)");
993   fill(&head);
994   debuged_remove(head, "12a");
995   traverse(head);
996   count(head, 6);
997   debuged_remove(head, "12b");
998   traverse(head);
999   count(head, 5);
1000   debuged_remove(head, "12");
1001   traverse(head);
1002   count(head, 4);
1003   debuged_remove(head, "123456");
1004   traverse(head);
1005   count(head, 3);
1006   TRY {
1007     debuged_remove(head, "12346");
1008   }
1009   CATCH(e) {
1010     if (e.category != not_found_error)
1011       xbt_test_exception(e);
1012     xbt_ex_free(e);
1013     traverse(head);
1014   }
1015   debuged_remove(head, "1234");
1016   traverse(head);
1017   debuged_remove(head, "123457");
1018   traverse(head);
1019   debuged_remove(head, "123");
1020   traverse(head);
1021   TRY {
1022     debuged_remove(head, "12346");
1023   }
1024   CATCH(e) {
1025     if (e.category != not_found_error)
1026       xbt_test_exception(e);
1027     xbt_ex_free(e);
1028   }
1029   traverse(head);
1030
1031   xbt_test_add
1032       ("Free dict, create new fresh one, and then reset the dict");
1033   xbt_dict_free(&head);
1034   fill(&head);
1035   xbt_dict_reset(head);
1036   count(head, 0);
1037   traverse(head);
1038
1039   xbt_test_add("Free the dictionary twice");
1040   xbt_dict_free(&head);
1041   xbt_dict_free(&head);
1042 }
1043
1044 XBT_TEST_UNIT("nulldata", test_dict_nulldata, "NULL data management")
1045 {
1046   fill(&head);
1047
1048   xbt_test_add("Store NULL under 'null'");
1049   xbt_dict_set(head, "null", NULL, NULL);
1050   search_ext(head, "null", NULL);
1051
1052   xbt_test_add("Check whether I see it while traversing...");
1053   {
1054     xbt_dict_cursor_t cursor = NULL;
1055     char *key;
1056     int found = 0;
1057
1058     xbt_dict_foreach(head, cursor, key, data) {
1059       if (!key || !data || strcmp(key, data)) {
1060         xbt_test_log("Seen:  %s->%s", PRINTF_STR(key), PRINTF_STR(data));
1061       } else {
1062         xbt_test_log("Seen:  %s", PRINTF_STR(key));
1063       }
1064
1065       if (!strcmp(key, "null"))
1066         found = 1;
1067     }
1068     xbt_test_assert(found,
1069                      "the key 'null', associated to NULL is not found");
1070   }
1071   xbt_dict_free(&head);
1072 }
1073
1074 static void debuged_addi(xbt_dict_t head, uintptr_t key, uintptr_t data)
1075 {
1076   uintptr_t stored_data = 0;
1077   xbt_test_log("Add %zu under %zu", data, key);
1078
1079   xbt_dicti_set(head, key, data);
1080   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
1081     xbt_dict_dump(head, (void (*)(void *)) &printf);
1082     fflush(stdout);
1083   }
1084   stored_data = xbt_dicti_get(head, key);
1085   xbt_test_assert(stored_data == data,
1086                    "Retrieved data (%zu) is not what I just stored (%zu) under key %zu",
1087                    stored_data, data, key);
1088 }
1089
1090 XBT_TEST_UNIT("dicti", test_dict_scalar, "Scalar data and key management")
1091 {
1092   xbt_test_add("Fill in the dictionnary");
1093
1094   head = xbt_dict_new();
1095   debuged_addi(head, 12, 12);
1096   debuged_addi(head, 13, 13);
1097   debuged_addi(head, 14, 14);
1098   debuged_addi(head, 15, 15);
1099   /* Change values */
1100   debuged_addi(head, 12, 15);
1101   debuged_addi(head, 15, 2000);
1102   debuged_addi(head, 15, 3000);
1103   /* 0 as key */
1104   debuged_addi(head, 0, 1000);
1105   debuged_addi(head, 0, 2000);
1106   debuged_addi(head, 0, 3000);
1107   /* 0 as value */
1108   debuged_addi(head, 12, 0);
1109   debuged_addi(head, 13, 0);
1110   debuged_addi(head, 12, 0);
1111   debuged_addi(head, 0, 0);
1112
1113   xbt_dict_free(&head);
1114 }
1115
1116 #define NB_ELM 20000
1117 #define SIZEOFKEY 1024
1118 static int countelems(xbt_dict_t head)
1119 {
1120   xbt_dict_cursor_t cursor;
1121   char *key;
1122   void *data;
1123   int res = 0;
1124
1125   xbt_dict_foreach(head, cursor, key, data) {
1126     res++;
1127   }
1128   return res;
1129 }
1130
1131 XBT_TEST_UNIT("crash", test_dict_crash, "Crash test")
1132 {
1133   xbt_dict_t head = NULL;
1134   int i, j, k;
1135   char *key;
1136   void *data;
1137
1138   srand((unsigned int) time(NULL));
1139
1140   for (i = 0; i < 10; i++) {
1141     xbt_test_add("CRASH test number %d (%d to go)", i + 1, 10 - i - 1);
1142     xbt_test_log
1143         ("Fill the struct, count its elems and frees the structure");
1144     xbt_test_log
1145         ("using 1000 elements with %d chars long randomized keys.",
1146          SIZEOFKEY);
1147     head = xbt_dict_new();
1148     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1149     for (j = 0; j < 1000; j++) {
1150       char *data = NULL;
1151       key = xbt_malloc(SIZEOFKEY);
1152
1153       do {
1154         for (k = 0; k < SIZEOFKEY - 1; k++)
1155           key[k] = rand() % ('z' - 'a') + 'a';
1156         key[k] = '\0';
1157         /*      printf("[%d %s]\n",j,key); */
1158         data = xbt_dict_get_or_null(head, key);
1159       } while (data != NULL);
1160
1161       xbt_dict_set(head, key, key, &free);
1162       data = xbt_dict_get(head, key);
1163       xbt_test_assert(!strcmp(key, data),
1164                        "Retrieved value (%s) != Injected value (%s)", key,
1165                        data);
1166
1167       count(head, j + 1);
1168     }
1169     /*    xbt_dict_dump(head,(void (*)(void*))&printf); */
1170     traverse(head);
1171     xbt_dict_free(&head);
1172     xbt_dict_free(&head);
1173   }
1174
1175
1176   head = xbt_dict_new();
1177   xbt_test_add("Fill %d elements, with keys being the number of element",
1178                 NB_ELM);
1179   for (j = 0; j < NB_ELM; j++) {
1180     /* if (!(j%1000)) { printf("."); fflush(stdout); } */
1181
1182     key = xbt_malloc(10);
1183
1184     sprintf(key, "%d", j);
1185     xbt_dict_set(head, key, key, &free);
1186   }
1187   /*xbt_dict_dump(head,(void (*)(void*))&printf); */
1188
1189   xbt_test_add
1190       ("Count the elements (retrieving the key and data for each)");
1191   i = countelems(head);
1192   xbt_test_log("There is %d elements", i);
1193
1194   xbt_test_add("Search my %d elements 20 times", NB_ELM);
1195   key = xbt_malloc(10);
1196   for (i = 0; i < 20; i++) {
1197     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1198     for (j = 0; j < NB_ELM; j++) {
1199
1200       sprintf(key, "%d", j);
1201       data = xbt_dict_get(head, key);
1202       xbt_test_assert(!strcmp(key, (char *) data),
1203                        "with get, key=%s != data=%s", key, (char *) data);
1204       data = xbt_dict_get_ext(head, key, strlen(key));
1205       xbt_test_assert(!strcmp(key, (char *) data),
1206                        "with get_ext, key=%s != data=%s", key,
1207                        (char *) data);
1208     }
1209   }
1210   free(key);
1211
1212   xbt_test_add("Remove my %d elements", NB_ELM);
1213   key = xbt_malloc(10);
1214   for (j = 0; j < NB_ELM; j++) {
1215     /* if (!(j%10000)) printf("."); fflush(stdout); */
1216
1217     sprintf(key, "%d", j);
1218     xbt_dict_remove(head, key);
1219   }
1220   free(key);
1221
1222
1223   xbt_test_add("Free the structure (twice)");
1224   xbt_dict_free(&head);
1225   xbt_dict_free(&head);
1226 }
1227
1228 static void str_free(void *s)
1229 {
1230   char *c = *(char **) s;
1231   free(c);
1232 }
1233
1234 XBT_TEST_UNIT("multicrash", test_dict_multicrash, "Multi-dict crash test")
1235 {
1236
1237 #undef NB_ELM
1238 #define NB_ELM 100              /*00 */
1239 #define DEPTH 5
1240 #define KEY_SIZE 512
1241 #define NB_TEST 20              /*20 */
1242   int verbose = 0;
1243
1244   xbt_dict_t mdict = NULL;
1245   int i, j, k, l;
1246   xbt_dynar_t keys = xbt_dynar_new(sizeof(char *), str_free);
1247   void *data;
1248   char *key;
1249
1250
1251   xbt_test_add("Generic multicache CRASH test");
1252   xbt_test_log
1253       (" Fill the struct and frees it %d times, using %d elements, "
1254        "depth of multicache=%d, key size=%d", NB_TEST, NB_ELM, DEPTH,
1255        KEY_SIZE);
1256
1257   for (l = 0; l < DEPTH; l++) {
1258     key = xbt_malloc(KEY_SIZE);
1259     xbt_dynar_push(keys, &key);
1260   }
1261
1262   for (i = 0; i < NB_TEST; i++) {
1263     mdict = xbt_dict_new();
1264     XBT_VERB("mdict=%p", mdict);
1265     if (verbose > 0)
1266       printf("Test %d\n", i);
1267     /* else if (i%10) printf("."); else printf("%d",i/10); */
1268
1269     for (j = 0; j < NB_ELM; j++) {
1270       if (verbose > 0)
1271         printf("  Add {");
1272
1273       for (l = 0; l < DEPTH; l++) {
1274         key = *(char **) xbt_dynar_get_ptr(keys, l);
1275
1276         for (k = 0; k < KEY_SIZE - 1; k++)
1277           key[k] = rand() % ('z' - 'a') + 'a';
1278
1279         key[k] = '\0';
1280
1281         if (verbose > 0)
1282           printf("%p=%s %s ", key, key, (l < DEPTH - 1 ? ";" : "}"));
1283       }
1284       if (verbose > 0)
1285         printf("in multitree %p.\n", mdict);
1286
1287       xbt_multidict_set(mdict, keys, xbt_strdup(key), free);
1288
1289       data = xbt_multidict_get(mdict, keys);
1290
1291       xbt_test_assert(data && !strcmp((char *) data, key),
1292                        "Retrieved value (%s) does not match the given one (%s)\n",
1293                        (char *) data, key);
1294     }
1295     xbt_dict_free(&mdict);
1296   }
1297
1298   xbt_dynar_free(&keys);
1299
1300   /*  if (verbose>0)
1301      xbt_dict_dump(mdict,&xbt_dict_print); */
1302
1303   xbt_dict_free(&mdict);
1304   xbt_dynar_free(&keys);
1305
1306 }
1307 #endif                          /* SIMGRID_TEST */