Logo AND Algorithmique Numérique Distribuée

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