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