Logo AND Algorithmique Numérique Distribuée

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