Logo AND Algorithmique Numérique Distribuée

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