Logo AND Algorithmique Numérique Distribuée

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