Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[mc] Fix mm_fake_malloc() implementation
[simgrid.git] / src / xbt / dict.c
1 /* dict - a generic dictionary, variation over hash table                   */
2
3 /* Copyright (c) 2004-2014. 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 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(xbt_dict);
682
683 XBT_TEST_SUITE("dict", "Dict data container");
684
685 static void debuged_add_ext(xbt_dict_t head, const char *key,
686                             const char *data_to_fill, void_f_pvoid_t free_f)
687 {
688   char *data = xbt_strdup(data_to_fill);
689
690   xbt_test_log("Add %s under %s", PRINTF_STR(data_to_fill),
691                 PRINTF_STR(key));
692
693   xbt_dict_set(head, key, data, free_f);
694   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
695     xbt_dict_dump(head, (void (*)(void *)) &printf);
696     fflush(stdout);
697   }
698 }
699
700 static void debuged_add(xbt_dict_t head, const char *key, void_f_pvoid_t free_f)
701 {
702   debuged_add_ext(head, key, key, free_f);
703 }
704
705 static void fill(xbt_dict_t * head, int homogeneous)
706 {
707   void_f_pvoid_t free_f = homogeneous ? NULL : &free;
708
709   xbt_test_add("Fill in the dictionnary");
710
711   *head = homogeneous ? xbt_dict_new_homogeneous(&free) : xbt_dict_new();
712   debuged_add(*head, "12", free_f);
713   debuged_add(*head, "12a", free_f);
714   debuged_add(*head, "12b", free_f);
715   debuged_add(*head, "123", free_f);
716   debuged_add(*head, "123456", free_f);
717   /* Child becomes child of what to add */
718   debuged_add(*head, "1234", free_f);
719   /* Need of common ancestor */
720   debuged_add(*head, "123457", free_f);
721 }
722
723
724 static void search_ext(xbt_dict_t head, const char *key, const char *data)
725 {
726   char *found;
727
728   xbt_test_add("Search %s", key);
729   found = xbt_dict_get(head, key);
730   xbt_test_log("Found %s", found);
731   if (data) {
732     xbt_test_assert(found,
733                     "data do not match expectations: found NULL while searching for %s",
734                     data);
735     if (found)
736       xbt_test_assert(!strcmp(data, found),
737                       "data do not match expectations: found %s while searching for %s",
738                       found, data);
739   } else {
740     xbt_test_assert(!found,
741                     "data do not match expectations: found %s while searching for NULL",
742                     found);
743   }
744 }
745
746 static void search(xbt_dict_t head, const char *key)
747 {
748   search_ext(head, key, key);
749 }
750
751 static void debuged_remove(xbt_dict_t head, const char *key)
752 {
753
754   xbt_test_add("Remove '%s'", PRINTF_STR(key));
755   xbt_dict_remove(head, key);
756   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
757 }
758
759
760 static void traverse(xbt_dict_t head)
761 {
762   xbt_dict_cursor_t cursor = NULL;
763   char *key;
764   char *data;
765   int i = 0;
766
767   xbt_dict_foreach(head, cursor, key, data) {
768     if (!key || !data || strcmp(key, data)) {
769       xbt_test_log("Seen #%d:  %s->%s", ++i, PRINTF_STR(key),
770                     PRINTF_STR(data));
771     } else {
772       xbt_test_log("Seen #%d:  %s", ++i, PRINTF_STR(key));
773     }
774     xbt_test_assert(!data || !strcmp(key, data),
775                      "Key(%s) != value(%s). Aborting", key, data);
776   }
777 }
778
779 static void search_not_found(xbt_dict_t head, const char *data)
780 {
781   int ok = 0;
782   xbt_ex_t e;
783
784   xbt_test_add("Search %s (expected not to be found)", data);
785
786   TRY {
787     data = xbt_dict_get(head, data);
788     THROWF(unknown_error, 0,
789            "Found something which shouldn't be there (%s)", data);
790   }
791   CATCH(e) {
792     if (e.category != not_found_error)
793       xbt_test_exception(e);
794     xbt_ex_free(e);
795     ok = 1;
796   }
797   xbt_test_assert(ok, "Exception not raised");
798 }
799
800 static void count(xbt_dict_t dict, int length)
801 {
802   xbt_dict_cursor_t cursor;
803   char *key;
804   void *data;
805   int effective = 0;
806
807
808   xbt_test_add("Count elements (expecting %d)", length);
809   xbt_test_assert(xbt_dict_length(dict) == length,
810                    "Announced length(%d) != %d.", xbt_dict_length(dict),
811                    length);
812
813   xbt_dict_foreach(dict, cursor, key, data)
814       effective++;
815
816   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
817                    effective, length);
818
819 }
820
821 static void count_check_get_key(xbt_dict_t dict, int length)
822 {
823   xbt_dict_cursor_t cursor;
824   char *key;
825   _XBT_GNUC_UNUSED char *key2;
826   void *data;
827   int effective = 0;
828
829
830   xbt_test_add
831       ("Count elements (expecting %d), and test the getkey function",
832        length);
833   xbt_test_assert(xbt_dict_length(dict) == length,
834                    "Announced length(%d) != %d.", xbt_dict_length(dict),
835                    length);
836
837   xbt_dict_foreach(dict, cursor, key, data) {
838     effective++;
839     key2 = xbt_dict_get_key(dict, data);
840     xbt_assert(!strcmp(key, key2),
841                 "The data was registered under %s instead of %s as expected",
842                 key2, key);
843   }
844
845   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
846                    effective, length);
847
848 }
849
850 xbt_ex_t e;
851 xbt_dict_t head = NULL;
852 char *data;
853
854 static void basic_test(int homogeneous)
855 {
856   void_f_pvoid_t free_f;
857
858   xbt_test_add("Traversal the null dictionary");
859   traverse(head);
860
861   xbt_test_add("Traversal and search the empty dictionary");
862   head = homogeneous ? xbt_dict_new_homogeneous(&free) : xbt_dict_new();
863   traverse(head);
864   TRY {
865     debuged_remove(head, "12346");
866   }
867   CATCH(e) {
868     if (e.category != not_found_error)
869       xbt_test_exception(e);
870     xbt_ex_free(e);
871   }
872   xbt_dict_free(&head);
873
874   free_f = homogeneous ? NULL : &free;
875
876   xbt_test_add("Traverse the full dictionary");
877   fill(&head, homogeneous);
878   count_check_get_key(head, 7);
879
880   debuged_add_ext(head, "toto", "tutu", free_f);
881   search_ext(head, "toto", "tutu");
882   debuged_remove(head, "toto");
883
884   search(head, "12a");
885   traverse(head);
886
887   xbt_test_add("Free the dictionary (twice)");
888   xbt_dict_free(&head);
889   xbt_dict_free(&head);
890
891   /* CHANGING */
892   fill(&head, homogeneous);
893   count_check_get_key(head, 7);
894   xbt_test_add("Change 123 to 'Changed 123'");
895   xbt_dict_set(head, "123", strdup("Changed 123"), free_f);
896   count_check_get_key(head, 7);
897
898   xbt_test_add("Change 123 back to '123'");
899   xbt_dict_set(head, "123", strdup("123"), free_f);
900   count_check_get_key(head, 7);
901
902   xbt_test_add("Change 12a to 'Dummy 12a'");
903   xbt_dict_set(head, "12a", strdup("Dummy 12a"), free_f);
904   count_check_get_key(head, 7);
905
906   xbt_test_add("Change 12a to '12a'");
907   xbt_dict_set(head, "12a", strdup("12a"), free_f);
908   count_check_get_key(head, 7);
909
910   xbt_test_add("Traverse the resulting dictionary");
911   traverse(head);
912
913   /* RETRIEVE */
914   xbt_test_add("Search 123");
915   data = xbt_dict_get(head, "123");
916   xbt_test_assert(data);
917   xbt_test_assert(!strcmp("123", data));
918
919   search_not_found(head, "Can't be found");
920   search_not_found(head, "123 Can't be found");
921   search_not_found(head, "12345678 NOT");
922
923   search(head, "12a");
924   search(head, "12b");
925   search(head, "12");
926   search(head, "123456");
927   search(head, "1234");
928   search(head, "123457");
929
930   xbt_test_add("Traverse the resulting dictionary");
931   traverse(head);
932
933   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
934
935   xbt_test_add("Free the dictionary twice");
936   xbt_dict_free(&head);
937   xbt_dict_free(&head);
938
939   xbt_test_add("Traverse the resulting dictionary");
940   traverse(head);
941 }
942
943 XBT_TEST_UNIT("basic_heterogeneous", test_dict_basic_heterogeneous, "Basic usage: change, retrieve, traverse: heterogeneous dict")
944 {
945   basic_test(0);
946 }
947
948 XBT_TEST_UNIT("basic_homogeneous", test_dict_basic_homogeneous, "Basic usage: change, retrieve, traverse: homogeneous dict")
949 {
950   basic_test(1);
951 }
952
953 static void remove_test(int homogeneous)
954 {
955   fill(&head, homogeneous);
956   count(head, 7);
957   xbt_test_add("Remove non existing data");
958   TRY {
959     debuged_remove(head, "Does not exist");
960   }
961   CATCH(e) {
962     if (e.category != not_found_error)
963       xbt_test_exception(e);
964     xbt_ex_free(e);
965   }
966   traverse(head);
967
968   xbt_dict_free(&head);
969
970   xbt_test_add
971       ("Remove each data manually (traversing the resulting dictionary each time)");
972   fill(&head, homogeneous);
973   debuged_remove(head, "12a");
974   traverse(head);
975   count(head, 6);
976   debuged_remove(head, "12b");
977   traverse(head);
978   count(head, 5);
979   debuged_remove(head, "12");
980   traverse(head);
981   count(head, 4);
982   debuged_remove(head, "123456");
983   traverse(head);
984   count(head, 3);
985   TRY {
986     debuged_remove(head, "12346");
987   }
988   CATCH(e) {
989     if (e.category != not_found_error)
990       xbt_test_exception(e);
991     xbt_ex_free(e);
992     traverse(head);
993   }
994   debuged_remove(head, "1234");
995   traverse(head);
996   debuged_remove(head, "123457");
997   traverse(head);
998   debuged_remove(head, "123");
999   traverse(head);
1000   TRY {
1001     debuged_remove(head, "12346");
1002   }
1003   CATCH(e) {
1004     if (e.category != not_found_error)
1005       xbt_test_exception(e);
1006     xbt_ex_free(e);
1007   }
1008   traverse(head);
1009
1010   xbt_test_add
1011       ("Free dict, create new fresh one, and then reset the dict");
1012   xbt_dict_free(&head);
1013   fill(&head, homogeneous);
1014   xbt_dict_reset(head);
1015   count(head, 0);
1016   traverse(head);
1017
1018   xbt_test_add("Free the dictionary twice");
1019   xbt_dict_free(&head);
1020   xbt_dict_free(&head);
1021 }
1022
1023 XBT_TEST_UNIT("remove_heterogeneous", test_dict_remove_heterogeneous, "Removing some values: heterogeneous dict")
1024 {
1025   remove_test(0);
1026 }
1027
1028 XBT_TEST_UNIT("remove_homogeneous", test_dict_remove_homogeneous, "Removing some values: homogeneous dict")
1029 {
1030   remove_test(1);
1031 }
1032
1033 XBT_TEST_UNIT("nulldata", test_dict_nulldata, "NULL data management")
1034 {
1035   fill(&head, 1);
1036
1037   xbt_test_add("Store NULL under 'null'");
1038   xbt_dict_set(head, "null", NULL, NULL);
1039   search_ext(head, "null", NULL);
1040
1041   xbt_test_add("Check whether I see it while traversing...");
1042   {
1043     xbt_dict_cursor_t cursor = NULL;
1044     char *key;
1045     int found = 0;
1046
1047     xbt_dict_foreach(head, cursor, key, data) {
1048       if (!key || !data || strcmp(key, data)) {
1049         xbt_test_log("Seen:  %s->%s", PRINTF_STR(key), PRINTF_STR(data));
1050       } else {
1051         xbt_test_log("Seen:  %s", PRINTF_STR(key));
1052       }
1053
1054       if (!strcmp(key, "null"))
1055         found = 1;
1056     }
1057     xbt_test_assert(found,
1058                      "the key 'null', associated to NULL is not found");
1059   }
1060   xbt_dict_free(&head);
1061 }
1062
1063 #define NB_ELM 20000
1064 #define SIZEOFKEY 1024
1065 static int countelems(xbt_dict_t head)
1066 {
1067   xbt_dict_cursor_t cursor;
1068   char *key;
1069   void *data;
1070   int res = 0;
1071
1072   xbt_dict_foreach(head, cursor, key, data) {
1073     res++;
1074   }
1075   return res;
1076 }
1077
1078 XBT_TEST_UNIT("crash", test_dict_crash, "Crash test")
1079 {
1080   xbt_dict_t head = NULL;
1081   int i, j, k;
1082   char *key;
1083
1084   srand((unsigned int) time(NULL));
1085
1086   for (i = 0; i < 10; i++) {
1087     xbt_test_add("CRASH test number %d (%d to go)", i + 1, 10 - i - 1);
1088     xbt_test_log
1089         ("Fill the struct, count its elems and frees the structure");
1090     xbt_test_log
1091         ("using 1000 elements with %d chars long randomized keys.",
1092          SIZEOFKEY);
1093     head = xbt_dict_new();
1094     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1095     for (j = 0; j < 1000; j++) {
1096       char *data = NULL;
1097       key = xbt_malloc(SIZEOFKEY);
1098
1099       do {
1100         for (k = 0; k < SIZEOFKEY - 1; k++)
1101           key[k] = rand() % ('z' - 'a') + 'a';
1102         key[k] = '\0';
1103         /*      printf("[%d %s]\n",j,key); */
1104         data = xbt_dict_get_or_null(head, key);
1105       } while (data != NULL);
1106
1107       xbt_dict_set(head, key, key, &free);
1108       data = xbt_dict_get(head, key);
1109       xbt_test_assert(!strcmp(key, data),
1110                        "Retrieved value (%s) != Injected value (%s)", key,
1111                        data);
1112
1113       count(head, j + 1);
1114     }
1115     /*    xbt_dict_dump(head,(void (*)(void*))&printf); */
1116     traverse(head);
1117     xbt_dict_free(&head);
1118     xbt_dict_free(&head);
1119   }
1120
1121
1122   head = xbt_dict_new();
1123   xbt_test_add("Fill %d elements, with keys being the number of element",
1124                 NB_ELM);
1125   for (j = 0; j < NB_ELM; j++) {
1126     /* if (!(j%1000)) { printf("."); fflush(stdout); } */
1127
1128     key = xbt_malloc(10);
1129
1130     sprintf(key, "%d", j);
1131     xbt_dict_set(head, key, key, &free);
1132   }
1133   /*xbt_dict_dump(head,(void (*)(void*))&printf); */
1134
1135   xbt_test_add
1136       ("Count the elements (retrieving the key and data for each)");
1137   i = countelems(head);
1138   xbt_test_log("There is %d elements", i);
1139
1140   xbt_test_add("Search my %d elements 20 times", NB_ELM);
1141   key = xbt_malloc(10);
1142   for (i = 0; i < 20; i++) {
1143     void *data;
1144     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1145     for (j = 0; j < NB_ELM; j++) {
1146
1147       sprintf(key, "%d", j);
1148       data = xbt_dict_get(head, key);
1149       xbt_test_assert(!strcmp(key, (char *) data),
1150                        "with get, key=%s != data=%s", key, (char *) data);
1151       data = xbt_dict_get_ext(head, key, strlen(key));
1152       xbt_test_assert(!strcmp(key, (char *) data),
1153                        "with get_ext, key=%s != data=%s", key,
1154                        (char *) data);
1155     }
1156   }
1157   free(key);
1158
1159   xbt_test_add("Remove my %d elements", NB_ELM);
1160   key = xbt_malloc(10);
1161   for (j = 0; j < NB_ELM; j++) {
1162     /* if (!(j%10000)) printf("."); fflush(stdout); */
1163
1164     sprintf(key, "%d", j);
1165     xbt_dict_remove(head, key);
1166   }
1167   free(key);
1168
1169
1170   xbt_test_add("Free the structure (twice)");
1171   xbt_dict_free(&head);
1172   xbt_dict_free(&head);
1173 }
1174
1175 XBT_TEST_UNIT("ext", test_dict_int, "Test dictionnary with int keys")
1176 {
1177   xbt_dict_t dict = xbt_dict_new();
1178   int count = 500;
1179
1180   xbt_test_add("Insert elements");
1181   int i;
1182   for (i = 0; i < count; ++i)
1183     xbt_dict_set_ext(dict, (char*) &i, sizeof(i), (void*) (intptr_t) i, NULL);
1184   xbt_test_assert(xbt_dict_size(dict) == count,
1185     "Bad number of elements in the dictionnary");
1186
1187   xbt_test_add("Check elements");
1188   for (i = 0; i < count; ++i) {
1189     int res = (int) (intptr_t) xbt_dict_get_ext(dict, (char*) &i, sizeof(i));
1190     xbt_test_assert(xbt_dict_size(dict) == count,
1191       "Unexpected value at index %i, expected %i but was %i", i, i, res);
1192   }
1193
1194   xbt_test_add("Free the array");
1195   xbt_dict_free(&dict);
1196 }
1197
1198 #endif                          /* SIMGRID_TEST */