Logo AND Algorithmique Numérique Distribuée

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