Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Two more hashing functions (chosen by define, not dynamically: who cares?), some...
[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   unsigned int i,count;
505   int size;
506   xbt_dictelm_t element;
507   xbt_dynar_t sizes = xbt_dynar_new(sizeof(int),NULL);
508    
509   printf("Dict %p: %d bucklets, %d used cells (of %d) ", dict, dict->count, dict->fill,dict->table_size);
510   if (dict != NULL) {
511     for (i = 0; i < dict->table_size; i++) {
512       element = dict->table[i];
513       size = 0;
514       if (element) {
515          while (element != NULL) {
516             size ++;
517             element = element->next;
518          }
519       }
520       if (xbt_dynar_length(sizes) <= size) {
521          int prevsize = 1;
522          xbt_dynar_set(sizes,size,&prevsize);
523       } else {
524          int prevsize;
525          xbt_dynar_get_cpy(sizes,size,&prevsize);
526          prevsize++;
527          xbt_dynar_set(sizes,size,&prevsize);
528       }       
529     }
530     if (!all_sizes)
531        all_sizes = xbt_dynar_new(sizeof(int), NULL);
532      
533     xbt_dynar_foreach(sizes,count,size) {
534        /* Copy values of this one into all_sizes */
535        int prevcount;
536        if (xbt_dynar_length(all_sizes) <= count) {
537           prevcount = size;
538           xbt_dynar_set(all_sizes,count,&prevcount);
539        } else {
540           xbt_dynar_get_cpy(all_sizes,count,&prevcount);
541           prevcount += size;
542           xbt_dynar_set(all_sizes,count,&prevcount);
543        }       
544
545        /* Report current sizes */
546        if (count==0)
547          continue;
548        if (size==0)
549          continue;
550        printf("%delm x %d cells; ",count,size);
551     }
552   }
553   printf("\n");
554   xbt_dynar_free(&sizes);
555 }
556
557 /**
558  * Destroy the dict mallocators.
559  * This is an internal XBT function called by xbt_exit().
560  */
561 void xbt_dict_exit(void) {
562   if (dict_mallocator != NULL) {
563     xbt_mallocator_free(dict_mallocator);
564     dict_mallocator = NULL;
565     xbt_mallocator_free(dict_elm_mallocator);
566     dict_elm_mallocator = NULL;
567   }
568   if (all_sizes) {
569      unsigned int count;
570      int size;
571      double avg = 0;
572      int total_count = 0;
573      printf("Overall stats:");
574      xbt_dynar_foreach(all_sizes,count,size) {
575         if (count==0)
576           continue;
577         if (size==0)
578           continue;
579         printf("%delm x %d cells; ",count,size);
580         avg += count * size;
581         total_count += size;
582      }
583      printf("; %f elm per cell\n",avg/(double)total_count);
584   }
585 }
586
587 static void* dict_mallocator_new_f(void) {
588   return xbt_new(s_xbt_dict_t, 1);
589 }
590
591 static void dict_mallocator_free_f(void* dict) {
592   xbt_free(dict);
593 }
594
595 static void dict_mallocator_reset_f(void* dict) {
596   /* nothing to do because all fields are
597    * initialized in xbt_dict_new
598    */
599 }
600
601 #ifdef SIMGRID_TEST
602 #include "xbt.h"
603 #include "xbt/ex.h"
604 #include "portable.h"
605
606 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
607 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
608
609 XBT_TEST_SUITE("dict","Dict data container");
610
611 static void print_str(void *str) {
612   printf("%s",(char*)PRINTF_STR(str));
613 }
614
615 static void debuged_add_ext(xbt_dict_t head,const char*key,const char*data_to_fill) {
616   char *data=xbt_strdup(data_to_fill);
617
618   xbt_test_log2("Add %s under %s",PRINTF_STR(data_to_fill),PRINTF_STR(key));
619
620   xbt_dict_set(head,key,data,&free);
621   if (XBT_LOG_ISENABLED(xbt_dict,xbt_log_priority_debug)) {
622     xbt_dict_dump(head,(void (*)(void*))&printf);
623     fflush(stdout);
624   }
625 }
626 static void debuged_add(xbt_dict_t head,const char*key) {
627    debuged_add_ext(head,key,key);
628 }
629
630 static void fill(xbt_dict_t *head) {
631   xbt_test_add0("Fill in the dictionnary");
632
633   *head = xbt_dict_new();
634   debuged_add(*head,"12");
635   debuged_add(*head,"12a");
636   debuged_add(*head,"12b");
637   debuged_add(*head,"123");
638   debuged_add(*head,"123456");
639   /* Child becomes child of what to add */
640   debuged_add(*head,"1234");
641   /* Need of common ancestor */
642   debuged_add(*head,"123457");
643 }
644
645
646 static void search_ext(xbt_dict_t head,const char*key, const char *data) {
647   void *found;
648   
649   xbt_test_add1("Search %s",key);
650   found=xbt_dict_get(head,key);
651   xbt_test_log1("Found %s",(char *)found);
652   if (data)
653     xbt_test_assert1(found,"data do not match expectations: found NULL while searching for %s",data);
654   if (found)
655     xbt_test_assert2(!strcmp((char*)data,found),"data do not match expectations: found %s while searching for %s", (char*)found, data);
656 }
657
658 static void search(xbt_dict_t head,const char*key) {
659   search_ext(head,key,key);
660 }
661
662 static void debuged_remove(xbt_dict_t head,const char*key) {
663
664   xbt_test_add1("Remove '%s'",PRINTF_STR(key));
665   xbt_dict_remove(head,key);
666   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
667 }
668
669
670 static void traverse(xbt_dict_t head) {
671   xbt_dict_cursor_t cursor=NULL;
672   char *key;
673   char *data;
674   int i = 0;
675
676   xbt_dict_foreach(head,cursor,key,data) {
677     if (!key || !data || strcmp(key,data)) {        
678        xbt_test_log3("Seen #%d:  %s->%s",++i,PRINTF_STR(key),PRINTF_STR(data));
679     } else {
680        xbt_test_log2("Seen #%d:  %s",++i,PRINTF_STR(key));
681     }
682     xbt_test_assert2(!data || !strcmp(key,data),
683                      "Key(%s) != value(%s). Abording",key,data);
684   }
685 }
686
687 static void search_not_found(xbt_dict_t head, const char *data) {
688   int ok=0;
689   xbt_ex_t e;
690
691   xbt_test_add1("Search %s (expected not to be found)",data);
692
693   TRY {    
694     data = xbt_dict_get(head, data);
695     THROW1(unknown_error,0,"Found something which shouldn't be there (%s)",data);
696   } CATCH(e) {
697     if (e.category != not_found_error) 
698       xbt_test_exception(e);
699     xbt_ex_free(e);
700     ok=1;
701   }
702   xbt_test_assert0(ok,"Exception not raised");
703 }
704
705 static void count(xbt_dict_t dict, int length) {
706   xbt_dict_cursor_t cursor;
707   char *key;
708   void *data;
709   int effective = 0;
710
711
712   xbt_test_add1("Count elements (expecting %d)", length);
713   xbt_test_assert2(xbt_dict_length(dict) == length, "Announced length(%d) != %d.", xbt_dict_length(dict), length);
714    
715   xbt_dict_foreach(dict,cursor,key,data) {
716     effective++;
717   }
718   xbt_test_assert2(effective == length, "Effective length(%d) != %d.", effective, length);
719 }
720
721 xbt_ex_t e;
722 xbt_dict_t head=NULL;
723 char *data;
724
725
726 XBT_TEST_UNIT("basic",test_dict_basic,"Basic usage: change, retrieve, traverse"){
727   xbt_test_add0("Traversal the null dictionnary");
728   traverse(head);
729
730   xbt_test_add0("Traversal and search the empty dictionnary");
731   head = xbt_dict_new();
732   traverse(head);
733   TRY {
734     debuged_remove(head,"12346");
735   } CATCH(e) {
736     if (e.category != not_found_error) 
737       xbt_test_exception(e);
738     xbt_ex_free(e);
739   }
740   xbt_dict_free(&head);
741
742   xbt_test_add0("Traverse the full dictionnary");
743   fill(&head);
744   count(head, 7);
745    
746   debuged_add_ext(head,"toto","tutu");
747   search_ext(head,"toto","tutu");
748   debuged_remove(head,"toto");
749
750   search(head,"12a");
751   traverse(head);
752
753   xbt_test_add0("Free the dictionnary (twice)");
754   xbt_dict_free(&head);
755   xbt_dict_free(&head);
756
757   /* CHANGING */
758   fill(&head);
759   count(head, 7);
760   xbt_test_add0("Change 123 to 'Changed 123'");
761   xbt_dict_set(head,"123",strdup("Changed 123"),&free);
762   count(head, 7);
763
764   xbt_test_add0("Change 123 back to '123'");
765   xbt_dict_set(head,"123",strdup("123"),&free);
766   count(head, 7);
767
768   xbt_test_add0("Change 12a to 'Dummy 12a'");
769   xbt_dict_set(head,"12a",strdup("Dummy 12a"),&free);
770   count(head, 7);
771
772   xbt_test_add0("Change 12a to '12a'");
773   xbt_dict_set(head,"12a",strdup("12a"),&free);
774   count(head, 7);
775
776   xbt_test_add0("Traverse the resulting dictionnary");
777   traverse(head);
778   
779   /* RETRIEVE */
780   xbt_test_add0("Search 123");
781   data = xbt_dict_get(head,"123");
782   xbt_test_assert(data);
783   xbt_test_assert(!strcmp("123",data));
784
785   search_not_found(head,"Can't be found");
786   search_not_found(head,"123 Can't be found");
787   search_not_found(head,"12345678 NOT");
788
789   search(head,"12a");
790   search(head,"12b");
791   search(head,"12");
792   search(head,"123456");
793   search(head,"1234");
794   search(head,"123457");
795
796   xbt_test_add0("Traverse the resulting dictionnary");
797   traverse(head);
798
799   /*  xbt_dict_dump(head,(void (*)(void*))&printf); */
800
801   xbt_test_add0("Free the dictionnary twice");
802   xbt_dict_free(&head);
803   xbt_dict_free(&head);
804
805   xbt_test_add0("Traverse the resulting dictionnary");
806   traverse(head);
807 }
808
809 XBT_TEST_UNIT("remove",test_dict_remove,"Removing some values"){
810   fill(&head);
811   count(head, 7);
812   xbt_test_add0("Remove non existing data");
813   TRY {
814     debuged_remove(head,"Does not exist");
815   } CATCH(e) {
816     if (e.category != not_found_error) 
817       xbt_test_exception(e);
818     xbt_ex_free(e);
819   }
820   traverse(head);
821
822   xbt_dict_free(&head);
823
824   xbt_test_add0("Remove each data manually (traversing the resulting dictionnary each time)");
825   fill(&head);
826   debuged_remove(head,"12a");    traverse(head);
827   count(head, 6);
828   debuged_remove(head,"12b");    traverse(head);
829   count(head, 5);
830   debuged_remove(head,"12");     traverse(head);
831   count(head, 4);
832   debuged_remove(head,"123456"); traverse(head);
833   count(head, 3);
834   TRY {
835     debuged_remove(head,"12346");
836   } CATCH(e) {
837     if (e.category != not_found_error) 
838       xbt_test_exception(e);
839     xbt_ex_free(e);         
840     traverse(head);
841   } 
842   debuged_remove(head,"1234");   traverse(head);
843   debuged_remove(head,"123457"); traverse(head);
844   debuged_remove(head,"123");    traverse(head);
845   TRY {
846     debuged_remove(head,"12346");
847   } CATCH(e) {
848     if (e.category != not_found_error) 
849       xbt_test_exception(e);
850     xbt_ex_free(e);
851   }                              traverse(head);
852   
853   xbt_test_add0("Free dict, create new fresh one, and then reset the dict");
854   xbt_dict_free(&head);
855   fill(&head);
856   xbt_dict_reset(head);
857   count(head, 0);
858   traverse(head);
859
860   xbt_test_add0("Free the dictionnary twice");
861   xbt_dict_free(&head);
862   xbt_dict_free(&head);      
863 }
864
865 XBT_TEST_UNIT("nulldata",test_dict_nulldata,"NULL data management"){
866   fill(&head);
867
868   xbt_test_add0("Store NULL under 'null'");
869   xbt_dict_set(head,"null",NULL,NULL);
870   search_ext(head,"null",NULL);
871
872   xbt_test_add0("Check whether I see it while traversing...");
873   {
874     xbt_dict_cursor_t cursor=NULL;
875     char *key;
876     int found=0;
877
878     xbt_dict_foreach(head,cursor,key,data) {
879       if (!key || !data || strcmp(key,data)) {      
880          xbt_test_log2("Seen:  %s->%s",PRINTF_STR(key),PRINTF_STR(data));
881       } else {
882          xbt_test_log1("Seen:  %s",PRINTF_STR(key));
883       }
884      
885       if (!strcmp(key,"null"))
886         found = 1;
887     }
888     xbt_test_assert0(found,"the key 'null', associated to NULL is not found");
889   }
890   xbt_dict_free(&head);
891 }
892
893 #define NB_ELM 20000
894 #define SIZEOFKEY 1024
895 static int countelems(xbt_dict_t head) {
896   xbt_dict_cursor_t cursor;
897   char *key;
898   void *data;
899   int res = 0;
900
901   xbt_dict_foreach(head,cursor,key,data) {
902     res++;
903   }
904   return res;
905 }
906    
907 XBT_TEST_UNIT("crash",test_dict_crash,"Crash test"){
908   xbt_dict_t head=NULL;
909   int i,j,k, nb;
910   char *key;
911   void *data;
912
913   srand((unsigned int)time(NULL));
914
915   for (i=0;i<10;i++) {
916     xbt_test_add2("CRASH test number %d (%d to go)",i+1,10-i-1);
917     xbt_test_log0("Fill the struct, count its elems and frees the structure");
918     xbt_test_log1("using 1000 elements with %d chars long randomized keys.",SIZEOFKEY);
919     head=xbt_dict_new();
920     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
921     nb=0;
922     for (j=0;j<1000;j++) {
923       char *data = NULL;
924       key=xbt_malloc(SIZEOFKEY);
925
926       do {          
927          for (k=0;k<SIZEOFKEY-1;k++)
928            key[k]=rand() % ('z' - 'a') + 'a';
929          key[k]='\0';
930          /*      printf("[%d %s]\n",j,key); */
931          data = xbt_dict_get_or_null(head,key);
932       } while (data != NULL);
933         
934       xbt_dict_set(head,key,key,&free);
935       data = xbt_dict_get(head,key);
936       xbt_test_assert2(!strcmp(key,data), "Retrieved value (%s) != Injected value (%s)",key,data);
937        
938       count(head,j+1);
939     }
940     /*    xbt_dict_dump(head,(void (*)(void*))&printf); */
941     traverse(head);
942     xbt_dict_free(&head);
943     xbt_dict_free(&head);
944   }
945
946
947   head=xbt_dict_new();
948   xbt_test_add1("Fill %d elements, with keys being the number of element",NB_ELM);
949   for (j=0;j<NB_ELM;j++) {
950     /* if (!(j%1000)) { printf("."); fflush(stdout); } */
951
952     key = xbt_malloc(10);
953     
954     sprintf(key,"%d",j);
955     xbt_dict_set(head,key,key,&free);
956   }
957    /*xbt_dict_dump(head,(void (*)(void*))&printf);*/
958    
959   xbt_test_add0("Count the elements (retrieving the key and data for each)");
960   i = countelems(head);
961   xbt_test_log1("There is %d elements",i);
962
963   xbt_test_add1("Search my %d elements 20 times",NB_ELM);
964   key=xbt_malloc(10);
965   for (i=0;i<20;i++) {
966     /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
967     for (j=0;j<NB_ELM;j++) {
968       
969       sprintf(key,"%d",j);
970       data = xbt_dict_get(head,key);
971       xbt_test_assert2(!strcmp(key,(char*)data),
972                        "with get, key=%s != data=%s",key,(char*)data);
973       data = xbt_dict_get_ext(head,key,strlen(key));
974       xbt_test_assert2(!strcmp(key,(char*)data),
975                        "with get_ext, key=%s != data=%s",key,(char*)data);
976     }
977   }
978   free(key);
979
980   xbt_test_add1("Remove my %d elements",NB_ELM);
981   key=xbt_malloc(10);
982   for (j=0;j<NB_ELM;j++) {
983     /* if (!(j%10000)) printf("."); fflush(stdout); */
984     
985     sprintf(key,"%d",j);
986     xbt_dict_remove(head,key);
987   }
988   free(key);
989
990   
991   xbt_test_add0("Free the structure (twice)");
992   xbt_dict_free(&head);
993   xbt_dict_free(&head);
994 }
995
996 static void str_free(void *s) {
997   char *c=*(char**)s;
998   free(c);
999 }
1000
1001 XBT_TEST_UNIT("multicrash",test_dict_multicrash,"Multi-dict crash test"){
1002
1003 #undef NB_ELM
1004 #define NB_ELM 100 /*00*/
1005 #define DEPTH 5
1006 #define KEY_SIZE 512
1007 #define NB_TEST 20 /*20*/
1008 int verbose=0;
1009
1010   xbt_dict_t mdict = NULL;
1011   int i,j,k,l;
1012   xbt_dynar_t keys = xbt_dynar_new(sizeof(char*),str_free);
1013   void *data;
1014   char *key;
1015
1016
1017   xbt_test_add0("Generic multicache CRASH test");
1018   xbt_test_log4(" Fill the struct and frees it %d times, using %d elements, "
1019                 "depth of multicache=%d, key size=%d",
1020                 NB_TEST,NB_ELM,DEPTH,KEY_SIZE);
1021
1022   for (l=0 ; l<DEPTH ; l++) {
1023     key=xbt_malloc(KEY_SIZE);
1024     xbt_dynar_push(keys,&key);
1025   }     
1026
1027   for (i=0;i<NB_TEST;i++) {
1028     mdict = xbt_dict_new();
1029     VERB1("mdict=%p",mdict);
1030     if (verbose>0)
1031       printf("Test %d\n",i);
1032     /* else if (i%10) printf("."); else printf("%d",i/10);*/
1033     
1034     for (j=0;j<NB_ELM;j++) {
1035       if (verbose>0) printf ("  Add {");
1036       
1037       for (l=0 ; l<DEPTH ; l++) {
1038         key=*(char**)xbt_dynar_get_ptr(keys,l);
1039         
1040         for (k=0;k<KEY_SIZE-1;k++) 
1041           key[k]=rand() % ('z' - 'a') + 'a';
1042           
1043         key[k]='\0';
1044         
1045         if (verbose>0) printf("%p=%s %s ",key, key,(l<DEPTH-1?";":"}"));
1046       }
1047       if (verbose>0) printf("in multitree %p.\n",mdict);
1048                                                         
1049       xbt_multidict_set(mdict,keys,xbt_strdup(key),free);
1050
1051       data = xbt_multidict_get(mdict,keys);
1052
1053       xbt_test_assert2(data && !strcmp((char*)data,key),
1054                        "Retrieved value (%s) does not match the entrered one (%s)\n",
1055                        (char*)data,key);
1056     }
1057     xbt_dict_free(&mdict);
1058   }
1059   
1060   xbt_dynar_free(&keys);
1061
1062 /*  if (verbose>0)
1063     xbt_dict_dump(mdict,&xbt_dict_print);*/
1064     
1065   xbt_dict_free(&mdict);
1066   xbt_dynar_free(&keys);
1067
1068 }
1069 #endif /* SIMGRID_TEST */