Logo AND Algorithmique Numérique Distribuée

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