Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
b0a5031b973a6f2f19a45f72f10dfcf3cea4d15f
[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 #define dict_mallocator_free_f xbt_free_f
27 #define dict_mallocator_reset_f ((void_f_pvoid_t)NULL)
28
29
30 /*####[ Code ]###############################################################*/
31
32 /**
33  * \brief Constructor
34  * \return pointer to the destination
35  * \see 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 !dict || (xbt_dict_length(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 #ifdef SIMGRID_TEST
820 #include "xbt.h"
821 #include "xbt/ex.h"
822 #include "portable.h"
823
824 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
825 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
826
827 XBT_TEST_SUITE("dict", "Dict data container");
828
829 static void print_str(void *str)
830 {
831   printf("%s", (char *) PRINTF_STR(str));
832 }
833
834 static void debuged_add_ext(xbt_dict_t head, const char *key,
835                             const char *data_to_fill)
836 {
837   char *data = xbt_strdup(data_to_fill);
838
839   xbt_test_log("Add %s under %s", PRINTF_STR(data_to_fill),
840                 PRINTF_STR(key));
841
842   xbt_dict_set(head, key, data, &free);
843   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
844     xbt_dict_dump(head, (void (*)(void *)) &printf);
845     fflush(stdout);
846   }
847 }
848
849 static void debuged_add(xbt_dict_t head, const char *key)
850 {
851   debuged_add_ext(head, key, key);
852 }
853
854 static void fill(xbt_dict_t * head)
855 {
856   xbt_test_add("Fill in the dictionnary");
857
858   *head = xbt_dict_new();
859   debuged_add(*head, "12");
860   debuged_add(*head, "12a");
861   debuged_add(*head, "12b");
862   debuged_add(*head, "123");
863   debuged_add(*head, "123456");
864   /* Child becomes child of what to add */
865   debuged_add(*head, "1234");
866   /* Need of common ancestor */
867   debuged_add(*head, "123457");
868 }
869
870
871 static void search_ext(xbt_dict_t head, const char *key, const char *data)
872 {
873   void *found;
874
875   xbt_test_add("Search %s", key);
876   found = xbt_dict_get(head, key);
877   xbt_test_log("Found %s", (char *) found);
878   if (data)
879     xbt_test_assert(found,
880                      "data do not match expectations: found NULL while searching for %s",
881                      data);
882   if (found)
883     xbt_test_assert(!strcmp((char *) data, found),
884                      "data do not match expectations: found %s while searching for %s",
885                      (char *) found, data);
886 }
887
888 static void search(xbt_dict_t head, const char *key)
889 {
890   search_ext(head, key, key);
891 }
892
893 static void debuged_remove(xbt_dict_t head, const char *key)
894 {
895
896   xbt_test_add("Remove '%s'", PRINTF_STR(key));
897   xbt_dict_remove(head, key);
898   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
899 }
900
901
902 static void traverse(xbt_dict_t head)
903 {
904   xbt_dict_cursor_t cursor = NULL;
905   char *key;
906   char *data;
907   int i = 0;
908
909   xbt_dict_foreach(head, cursor, key, data) {
910     if (!key || !data || strcmp(key, data)) {
911       xbt_test_log("Seen #%d:  %s->%s", ++i, PRINTF_STR(key),
912                     PRINTF_STR(data));
913     } else {
914       xbt_test_log("Seen #%d:  %s", ++i, PRINTF_STR(key));
915     }
916     xbt_test_assert(!data || !strcmp(key, data),
917                      "Key(%s) != value(%s). Aborting", key, data);
918   }
919 }
920
921 static void search_not_found(xbt_dict_t head, const char *data)
922 {
923   int ok = 0;
924   xbt_ex_t e;
925
926   xbt_test_add("Search %s (expected not to be found)", data);
927
928   TRY {
929     data = xbt_dict_get(head, data);
930     THROWF(unknown_error, 0,
931            "Found something which shouldn't be there (%s)", data);
932   }
933   CATCH(e) {
934     if (e.category != not_found_error)
935       xbt_test_exception(e);
936     xbt_ex_free(e);
937     ok = 1;
938   }
939   xbt_test_assert(ok, "Exception not raised");
940 }
941
942 static void count(xbt_dict_t dict, int length)
943 {
944   xbt_dict_cursor_t cursor;
945   char *key;
946   void *data;
947   int effective = 0;
948
949
950   xbt_test_add("Count elements (expecting %d)", length);
951   xbt_test_assert(xbt_dict_length(dict) == length,
952                    "Announced length(%d) != %d.", xbt_dict_length(dict),
953                    length);
954
955   xbt_dict_foreach(dict, cursor, key, data)
956       effective++;
957
958   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
959                    effective, length);
960
961 }
962
963 static void count_check_get_key(xbt_dict_t dict, int length)
964 {
965   xbt_dict_cursor_t cursor;
966   char *key;
967   _XBT_GNUC_UNUSED char *key2;
968   void *data;
969   int effective = 0;
970
971
972   xbt_test_add
973       ("Count elements (expecting %d), and test the getkey function",
974        length);
975   xbt_test_assert(xbt_dict_length(dict) == length,
976                    "Announced length(%d) != %d.", xbt_dict_length(dict),
977                    length);
978
979   xbt_dict_foreach(dict, cursor, key, data) {
980     effective++;
981     key2 = xbt_dict_get_key(dict, data);
982     xbt_assert(!strcmp(key, key2),
983                 "The data was registered under %s instead of %s as expected",
984                 key2, key);
985   }
986
987   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
988                    effective, length);
989
990 }
991
992 xbt_ex_t e;
993 xbt_dict_t head = NULL;
994 char *data;
995
996
997 XBT_TEST_UNIT("basic", test_dict_basic, "Basic usage: change, retrieve, traverse")
998 {
999   xbt_test_add("Traversal the null dictionary");
1000   traverse(head);
1001
1002   xbt_test_add("Traversal and search the empty dictionary");
1003   head = xbt_dict_new();
1004   traverse(head);
1005   TRY {
1006     debuged_remove(head, "12346");
1007   }
1008   CATCH(e) {
1009     if (e.category != not_found_error)
1010       xbt_test_exception(e);
1011     xbt_ex_free(e);
1012   }
1013   xbt_dict_free(&head);
1014
1015   xbt_test_add("Traverse the full dictionary");
1016   fill(&head);
1017   count_check_get_key(head, 7);
1018
1019   debuged_add_ext(head, "toto", "tutu");
1020   search_ext(head, "toto", "tutu");
1021   debuged_remove(head, "toto");
1022
1023   search(head, "12a");
1024   traverse(head);
1025
1026   xbt_test_add("Free the dictionary (twice)");
1027   xbt_dict_free(&head);
1028   xbt_dict_free(&head);
1029
1030   /* CHANGING */
1031   fill(&head);
1032   count_check_get_key(head, 7);
1033   xbt_test_add("Change 123 to 'Changed 123'");
1034   xbt_dict_set(head, "123", strdup("Changed 123"), &free);
1035   count_check_get_key(head, 7);
1036
1037   xbt_test_add("Change 123 back to '123'");
1038   xbt_dict_set(head, "123", strdup("123"), &free);
1039   count_check_get_key(head, 7);
1040
1041   xbt_test_add("Change 12a to 'Dummy 12a'");
1042   xbt_dict_set(head, "12a", strdup("Dummy 12a"), &free);
1043   count_check_get_key(head, 7);
1044
1045   xbt_test_add("Change 12a to '12a'");
1046   xbt_dict_set(head, "12a", strdup("12a"), &free);
1047   count_check_get_key(head, 7);
1048
1049   xbt_test_add("Traverse the resulting dictionary");
1050   traverse(head);
1051
1052   /* RETRIEVE */
1053   xbt_test_add("Search 123");
1054   data = xbt_dict_get(head, "123");
1055   xbt_test_assert(data);
1056   xbt_test_assert(!strcmp("123", data));
1057
1058   search_not_found(head, "Can't be found");
1059   search_not_found(head, "123 Can't be found");
1060   search_not_found(head, "12345678 NOT");
1061
1062   search(head, "12a");
1063   search(head, "12b");
1064   search(head, "12");
1065   search(head, "123456");
1066   search(head, "1234");
1067   search(head, "123457");
1068
1069   xbt_test_add("Traverse the resulting dictionary");
1070   traverse(head);
1071
1072   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
1073
1074   xbt_test_add("Free the dictionary twice");
1075   xbt_dict_free(&head);
1076   xbt_dict_free(&head);
1077
1078   xbt_test_add("Traverse the resulting dictionary");
1079   traverse(head);
1080 }
1081
1082 XBT_TEST_UNIT("remove", test_dict_remove, "Removing some values")
1083 {
1084   fill(&head);
1085   count(head, 7);
1086   xbt_test_add("Remove non existing data");
1087   TRY {
1088     debuged_remove(head, "Does not exist");
1089   }
1090   CATCH(e) {
1091     if (e.category != not_found_error)
1092       xbt_test_exception(e);
1093     xbt_ex_free(e);
1094   }
1095   traverse(head);
1096
1097   xbt_dict_free(&head);
1098
1099   xbt_test_add
1100       ("Remove each data manually (traversing the resulting dictionary each time)");
1101   fill(&head);
1102   debuged_remove(head, "12a");
1103   traverse(head);
1104   count(head, 6);
1105   debuged_remove(head, "12b");
1106   traverse(head);
1107   count(head, 5);
1108   debuged_remove(head, "12");
1109   traverse(head);
1110   count(head, 4);
1111   debuged_remove(head, "123456");
1112   traverse(head);
1113   count(head, 3);
1114   TRY {
1115     debuged_remove(head, "12346");
1116   }
1117   CATCH(e) {
1118     if (e.category != not_found_error)
1119       xbt_test_exception(e);
1120     xbt_ex_free(e);
1121     traverse(head);
1122   }
1123   debuged_remove(head, "1234");
1124   traverse(head);
1125   debuged_remove(head, "123457");
1126   traverse(head);
1127   debuged_remove(head, "123");
1128   traverse(head);
1129   TRY {
1130     debuged_remove(head, "12346");
1131   }
1132   CATCH(e) {
1133     if (e.category != not_found_error)
1134       xbt_test_exception(e);
1135     xbt_ex_free(e);
1136   }
1137   traverse(head);
1138
1139   xbt_test_add
1140       ("Free dict, create new fresh one, and then reset the dict");
1141   xbt_dict_free(&head);
1142   fill(&head);
1143   xbt_dict_reset(head);
1144   count(head, 0);
1145   traverse(head);
1146
1147   xbt_test_add("Free the dictionary twice");
1148   xbt_dict_free(&head);
1149   xbt_dict_free(&head);
1150 }
1151
1152 XBT_TEST_UNIT("nulldata", test_dict_nulldata, "NULL data management")
1153 {
1154   fill(&head);
1155
1156   xbt_test_add("Store NULL under 'null'");
1157   xbt_dict_set(head, "null", NULL, NULL);
1158   search_ext(head, "null", NULL);
1159
1160   xbt_test_add("Check whether I see it while traversing...");
1161   {
1162     xbt_dict_cursor_t cursor = NULL;
1163     char *key;
1164     int found = 0;
1165
1166     xbt_dict_foreach(head, cursor, key, data) {
1167       if (!key || !data || strcmp(key, data)) {
1168         xbt_test_log("Seen:  %s->%s", PRINTF_STR(key), PRINTF_STR(data));
1169       } else {
1170         xbt_test_log("Seen:  %s", PRINTF_STR(key));
1171       }
1172
1173       if (!strcmp(key, "null"))
1174         found = 1;
1175     }
1176     xbt_test_assert(found,
1177                      "the key 'null', associated to NULL is not found");
1178   }
1179   xbt_dict_free(&head);
1180 }
1181
1182 static void debuged_addi(xbt_dict_t head, uintptr_t key, uintptr_t data)
1183 {
1184   uintptr_t stored_data = 0;
1185   xbt_test_log("Add %zu under %zu", data, key);
1186
1187   xbt_dicti_set(head, key, data);
1188   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
1189     xbt_dict_dump(head, (void (*)(void *)) &printf);
1190     fflush(stdout);
1191   }
1192   stored_data = xbt_dicti_get(head, key);
1193   xbt_test_assert(stored_data == data,
1194                    "Retrieved data (%zu) is not what I just stored (%zu) under key %zu",
1195                    stored_data, data, key);
1196 }
1197
1198 XBT_TEST_UNIT("dicti", test_dict_scalar, "Scalar data and key management")
1199 {
1200   xbt_test_add("Fill in the dictionnary");
1201
1202   head = xbt_dict_new();
1203   debuged_addi(head, 12, 12);
1204   debuged_addi(head, 13, 13);
1205   debuged_addi(head, 14, 14);
1206   debuged_addi(head, 15, 15);
1207   /* Change values */
1208   debuged_addi(head, 12, 15);
1209   debuged_addi(head, 15, 2000);
1210   debuged_addi(head, 15, 3000);
1211   /* 0 as key */
1212   debuged_addi(head, 0, 1000);
1213   debuged_addi(head, 0, 2000);
1214   debuged_addi(head, 0, 3000);
1215   /* 0 as value */
1216   debuged_addi(head, 12, 0);
1217   debuged_addi(head, 13, 0);
1218   debuged_addi(head, 12, 0);
1219   debuged_addi(head, 0, 0);
1220
1221   xbt_dict_free(&head);
1222 }
1223
1224 #define NB_ELM 20000
1225 #define SIZEOFKEY 1024
1226 static int countelems(xbt_dict_t head)
1227 {
1228   xbt_dict_cursor_t cursor;
1229   char *key;
1230   void *data;
1231   int res = 0;
1232
1233   xbt_dict_foreach(head, cursor, key, data) {
1234     res++;
1235   }
1236   return res;
1237 }
1238
1239 XBT_TEST_UNIT("crash", test_dict_crash, "Crash test")
1240 {
1241   xbt_dict_t head = NULL;
1242   int i, j, k;
1243   char *key;
1244   void *data;
1245
1246   srand((unsigned int) time(NULL));
1247
1248   for (i = 0; i < 10; i++) {
1249     xbt_test_add("CRASH test number %d (%d to go)", i + 1, 10 - i - 1);
1250     xbt_test_log
1251         ("Fill the struct, count its elems and frees the structure");
1252     xbt_test_log
1253         ("using 1000 elements with %d chars long randomized keys.",
1254          SIZEOFKEY);
1255     head = xbt_dict_new();
1256     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1257     for (j = 0; j < 1000; j++) {
1258       char *data = NULL;
1259       key = xbt_malloc(SIZEOFKEY);
1260
1261       do {
1262         for (k = 0; k < SIZEOFKEY - 1; k++)
1263           key[k] = rand() % ('z' - 'a') + 'a';
1264         key[k] = '\0';
1265         /*      printf("[%d %s]\n",j,key); */
1266         data = xbt_dict_get_or_null(head, key);
1267       } while (data != NULL);
1268
1269       xbt_dict_set(head, key, key, &free);
1270       data = xbt_dict_get(head, key);
1271       xbt_test_assert(!strcmp(key, data),
1272                        "Retrieved value (%s) != Injected value (%s)", key,
1273                        data);
1274
1275       count(head, j + 1);
1276     }
1277     /*    xbt_dict_dump(head,(void (*)(void*))&printf); */
1278     traverse(head);
1279     xbt_dict_free(&head);
1280     xbt_dict_free(&head);
1281   }
1282
1283
1284   head = xbt_dict_new();
1285   xbt_test_add("Fill %d elements, with keys being the number of element",
1286                 NB_ELM);
1287   for (j = 0; j < NB_ELM; j++) {
1288     /* if (!(j%1000)) { printf("."); fflush(stdout); } */
1289
1290     key = xbt_malloc(10);
1291
1292     sprintf(key, "%d", j);
1293     xbt_dict_set(head, key, key, &free);
1294   }
1295   /*xbt_dict_dump(head,(void (*)(void*))&printf); */
1296
1297   xbt_test_add
1298       ("Count the elements (retrieving the key and data for each)");
1299   i = countelems(head);
1300   xbt_test_log("There is %d elements", i);
1301
1302   xbt_test_add("Search my %d elements 20 times", NB_ELM);
1303   key = xbt_malloc(10);
1304   for (i = 0; i < 20; i++) {
1305     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1306     for (j = 0; j < NB_ELM; j++) {
1307
1308       sprintf(key, "%d", j);
1309       data = xbt_dict_get(head, key);
1310       xbt_test_assert(!strcmp(key, (char *) data),
1311                        "with get, key=%s != data=%s", key, (char *) data);
1312       data = xbt_dict_get_ext(head, key, strlen(key));
1313       xbt_test_assert(!strcmp(key, (char *) data),
1314                        "with get_ext, key=%s != data=%s", key,
1315                        (char *) data);
1316     }
1317   }
1318   free(key);
1319
1320   xbt_test_add("Remove my %d elements", NB_ELM);
1321   key = xbt_malloc(10);
1322   for (j = 0; j < NB_ELM; j++) {
1323     /* if (!(j%10000)) printf("."); fflush(stdout); */
1324
1325     sprintf(key, "%d", j);
1326     xbt_dict_remove(head, key);
1327   }
1328   free(key);
1329
1330
1331   xbt_test_add("Free the structure (twice)");
1332   xbt_dict_free(&head);
1333   xbt_dict_free(&head);
1334 }
1335
1336 static void str_free(void *s)
1337 {
1338   char *c = *(char **) s;
1339   free(c);
1340 }
1341
1342 XBT_TEST_UNIT("multicrash", test_dict_multicrash, "Multi-dict crash test")
1343 {
1344
1345 #undef NB_ELM
1346 #define NB_ELM 100              /*00 */
1347 #define DEPTH 5
1348 #define KEY_SIZE 512
1349 #define NB_TEST 20              /*20 */
1350   int verbose = 0;
1351
1352   xbt_dict_t mdict = NULL;
1353   int i, j, k, l;
1354   xbt_dynar_t keys = xbt_dynar_new(sizeof(char *), str_free);
1355   void *data;
1356   char *key;
1357
1358
1359   xbt_test_add("Generic multicache CRASH test");
1360   xbt_test_log
1361       (" Fill the struct and frees it %d times, using %d elements, "
1362        "depth of multicache=%d, key size=%d", NB_TEST, NB_ELM, DEPTH,
1363        KEY_SIZE);
1364
1365   for (l = 0; l < DEPTH; l++) {
1366     key = xbt_malloc(KEY_SIZE);
1367     xbt_dynar_push(keys, &key);
1368   }
1369
1370   for (i = 0; i < NB_TEST; i++) {
1371     mdict = xbt_dict_new();
1372     XBT_VERB("mdict=%p", mdict);
1373     if (verbose > 0)
1374       printf("Test %d\n", i);
1375     /* else if (i%10) printf("."); else printf("%d",i/10); */
1376
1377     for (j = 0; j < NB_ELM; j++) {
1378       if (verbose > 0)
1379         printf("  Add {");
1380
1381       for (l = 0; l < DEPTH; l++) {
1382         key = *(char **) xbt_dynar_get_ptr(keys, l);
1383
1384         for (k = 0; k < KEY_SIZE - 1; k++)
1385           key[k] = rand() % ('z' - 'a') + 'a';
1386
1387         key[k] = '\0';
1388
1389         if (verbose > 0)
1390           printf("%p=%s %s ", key, key, (l < DEPTH - 1 ? ";" : "}"));
1391       }
1392       if (verbose > 0)
1393         printf("in multitree %p.\n", mdict);
1394
1395       xbt_multidict_set(mdict, keys, xbt_strdup(key), free);
1396
1397       data = xbt_multidict_get(mdict, keys);
1398
1399       xbt_test_assert(data && !strcmp((char *) data, key),
1400                        "Retrieved value (%s) does not match the given one (%s)\n",
1401                        (char *) data, key);
1402     }
1403     xbt_dict_free(&mdict);
1404   }
1405
1406   xbt_dynar_free(&keys);
1407
1408   /*  if (verbose>0)
1409      xbt_dict_dump(mdict,&xbt_dict_print); */
1410
1411   xbt_dict_free(&mdict);
1412   xbt_dynar_free(&keys);
1413
1414 }
1415 #endif                          /* SIMGRID_TEST */