Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
4ec20c9d4e4220c39b797f46d710e7dfab90c985
[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(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(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
259     XBT_DEBUG("Replace %.*s by %.*s under key %.*s",
260            key_len, (char *) current->content,
261            key_len, (char *) data, key_len, (char *) key);
262     /* there is already an element with the same key: overwrite it */
263     if (current->content != NULL && current->free_f != NULL) {
264       current->free_f(current->content);
265     }
266     current->content = data;
267     current->free_f = free_ctn;
268   }
269 }
270
271 /**
272  * \brief Add data to the dict (null-terminated key)
273  *
274  * \param dict the dict
275  * \param key the key to set the new data
276  * \param data the data to add in the dict
277  * \param free_ctn function to call with (\a data as argument) when
278  *        \a data is removed from the dictionary
279  *
280  * set the \a data in the structure under the \a key, which is a
281  * null terminated string.
282  */
283 XBT_INLINE void xbt_dict_set(xbt_dict_t dict,
284                              const char *key, void *data,
285                              void_f_pvoid_t free_ctn)
286 {
287
288   xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
289 }
290
291 /**
292  * \brief Retrieve data from the dict (arbitrary key)
293  *
294  * \param dict the dealer of data
295  * \param key the key to find data
296  * \param key_len the size of the \a key
297  * \return the data that we are looking for
298  *
299  * Search the given \a key. Throws not_found_error when not found.
300  */
301 XBT_INLINE void *xbt_dict_get_ext(xbt_dict_t dict, const char *key,
302                                   int key_len)
303 {
304
305
306   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
307   xbt_dictelm_t current;
308
309   xbt_assert(dict);
310
311   current = dict->table[hash_code & dict->table_size];
312   while (current != NULL &&
313          (hash_code != current->hash_code || key_len != current->key_len
314           || memcmp(key, current->key, key_len))) {
315     current = current->next;
316   }
317
318   if (current == NULL)
319     THROWF(not_found_error, 0, "key %.*s not found", key_len, key);
320
321   return current->content;
322 }
323
324 /**
325  * \brief like xbt_dict_get_ext(), but returning NULL when not found
326  */
327 void *xbt_dict_get_or_null_ext(xbt_dict_t dict, const char *key,
328                                int key_len)
329 {
330
331   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
332   xbt_dictelm_t current;
333
334   xbt_assert(dict);
335
336   current = dict->table[hash_code & dict->table_size];
337   while (current != NULL &&
338          (hash_code != current->hash_code || key_len != current->key_len
339           || memcmp(key, current->key, key_len))) {
340     current = current->next;
341   }
342
343   if (current == NULL)
344     return NULL;
345
346   return current->content;
347 }
348
349 /**
350  * @brief retrieve the key associated to that object. Warning, that's a linear search
351  *
352  * Returns NULL if the object cannot be found
353  */
354 char *xbt_dict_get_key(xbt_dict_t dict, const void *data)
355 {
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     THROWF(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,
434                                     int key_len)
435 {
436
437
438   unsigned int hash_code = xbt_dict_hash_ext(key, key_len);
439   xbt_dictelm_t current, previous = NULL;
440
441   xbt_assert(dict);
442
443   //  fprintf(stderr,"RM %.*s hash = %d, size = %d, & = %d\n",key_len,key,hash_code, dict->table_size, hash_code & dict->table_size);
444   current = dict->table[hash_code & dict->table_size];
445   while (current != NULL &&
446          (hash_code != current->hash_code || key_len != current->key_len
447           || strncmp(key, current->key, key_len))) {
448     previous = current;         /* save the previous node */
449     current = current->next;
450   }
451
452   if (current == NULL)
453     THROWF(not_found_error, 0, "key %.*s not found", key_len, key);
454
455   if (previous != NULL) {
456     previous->next = current->next;
457   } else {
458     dict->table[hash_code & dict->table_size] = current->next;
459   }
460
461   if (!dict->table[hash_code & dict->table_size])
462     dict->fill--;
463
464   xbt_dictelm_free(current);
465   dict->count--;
466 }
467
468
469
470 /**
471  * \brief Remove data from the dict (null-terminated key)
472  *
473  * \param dict the dict
474  * \param key the key of the data to be removed
475  *
476  * Remove the entry associated with the given \a key
477  */
478 XBT_INLINE void xbt_dict_remove(xbt_dict_t dict, const char *key)
479 {
480   xbt_dict_remove_ext(dict, key, strlen(key));
481 }
482
483 /**
484  * \brief Add data to the dict (arbitrary key)
485  * \param dict the container
486  * \param key the key to set the new data
487  * \param data the data to add in the dict
488  *
489  * Set the \a data in the structure under the \a key.
490  * Both \a data and \a key are considered as uintptr_t.
491  */
492 XBT_INLINE void xbt_dicti_set(xbt_dict_t dict,
493                               uintptr_t key, uintptr_t data)
494 {
495   xbt_dict_set_ext(dict, (void *)&key, sizeof key, (void*)data, NULL);
496 }
497
498 /**
499  * \brief Retrieve data from the dict (key considered as a uintptr_t)
500  *
501  * \param dict the dealer of data
502  * \param key the key to find data
503  * \return the data that we are looking for (or 0 if not found)
504  *
505  * Mixing uintptr_t keys with regular keys in the same dict is discouraged
506  */
507 XBT_INLINE uintptr_t xbt_dicti_get(xbt_dict_t dict, uintptr_t key)
508 {
509   return (uintptr_t)xbt_dict_get_or_null_ext(dict, (void *)&key, sizeof key);
510 }
511
512 /** Remove a uintptr_t key from the dict */
513 XBT_INLINE void xbt_dicti_remove(xbt_dict_t dict, uintptr_t key)
514 {
515   xbt_dict_remove_ext(dict, (void *)&key, sizeof key);
516 }
517
518
519 /**
520  * \brief Remove all data from the dict
521  * \param dict the dict
522  */
523 void xbt_dict_reset(xbt_dict_t dict)
524 {
525
526   int i;
527   xbt_dictelm_t current, previous = NULL;
528
529   xbt_assert(dict);
530
531   if (dict->count == 0)
532     return;
533
534   for (i = 0; i <= dict->table_size; i++) {
535     current = dict->table[i];
536     while (current != NULL) {
537       previous = current;
538       current = current->next;
539       xbt_dictelm_free(previous);
540     }
541     dict->table[i] = NULL;
542   }
543
544   dict->count = 0;
545   dict->fill = 0;
546 }
547
548 /**
549  * \brief Return the number of elements in the dict.
550  * \param dict a dictionary
551  */
552 XBT_INLINE int xbt_dict_length(xbt_dict_t dict)
553 {
554   xbt_assert(dict);
555
556   return dict->count;
557 }
558
559 /** @brief function to be used in xbt_dict_dump as long as the stored values are strings */
560 void xbt_dict_dump_output_string(void *s)
561 {
562   fputs(s, stdout);
563 }
564
565 /**
566  * \brief test if the dict is empty or not
567  */
568 XBT_INLINE int xbt_dict_is_empty(xbt_dict_t dict)
569 {
570   return !dict || (xbt_dict_length(dict) == 0);
571 }
572
573 /**
574  * \brief Outputs the content of the structure (debugging purpose)
575  *
576  * \param dict the exibitionist
577  * \param output a function to dump each data in the tree (check @ref xbt_dict_dump_output_string)
578  *
579  * Outputs the content of the structure. (for debugging purpose). \a output is a
580  * function to output the data. If NULL, data won't be displayed.
581  */
582
583 void xbt_dict_dump(xbt_dict_t dict, void_f_pvoid_t output)
584 {
585   int i;
586   xbt_dictelm_t element;
587   printf("Dict %p:\n", dict);
588   if (dict != NULL) {
589     for (i = 0; i < dict->table_size; i++) {
590       element = dict->table[i];
591       if (element) {
592         printf("[\n");
593         while (element != NULL) {
594           printf(" %s -> '", element->key);
595           if (output != NULL) {
596             output(element->content);
597           }
598           printf("'\n");
599           element = element->next;
600         }
601         printf("]\n");
602       } else {
603         printf("[]\n");
604       }
605     }
606   }
607 }
608
609 xbt_dynar_t all_sizes = NULL;
610 /** @brief shows some debugging info about the bucklet repartition */
611 void xbt_dict_dump_sizes(xbt_dict_t dict)
612 {
613
614   int i;
615   unsigned int count;
616   unsigned int size;
617   xbt_dictelm_t element;
618   xbt_dynar_t sizes = xbt_dynar_new(sizeof(int), NULL);
619
620   printf("Dict %p: %d bucklets, %d used cells (of %d) ", dict, dict->count,
621          dict->fill, dict->table_size);
622   if (dict != NULL) {
623     for (i = 0; i < dict->table_size; i++) {
624       element = dict->table[i];
625       size = 0;
626       if (element) {
627         while (element != NULL) {
628           size++;
629           element = element->next;
630         }
631       }
632       if (xbt_dynar_length(sizes) <= size) {
633         int prevsize = 1;
634         xbt_dynar_set(sizes, size, &prevsize);
635       } else {
636         int prevsize;
637         xbt_dynar_get_cpy(sizes, size, &prevsize);
638         prevsize++;
639         xbt_dynar_set(sizes, size, &prevsize);
640       }
641     }
642     if (!all_sizes)
643       all_sizes = xbt_dynar_new(sizeof(int), NULL);
644
645     xbt_dynar_foreach(sizes, count, size) {
646       /* Copy values of this one into all_sizes */
647       int prevcount;
648       if (xbt_dynar_length(all_sizes) <= count) {
649         prevcount = size;
650         xbt_dynar_set(all_sizes, count, &prevcount);
651       } else {
652         xbt_dynar_get_cpy(all_sizes, count, &prevcount);
653         prevcount += size;
654         xbt_dynar_set(all_sizes, count, &prevcount);
655       }
656
657       /* Report current sizes */
658       if (count == 0)
659         continue;
660       if (size == 0)
661         continue;
662       printf("%delm x %u cells; ", count, size);
663     }
664   }
665   printf("\n");
666   xbt_dynar_free(&sizes);
667 }
668
669 /**
670  * Create the dict mallocators.
671  * This is an internal XBT function called during the lib initialization.
672  * It can be used several times to recreate the mallocator, for example when you switch to MC mode
673  */
674 void xbt_dict_preinit(void)
675 {
676   if (dict_elm_mallocator != NULL) {
677     /* Already created. I guess we want to switch to MC mode, so kill the previously created mallocator */
678     xbt_mallocator_free(dict_elm_mallocator);
679   }
680
681   dict_elm_mallocator = xbt_mallocator_new(256,
682                                            dict_elm_mallocator_new_f,
683                                            dict_elm_mallocator_free_f,
684                                            dict_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   }
697   if (all_sizes) {
698     unsigned int count;
699     int size;
700     double avg = 0;
701     int total_count = 0;
702     printf("Overall stats:");
703     xbt_dynar_foreach(all_sizes, count, size) {
704       if (count == 0)
705         continue;
706       if (size == 0)
707         continue;
708       printf("%delm x %d cells; ", count, size);
709       avg += count * size;
710       total_count += size;
711     }
712     printf("; %f elm per cell\n", avg / (double) total_count);
713   }
714 }
715
716 #ifdef SIMGRID_TEST
717 #include "xbt.h"
718 #include "xbt/ex.h"
719 #include "portable.h"
720
721 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
722 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
723
724 XBT_TEST_SUITE("dict", "Dict data container");
725
726 static void print_str(void *str)
727 {
728   printf("%s", (char *) PRINTF_STR(str));
729 }
730
731 static void debuged_add_ext(xbt_dict_t head, const char *key,
732                             const char *data_to_fill)
733 {
734   char *data = xbt_strdup(data_to_fill);
735
736   xbt_test_log("Add %s under %s", PRINTF_STR(data_to_fill),
737                 PRINTF_STR(key));
738
739   xbt_dict_set(head, key, data, &free);
740   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
741     xbt_dict_dump(head, (void (*)(void *)) &printf);
742     fflush(stdout);
743   }
744 }
745
746 static void debuged_add(xbt_dict_t head, const char *key)
747 {
748   debuged_add_ext(head, key, key);
749 }
750
751 static void fill(xbt_dict_t * head)
752 {
753   xbt_test_add("Fill in the dictionnary");
754
755   *head = xbt_dict_new();
756   debuged_add(*head, "12");
757   debuged_add(*head, "12a");
758   debuged_add(*head, "12b");
759   debuged_add(*head, "123");
760   debuged_add(*head, "123456");
761   /* Child becomes child of what to add */
762   debuged_add(*head, "1234");
763   /* Need of common ancestor */
764   debuged_add(*head, "123457");
765 }
766
767
768 static void search_ext(xbt_dict_t head, const char *key, const char *data)
769 {
770   void *found;
771
772   xbt_test_add("Search %s", key);
773   found = xbt_dict_get(head, key);
774   xbt_test_log("Found %s", (char *) found);
775   if (data)
776     xbt_test_assert(found,
777                      "data do not match expectations: found NULL while searching for %s",
778                      data);
779   if (found)
780     xbt_test_assert(!strcmp((char *) data, found),
781                      "data do not match expectations: found %s while searching for %s",
782                      (char *) found, data);
783 }
784
785 static void search(xbt_dict_t head, const char *key)
786 {
787   search_ext(head, key, key);
788 }
789
790 static void debuged_remove(xbt_dict_t head, const char *key)
791 {
792
793   xbt_test_add("Remove '%s'", PRINTF_STR(key));
794   xbt_dict_remove(head, key);
795   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
796 }
797
798
799 static void traverse(xbt_dict_t head)
800 {
801   xbt_dict_cursor_t cursor = NULL;
802   char *key;
803   char *data;
804   int i = 0;
805
806   xbt_dict_foreach(head, cursor, key, data) {
807     if (!key || !data || strcmp(key, data)) {
808       xbt_test_log("Seen #%d:  %s->%s", ++i, PRINTF_STR(key),
809                     PRINTF_STR(data));
810     } else {
811       xbt_test_log("Seen #%d:  %s", ++i, PRINTF_STR(key));
812     }
813     xbt_test_assert(!data || !strcmp(key, data),
814                      "Key(%s) != value(%s). Aborting", key, data);
815   }
816 }
817
818 static void search_not_found(xbt_dict_t head, const char *data)
819 {
820   int ok = 0;
821   xbt_ex_t e;
822
823   xbt_test_add("Search %s (expected not to be found)", data);
824
825   TRY {
826     data = xbt_dict_get(head, data);
827     THROWF(unknown_error, 0,
828            "Found something which shouldn't be there (%s)", data);
829   }
830   CATCH(e) {
831     if (e.category != not_found_error)
832       xbt_test_exception(e);
833     xbt_ex_free(e);
834     ok = 1;
835   }
836   xbt_test_assert(ok, "Exception not raised");
837 }
838
839 static void count(xbt_dict_t dict, int length)
840 {
841   xbt_dict_cursor_t cursor;
842   char *key;
843   void *data;
844   int effective = 0;
845
846
847   xbt_test_add("Count elements (expecting %d)", length);
848   xbt_test_assert(xbt_dict_length(dict) == length,
849                    "Announced length(%d) != %d.", xbt_dict_length(dict),
850                    length);
851
852   xbt_dict_foreach(dict, cursor, key, data)
853       effective++;
854
855   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
856                    effective, length);
857
858 }
859
860 static void count_check_get_key(xbt_dict_t dict, int length)
861 {
862   xbt_dict_cursor_t cursor;
863   char *key;
864   _XBT_GNUC_UNUSED char *key2;
865   void *data;
866   int effective = 0;
867
868
869   xbt_test_add
870       ("Count elements (expecting %d), and test the getkey function",
871        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     key2 = xbt_dict_get_key(dict, data);
879     xbt_assert(!strcmp(key, key2),
880                 "The data was registered under %s instead of %s as expected",
881                 key2, key);
882   }
883
884   xbt_test_assert(effective == length, "Effective length(%d) != %d.",
885                    effective, length);
886
887 }
888
889 xbt_ex_t e;
890 xbt_dict_t head = NULL;
891 char *data;
892
893
894 XBT_TEST_UNIT("basic", test_dict_basic, "Basic usage: change, retrieve, traverse")
895 {
896   xbt_test_add("Traversal the null dictionary");
897   traverse(head);
898
899   xbt_test_add("Traversal and search the empty dictionary");
900   head = xbt_dict_new();
901   traverse(head);
902   TRY {
903     debuged_remove(head, "12346");
904   }
905   CATCH(e) {
906     if (e.category != not_found_error)
907       xbt_test_exception(e);
908     xbt_ex_free(e);
909   }
910   xbt_dict_free(&head);
911
912   xbt_test_add("Traverse the full dictionary");
913   fill(&head);
914   count_check_get_key(head, 7);
915
916   debuged_add_ext(head, "toto", "tutu");
917   search_ext(head, "toto", "tutu");
918   debuged_remove(head, "toto");
919
920   search(head, "12a");
921   traverse(head);
922
923   xbt_test_add("Free the dictionary (twice)");
924   xbt_dict_free(&head);
925   xbt_dict_free(&head);
926
927   /* CHANGING */
928   fill(&head);
929   count_check_get_key(head, 7);
930   xbt_test_add("Change 123 to 'Changed 123'");
931   xbt_dict_set(head, "123", strdup("Changed 123"), &free);
932   count_check_get_key(head, 7);
933
934   xbt_test_add("Change 123 back to '123'");
935   xbt_dict_set(head, "123", strdup("123"), &free);
936   count_check_get_key(head, 7);
937
938   xbt_test_add("Change 12a to 'Dummy 12a'");
939   xbt_dict_set(head, "12a", strdup("Dummy 12a"), &free);
940   count_check_get_key(head, 7);
941
942   xbt_test_add("Change 12a to '12a'");
943   xbt_dict_set(head, "12a", strdup("12a"), &free);
944   count_check_get_key(head, 7);
945
946   xbt_test_add("Traverse the resulting dictionary");
947   traverse(head);
948
949   /* RETRIEVE */
950   xbt_test_add("Search 123");
951   data = xbt_dict_get(head, "123");
952   xbt_test_assert(data);
953   xbt_test_assert(!strcmp("123", data));
954
955   search_not_found(head, "Can't be found");
956   search_not_found(head, "123 Can't be found");
957   search_not_found(head, "12345678 NOT");
958
959   search(head, "12a");
960   search(head, "12b");
961   search(head, "12");
962   search(head, "123456");
963   search(head, "1234");
964   search(head, "123457");
965
966   xbt_test_add("Traverse the resulting dictionary");
967   traverse(head);
968
969   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
970
971   xbt_test_add("Free the dictionary twice");
972   xbt_dict_free(&head);
973   xbt_dict_free(&head);
974
975   xbt_test_add("Traverse the resulting dictionary");
976   traverse(head);
977 }
978
979 XBT_TEST_UNIT("remove", test_dict_remove, "Removing some values")
980 {
981   fill(&head);
982   count(head, 7);
983   xbt_test_add("Remove non existing data");
984   TRY {
985     debuged_remove(head, "Does not exist");
986   }
987   CATCH(e) {
988     if (e.category != not_found_error)
989       xbt_test_exception(e);
990     xbt_ex_free(e);
991   }
992   traverse(head);
993
994   xbt_dict_free(&head);
995
996   xbt_test_add
997       ("Remove each data manually (traversing the resulting dictionary each time)");
998   fill(&head);
999   debuged_remove(head, "12a");
1000   traverse(head);
1001   count(head, 6);
1002   debuged_remove(head, "12b");
1003   traverse(head);
1004   count(head, 5);
1005   debuged_remove(head, "12");
1006   traverse(head);
1007   count(head, 4);
1008   debuged_remove(head, "123456");
1009   traverse(head);
1010   count(head, 3);
1011   TRY {
1012     debuged_remove(head, "12346");
1013   }
1014   CATCH(e) {
1015     if (e.category != not_found_error)
1016       xbt_test_exception(e);
1017     xbt_ex_free(e);
1018     traverse(head);
1019   }
1020   debuged_remove(head, "1234");
1021   traverse(head);
1022   debuged_remove(head, "123457");
1023   traverse(head);
1024   debuged_remove(head, "123");
1025   traverse(head);
1026   TRY {
1027     debuged_remove(head, "12346");
1028   }
1029   CATCH(e) {
1030     if (e.category != not_found_error)
1031       xbt_test_exception(e);
1032     xbt_ex_free(e);
1033   }
1034   traverse(head);
1035
1036   xbt_test_add
1037       ("Free dict, create new fresh one, and then reset the dict");
1038   xbt_dict_free(&head);
1039   fill(&head);
1040   xbt_dict_reset(head);
1041   count(head, 0);
1042   traverse(head);
1043
1044   xbt_test_add("Free the dictionary twice");
1045   xbt_dict_free(&head);
1046   xbt_dict_free(&head);
1047 }
1048
1049 XBT_TEST_UNIT("nulldata", test_dict_nulldata, "NULL data management")
1050 {
1051   fill(&head);
1052
1053   xbt_test_add("Store NULL under 'null'");
1054   xbt_dict_set(head, "null", NULL, NULL);
1055   search_ext(head, "null", NULL);
1056
1057   xbt_test_add("Check whether I see it while traversing...");
1058   {
1059     xbt_dict_cursor_t cursor = NULL;
1060     char *key;
1061     int found = 0;
1062
1063     xbt_dict_foreach(head, cursor, key, data) {
1064       if (!key || !data || strcmp(key, data)) {
1065         xbt_test_log("Seen:  %s->%s", PRINTF_STR(key), PRINTF_STR(data));
1066       } else {
1067         xbt_test_log("Seen:  %s", PRINTF_STR(key));
1068       }
1069
1070       if (!strcmp(key, "null"))
1071         found = 1;
1072     }
1073     xbt_test_assert(found,
1074                      "the key 'null', associated to NULL is not found");
1075   }
1076   xbt_dict_free(&head);
1077 }
1078
1079 static void debuged_addi(xbt_dict_t head, uintptr_t key, uintptr_t data)
1080 {
1081   uintptr_t stored_data = 0;
1082   xbt_test_log("Add %zu under %zu", data, key);
1083
1084   xbt_dicti_set(head, key, data);
1085   if (XBT_LOG_ISENABLED(xbt_dict, xbt_log_priority_debug)) {
1086     xbt_dict_dump(head, (void (*)(void *)) &printf);
1087     fflush(stdout);
1088   }
1089   stored_data = xbt_dicti_get(head, key);
1090   xbt_test_assert(stored_data == data,
1091                    "Retrieved data (%zu) is not what I just stored (%zu) under key %zu",
1092                    stored_data, data, key);
1093 }
1094
1095 XBT_TEST_UNIT("dicti", test_dict_scalar, "Scalar data and key management")
1096 {
1097   xbt_test_add("Fill in the dictionnary");
1098
1099   head = xbt_dict_new();
1100   debuged_addi(head, 12, 12);
1101   debuged_addi(head, 13, 13);
1102   debuged_addi(head, 14, 14);
1103   debuged_addi(head, 15, 15);
1104   /* Change values */
1105   debuged_addi(head, 12, 15);
1106   debuged_addi(head, 15, 2000);
1107   debuged_addi(head, 15, 3000);
1108   /* 0 as key */
1109   debuged_addi(head, 0, 1000);
1110   debuged_addi(head, 0, 2000);
1111   debuged_addi(head, 0, 3000);
1112   /* 0 as value */
1113   debuged_addi(head, 12, 0);
1114   debuged_addi(head, 13, 0);
1115   debuged_addi(head, 12, 0);
1116   debuged_addi(head, 0, 0);
1117
1118   xbt_dict_free(&head);
1119 }
1120
1121 #define NB_ELM 20000
1122 #define SIZEOFKEY 1024
1123 static int countelems(xbt_dict_t head)
1124 {
1125   xbt_dict_cursor_t cursor;
1126   char *key;
1127   void *data;
1128   int res = 0;
1129
1130   xbt_dict_foreach(head, cursor, key, data) {
1131     res++;
1132   }
1133   return res;
1134 }
1135
1136 XBT_TEST_UNIT("crash", test_dict_crash, "Crash test")
1137 {
1138   xbt_dict_t head = NULL;
1139   int i, j, k;
1140   char *key;
1141   void *data;
1142
1143   srand((unsigned int) time(NULL));
1144
1145   for (i = 0; i < 10; i++) {
1146     xbt_test_add("CRASH test number %d (%d to go)", i + 1, 10 - i - 1);
1147     xbt_test_log
1148         ("Fill the struct, count its elems and frees the structure");
1149     xbt_test_log
1150         ("using 1000 elements with %d chars long randomized keys.",
1151          SIZEOFKEY);
1152     head = xbt_dict_new();
1153     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1154     for (j = 0; j < 1000; j++) {
1155       char *data = NULL;
1156       key = xbt_malloc(SIZEOFKEY);
1157
1158       do {
1159         for (k = 0; k < SIZEOFKEY - 1; k++)
1160           key[k] = rand() % ('z' - 'a') + 'a';
1161         key[k] = '\0';
1162         /*      printf("[%d %s]\n",j,key); */
1163         data = xbt_dict_get_or_null(head, key);
1164       } while (data != NULL);
1165
1166       xbt_dict_set(head, key, key, &free);
1167       data = xbt_dict_get(head, key);
1168       xbt_test_assert(!strcmp(key, data),
1169                        "Retrieved value (%s) != Injected value (%s)", key,
1170                        data);
1171
1172       count(head, j + 1);
1173     }
1174     /*    xbt_dict_dump(head,(void (*)(void*))&printf); */
1175     traverse(head);
1176     xbt_dict_free(&head);
1177     xbt_dict_free(&head);
1178   }
1179
1180
1181   head = xbt_dict_new();
1182   xbt_test_add("Fill %d elements, with keys being the number of element",
1183                 NB_ELM);
1184   for (j = 0; j < NB_ELM; j++) {
1185     /* if (!(j%1000)) { printf("."); fflush(stdout); } */
1186
1187     key = xbt_malloc(10);
1188
1189     sprintf(key, "%d", j);
1190     xbt_dict_set(head, key, key, &free);
1191   }
1192   /*xbt_dict_dump(head,(void (*)(void*))&printf); */
1193
1194   xbt_test_add
1195       ("Count the elements (retrieving the key and data for each)");
1196   i = countelems(head);
1197   xbt_test_log("There is %d elements", i);
1198
1199   xbt_test_add("Search my %d elements 20 times", NB_ELM);
1200   key = xbt_malloc(10);
1201   for (i = 0; i < 20; i++) {
1202     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
1203     for (j = 0; j < NB_ELM; j++) {
1204
1205       sprintf(key, "%d", j);
1206       data = xbt_dict_get(head, key);
1207       xbt_test_assert(!strcmp(key, (char *) data),
1208                        "with get, key=%s != data=%s", key, (char *) data);
1209       data = xbt_dict_get_ext(head, key, strlen(key));
1210       xbt_test_assert(!strcmp(key, (char *) data),
1211                        "with get_ext, key=%s != data=%s", key,
1212                        (char *) data);
1213     }
1214   }
1215   free(key);
1216
1217   xbt_test_add("Remove my %d elements", NB_ELM);
1218   key = xbt_malloc(10);
1219   for (j = 0; j < NB_ELM; j++) {
1220     /* if (!(j%10000)) printf("."); fflush(stdout); */
1221
1222     sprintf(key, "%d", j);
1223     xbt_dict_remove(head, key);
1224   }
1225   free(key);
1226
1227
1228   xbt_test_add("Free the structure (twice)");
1229   xbt_dict_free(&head);
1230   xbt_dict_free(&head);
1231 }
1232
1233 static void str_free(void *s)
1234 {
1235   char *c = *(char **) s;
1236   free(c);
1237 }
1238
1239 XBT_TEST_UNIT("multicrash", test_dict_multicrash, "Multi-dict crash test")
1240 {
1241
1242 #undef NB_ELM
1243 #define NB_ELM 100              /*00 */
1244 #define DEPTH 5
1245 #define KEY_SIZE 512
1246 #define NB_TEST 20              /*20 */
1247   int verbose = 0;
1248
1249   xbt_dict_t mdict = NULL;
1250   int i, j, k, l;
1251   xbt_dynar_t keys = xbt_dynar_new(sizeof(char *), str_free);
1252   void *data;
1253   char *key;
1254
1255
1256   xbt_test_add("Generic multicache CRASH test");
1257   xbt_test_log
1258       (" Fill the struct and frees it %d times, using %d elements, "
1259        "depth of multicache=%d, key size=%d", NB_TEST, NB_ELM, DEPTH,
1260        KEY_SIZE);
1261
1262   for (l = 0; l < DEPTH; l++) {
1263     key = xbt_malloc(KEY_SIZE);
1264     xbt_dynar_push(keys, &key);
1265   }
1266
1267   for (i = 0; i < NB_TEST; i++) {
1268     mdict = xbt_dict_new();
1269     XBT_VERB("mdict=%p", mdict);
1270     if (verbose > 0)
1271       printf("Test %d\n", i);
1272     /* else if (i%10) printf("."); else printf("%d",i/10); */
1273
1274     for (j = 0; j < NB_ELM; j++) {
1275       if (verbose > 0)
1276         printf("  Add {");
1277
1278       for (l = 0; l < DEPTH; l++) {
1279         key = *(char **) xbt_dynar_get_ptr(keys, l);
1280
1281         for (k = 0; k < KEY_SIZE - 1; k++)
1282           key[k] = rand() % ('z' - 'a') + 'a';
1283
1284         key[k] = '\0';
1285
1286         if (verbose > 0)
1287           printf("%p=%s %s ", key, key, (l < DEPTH - 1 ? ";" : "}"));
1288       }
1289       if (verbose > 0)
1290         printf("in multitree %p.\n", mdict);
1291
1292       xbt_multidict_set(mdict, keys, xbt_strdup(key), free);
1293
1294       data = xbt_multidict_get(mdict, keys);
1295
1296       xbt_test_assert(data && !strcmp((char *) data, key),
1297                        "Retrieved value (%s) does not match the given one (%s)\n",
1298                        (char *) data, key);
1299     }
1300     xbt_dict_free(&mdict);
1301   }
1302
1303   xbt_dynar_free(&keys);
1304
1305   /*  if (verbose>0)
1306      xbt_dict_dump(mdict,&xbt_dict_print); */
1307
1308   xbt_dict_free(&mdict);
1309   xbt_dynar_free(&keys);
1310
1311 }
1312 #endif                          /* SIMGRID_TEST */