Logo AND Algorithmique Numérique Distribuée

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