Logo AND Algorithmique Numérique Distribuée

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