Logo AND Algorithmique Numérique Distribuée

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