Logo AND Algorithmique Numérique Distribuée

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