Logo AND Algorithmique Numérique Distribuée

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