Logo AND Algorithmique Numérique Distribuée

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