Logo AND Algorithmique Numérique Distribuée

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