Logo AND Algorithmique Numérique Distribuée

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