Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
For tesh, produce the same output for different context settings
[simgrid.git] / src / xbt / dict.c
1 /* dict - a generic dictionary, variation over hash table                   */
2
3 /* Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009, 2010. 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 #define DJB2_HASH_FUNCTION
10 //#define FNV_HASH_FUNCTION
11
12 #include <string.h>
13 #include <stdio.h>
14 #include "xbt/ex.h"
15 #include "xbt/log.h"
16 #include "xbt/mallocator.h"
17 #include "xbt_modinter.h"
18 #include "dict_private.h"
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict, xbt,
21                                 "Dictionaries provide the same functionalities than hash tables");
22 /*####[ Private prototypes ]#################################################*/
23
24 static xbt_mallocator_t dict_mallocator = NULL;
25 static void *dict_mallocator_new_f(void);
26 static void dict_mallocator_free_f(void *dict);
27 static void dict_mallocator_reset_f(void *dict);
28
29
30 /*####[ Code ]###############################################################*/
31
32 /**
33  * \brief Constructor
34  * \return pointer to the destination
35  * \see xbt_dict_new_ext(), xbt_dict_free()
36  *
37  * Creates and initialize a new dictionary with a default hashtable size.
38  */
39 xbt_dict_t xbt_dict_new(void)
40 {
41   xbt_dict_t dict;
42
43   dict = xbt_mallocator_get(dict_mallocator);
44   dict->table_size = 127;
45   dict->table = xbt_new0(xbt_dictelm_t, dict->table_size + 1);
46   dict->count = 0;
47   dict->fill = 0;
48
49   return dict;
50 }
51
52 /**
53  * \brief Destructor
54  * \param dict the dictionary to be freed
55  *
56  * Frees a dictionary with all the data
57  */
58 void xbt_dict_free(xbt_dict_t * dict)
59 {
60   int i;
61   xbt_dictelm_t current, previous;
62   int table_size;
63   xbt_dictelm_t *table;
64
65   //  if ( *dict )  xbt_dict_dump_sizes(*dict);
66
67   if (dict != NULL && *dict != NULL) {
68     table_size = (*dict)->table_size;
69     table = (*dict)->table;
70     /* Warning: the size of the table is 'table_size+1'...
71      * This is because table_size is used as a binary mask in xbt_dict_rehash */
72     for (i = 0; (*dict)->count && i <= table_size; i++) {
73       current = table[i];
74       while (current != NULL) {
75         previous = current;
76         current = current->next;
77         xbt_dictelm_free(previous);
78         (*dict)->count--;
79       }
80     }
81     xbt_free(table);
82     xbt_mallocator_release(dict_mallocator, *dict);
83     *dict = NULL;
84   }
85 }
86
87 /**
88  * Returns the amount of elements in the dict
89  */
90 XBT_INLINE unsigned int xbt_dict_size(xbt_dict_t dict)
91 {
92   return (dict ? (unsigned int) dict->count : (unsigned int) 0);
93 }
94
95 /**
96  * Returns the hash code of a string.
97  */
98 static XBT_INLINE unsigned int xbt_dict_hash_ext(const char *str,
99                                                  int str_len)
100 {
101
102
103 #ifdef DJB2_HASH_FUNCTION
104   /* fast implementation of djb2 algorithm */
105   int c;
106   register unsigned int hash = 5381;
107
108   while (str_len--) {
109     c = *str++;
110     hash = ((hash << 5) + hash) + c;    /* hash * 33 + c */
111   }
112 # elif defined(FNV_HASH_FUNCTION)
113   register unsigned int hash = 0x811c9dc5;
114   unsigned char *bp = (unsigned char *) str;    /* start of buffer */
115   unsigned char *be = bp + str_len;     /* beyond end of buffer */
116
117   while (bp < be) {
118     /* multiply by the 32 bit FNV magic prime mod 2^32 */
119     hash +=
120         (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) +
121         (hash << 24);
122
123     /* xor the bottom with the current octet */
124     hash ^= (unsigned int) *bp++;
125   }
126
127 # else
128   register unsigned int hash = 0;
129
130   while (str_len--) {
131     hash += (*str) * (*str);
132     str++;
133   }
134 #endif
135
136   return hash;
137 }
138
139 static XBT_INLINE unsigned int xbt_dict_hash(const char *str)
140 {
141 #ifdef DJB2_HASH_FUNCTION
142   /* fast implementation of djb2 algorithm */
143   int c;
144   register unsigned int hash = 5381;
145
146   while ((c = *str++)) {
147     hash = ((hash << 5) + hash) + c;    /* hash * 33 + c */
148   }
149
150 # elif defined(FNV_HASH_FUNCTION)
151   register unsigned int hash = 0x811c9dc5;
152
153   while (*str) {
154     /* multiply by the 32 bit FNV magic prime mod 2^32 */
155     hash +=
156         (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) +
157         (hash << 24);
158
159     /* xor the bottom with the current byte */
160     hash ^= (unsigned int) *str++;
161   }
162
163 # else
164   register unsigned int hash = 0;
165
166   while (*str) {
167     hash += (*str) * (*str);
168     str++;
169   }
170 #endif
171   return hash;
172 }
173
174 /* Expend the size of the dict */
175 static void xbt_dict_rehash(xbt_dict_t dict)
176 {
177   const int oldsize = dict->table_size + 1;
178   register int newsize = oldsize * 2;
179   register int i;
180   register xbt_dictelm_t *currcell;
181   register xbt_dictelm_t *twincell;
182   register xbt_dictelm_t bucklet;
183   register xbt_dictelm_t *pprev;
184
185   currcell =
186       (xbt_dictelm_t *) xbt_realloc((char *) dict->table,
187                                     newsize * sizeof(xbt_dictelm_t));
188   memset(&currcell[oldsize], 0, oldsize * sizeof(xbt_dictelm_t));       /* zero second half */
189   dict->table_size = --newsize;
190   dict->table = currcell;
191   XBT_DEBUG("REHASH (%d->%d)", oldsize, newsize);
192
193   for (i = 0; i < oldsize; i++, currcell++) {
194     if (!*currcell)             /* empty cell */
195       continue;
196     twincell = currcell + oldsize;
197     for (pprev = currcell, bucklet = *currcell; bucklet; bucklet = *pprev) {
198       /* Since we use "& size" instead of "%size" and since the size was doubled,
199          each bucklet of this cell must either :
200          - stay  in  cell i (ie, currcell)
201          - go to the cell i+oldsize (ie, twincell) */
202       if ((bucklet->hash_code & newsize) != i) {        /* Move to b */
203         *pprev = bucklet->next;
204         bucklet->next = *twincell;
205         if (!*twincell)
206           dict->fill++;
207         *twincell = bucklet;
208         continue;
209       } else {
210         pprev = &bucklet->next;
211       }
212
213     }
214
215     if (!*currcell)             /* everything moved */
216       dict->fill--;
217   }
218 }
219
220 /**
221  * \brief Add data to the dict (arbitrary key)
222  * \param dict the container
223  * \param key the key to set the new data
224  * \param key_len the size of the \a key
225  * \param data the data to add in the dict
226  * \param free_ctn function to call with (\a data as argument) when
227  *        \a data is removed from the dictionary
228  *
229  * Set the \a data in the structure under the \a key, which can be any kind
230  * of data, as long as its length is provided in \a key_len.
231  */
232 XBT_INLINE void xbt_dict_set_ext(xbt_dict_t dict,
233                                  const char *key, int key_len,
234                                  void *data, void_f_pvoid_t free_ctn)
235 {
236
237   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
238
239   xbt_dictelm_t current, previous = NULL;
240   xbt_assert(dict);
241
242   XBT_DEBUG("ADD %.*s hash = %d, size = %d, & = %d", key_len, key, hash_code,
243          dict->table_size, hash_code & dict->table_size);
244   current = dict->table[hash_code & dict->table_size];
245   while (current != NULL &&
246          (hash_code != current->hash_code || key_len != current->key_len
247           || memcmp(key, current->key, key_len))) {
248     previous = current;
249     current = current->next;
250   }
251
252   if (current == NULL) {
253     /* this key doesn't exist yet */
254     current = xbt_dictelm_new(key, key_len, hash_code, data, free_ctn);
255     dict->count++;
256     if (previous == NULL) {
257       dict->table[hash_code & dict->table_size] = current;
258       dict->fill++;
259       if ((dict->fill * 100) / (dict->table_size + 1) > MAX_FILL_PERCENT)
260         xbt_dict_rehash(dict);
261     } else {
262       previous->next = current;
263     }
264   } else {
265
266     XBT_DEBUG("Replace %.*s by %.*s under key %.*s",
267            key_len, (char *) current->content,
268            key_len, (char *) data, key_len, (char *) key);
269     /* there is already an element with the same key: overwrite it */
270     if (current->content != NULL && current->free_f != NULL) {
271       current->free_f(current->content);
272     }
273     current->content = data;
274     current->free_f = free_ctn;
275   }
276 }
277
278 /**
279  * \brief Add data to the dict (null-terminated key)
280  *
281  * \param dict the dict
282  * \param key the key to set the new data
283  * \param data the data to add in the dict
284  * \param free_ctn function to call with (\a data as argument) when
285  *        \a data is removed from the dictionary
286  *
287  * set the \a data in the structure under the \a key, which is a
288  * null terminated string.
289  */
290 XBT_INLINE void xbt_dict_set(xbt_dict_t dict,
291                              const char *key, void *data,
292                              void_f_pvoid_t free_ctn)
293 {
294
295   xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
296 }
297
298 /**
299  * \brief Retrieve data from the dict (arbitrary key)
300  *
301  * \param dict the dealer of data
302  * \param key the key to find data
303  * \param key_len the size of the \a key
304  * \return the data that we are looking for
305  *
306  * Search the given \a key. Throws not_found_error when not found.
307  */
308 XBT_INLINE void *xbt_dict_get_ext(xbt_dict_t dict, const char *key,
309                                   int key_len)
310 {
311
312
313   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
314   xbt_dictelm_t current;
315
316   xbt_assert(dict);
317
318   current = dict->table[hash_code & dict->table_size];
319   while (current != NULL &&
320          (hash_code != current->hash_code || key_len != current->key_len
321           || memcmp(key, current->key, key_len))) {
322     current = current->next;
323   }
324
325   if (current == NULL)
326     THROWF(not_found_error, 0, "key %.*s not found", key_len, key);
327
328   return current->content;
329 }
330
331 /**
332  * \brief like xbt_dict_get_ext(), but returning NULL when not found
333  */
334 void *xbt_dict_get_or_null_ext(xbt_dict_t dict, const char *key,
335                                int key_len)
336 {
337
338   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
339   xbt_dictelm_t current;
340
341   xbt_assert(dict);
342
343   current = dict->table[hash_code & dict->table_size];
344   while (current != NULL &&
345          (hash_code != current->hash_code || key_len != current->key_len
346           || memcmp(key, current->key, key_len))) {
347     current = current->next;
348   }
349
350   if (current == NULL)
351     return NULL;
352
353   return current->content;
354 }
355
356 /**
357  * @brief retrieve the key associated to that object. Warning, that's a linear search
358  *
359  * Returns NULL if the object cannot be found
360  */
361 char *xbt_dict_get_key(xbt_dict_t dict, const void *data)
362 {
363   int i;
364   xbt_dictelm_t current;
365
366
367   for (i = 0; i <= dict->table_size; i++) {
368     current = dict->table[i];
369     while (current != NULL) {
370       if (current->content == data)
371         return current->key;
372       current = current->next;
373     }
374   }
375
376   return NULL;
377 }
378
379 /**
380  * \brief Retrieve data from the dict (null-terminated key)
381  *
382  * \param dict the dealer of data
383  * \param key the key to find data
384  * \return the data that we are looking for
385  *
386  * Search the given \a key. Throws not_found_error when not found.
387  * Check xbt_dict_get_or_null() for a version returning NULL without exception when
388  * not found.
389  */
390 XBT_INLINE void *xbt_dict_get(xbt_dict_t dict, const char *key)
391 {
392
393   unsigned int hash_code = xbt_dict_hash(key);
394   xbt_dictelm_t current;
395
396   xbt_assert(dict);
397
398   current = dict->table[hash_code & dict->table_size];
399   while (current != NULL
400          && (hash_code != current->hash_code || strcmp(key, current->key)))
401     current = current->next;
402
403   if (current == NULL)
404     THROWF(not_found_error, 0, "key %s not found", key);
405
406   return current->content;
407 }
408
409 /**
410  * \brief like xbt_dict_get(), but returning NULL when not found
411  */
412 XBT_INLINE void *xbt_dict_get_or_null(xbt_dict_t dict, const char *key)
413 {
414   unsigned int hash_code = xbt_dict_hash(key);
415   xbt_dictelm_t current;
416
417   xbt_assert(dict);
418
419   current = dict->table[hash_code & dict->table_size];
420   while (current != NULL &&
421          (hash_code != current->hash_code || strcmp(key, current->key)))
422     current = current->next;
423
424   if (current == NULL)
425     return NULL;
426
427   return current->content;
428 }
429
430
431 /**
432  * \brief Remove data from the dict (arbitrary key)
433  *
434  * \param dict the trash can
435  * \param key the key of the data to be removed
436  * \param key_len the size of the \a key
437  *
438  * Remove the entry associated with the given \a key (throws not_found)
439  */
440 XBT_INLINE void xbt_dict_remove_ext(xbt_dict_t dict, const char *key,
441                                     int key_len)
442 {
443
444
445   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
446   xbt_dictelm_t current, previous = NULL;
447
448   xbt_assert(dict);
449
450   //  fprintf(stderr,"RM %.*s hash = %d, size = %d, & = %d\n",key_len,key,hash_code, dict->table_size, hash_code & dict->table_size);
451   current = dict->table[hash_code & dict->table_size];
452   while (current != NULL &&
453          (hash_code != current->hash_code || key_len != current->key_len
454           || strncmp(key, current->key, key_len))) {
455     previous = current;         /* save the previous node */
456     current = current->next;
457   }
458
459   if (current == NULL)
460     THROWF(not_found_error, 0, "key %.*s not found", key_len, key);
461
462   if (previous != NULL) {
463     previous->next = current->next;
464   } else {
465     dict->table[hash_code & dict->table_size] = current->next;
466   }
467
468   if (!dict->table[hash_code & dict->table_size])
469     dict->fill--;
470
471   xbt_dictelm_free(current);
472   dict->count--;
473 }
474
475
476
477 /**
478  * \brief Remove data from the dict (null-terminated key)
479  *
480  * \param dict the dict
481  * \param key the key of the data to be removed
482  *
483  * Remove the entry associated with the given \a key
484  */
485 XBT_INLINE void xbt_dict_remove(xbt_dict_t dict, const char *key)
486 {
487   xbt_dict_remove_ext(dict, key, strlen(key));
488 }
489
490 /**
491  * \brief Add data to the dict (arbitrary key)
492  * \param dict the container
493  * \param key the key to set the new data
494  * \param data the data to add in the dict
495  *
496  * Set the \a data in the structure under the \a key.
497  * Both \a data and \a key are considered as uintptr_t.
498  */
499 XBT_INLINE void xbt_dicti_set(xbt_dict_t dict,
500                               uintptr_t key, uintptr_t data)
501 {
502
503   unsigned int hash_code =
504       xbt_dict_hash_ext((void *) &key, sizeof(uintptr_t));
505
506   xbt_dictelm_t current, previous = NULL;
507   xbt_assert(dict);
508
509   XBT_DEBUG("ADD %zu->%zu; hash = %d, size = %d, & = %d", key, data,
510          hash_code, dict->table_size, hash_code & dict->table_size);
511   current = dict->table[hash_code & dict->table_size];
512   while (current != NULL &&
513          (hash_code != current->hash_code
514           || sizeof(uintptr_t) != current->key_len
515           || (((uintptr_t) key) != ((uintptr_t) current->key)))) {
516     previous = current;
517     current = current->next;
518   }
519
520   if (current == NULL) {
521     /* this key doesn't exist yet */
522     current = xbt_dictielm_new(key, hash_code, data);
523     dict->count++;
524     if (previous == NULL) {
525       dict->table[hash_code & dict->table_size] = current;
526       dict->fill++;
527       if ((dict->fill * 100) / (dict->table_size + 1) > MAX_FILL_PERCENT)
528         xbt_dict_rehash(dict);
529     } else {
530       previous->next = current;
531     }
532   } else {
533
534     /* there is already an element with the same key: overwrite it */
535     if (current->content != NULL && current->free_f != NULL) {
536       current->free_f(current->content);
537     }
538     current->content = (void *) data;
539     current->free_f = NULL;
540   }
541 }
542
543 /**
544  * \brief Retrieve data from the dict (key considered as a uintptr_t)
545  *
546  * \param dict the dealer of data
547  * \param key the key to find data
548  * \return the data that we are looking for (or 0 if not found)
549  *
550  * Mixing uintptr_t keys with regular keys in the same dict is discouraged
551  */
552 XBT_INLINE uintptr_t xbt_dicti_get(xbt_dict_t dict, uintptr_t key)
553 {
554
555   unsigned int hash_code =
556       xbt_dict_hash_ext(((void *) &key), sizeof(uintptr_t));
557   xbt_dictelm_t current;
558
559   xbt_assert(dict);
560
561   current = dict->table[hash_code & dict->table_size];
562   while (current != NULL &&
563          (hash_code != current->hash_code
564           || sizeof(uintptr_t) != current->key_len
565           || (((uintptr_t) key) != ((uintptr_t) current->key)))) {
566     current = current->next;
567   }
568
569   if (current == NULL)
570     return 0;
571
572   return (uintptr_t) (current->content);
573 }
574
575 /** Remove a uintptr_t key from the dict */
576 XBT_INLINE void xbt_dicti_remove(xbt_dict_t dict, uintptr_t key)
577 {
578
579   unsigned int hash_code =
580       xbt_dict_hash_ext(((void *) &key), sizeof(uintptr_t));
581   xbt_dictelm_t current, previous = NULL;
582
583
584   current = dict->table[hash_code & dict->table_size];
585   while (current != NULL &&
586          (hash_code != current->hash_code
587           || sizeof(uintptr_t) != current->key_len
588           || (((uintptr_t) key) != ((uintptr_t) current->key)))) {
589     previous = current;         /* save the previous node */
590     current = current->next;
591   }
592
593   if (current == NULL)
594     THROWF(not_found_error, 0, "key %zu not found", key);
595
596   if (previous != NULL) {
597     previous->next = current->next;
598   } else {
599     dict->table[hash_code & dict->table_size] = current->next;
600   }
601
602   if (!dict->table[hash_code & dict->table_size])
603     dict->fill--;
604
605   xbt_dictelm_free(current);
606   dict->count--;
607 }
608
609
610 /**
611  * \brief Remove all data from the dict
612  * \param dict the dict
613  */
614 void xbt_dict_reset(xbt_dict_t dict)
615 {
616
617   int i;
618   xbt_dictelm_t current, previous = NULL;
619
620   xbt_assert(dict);
621
622   if (dict->count == 0)
623     return;
624
625   for (i = 0; i <= dict->table_size; i++) {
626     current = dict->table[i];
627     while (current != NULL) {
628       previous = current;
629       current = current->next;
630       xbt_dictelm_free(previous);
631     }
632     dict->table[i] = NULL;
633   }
634
635   dict->count = 0;
636   dict->fill = 0;
637 }
638
639 /**
640  * \brief Return the number of elements in the dict.
641  * \param dict a dictionary
642  */
643 XBT_INLINE int xbt_dict_length(xbt_dict_t dict)
644 {
645   xbt_assert(dict);
646
647   return dict->count;
648 }
649
650 /** @brief function to be used in xbt_dict_dump as long as the stored values are strings */
651 void xbt_dict_dump_output_string(void *s)
652 {
653   fputs(s, stdout);
654 }
655
656 /**
657  * \brief test if the dict is empty or not
658  */
659 XBT_INLINE int xbt_dict_is_empty(xbt_dict_t dict)
660 {
661   return (xbt_dict_size(dict) == 0);
662 }
663
664 /**
665  * \brief Outputs the content of the structure (debugging purpose)
666  *
667  * \param dict the exibitionist
668  * \param output a function to dump each data in the tree (check @ref xbt_dict_dump_output_string)
669  *
670  * Outputs the content of the structure. (for debugging purpose). \a output is a
671  * function to output the data. If NULL, data won't be displayed.
672  */
673
674 void xbt_dict_dump(xbt_dict_t dict, void_f_pvoid_t output)
675 {
676   int i;
677   xbt_dictelm_t element;
678   printf("Dict %p:\n", dict);
679   if (dict != NULL) {
680     for (i = 0; i < dict->table_size; i++) {
681       element = dict->table[i];
682       if (element) {
683         printf("[\n");
684         while (element != NULL) {
685           printf(" %s -> '", element->key);
686           if (output != NULL) {
687             (*output) (element->content);
688           }
689           printf("'\n");
690           element = element->next;
691         }
692         printf("]\n");
693       } else {
694         printf("[]\n");
695       }
696     }
697   }
698 }
699
700 xbt_dynar_t all_sizes = NULL;
701 /** @brief shows some debugging info about the bucklet repartition */
702 void xbt_dict_dump_sizes(xbt_dict_t dict)
703 {
704
705   int i;
706   unsigned int count;
707   unsigned int size;
708   xbt_dictelm_t element;
709   xbt_dynar_t sizes = xbt_dynar_new(sizeof(int), NULL);
710
711   printf("Dict %p: %d bucklets, %d used cells (of %d) ", dict, dict->count,
712          dict->fill, dict->table_size);
713   if (dict != NULL) {
714     for (i = 0; i < dict->table_size; i++) {
715       element = dict->table[i];
716       size = 0;
717       if (element) {
718         while (element != NULL) {
719           size++;
720           element = element->next;
721         }
722       }
723       if (xbt_dynar_length(sizes) <= size) {
724         int prevsize = 1;
725         xbt_dynar_set(sizes, size, &prevsize);
726       } else {
727         int prevsize;
728         xbt_dynar_get_cpy(sizes, size, &prevsize);
729         prevsize++;
730         xbt_dynar_set(sizes, size, &prevsize);
731       }
732     }
733     if (!all_sizes)
734       all_sizes = xbt_dynar_new(sizeof(int), NULL);
735
736     xbt_dynar_foreach(sizes, count, size) {
737       /* Copy values of this one into all_sizes */
738       int prevcount;
739       if (xbt_dynar_length(all_sizes) <= count) {
740         prevcount = size;
741         xbt_dynar_set(all_sizes, count, &prevcount);
742       } else {
743         xbt_dynar_get_cpy(all_sizes, count, &prevcount);
744         prevcount += size;
745         xbt_dynar_set(all_sizes, count, &prevcount);
746       }
747
748       /* Report current sizes */
749       if (count == 0)
750         continue;
751       if (size == 0)
752         continue;
753       printf("%delm x %u cells; ", count, size);
754     }
755   }
756   printf("\n");
757   xbt_dynar_free(&sizes);
758 }
759
760 /**
761  * Create the dict mallocators.
762  * This is an internal XBT function called during the lib initialization.
763  * It can be used several times to recreate the mallocator, for example when you switch to MC mode
764  */
765 void xbt_dict_preinit(void)
766 {
767   if (dict_mallocator != NULL) {
768     /* Already created. I guess we want to switch to MC mode, so kill the previously created mallocator */
769     xbt_mallocator_free(dict_mallocator);
770     xbt_mallocator_free(dict_elm_mallocator);
771   }
772
773   dict_mallocator = xbt_mallocator_new(256,
774                                        dict_mallocator_new_f,
775                                        dict_mallocator_free_f,
776                                        dict_mallocator_reset_f);
777   dict_elm_mallocator = xbt_mallocator_new(256,
778                                            dict_elm_mallocator_new_f,
779                                            dict_elm_mallocator_free_f,
780                                            dict_elm_mallocator_reset_f);
781 }
782
783 /**
784  * Destroy the dict mallocators.
785  * This is an internal XBT function during the lib initialization
786  */
787 void xbt_dict_postexit(void)
788 {
789   if (dict_mallocator != NULL) {
790     xbt_mallocator_free(dict_mallocator);
791     dict_mallocator = NULL;
792     xbt_mallocator_free(dict_elm_mallocator);
793     dict_elm_mallocator = NULL;
794   }
795   if (all_sizes) {
796     unsigned int count;
797     int size;
798     double avg = 0;
799     int total_count = 0;
800     printf("Overall stats:");
801     xbt_dynar_foreach(all_sizes, count, size) {
802       if (count == 0)
803         continue;
804       if (size == 0)
805         continue;
806       printf("%delm x %d cells; ", count, size);
807       avg += count * size;
808       total_count += size;
809     }
810     printf("; %f elm per cell\n", avg / (double) total_count);
811   }
812 }
813
814 static void *dict_mallocator_new_f(void)
815 {
816   return xbt_new(s_xbt_dict_t, 1);
817 }
818
819 static void dict_mallocator_free_f(void *dict)
820 {
821   xbt_free(dict);
822 }
823
824 static void dict_mallocator_reset_f(void *dict)
825 {
826   /* nothing to do because all fields are
827    * initialized in xbt_dict_new
828    */
829 }
830
831 #ifdef SIMGRID_TEST
832 #include "xbt.h"
833 #include "xbt/ex.h"
834 #include "portable.h"
835
836 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
837 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
838
839 XBT_TEST_SUITE("dict", "Dict data container");
840
841 static void print_str(void *str)
842 {
843   printf("%s", (char *) PRINTF_STR(str));
844 }
845
846 static void debuged_add_ext(xbt_dict_t head, const char *key,
847                             const char *data_to_fill)
848 {
849   char *data = xbt_strdup(data_to_fill);
850
851   xbt_test_log("Add %s under %s", PRINTF_STR(data_to_fill),
852                 PRINTF_STR(key));
853
854   xbt_dict_set(head, key, data, &free);
855   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
856     xbt_dict_dump(head, (void (*)(void *)) &printf);
857     fflush(stdout);
858   }
859 }
860
861 static void debuged_add(xbt_dict_t head, const char *key)
862 {
863   debuged_add_ext(head, key, key);
864 }
865
866 static void fill(xbt_dict_t * head)
867 {
868   xbt_test_add("Fill in the dictionnary");
869
870   *head = xbt_dict_new();
871   debuged_add(*head, "12");
872   debuged_add(*head, "12a");
873   debuged_add(*head, "12b");
874   debuged_add(*head, "123");
875   debuged_add(*head, "123456");
876   /* Child becomes child of what to add */
877   debuged_add(*head, "1234");
878   /* Need of common ancestor */
879   debuged_add(*head, "123457");
880 }
881
882
883 static void search_ext(xbt_dict_t head, const char *key, const char *data)
884 {
885   void *found;
886
887   xbt_test_add("Search %s", key);
888   found = xbt_dict_get(head, key);
889   xbt_test_log("Found %s", (char *) found);
890   if (data)
891     xbt_test_assert(found,
892                      "data do not match expectations: found NULL while searching for %s",
893                      data);
894   if (found)
895     xbt_test_assert(!strcmp((char *) data, found),
896                      "data do not match expectations: found %s while searching for %s",
897                      (char *) found, data);
898 }
899
900 static void search(xbt_dict_t head, const char *key)
901 {
902   search_ext(head, key, key);
903 }
904
905 static void debuged_remove(xbt_dict_t head, const char *key)
906 {
907
908   xbt_test_add("Remove '%s'", PRINTF_STR(key));
909   xbt_dict_remove(head, key);
910   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
911 }
912
913
914 static void traverse(xbt_dict_t head)
915 {
916   xbt_dict_cursor_t cursor = NULL;
917   char *key;
918   char *data;
919   int i = 0;
920
921   xbt_dict_foreach(head, cursor, key, data) {
922     if (!key || !data || strcmp(key, data)) {
923       xbt_test_log("Seen #%d:  %s->%s", ++i, PRINTF_STR(key),
924                     PRINTF_STR(data));
925     } else {
926       xbt_test_log("Seen #%d:  %s", ++i, PRINTF_STR(key));
927     }
928     xbt_test_assert(!data || !strcmp(key, data),
929                      "Key(%s) != value(%s). Aborting", key, data);
930   }
931 }
932
933 static void search_not_found(xbt_dict_t head, const char *data)
934 {
935   int ok = 0;
936   xbt_ex_t e;
937
938   xbt_test_add("Search %s (expected not to be found)", data);
939
940   TRY {
941     data = xbt_dict_get(head, data);
942     THROWF(unknown_error, 0,
943            "Found something which shouldn't be there (%s)", data);
944   } CATCH(e) {
945     if (e.category != not_found_error)
946       xbt_test_exception(e);
947     xbt_ex_free(e);
948     ok = 1;
949   }
950   xbt_test_assert(ok, "Exception not raised");
951 }
952
953 static void count(xbt_dict_t dict, int length)
954 {
955   xbt_dict_cursor_t cursor;
956   char *key;
957   void *data;
958   int effective = 0;
959
960
961   xbt_test_add("Count elements (expecting %d)", length);
962   xbt_test_assert(xbt_dict_length(dict) == length,
963                    "Announced length(%d) != %d.", xbt_dict_length(dict),
964                    length);
965
966   xbt_dict_foreach(dict, cursor, key, data)
967       effective++;
968
969   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
970                    effective, length);
971
972 }
973
974 static void count_check_get_key(xbt_dict_t dict, int length)
975 {
976   xbt_dict_cursor_t cursor;
977   char *key, *key2;
978   void *data;
979   int effective = 0;
980
981
982   xbt_test_add
983       ("Count elements (expecting %d), and test the getkey function",
984        length);
985   xbt_test_assert(xbt_dict_length(dict) == length,
986                    "Announced length(%d) != %d.", xbt_dict_length(dict),
987                    length);
988
989   xbt_dict_foreach(dict, cursor, key, data) {
990     effective++;
991     key2 = xbt_dict_get_key(dict, data);
992     xbt_assert(!strcmp(key, key2),
993                 "The data was registered under %s instead of %s as expected",
994                 key2, key);
995   }
996
997   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
998                    effective, length);
999
1000 }
1001
1002 xbt_ex_t e;
1003 xbt_dict_t head = NULL;
1004 char *data;
1005
1006
1007 XBT_TEST_UNIT("basic", test_dict_basic, "Basic usage: change, retrieve, traverse")
1008 {
1009   xbt_test_add("Traversal the null dictionary");
1010   traverse(head);
1011
1012   xbt_test_add("Traversal and search the empty dictionary");
1013   head = xbt_dict_new();
1014   traverse(head);
1015   TRY {
1016     debuged_remove(head, "12346");
1017   } CATCH(e) {
1018     if (e.category != not_found_error)
1019       xbt_test_exception(e);
1020     xbt_ex_free(e);
1021   }
1022   xbt_dict_free(&head);
1023
1024   xbt_test_add("Traverse the full dictionary");
1025   fill(&head);
1026   count_check_get_key(head, 7);
1027
1028   debuged_add_ext(head, "toto", "tutu");
1029   search_ext(head, "toto", "tutu");
1030   debuged_remove(head, "toto");
1031
1032   search(head, "12a");
1033   traverse(head);
1034
1035   xbt_test_add("Free the dictionary (twice)");
1036   xbt_dict_free(&head);
1037   xbt_dict_free(&head);
1038
1039   /* CHANGING */
1040   fill(&head);
1041   count_check_get_key(head, 7);
1042   xbt_test_add("Change 123 to 'Changed 123'");
1043   xbt_dict_set(head, "123", strdup("Changed 123"), &free);
1044   count_check_get_key(head, 7);
1045
1046   xbt_test_add("Change 123 back to '123'");
1047   xbt_dict_set(head, "123", strdup("123"), &free);
1048   count_check_get_key(head, 7);
1049
1050   xbt_test_add("Change 12a to 'Dummy 12a'");
1051   xbt_dict_set(head, "12a", strdup("Dummy 12a"), &free);
1052   count_check_get_key(head, 7);
1053
1054   xbt_test_add("Change 12a to '12a'");
1055   xbt_dict_set(head, "12a", strdup("12a"), &free);
1056   count_check_get_key(head, 7);
1057
1058   xbt_test_add("Traverse the resulting dictionary");
1059   traverse(head);
1060
1061   /* RETRIEVE */
1062   xbt_test_add("Search 123");
1063   data = xbt_dict_get(head, "123");
1064   xbt_test_assert(data);
1065   xbt_test_assert(!strcmp("123", data));
1066
1067   search_not_found(head, "Can't be found");
1068   search_not_found(head, "123 Can't be found");
1069   search_not_found(head, "12345678 NOT");
1070
1071   search(head, "12a");
1072   search(head, "12b");
1073   search(head, "12");
1074   search(head, "123456");
1075   search(head, "1234");
1076   search(head, "123457");
1077
1078   xbt_test_add("Traverse the resulting dictionary");
1079   traverse(head);
1080
1081   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
1082
1083   xbt_test_add("Free the dictionary twice");
1084   xbt_dict_free(&head);
1085   xbt_dict_free(&head);
1086
1087   xbt_test_add("Traverse the resulting dictionary");
1088   traverse(head);
1089 }
1090
1091 XBT_TEST_UNIT("remove", test_dict_remove, "Removing some values")
1092 {
1093   fill(&head);
1094   count(head, 7);
1095   xbt_test_add("Remove non existing data");
1096   TRY {
1097     debuged_remove(head, "Does not exist");
1098   }
1099   CATCH(e) {
1100     if (e.category != not_found_error)
1101       xbt_test_exception(e);
1102     xbt_ex_free(e);
1103   }
1104   traverse(head);
1105
1106   xbt_dict_free(&head);
1107
1108   xbt_test_add
1109       ("Remove each data manually (traversing the resulting dictionary each time)");
1110   fill(&head);
1111   debuged_remove(head, "12a");
1112   traverse(head);
1113   count(head, 6);
1114   debuged_remove(head, "12b");
1115   traverse(head);
1116   count(head, 5);
1117   debuged_remove(head, "12");
1118   traverse(head);
1119   count(head, 4);
1120   debuged_remove(head, "123456");
1121   traverse(head);
1122   count(head, 3);
1123   TRY {
1124     debuged_remove(head, "12346");
1125   }
1126   CATCH(e) {
1127     if (e.category != not_found_error)
1128       xbt_test_exception(e);
1129     xbt_ex_free(e);
1130     traverse(head);
1131   }
1132   debuged_remove(head, "1234");
1133   traverse(head);
1134   debuged_remove(head, "123457");
1135   traverse(head);
1136   debuged_remove(head, "123");
1137   traverse(head);
1138   TRY {
1139     debuged_remove(head, "12346");
1140   }
1141   CATCH(e) {
1142     if (e.category != not_found_error)
1143       xbt_test_exception(e);
1144     xbt_ex_free(e);
1145   }
1146   traverse(head);
1147
1148   xbt_test_add
1149       ("Free dict, create new fresh one, and then reset the dict");
1150   xbt_dict_free(&head);
1151   fill(&head);
1152   xbt_dict_reset(head);
1153   count(head, 0);
1154   traverse(head);
1155
1156   xbt_test_add("Free the dictionary twice");
1157   xbt_dict_free(&head);
1158   xbt_dict_free(&head);
1159 }
1160
1161 XBT_TEST_UNIT("nulldata", test_dict_nulldata, "NULL data management")
1162 {
1163   fill(&head);
1164
1165   xbt_test_add("Store NULL under 'null'");
1166   xbt_dict_set(head, "null", NULL, NULL);
1167   search_ext(head, "null", NULL);
1168
1169   xbt_test_add("Check whether I see it while traversing...");
1170   {
1171     xbt_dict_cursor_t cursor = NULL;
1172     char *key;
1173     int found = 0;
1174
1175     xbt_dict_foreach(head, cursor, key, data) {
1176       if (!key || !data || strcmp(key, data)) {
1177         xbt_test_log("Seen:  %s->%s", PRINTF_STR(key), PRINTF_STR(data));
1178       } else {
1179         xbt_test_log("Seen:  %s", PRINTF_STR(key));
1180       }
1181
1182       if (!strcmp(key, "null"))
1183         found = 1;
1184     }
1185     xbt_test_assert(found,
1186                      "the key 'null', associated to NULL is not found");
1187   }
1188   xbt_dict_free(&head);
1189 }
1190
1191 static void debuged_addi(xbt_dict_t head, uintptr_t key, uintptr_t data)
1192 {
1193   uintptr_t stored_data = 0;
1194   xbt_test_log("Add %zu under %zu", data, key);
1195
1196   xbt_dicti_set(head, key, data);
1197   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
1198     xbt_dict_dump(head, (void (*)(void *)) &printf);
1199     fflush(stdout);
1200   }
1201   stored_data = xbt_dicti_get(head, key);
1202   xbt_test_assert(stored_data == data,
1203                    "Retrieved data (%zu) is not what I just stored (%zu) under key %zu",
1204                    stored_data, data, key);
1205 }
1206
1207 XBT_TEST_UNIT("dicti", test_dict_scalar, "Scalar data and key management")
1208 {
1209   xbt_test_add("Fill in the dictionnary");
1210
1211   head = xbt_dict_new();
1212   debuged_addi(head, 12, 12);
1213   debuged_addi(head, 13, 13);
1214   debuged_addi(head, 14, 14);
1215   debuged_addi(head, 15, 15);
1216   /* Change values */
1217   debuged_addi(head, 12, 15);
1218   debuged_addi(head, 15, 2000);
1219   debuged_addi(head, 15, 3000);
1220   /* 0 as key */
1221   debuged_addi(head, 0, 1000);
1222   debuged_addi(head, 0, 2000);
1223   debuged_addi(head, 0, 3000);
1224   /* 0 as value */
1225   debuged_addi(head, 12, 0);
1226   debuged_addi(head, 13, 0);
1227   debuged_addi(head, 12, 0);
1228   debuged_addi(head, 0, 0);
1229
1230   xbt_dict_free(&head);
1231 }
1232
1233 #define NB_ELM 20000
1234 #define SIZEOFKEY 1024
1235 static int countelems(xbt_dict_t head)
1236 {
1237   xbt_dict_cursor_t cursor;
1238   char *key;
1239   void *data;
1240   int res = 0;
1241
1242   xbt_dict_foreach(head, cursor, key, data) {
1243     res++;
1244   }
1245   return res;
1246 }
1247
1248 XBT_TEST_UNIT("crash", test_dict_crash, "Crash test")
1249 {
1250   xbt_dict_t head = NULL;
1251   int i, j, k, nb;
1252   char *key;
1253   void *data;
1254
1255   srand((unsigned int) time(NULL));
1256
1257   for (i = 0; i < 10; i++) {
1258     xbt_test_add("CRASH test number %d (%d to go)", i + 1, 10 - i - 1);
1259     xbt_test_log
1260         ("Fill the struct, count its elems and frees the structure");
1261     xbt_test_log
1262         ("using 1000 elements with %d chars long randomized keys.",
1263          SIZEOFKEY);
1264     head = xbt_dict_new();
1265     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1266     nb = 0;
1267     for (j = 0; j < 1000; j++) {
1268       char *data = NULL;
1269       key = xbt_malloc(SIZEOFKEY);
1270
1271       do {
1272         for (k = 0; k < SIZEOFKEY - 1; k++)
1273           key[k] = rand() % ('z' - 'a') + 'a';
1274         key[k] = '\0';
1275         /*      printf("[%d %s]\n",j,key); */
1276         data = xbt_dict_get_or_null(head, key);
1277       } while (data != NULL);
1278
1279       xbt_dict_set(head, key, key, &free);
1280       data = xbt_dict_get(head, key);
1281       xbt_test_assert(!strcmp(key, data),
1282                        "Retrieved value (%s) != Injected value (%s)", key,
1283                        data);
1284
1285       count(head, j + 1);
1286     }
1287     /*    xbt_dict_dump(head,(void (*)(void*))&printf); */
1288     traverse(head);
1289     xbt_dict_free(&head);
1290     xbt_dict_free(&head);
1291   }
1292
1293
1294   head = xbt_dict_new();
1295   xbt_test_add("Fill %d elements, with keys being the number of element",
1296                 NB_ELM);
1297   for (j = 0; j < NB_ELM; j++) {
1298     /* if (!(j%1000)) { printf("."); fflush(stdout); } */
1299
1300     key = xbt_malloc(10);
1301
1302     sprintf(key, "%d", j);
1303     xbt_dict_set(head, key, key, &free);
1304   }
1305   /*xbt_dict_dump(head,(void (*)(void*))&printf); */
1306
1307   xbt_test_add
1308       ("Count the elements (retrieving the key and data for each)");
1309   i = countelems(head);
1310   xbt_test_log("There is %d elements", i);
1311
1312   xbt_test_add("Search my %d elements 20 times", NB_ELM);
1313   key = xbt_malloc(10);
1314   for (i = 0; i < 20; i++) {
1315     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1316     for (j = 0; j < NB_ELM; j++) {
1317
1318       sprintf(key, "%d", j);
1319       data = xbt_dict_get(head, key);
1320       xbt_test_assert(!strcmp(key, (char *) data),
1321                        "with get, key=%s != data=%s", key, (char *) data);
1322       data = xbt_dict_get_ext(head, key, strlen(key));
1323       xbt_test_assert(!strcmp(key, (char *) data),
1324                        "with get_ext, key=%s != data=%s", key,
1325                        (char *) data);
1326     }
1327   }
1328   free(key);
1329
1330   xbt_test_add("Remove my %d elements", NB_ELM);
1331   key = xbt_malloc(10);
1332   for (j = 0; j < NB_ELM; j++) {
1333     /* if (!(j%10000)) printf("."); fflush(stdout); */
1334
1335     sprintf(key, "%d", j);
1336     xbt_dict_remove(head, key);
1337   }
1338   free(key);
1339
1340
1341   xbt_test_add("Free the structure (twice)");
1342   xbt_dict_free(&head);
1343   xbt_dict_free(&head);
1344 }
1345
1346 static void str_free(void *s)
1347 {
1348   char *c = *(char **) s;
1349   free(c);
1350 }
1351
1352 XBT_TEST_UNIT("multicrash", test_dict_multicrash, "Multi-dict crash test")
1353 {
1354
1355 #undef NB_ELM
1356 #define NB_ELM 100              /*00 */
1357 #define DEPTH 5
1358 #define KEY_SIZE 512
1359 #define NB_TEST 20              /*20 */
1360   int verbose = 0;
1361
1362   xbt_dict_t mdict = NULL;
1363   int i, j, k, l;
1364   xbt_dynar_t keys = xbt_dynar_new(sizeof(char *), str_free);
1365   void *data;
1366   char *key;
1367
1368
1369   xbt_test_add("Generic multicache CRASH test");
1370   xbt_test_log
1371       (" Fill the struct and frees it %d times, using %d elements, "
1372        "depth of multicache=%d, key size=%d", NB_TEST, NB_ELM, DEPTH,
1373        KEY_SIZE);
1374
1375   for (l = 0; l < DEPTH; l++) {
1376     key = xbt_malloc(KEY_SIZE);
1377     xbt_dynar_push(keys, &key);
1378   }
1379
1380   for (i = 0; i < NB_TEST; i++) {
1381     mdict = xbt_dict_new();
1382     XBT_VERB("mdict=%p", mdict);
1383     if (verbose > 0)
1384       printf("Test %d\n", i);
1385     /* else if (i%10) printf("."); else printf("%d",i/10); */
1386
1387     for (j = 0; j < NB_ELM; j++) {
1388       if (verbose > 0)
1389         printf("  Add {");
1390
1391       for (l = 0; l < DEPTH; l++) {
1392         key = *(char **) xbt_dynar_get_ptr(keys, l);
1393
1394         for (k = 0; k < KEY_SIZE - 1; k++)
1395           key[k] = rand() % ('z' - 'a') + 'a';
1396
1397         key[k] = '\0';
1398
1399         if (verbose > 0)
1400           printf("%p=%s %s ", key, key, (l < DEPTH - 1 ? ";" : "}"));
1401       }
1402       if (verbose > 0)
1403         printf("in multitree %p.\n", mdict);
1404
1405       xbt_multidict_set(mdict, keys, xbt_strdup(key), free);
1406
1407       data = xbt_multidict_get(mdict, keys);
1408
1409       xbt_test_assert(data && !strcmp((char *) data, key),
1410                        "Retrieved value (%s) does not match the given one (%s)\n",
1411                        (char *) data, key);
1412     }
1413     xbt_dict_free(&mdict);
1414   }
1415
1416   xbt_dynar_free(&keys);
1417
1418   /*  if (verbose>0)
1419      xbt_dict_dump(mdict,&xbt_dict_print); */
1420
1421   xbt_dict_free(&mdict);
1422   xbt_dynar_free(&keys);
1423
1424 }
1425 #endif                          /* SIMGRID_TEST */