Logo AND Algorithmique Numérique Distribuée

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