Logo AND Algorithmique Numérique Distribuée

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