Logo AND Algorithmique Numérique Distribuée

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