Logo AND Algorithmique Numérique Distribuée

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