Logo AND Algorithmique Numérique Distribuée

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