Logo AND Algorithmique Numérique Distribuée

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