Logo AND Algorithmique Numérique Distribuée

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