Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
The mallocators of dict and fifo are created in pre-init, ie before we know whether...
[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->count;
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
642 /**
643  * \brief Outputs the content of the structure (debugging purpose)
644  *
645  * \param dict the exibitionist
646  * \param output a function to dump each data in the tree (check @ref xbt_dict_dump_output_string)
647  *
648  * Outputs the content of the structure. (for debugging purpose). \a output is a
649  * function to output the data. If NULL, data won't be displayed.
650  */
651
652 void xbt_dict_dump(xbt_dict_t dict, void_f_pvoid_t output)
653 {
654   int i;
655   xbt_dictelm_t element;
656   printf("Dict %p:\n", dict);
657   if (dict != NULL) {
658     for (i = 0; i < dict->table_size; i++) {
659       element = dict->table[i];
660       if (element) {
661         printf("[\n");
662         while (element != NULL) {
663           printf(" %s -> '", element->key);
664           if (output != NULL) {
665             (*output) (element->content);
666           }
667           printf("'\n");
668           element = element->next;
669         }
670         printf("]\n");
671       } else {
672         printf("[]\n");
673       }
674     }
675   }
676 }
677
678 xbt_dynar_t all_sizes = NULL;
679 /** @brief shows some debugging info about the bucklet repartition */
680 void xbt_dict_dump_sizes(xbt_dict_t dict)
681 {
682
683   int i;
684   unsigned int count;
685   unsigned int size;
686   xbt_dictelm_t element;
687   xbt_dynar_t sizes = xbt_dynar_new(sizeof(int), NULL);
688
689   printf("Dict %p: %d bucklets, %d used cells (of %d) ", dict, dict->count,
690          dict->fill, dict->table_size);
691   if (dict != NULL) {
692     for (i = 0; i < dict->table_size; i++) {
693       element = dict->table[i];
694       size = 0;
695       if (element) {
696         while (element != NULL) {
697           size++;
698           element = element->next;
699         }
700       }
701       if (xbt_dynar_length(sizes) <= size) {
702         int prevsize = 1;
703         xbt_dynar_set(sizes, size, &prevsize);
704       } else {
705         int prevsize;
706         xbt_dynar_get_cpy(sizes, size, &prevsize);
707         prevsize++;
708         xbt_dynar_set(sizes, size, &prevsize);
709       }
710     }
711     if (!all_sizes)
712       all_sizes = xbt_dynar_new(sizeof(int), NULL);
713
714     xbt_dynar_foreach(sizes, count, size) {
715       /* Copy values of this one into all_sizes */
716       int prevcount;
717       if (xbt_dynar_length(all_sizes) <= count) {
718         prevcount = size;
719         xbt_dynar_set(all_sizes, count, &prevcount);
720       } else {
721         xbt_dynar_get_cpy(all_sizes, count, &prevcount);
722         prevcount += size;
723         xbt_dynar_set(all_sizes, count, &prevcount);
724       }
725
726       /* Report current sizes */
727       if (count == 0)
728         continue;
729       if (size == 0)
730         continue;
731       printf("%delm x %u cells; ", count, size);
732     }
733   }
734   printf("\n");
735   xbt_dynar_free(&sizes);
736 }
737
738 /**
739  * Create the dict mallocators.
740  * This is an internal XBT function called during the lib initialization.
741  * It can be used several times to recreate the mallocator, for example when you switch to MC mode
742  */
743 void xbt_dict_preinit(void) {
744   if (dict_mallocator != NULL) {
745     /* Already created. I guess we want to switch to MC mode, so kill the previously created mallocator */
746     xbt_mallocator_free(dict_mallocator);
747     xbt_mallocator_free(dict_elm_mallocator);
748   }
749
750   dict_mallocator = xbt_mallocator_new(256,
751       dict_mallocator_new_f,
752       dict_mallocator_free_f,
753       dict_mallocator_reset_f);
754   dict_elm_mallocator = xbt_mallocator_new(256,
755       dict_elm_mallocator_new_f,
756       dict_elm_mallocator_free_f,
757       dict_elm_mallocator_reset_f);
758 }
759
760 /**
761  * Destroy the dict mallocators.
762  * This is an internal XBT function during the lib initialization
763  */
764 void xbt_dict_postexit(void)
765 {
766   if (dict_mallocator != NULL) {
767     xbt_mallocator_free(dict_mallocator);
768     dict_mallocator = NULL;
769     xbt_mallocator_free(dict_elm_mallocator);
770     dict_elm_mallocator = NULL;
771   }
772   if (all_sizes) {
773     unsigned int count;
774     int size;
775     double avg = 0;
776     int total_count = 0;
777     printf("Overall stats:");
778     xbt_dynar_foreach(all_sizes, count, size) {
779       if (count == 0)
780         continue;
781       if (size == 0)
782         continue;
783       printf("%delm x %d cells; ", count, size);
784       avg += count * size;
785       total_count += size;
786     }
787     printf("; %f elm per cell\n", avg / (double) total_count);
788   }
789 }
790
791 static void *dict_mallocator_new_f(void)
792 {
793   return xbt_new(s_xbt_dict_t, 1);
794 }
795
796 static void dict_mallocator_free_f(void *dict)
797 {
798   xbt_free(dict);
799 }
800
801 static void dict_mallocator_reset_f(void *dict)
802 {
803   /* nothing to do because all fields are
804    * initialized in xbt_dict_new
805    */
806 }
807
808 #ifdef SIMGRID_TEST
809 #include "xbt.h"
810 #include "xbt/ex.h"
811 #include "portable.h"
812
813 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
814 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
815
816 XBT_TEST_SUITE("dict", "Dict data container");
817
818 static void print_str(void *str)
819 {
820   printf("%s", (char *) PRINTF_STR(str));
821 }
822
823 static void debuged_add_ext(xbt_dict_t head, const char *key,
824                             const char *data_to_fill)
825 {
826   char *data = xbt_strdup(data_to_fill);
827
828   xbt_test_log2("Add %s under %s", PRINTF_STR(data_to_fill), PRINTF_STR(key));
829
830   xbt_dict_set(head, key, data, &free);
831   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
832     xbt_dict_dump(head, (void (*)(void *)) &printf);
833     fflush(stdout);
834   }
835 }
836
837 static void debuged_add(xbt_dict_t head, const char *key)
838 {
839   debuged_add_ext(head, key, key);
840 }
841
842 static void fill(xbt_dict_t * head)
843 {
844   xbt_test_add0("Fill in the dictionnary");
845
846   *head = xbt_dict_new();
847   debuged_add(*head, "12");
848   debuged_add(*head, "12a");
849   debuged_add(*head, "12b");
850   debuged_add(*head, "123");
851   debuged_add(*head, "123456");
852   /* Child becomes child of what to add */
853   debuged_add(*head, "1234");
854   /* Need of common ancestor */
855   debuged_add(*head, "123457");
856 }
857
858
859 static void search_ext(xbt_dict_t head, const char *key, const char *data)
860 {
861   void *found;
862
863   xbt_test_add1("Search %s", key);
864   found = xbt_dict_get(head, key);
865   xbt_test_log1("Found %s", (char *) found);
866   if (data)
867     xbt_test_assert1(found,
868                      "data do not match expectations: found NULL while searching for %s",
869                      data);
870   if (found)
871     xbt_test_assert2(!strcmp((char *) data, found),
872                      "data do not match expectations: found %s while searching for %s",
873                      (char *) found, data);
874 }
875
876 static void search(xbt_dict_t head, const char *key)
877 {
878   search_ext(head, key, key);
879 }
880
881 static void debuged_remove(xbt_dict_t head, const char *key)
882 {
883
884   xbt_test_add1("Remove '%s'", PRINTF_STR(key));
885   xbt_dict_remove(head, key);
886   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
887 }
888
889
890 static void traverse(xbt_dict_t head)
891 {
892   xbt_dict_cursor_t cursor = NULL;
893   char *key;
894   char *data;
895   int i = 0;
896
897   xbt_dict_foreach(head, cursor, key, data) {
898     if (!key || !data || strcmp(key, data)) {
899       xbt_test_log3("Seen #%d:  %s->%s", ++i, PRINTF_STR(key),
900                     PRINTF_STR(data));
901     } else {
902       xbt_test_log2("Seen #%d:  %s", ++i, PRINTF_STR(key));
903     }
904     xbt_test_assert2(!data || !strcmp(key, data),
905                      "Key(%s) != value(%s). Aborting", key, data);
906   }
907 }
908
909 static void search_not_found(xbt_dict_t head, const char *data)
910 {
911   int ok = 0;
912   xbt_ex_t e;
913
914   xbt_test_add1("Search %s (expected not to be found)", data);
915
916   TRY {
917     data = xbt_dict_get(head, data);
918     THROW1(unknown_error, 0, "Found something which shouldn't be there (%s)",
919            data);
920   } CATCH(e) {
921     if (e.category != not_found_error)
922       xbt_test_exception(e);
923     xbt_ex_free(e);
924     ok = 1;
925   }
926   xbt_test_assert0(ok, "Exception not raised");
927 }
928
929 static void count(xbt_dict_t dict, int length)
930 {
931   xbt_dict_cursor_t cursor;
932   char *key;
933   void *data;
934   int effective = 0;
935
936
937   xbt_test_add1("Count elements (expecting %d)", length);
938   xbt_test_assert2(xbt_dict_length(dict) == length,
939                    "Announced length(%d) != %d.", xbt_dict_length(dict),
940                    length);
941
942   xbt_dict_foreach(dict, cursor, key, data)
943     effective++;
944
945   xbt_test_assert2(effective == length, "Effective length(%d) != %d.",
946                    effective, length);
947
948 }
949
950 static void count_check_get_key(xbt_dict_t dict, int length)
951 {
952   xbt_dict_cursor_t cursor;
953   char *key,*key2;
954   void *data;
955   int effective = 0;
956
957
958   xbt_test_add1("Count elements (expecting %d), and test the getkey function", length);
959   xbt_test_assert2(xbt_dict_length(dict) == length,
960                    "Announced length(%d) != %d.", xbt_dict_length(dict),
961                    length);
962
963   xbt_dict_foreach(dict, cursor, key, data) {
964     effective++;
965     key2 = xbt_dict_get_key(dict,data);
966     xbt_assert2(!strcmp(key,key2),
967           "The data was registered under %s instead of %s as expected",key2,key);
968   }
969
970   xbt_test_assert2(effective == length, "Effective length(%d) != %d.",
971                    effective, length);
972
973 }
974
975 xbt_ex_t e;
976 xbt_dict_t head = NULL;
977 char *data;
978
979
980 XBT_TEST_UNIT("basic", test_dict_basic,"Basic usage: change, retrieve, traverse")
981 {
982   xbt_test_add0("Traversal the null dictionary");
983   traverse(head);
984
985   xbt_test_add0("Traversal and search the empty dictionary");
986   head = xbt_dict_new();
987   traverse(head);
988   TRY {
989     debuged_remove(head, "12346");
990   } CATCH(e) {
991     if (e.category != not_found_error)
992       xbt_test_exception(e);
993     xbt_ex_free(e);
994   }
995   xbt_dict_free(&head);
996
997   xbt_test_add0("Traverse the full dictionary");
998   fill(&head);
999   count_check_get_key(head, 7);
1000
1001   debuged_add_ext(head, "toto", "tutu");
1002   search_ext(head, "toto", "tutu");
1003   debuged_remove(head, "toto");
1004
1005   search(head, "12a");
1006   traverse(head);
1007
1008   xbt_test_add0("Free the dictionary (twice)");
1009   xbt_dict_free(&head);
1010   xbt_dict_free(&head);
1011
1012   /* CHANGING */
1013   fill(&head);
1014   count_check_get_key(head, 7);
1015   xbt_test_add0("Change 123 to 'Changed 123'");
1016   xbt_dict_set(head, "123", strdup("Changed 123"), &free);
1017   count_check_get_key(head, 7);
1018
1019   xbt_test_add0("Change 123 back to '123'");
1020   xbt_dict_set(head, "123", strdup("123"), &free);
1021   count_check_get_key(head, 7);
1022
1023   xbt_test_add0("Change 12a to 'Dummy 12a'");
1024   xbt_dict_set(head, "12a", strdup("Dummy 12a"), &free);
1025   count_check_get_key(head, 7);
1026
1027   xbt_test_add0("Change 12a to '12a'");
1028   xbt_dict_set(head, "12a", strdup("12a"), &free);
1029   count_check_get_key(head, 7);
1030
1031   xbt_test_add0("Traverse the resulting dictionary");
1032   traverse(head);
1033
1034   /* RETRIEVE */
1035   xbt_test_add0("Search 123");
1036   data = xbt_dict_get(head, "123");
1037   xbt_test_assert(data);
1038   xbt_test_assert(!strcmp("123", data));
1039
1040   search_not_found(head, "Can't be found");
1041   search_not_found(head, "123 Can't be found");
1042   search_not_found(head, "12345678 NOT");
1043
1044   search(head, "12a");
1045   search(head, "12b");
1046   search(head, "12");
1047   search(head, "123456");
1048   search(head, "1234");
1049   search(head, "123457");
1050
1051   xbt_test_add0("Traverse the resulting dictionary");
1052   traverse(head);
1053
1054   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
1055
1056   xbt_test_add0("Free the dictionary twice");
1057   xbt_dict_free(&head);
1058   xbt_dict_free(&head);
1059
1060   xbt_test_add0("Traverse the resulting dictionary");
1061   traverse(head);
1062 }
1063
1064 XBT_TEST_UNIT("remove", test_dict_remove, "Removing some values")
1065 {
1066   fill(&head);
1067   count(head, 7);
1068   xbt_test_add0("Remove non existing data");
1069   TRY {
1070     debuged_remove(head, "Does not exist");
1071   }
1072   CATCH(e) {
1073     if (e.category != not_found_error)
1074       xbt_test_exception(e);
1075     xbt_ex_free(e);
1076   }
1077   traverse(head);
1078
1079   xbt_dict_free(&head);
1080
1081   xbt_test_add0
1082     ("Remove each data manually (traversing the resulting dictionary each time)");
1083   fill(&head);
1084   debuged_remove(head, "12a");
1085   traverse(head);
1086   count(head, 6);
1087   debuged_remove(head, "12b");
1088   traverse(head);
1089   count(head, 5);
1090   debuged_remove(head, "12");
1091   traverse(head);
1092   count(head, 4);
1093   debuged_remove(head, "123456");
1094   traverse(head);
1095   count(head, 3);
1096   TRY {
1097     debuged_remove(head, "12346");
1098   }
1099   CATCH(e) {
1100     if (e.category != not_found_error)
1101       xbt_test_exception(e);
1102     xbt_ex_free(e);
1103     traverse(head);
1104   }
1105   debuged_remove(head, "1234");
1106   traverse(head);
1107   debuged_remove(head, "123457");
1108   traverse(head);
1109   debuged_remove(head, "123");
1110   traverse(head);
1111   TRY {
1112     debuged_remove(head, "12346");
1113   }
1114   CATCH(e) {
1115     if (e.category != not_found_error)
1116       xbt_test_exception(e);
1117     xbt_ex_free(e);
1118   }
1119   traverse(head);
1120
1121   xbt_test_add0("Free dict, create new fresh one, and then reset the dict");
1122   xbt_dict_free(&head);
1123   fill(&head);
1124   xbt_dict_reset(head);
1125   count(head, 0);
1126   traverse(head);
1127
1128   xbt_test_add0("Free the dictionary twice");
1129   xbt_dict_free(&head);
1130   xbt_dict_free(&head);
1131 }
1132
1133 XBT_TEST_UNIT("nulldata", test_dict_nulldata, "NULL data management")
1134 {
1135   fill(&head);
1136
1137   xbt_test_add0("Store NULL under 'null'");
1138   xbt_dict_set(head, "null", NULL, NULL);
1139   search_ext(head, "null", NULL);
1140
1141   xbt_test_add0("Check whether I see it while traversing...");
1142   {
1143     xbt_dict_cursor_t cursor = NULL;
1144     char *key;
1145     int found = 0;
1146
1147     xbt_dict_foreach(head, cursor, key, data) {
1148       if (!key || !data || strcmp(key, data)) {
1149         xbt_test_log2("Seen:  %s->%s", PRINTF_STR(key), PRINTF_STR(data));
1150       } else {
1151         xbt_test_log1("Seen:  %s", PRINTF_STR(key));
1152       }
1153
1154       if (!strcmp(key, "null"))
1155         found = 1;
1156     }
1157     xbt_test_assert0(found,
1158                      "the key 'null', associated to NULL is not found");
1159   }
1160   xbt_dict_free(&head);
1161 }
1162
1163 static void debuged_addi(xbt_dict_t head, uintptr_t key, uintptr_t data) {
1164   xbt_test_log2("Add %zu under %zu", data, key);
1165
1166   xbt_dicti_set(head, key, data);
1167   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
1168     xbt_dict_dump(head, (void (*)(void *)) &printf);
1169     fflush(stdout);
1170   }
1171   uintptr_t stored_data = xbt_dicti_get(head, key);
1172   xbt_test_assert3(stored_data==data,
1173       "Retrieved data (%zu) is not what I just stored (%zu) under key %zu",stored_data,data,key);
1174 }
1175
1176 XBT_TEST_UNIT("dicti", test_dict_scalar, "Scalar data and key management")
1177 {
1178   xbt_test_add0("Fill in the dictionnary");
1179
1180   head = xbt_dict_new();
1181   debuged_addi(head, 12, 12);
1182   debuged_addi(head, 13, 13);
1183   debuged_addi(head, 14, 14);
1184   debuged_addi(head, 15, 15);
1185   /* Change values */
1186   debuged_addi(head, 12, 15);
1187   debuged_addi(head, 15, 2000);
1188   debuged_addi(head, 15, 3000);
1189   /* 0 as key */
1190   debuged_addi(head, 0, 1000);
1191   debuged_addi(head, 0, 2000);
1192   debuged_addi(head, 0, 3000);
1193   /* 0 as value */
1194   debuged_addi(head, 12, 0);
1195   debuged_addi(head, 13, 0);
1196   debuged_addi(head, 12, 0);
1197   debuged_addi(head, 0, 0);
1198
1199   xbt_dict_free(&head);
1200 }
1201
1202 #define NB_ELM 20000
1203 #define SIZEOFKEY 1024
1204 static int countelems(xbt_dict_t head)
1205 {
1206   xbt_dict_cursor_t cursor;
1207   char *key;
1208   void *data;
1209   int res = 0;
1210
1211   xbt_dict_foreach(head, cursor, key, data) {
1212     res++;
1213   }
1214   return res;
1215 }
1216
1217 XBT_TEST_UNIT("crash", test_dict_crash, "Crash test")
1218 {
1219   xbt_dict_t head = NULL;
1220   int i, j, k, nb;
1221   char *key;
1222   void *data;
1223
1224   srand((unsigned int) time(NULL));
1225
1226   for (i = 0; i < 10; i++) {
1227     xbt_test_add2("CRASH test number %d (%d to go)", i + 1, 10 - i - 1);
1228     xbt_test_log0("Fill the struct, count its elems and frees the structure");
1229     xbt_test_log1("using 1000 elements with %d chars long randomized keys.",
1230                   SIZEOFKEY);
1231     head = xbt_dict_new();
1232     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1233     nb = 0;
1234     for (j = 0; j < 1000; j++) {
1235       char *data = NULL;
1236       key = xbt_malloc(SIZEOFKEY);
1237
1238       do {
1239         for (k = 0; k < SIZEOFKEY - 1; k++)
1240           key[k] = rand() % ('z' - 'a') + 'a';
1241         key[k] = '\0';
1242         /*      printf("[%d %s]\n",j,key); */
1243         data = xbt_dict_get_or_null(head, key);
1244       } while (data != NULL);
1245
1246       xbt_dict_set(head, key, key, &free);
1247       data = xbt_dict_get(head, key);
1248       xbt_test_assert2(!strcmp(key, data),
1249                        "Retrieved value (%s) != Injected value (%s)", key,
1250                        data);
1251
1252       count(head, j + 1);
1253     }
1254     /*    xbt_dict_dump(head,(void (*)(void*))&printf); */
1255     traverse(head);
1256     xbt_dict_free(&head);
1257     xbt_dict_free(&head);
1258   }
1259
1260
1261   head = xbt_dict_new();
1262   xbt_test_add1("Fill %d elements, with keys being the number of element",
1263                 NB_ELM);
1264   for (j = 0; j < NB_ELM; j++) {
1265     /* if (!(j%1000)) { printf("."); fflush(stdout); } */
1266
1267     key = xbt_malloc(10);
1268
1269     sprintf(key, "%d", j);
1270     xbt_dict_set(head, key, key, &free);
1271   }
1272   /*xbt_dict_dump(head,(void (*)(void*))&printf); */
1273
1274   xbt_test_add0("Count the elements (retrieving the key and data for each)");
1275   i = countelems(head);
1276   xbt_test_log1("There is %d elements", i);
1277
1278   xbt_test_add1("Search my %d elements 20 times", NB_ELM);
1279   key = xbt_malloc(10);
1280   for (i = 0; i < 20; i++) {
1281     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1282     for (j = 0; j < NB_ELM; j++) {
1283
1284       sprintf(key, "%d", j);
1285       data = xbt_dict_get(head, key);
1286       xbt_test_assert2(!strcmp(key, (char *) data),
1287                        "with get, key=%s != data=%s", key, (char *) data);
1288       data = xbt_dict_get_ext(head, key, strlen(key));
1289       xbt_test_assert2(!strcmp(key, (char *) data),
1290                        "with get_ext, key=%s != data=%s", key, (char *) data);
1291     }
1292   }
1293   free(key);
1294
1295   xbt_test_add1("Remove my %d elements", NB_ELM);
1296   key = xbt_malloc(10);
1297   for (j = 0; j < NB_ELM; j++) {
1298     /* if (!(j%10000)) printf("."); fflush(stdout); */
1299
1300     sprintf(key, "%d", j);
1301     xbt_dict_remove(head, key);
1302   }
1303   free(key);
1304
1305
1306   xbt_test_add0("Free the structure (twice)");
1307   xbt_dict_free(&head);
1308   xbt_dict_free(&head);
1309 }
1310
1311 static void str_free(void *s)
1312 {
1313   char *c = *(char **) s;
1314   free(c);
1315 }
1316
1317 XBT_TEST_UNIT("multicrash", test_dict_multicrash, "Multi-dict crash test")
1318 {
1319
1320 #undef NB_ELM
1321 #define NB_ELM 100              /*00 */
1322 #define DEPTH 5
1323 #define KEY_SIZE 512
1324 #define NB_TEST 20              /*20 */
1325   int verbose = 0;
1326
1327   xbt_dict_t mdict = NULL;
1328   int i, j, k, l;
1329   xbt_dynar_t keys = xbt_dynar_new(sizeof(char *), str_free);
1330   void *data;
1331   char *key;
1332
1333
1334   xbt_test_add0("Generic multicache CRASH test");
1335   xbt_test_log4(" Fill the struct and frees it %d times, using %d elements, "
1336                 "depth of multicache=%d, key size=%d",
1337                 NB_TEST, NB_ELM, DEPTH, KEY_SIZE);
1338
1339   for (l = 0; l < DEPTH; l++) {
1340     key = xbt_malloc(KEY_SIZE);
1341     xbt_dynar_push(keys, &key);
1342   }
1343
1344   for (i = 0; i < NB_TEST; i++) {
1345     mdict = xbt_dict_new();
1346     VERB1("mdict=%p", mdict);
1347     if (verbose > 0)
1348       printf("Test %d\n", i);
1349     /* else if (i%10) printf("."); else printf("%d",i/10); */
1350
1351     for (j = 0; j < NB_ELM; j++) {
1352       if (verbose > 0)
1353         printf("  Add {");
1354
1355       for (l = 0; l < DEPTH; l++) {
1356         key = *(char **) xbt_dynar_get_ptr(keys, l);
1357
1358         for (k = 0; k < KEY_SIZE - 1; k++)
1359           key[k] = rand() % ('z' - 'a') + 'a';
1360
1361         key[k] = '\0';
1362
1363         if (verbose > 0)
1364           printf("%p=%s %s ", key, key, (l < DEPTH - 1 ? ";" : "}"));
1365       }
1366       if (verbose > 0)
1367         printf("in multitree %p.\n", mdict);
1368
1369       xbt_multidict_set(mdict, keys, xbt_strdup(key), free);
1370
1371       data = xbt_multidict_get(mdict, keys);
1372
1373       xbt_test_assert2(data && !strcmp((char *) data, key),
1374                        "Retrieved value (%s) does not match the given one (%s)\n",
1375                        (char *) data, key);
1376     }
1377     xbt_dict_free(&mdict);
1378   }
1379
1380   xbt_dynar_free(&keys);
1381
1382   /*  if (verbose>0)
1383      xbt_dict_dump(mdict,&xbt_dict_print); */
1384
1385   xbt_dict_free(&mdict);
1386   xbt_dynar_free(&keys);
1387
1388 }
1389 #endif /* SIMGRID_TEST */