Logo AND Algorithmique Numérique Distribuée

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