Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr//gitroot/simgrid/simgrid
[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 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 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 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 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 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 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 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 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 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 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 /** @brief Remove all data from the dict */
416 void xbt_dict_reset(xbt_dict_t dict)
417 {
418   if (dict->count == 0)
419     return;
420
421   for (int i = 0; i <= dict->table_size; i++) {
422     xbt_dictelm_t previous = NULL;
423     xbt_dictelm_t current = dict->table[i];
424     while (current != NULL) {
425       previous = current;
426       current = current->next;
427       xbt_dictelm_free(dict, previous);
428     }
429     dict->table[i] = NULL;
430   }
431
432   dict->count = 0;
433   dict->fill = 0;
434 }
435
436 /**
437  * \brief Return the number of elements in the dict.
438  * \param dict a dictionary
439  */
440 inline int xbt_dict_length(xbt_dict_t dict)
441 {
442   return dict->count;
443 }
444
445 /** @brief function to be used in xbt_dict_dump as long as the stored values are strings */
446 void xbt_dict_dump_output_string(void *s)
447 {
448   fputs(s, stdout);
449 }
450
451 /**
452  * \brief test if the dict is empty or not
453  */
454 inline int xbt_dict_is_empty(xbt_dict_t dict)
455 {
456   return !dict || (xbt_dict_length(dict) == 0);
457 }
458
459 /**
460  * \brief Outputs the content of the structure (debugging purpose)
461  *
462  * \param dict the exibitionist
463  * \param output a function to dump each data in the tree (check @ref xbt_dict_dump_output_string)
464  *
465  * Outputs the content of the structure. (for debugging purpose). \a output is a
466  * function to output the data. If NULL, data won't be displayed.
467  */
468
469 void xbt_dict_dump(xbt_dict_t dict, void_f_pvoid_t output)
470 {
471   int i;
472   xbt_dictelm_t element;
473   printf("Dict %p:\n", dict);
474   if (dict != NULL) {
475     for (i = 0; i < dict->table_size; i++) {
476       element = dict->table[i];
477       if (element) {
478         printf("[\n");
479         while (element != NULL) {
480           printf(" %s -> '", element->key);
481           if (output != NULL) {
482             output(element->content);
483           }
484           printf("'\n");
485           element = element->next;
486         }
487         printf("]\n");
488       } else {
489         printf("[]\n");
490       }
491     }
492   }
493 }
494
495 xbt_dynar_t all_sizes = NULL;
496 /** @brief shows some debugging info about the bucklet repartition */
497 void xbt_dict_dump_sizes(xbt_dict_t dict)
498 {
499   unsigned int count;
500   unsigned int size;
501
502   printf("Dict %p: %d bucklets, %d used cells (of %d) ", dict, dict->count, dict->fill, dict->table_size);
503
504   if (!dict) {
505     printf("\n");
506     return;
507   }
508   xbt_dynar_t sizes = xbt_dynar_new(sizeof(int), NULL);
509
510   for (int i = 0; i < dict->table_size; i++) {
511     xbt_dictelm_t element = dict->table[i];
512     size = 0;
513     if (element) {
514       while (element != NULL) {
515         size++;
516         element = element->next;
517       }
518     }
519     if (xbt_dynar_length(sizes) <= size) {
520       int prevsize = 1;
521       xbt_dynar_set(sizes, size, &prevsize);
522     } else {
523       int prevsize;
524       xbt_dynar_get_cpy(sizes, size, &prevsize);
525       prevsize++;
526       xbt_dynar_set(sizes, size, &prevsize);
527     }
528   }
529   if (!all_sizes)
530     all_sizes = xbt_dynar_new(sizeof(int), NULL);
531
532   xbt_dynar_foreach(sizes, count, size) {
533     /* Copy values of this one into all_sizes */
534     int prevcount;
535     if (xbt_dynar_length(all_sizes) <= count) {
536       prevcount = size;
537       xbt_dynar_set(all_sizes, count, &prevcount);
538     } else {
539       xbt_dynar_get_cpy(all_sizes, count, &prevcount);
540       prevcount += size;
541       xbt_dynar_set(all_sizes, count, &prevcount);
542     }
543
544     /* Report current sizes */
545     if (count == 0)
546       continue;
547     if (size == 0)
548       continue;
549     printf("%uelm x %u cells; ", count, size);
550   }
551   printf("\n");
552   xbt_dynar_free(&sizes);
553 }
554
555 /**
556  * Create the dict mallocators.
557  * This is an internal XBT function called during the lib initialization.
558  * It can be used several times to recreate the mallocator, for example when you switch to MC mode
559  */
560 void xbt_dict_preinit(void)
561 {
562   dict_elm_mallocator = xbt_mallocator_new(256,
563                                            dict_elm_mallocator_new_f,
564                                            dict_elm_mallocator_free_f,
565                                            dict_elm_mallocator_reset_f);
566   dict_het_elm_mallocator = xbt_mallocator_new(256,
567                                                dict_het_elm_mallocator_new_f,
568                                                dict_het_elm_mallocator_free_f,
569                                                dict_het_elm_mallocator_reset_f);
570 }
571
572 /**
573  * Destroy the dict mallocators.
574  * This is an internal XBT function during the lib initialization
575  */
576 void xbt_dict_postexit(void)
577 {
578   if (dict_elm_mallocator != NULL) {
579     xbt_mallocator_free(dict_elm_mallocator);
580     dict_elm_mallocator = NULL;
581     xbt_mallocator_free(dict_het_elm_mallocator);
582     dict_het_elm_mallocator = NULL;
583   }
584   if (all_sizes) {
585     unsigned int count;
586     int size;
587     double avg = 0;
588     int total_count = 0;
589     printf("Overall stats:");
590     xbt_dynar_foreach(all_sizes, count, size) {
591       if (count == 0)
592         continue;
593       if (size == 0)
594         continue;
595       printf("%uelm x %d cells; ", count, size);
596       avg += count * size;
597       total_count += size;
598     }
599     printf("; %f elm per cell\n", avg / (double) total_count);
600   }
601 }
602
603 #ifdef SIMGRID_TEST
604 #include "xbt.h"
605 #include "xbt/ex.h"
606 #include "src/internal_config.h"
607
608
609 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_dict);
610
611 XBT_TEST_SUITE("dict", "Dict data container");
612
613 static void debuged_add_ext(xbt_dict_t head, const char *key,
614                             const char *data_to_fill, void_f_pvoid_t free_f)
615 {
616   char *data = xbt_strdup(data_to_fill);
617
618   xbt_test_log("Add %s under %s", data_to_fill, key);
619
620   xbt_dict_set(head, key, data, free_f);
621   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
622     xbt_dict_dump(head, (void (*)(void *)) &printf);
623     fflush(stdout);
624   }
625 }
626
627 static void debuged_add(xbt_dict_t head, const char *key, void_f_pvoid_t free_f)
628 {
629   debuged_add_ext(head, key, key, free_f);
630 }
631
632 static void fill(xbt_dict_t * head, int homogeneous)
633 {
634   void_f_pvoid_t free_f = homogeneous ? NULL : &free;
635
636   xbt_test_add("Fill in the dictionnary");
637
638   *head = homogeneous ? xbt_dict_new_homogeneous(&free) : xbt_dict_new();
639   debuged_add(*head, "12", free_f);
640   debuged_add(*head, "12a", free_f);
641   debuged_add(*head, "12b", free_f);
642   debuged_add(*head, "123", free_f);
643   debuged_add(*head, "123456", free_f);
644   /* Child becomes child of what to add */
645   debuged_add(*head, "1234", free_f);
646   /* Need of common ancestor */
647   debuged_add(*head, "123457", free_f);
648 }
649
650
651 static void search_ext(xbt_dict_t head, const char *key, const char *data)
652 {
653   char *found;
654
655   xbt_test_add("Search %s", key);
656   found = xbt_dict_get(head, key);
657   xbt_test_log("Found %s", found);
658   if (data) {
659     xbt_test_assert(found,
660                     "data do not match expectations: found NULL while searching for %s",
661                     data);
662     if (found)
663       xbt_test_assert(!strcmp(data, found),
664                       "data do not match expectations: found %s while searching for %s",
665                       found, data);
666   } else {
667     xbt_test_assert(!found,
668                     "data do not match expectations: found %s while searching for NULL",
669                     found);
670   }
671 }
672
673 static void search(xbt_dict_t head, const char *key)
674 {
675   search_ext(head, key, key);
676 }
677
678 static void debuged_remove(xbt_dict_t head, const char *key)
679 {
680
681   xbt_test_add("Remove '%s'", key);
682   xbt_dict_remove(head, key);
683   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
684 }
685
686
687 static void traverse(xbt_dict_t head)
688 {
689   xbt_dict_cursor_t cursor = NULL;
690   char *key;
691   char *data;
692   int i = 0;
693
694   xbt_dict_foreach(head, cursor, key, data) {
695     if (!key || !data || strcmp(key, data)) {
696       xbt_test_log("Seen #%d:  %s->%s", ++i, key, data);
697     } else {
698       xbt_test_log("Seen #%d:  %s", ++i, key);
699     }
700     xbt_test_assert(!data || !strcmp(key, data),
701                      "Key(%s) != value(%s). Aborting", key, data);
702   }
703 }
704
705 static void search_not_found(xbt_dict_t head, const char *data)
706 {
707   int ok = 0;
708   xbt_ex_t e;
709
710   xbt_test_add("Search %s (expected not to be found)", data);
711
712   TRY {
713     data = xbt_dict_get(head, data);
714     THROWF(unknown_error, 0,
715            "Found something which shouldn't be there (%s)", data);
716   }
717   CATCH(e) {
718     if (e.category != not_found_error)
719       xbt_test_exception(e);
720     xbt_ex_free(e);
721     ok = 1;
722   }
723   xbt_test_assert(ok, "Exception not raised");
724 }
725
726 static void count(xbt_dict_t dict, int length)
727 {
728   xbt_dict_cursor_t cursor;
729   char *key;
730   void *data;
731   int effective = 0;
732
733
734   xbt_test_add("Count elements (expecting %d)", length);
735   xbt_test_assert(xbt_dict_length(dict) == length,
736                    "Announced length(%d) != %d.", xbt_dict_length(dict),
737                    length);
738
739   xbt_dict_foreach(dict, cursor, key, data)
740       effective++;
741
742   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
743                    effective, length);
744
745 }
746
747 static void count_check_get_key(xbt_dict_t dict, int length)
748 {
749   xbt_dict_cursor_t cursor;
750   char *key;
751   XBT_ATTRIB_UNUSED char *key2;
752   void *data;
753   int effective = 0;
754
755
756   xbt_test_add
757       ("Count elements (expecting %d), and test the getkey function",
758        length);
759   xbt_test_assert(xbt_dict_length(dict) == length,
760                    "Announced length(%d) != %d.", xbt_dict_length(dict),
761                    length);
762
763   xbt_dict_foreach(dict, cursor, key, data) {
764     effective++;
765     key2 = xbt_dict_get_key(dict, data);
766     xbt_assert(!strcmp(key, key2),
767                 "The data was registered under %s instead of %s as expected",
768                 key2, key);
769   }
770
771   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
772                    effective, length);
773
774 }
775
776 xbt_ex_t e;
777 xbt_dict_t head = NULL;
778 char *data;
779
780 static void basic_test(int homogeneous)
781 {
782   void_f_pvoid_t free_f;
783
784   xbt_test_add("Traversal the null dictionary");
785   traverse(head);
786
787   xbt_test_add("Traversal and search the empty dictionary");
788   head = homogeneous ? xbt_dict_new_homogeneous(&free) : xbt_dict_new();
789   traverse(head);
790   TRY {
791     debuged_remove(head, "12346");
792   }
793   CATCH(e) {
794     if (e.category != not_found_error)
795       xbt_test_exception(e);
796     xbt_ex_free(e);
797   }
798   xbt_dict_free(&head);
799
800   free_f = homogeneous ? NULL : &free;
801
802   xbt_test_add("Traverse the full dictionary");
803   fill(&head, homogeneous);
804   count_check_get_key(head, 7);
805
806   debuged_add_ext(head, "toto", "tutu", free_f);
807   search_ext(head, "toto", "tutu");
808   debuged_remove(head, "toto");
809
810   search(head, "12a");
811   traverse(head);
812
813   xbt_test_add("Free the dictionary (twice)");
814   xbt_dict_free(&head);
815   xbt_dict_free(&head);
816
817   /* CHANGING */
818   fill(&head, homogeneous);
819   count_check_get_key(head, 7);
820   xbt_test_add("Change 123 to 'Changed 123'");
821   xbt_dict_set(head, "123", xbt_strdup("Changed 123"), free_f);
822   count_check_get_key(head, 7);
823
824   xbt_test_add("Change 123 back to '123'");
825   xbt_dict_set(head, "123", xbt_strdup("123"), free_f);
826   count_check_get_key(head, 7);
827
828   xbt_test_add("Change 12a to 'Dummy 12a'");
829   xbt_dict_set(head, "12a", xbt_strdup("Dummy 12a"), free_f);
830   count_check_get_key(head, 7);
831
832   xbt_test_add("Change 12a to '12a'");
833   xbt_dict_set(head, "12a", xbt_strdup("12a"), free_f);
834   count_check_get_key(head, 7);
835
836   xbt_test_add("Traverse the resulting dictionary");
837   traverse(head);
838
839   /* RETRIEVE */
840   xbt_test_add("Search 123");
841   data = xbt_dict_get(head, "123");
842   xbt_test_assert(data);
843   xbt_test_assert(!strcmp("123", data));
844
845   search_not_found(head, "Can't be found");
846   search_not_found(head, "123 Can't be found");
847   search_not_found(head, "12345678 NOT");
848
849   search(head, "12a");
850   search(head, "12b");
851   search(head, "12");
852   search(head, "123456");
853   search(head, "1234");
854   search(head, "123457");
855
856   xbt_test_add("Traverse the resulting dictionary");
857   traverse(head);
858
859   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
860
861   xbt_test_add("Free the dictionary twice");
862   xbt_dict_free(&head);
863   xbt_dict_free(&head);
864
865   xbt_test_add("Traverse the resulting dictionary");
866   traverse(head);
867 }
868
869 XBT_TEST_UNIT("basic_heterogeneous", test_dict_basic_heterogeneous, "Basic usage: change, retrieve, traverse: heterogeneous dict")
870 {
871   basic_test(0);
872 }
873
874 XBT_TEST_UNIT("basic_homogeneous", test_dict_basic_homogeneous, "Basic usage: change, retrieve, traverse: homogeneous dict")
875 {
876   basic_test(1);
877 }
878
879 static void remove_test(int homogeneous)
880 {
881   fill(&head, homogeneous);
882   count(head, 7);
883   xbt_test_add("Remove non existing data");
884   TRY {
885     debuged_remove(head, "Does not exist");
886   }
887   CATCH(e) {
888     if (e.category != not_found_error)
889       xbt_test_exception(e);
890     xbt_ex_free(e);
891   }
892   traverse(head);
893
894   xbt_dict_free(&head);
895
896   xbt_test_add
897       ("Remove each data manually (traversing the resulting dictionary each time)");
898   fill(&head, homogeneous);
899   debuged_remove(head, "12a");
900   traverse(head);
901   count(head, 6);
902   debuged_remove(head, "12b");
903   traverse(head);
904   count(head, 5);
905   debuged_remove(head, "12");
906   traverse(head);
907   count(head, 4);
908   debuged_remove(head, "123456");
909   traverse(head);
910   count(head, 3);
911   TRY {
912     debuged_remove(head, "12346");
913   }
914   CATCH(e) {
915     if (e.category != not_found_error)
916       xbt_test_exception(e);
917     xbt_ex_free(e);
918     traverse(head);
919   }
920   debuged_remove(head, "1234");
921   traverse(head);
922   debuged_remove(head, "123457");
923   traverse(head);
924   debuged_remove(head, "123");
925   traverse(head);
926   TRY {
927     debuged_remove(head, "12346");
928   }
929   CATCH(e) {
930     if (e.category != not_found_error)
931       xbt_test_exception(e);
932     xbt_ex_free(e);
933   }
934   traverse(head);
935
936   xbt_test_add
937       ("Free dict, create new fresh one, and then reset the dict");
938   xbt_dict_free(&head);
939   fill(&head, homogeneous);
940   xbt_dict_reset(head);
941   count(head, 0);
942   traverse(head);
943
944   xbt_test_add("Free the dictionary twice");
945   xbt_dict_free(&head);
946   xbt_dict_free(&head);
947 }
948
949 XBT_TEST_UNIT("remove_heterogeneous", test_dict_remove_heterogeneous, "Removing some values: heterogeneous dict")
950 {
951   remove_test(0);
952 }
953
954 XBT_TEST_UNIT("remove_homogeneous", test_dict_remove_homogeneous, "Removing some values: homogeneous dict")
955 {
956   remove_test(1);
957 }
958
959 XBT_TEST_UNIT("nulldata", test_dict_nulldata, "NULL data management")
960 {
961   fill(&head, 1);
962
963   xbt_test_add("Store NULL under 'null'");
964   xbt_dict_set(head, "null", NULL, NULL);
965   search_ext(head, "null", NULL);
966
967   xbt_test_add("Check whether I see it while traversing...");
968   {
969     xbt_dict_cursor_t cursor = NULL;
970     char *key;
971     int found = 0;
972
973     xbt_dict_foreach(head, cursor, key, data) {
974       if (!key || !data || strcmp(key, data)) {
975         xbt_test_log("Seen:  %s->%s", key, data);
976       } else {
977         xbt_test_log("Seen:  %s", key);
978       }
979
980       if (!strcmp(key, "null"))
981         found = 1;
982     }
983     xbt_test_assert(found,
984                      "the key 'null', associated to NULL is not found");
985   }
986   xbt_dict_free(&head);
987 }
988
989 #define NB_ELM 20000
990 #define SIZEOFKEY 1024
991 static int countelems(xbt_dict_t head)
992 {
993   xbt_dict_cursor_t cursor;
994   char *key;
995   void *data;
996   int res = 0;
997
998   xbt_dict_foreach(head, cursor, key, data) {
999     res++;
1000   }
1001   return res;
1002 }
1003
1004 XBT_TEST_UNIT("crash", test_dict_crash, "Crash test")
1005 {
1006   xbt_dict_t head = NULL;
1007   int i, j, k;
1008   char *key;
1009
1010   srand((unsigned int) time(NULL));
1011
1012   for (i = 0; i < 10; i++) {
1013     xbt_test_add("CRASH test number %d (%d to go)", i + 1, 10 - i - 1);
1014     xbt_test_log
1015         ("Fill the struct, count its elems and frees the structure");
1016     xbt_test_log
1017         ("using 1000 elements with %d chars long randomized keys.",
1018          SIZEOFKEY);
1019     head = xbt_dict_new();
1020     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1021     for (j = 0; j < 1000; j++) {
1022       char *data = NULL;
1023       key = xbt_malloc(SIZEOFKEY);
1024
1025       do {
1026         for (k = 0; k < SIZEOFKEY - 1; k++)
1027           key[k] = rand() % ('z' - 'a') + 'a';
1028         key[k] = '\0';
1029         /*      printf("[%d %s]\n",j,key); */
1030         data = xbt_dict_get_or_null(head, key);
1031       } while (data != NULL);
1032
1033       xbt_dict_set(head, key, key, &free);
1034       data = xbt_dict_get(head, key);
1035       xbt_test_assert(!strcmp(key, data),
1036                        "Retrieved value (%s) != Injected value (%s)", key,
1037                        data);
1038
1039       count(head, j + 1);
1040     }
1041     /*    xbt_dict_dump(head,(void (*)(void*))&printf); */
1042     traverse(head);
1043     xbt_dict_free(&head);
1044     xbt_dict_free(&head);
1045   }
1046
1047
1048   head = xbt_dict_new();
1049   xbt_test_add("Fill %d elements, with keys being the number of element",
1050                 NB_ELM);
1051   for (j = 0; j < NB_ELM; j++) {
1052     /* if (!(j%1000)) { printf("."); fflush(stdout); } */
1053
1054     key = xbt_malloc(10);
1055
1056     sprintf(key, "%d", j);
1057     xbt_dict_set(head, key, key, &free);
1058   }
1059   /*xbt_dict_dump(head,(void (*)(void*))&printf); */
1060
1061   xbt_test_add
1062       ("Count the elements (retrieving the key and data for each)");
1063   i = countelems(head);
1064   xbt_test_log("There is %d elements", i);
1065
1066   xbt_test_add("Search my %d elements 20 times", NB_ELM);
1067   key = xbt_malloc(10);
1068   for (i = 0; i < 20; i++) {
1069     void *data;
1070     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1071     for (j = 0; j < NB_ELM; j++) {
1072
1073       sprintf(key, "%d", j);
1074       data = xbt_dict_get(head, key);
1075       xbt_test_assert(!strcmp(key, (char *) data),
1076                        "with get, key=%s != data=%s", key, (char *) data);
1077       data = xbt_dict_get_ext(head, key, strlen(key));
1078       xbt_test_assert(!strcmp(key, (char *) data),
1079                        "with get_ext, key=%s != data=%s", key,
1080                        (char *) data);
1081     }
1082   }
1083   free(key);
1084
1085   xbt_test_add("Remove my %d elements", NB_ELM);
1086   key = xbt_malloc(10);
1087   for (j = 0; j < NB_ELM; j++) {
1088     /* if (!(j%10000)) printf("."); fflush(stdout); */
1089
1090     sprintf(key, "%d", j);
1091     xbt_dict_remove(head, key);
1092   }
1093   free(key);
1094
1095
1096   xbt_test_add("Free the structure (twice)");
1097   xbt_dict_free(&head);
1098   xbt_dict_free(&head);
1099 }
1100
1101 XBT_TEST_UNIT("ext", test_dict_int, "Test dictionnary with int keys")
1102 {
1103   xbt_dict_t dict = xbt_dict_new();
1104   int count = 500;
1105
1106   xbt_test_add("Insert elements");
1107   int i;
1108   for (i = 0; i < count; ++i)
1109     xbt_dict_set_ext(dict, (char*) &i, sizeof(i), (void*) (intptr_t) i, NULL);
1110   xbt_test_assert(xbt_dict_size(dict) == count,
1111     "Bad number of elements in the dictionnary");
1112
1113   xbt_test_add("Check elements");
1114   for (i = 0; i < count; ++i) {
1115     int res = (int) (intptr_t) xbt_dict_get_ext(dict, (char*) &i, sizeof(i));
1116     xbt_test_assert(xbt_dict_size(dict) == count,
1117       "Unexpected value at index %i, expected %i but was %i", i, i, res);
1118   }
1119
1120   xbt_test_add("Free the array");
1121   xbt_dict_free(&dict);
1122 }
1123
1124 #endif                          /* SIMGRID_TEST */