Logo AND Algorithmique Numérique Distribuée

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