3 /* dict - a generic dictionnary, variation over the B-tree concept */
5 /* Copyright (c) 2003,2004 Martin Quinson. All rights reserved. */
7 /* This program is free software; you can redistribute it and/or modify it
8 * under the terms of the license (GNU LGPL) which comes with this package. */
13 #include "xbt/mallocator.h"
14 #include "xbt_modinter.h"
15 #include "dict_private.h"
17 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict,xbt,
18 "Dictionaries provide the same functionnalities than hash tables");
19 /*####[ Private prototypes ]#################################################*/
21 static xbt_mallocator_t dict_mallocator = NULL;
22 static void* dict_mallocator_new_f(void);
23 static void dict_mallocator_free_f(void* dict);
24 static void dict_mallocator_reset_f(void* dict);
27 /*####[ Code ]###############################################################*/
31 * \return pointer to the destination
32 * \see xbt_dict_new_ext(), xbt_dict_free()
34 * Creates and initialize a new dictionnary with a default hashtable size.
36 xbt_dict_t xbt_dict_new(void) {
37 return xbt_dict_new_ext(256);
41 * \brief Create a new dictionary with the specified hashtable size
42 * \param hashsize the hashtable size
43 * \return a pointer to the created object
44 * \see xbt_dict_new(), xbt_dict_free()
46 xbt_dict_t xbt_dict_new_ext(int hashsize) {
49 if (dict_mallocator == NULL) {
51 dict_mallocator = xbt_mallocator_new(256,
52 dict_mallocator_new_f,
53 dict_mallocator_free_f,
54 dict_mallocator_reset_f);
55 dict_elm_mallocator = xbt_mallocator_new(256,
56 dict_elm_mallocator_new_f,
57 dict_elm_mallocator_free_f,
58 dict_elm_mallocator_reset_f);
61 dict = xbt_mallocator_get(dict_mallocator);
62 dict->table_size = hashsize;
63 dict->table = xbt_new0(xbt_dictelm_t, dict->table_size);
71 * \param dict the dictionnary to be freed
73 * Frees a dictionary with all the data
75 void xbt_dict_free(xbt_dict_t *dict) {
77 xbt_dictelm_t current, previous;
81 if (dict != NULL && *dict != NULL) {
82 table_size = (*dict)->table_size;
83 table = (*dict)->table;
84 for (i = 0; i < table_size; i++) {
86 while (current != NULL) {
88 current = current->next;
89 xbt_dictelm_free(previous);
93 xbt_mallocator_release(dict_mallocator, *dict);
99 * \brief Change the hashtable size
100 * \param dict a dictionary
101 * \param hashsize the new hashtable size
103 * Change the hashtable size is a long operation, so it's better
104 * to use xbt_dict_new_ext or to call xbt_dict_hashsize_set when
105 * the dictionary is empty.
107 void xbt_dict_hashsize_set(xbt_dict_t dict, int hashsize) {
108 xbt_dict_t new_dict = xbt_dict_new_ext(hashsize);
109 xbt_dictelm_t element, next;
112 for (i = 0; i < dict->table_size; i++) {
113 element = dict->table[i];
114 while (element != NULL) {
115 next = element->next; /* save the next because it will be lost */
116 xbt_dict_add_element(new_dict, element); /* no new xbt_dictelm_t is mallocated */
121 xbt_free(dict->table);
122 dict->table = new_dict->table;
123 dict->table_size = hashsize;
128 * Returns the hash code of a string.
130 static unsigned int xbt_dict_hash_ext(const char *str, int str_len) {
131 /* fast implementation of djb2 algorithm */
132 unsigned int hash = 5381;
137 hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
143 static unsigned int xbt_dict_hash(const char *str) {
144 /* fast implementation of djb2 algorithm */
145 unsigned int hash = 5381;
148 while ( (c = *str++) ) {
149 hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
156 * \brief Add data to the dict (arbitrary key)
157 * \param dict the container
158 * \param key the key to set the new data
159 * \param key_len the size of the \a key
160 * \param data the data to add in the dict
161 * \param free_ctn function to call with (\a key as argument) when
162 * \a key is removed from the dictionnary
164 * Set the \a data in the structure under the \a key, which can be any kind
165 * of data, as long as its length is provided in \a key_len.
167 void xbt_dict_set_ext(xbt_dict_t dict,
171 void_f_pvoid_t *free_ctn) {
173 unsigned int hash_code;
174 xbt_dictelm_t current, previous = NULL;
177 hash_code = xbt_dict_hash_ext(key,key_len) % dict->table_size;
179 current = dict->table[hash_code];
180 while (current != NULL &&
181 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
183 current = current->next;
186 if (current == NULL) {
187 /* this key doesn't exist yet */
188 current = xbt_dictelm_new(key, key_len, data, free_ctn, NULL);
189 if (previous == NULL) {
190 dict->table[hash_code] = current;
193 previous->next = current;
198 /* there is already an element with the same key: we overwrite it */
199 if (current->content != NULL && current->free_f != NULL) {
200 current->free_f(current->content);
202 current->content = data;
203 current->free_f = free_ctn;
208 * \brief Add data to the dict (null-terminated key)
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 key as argument) when
214 * \a key is removed from the dictionnary
216 * set the \a data in the structure under the \a key, which is a
217 * null terminated string.
219 void xbt_dict_set(xbt_dict_t dict,
222 void_f_pvoid_t *free_ctn) {
226 xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn);
230 * \brief Retrieve data from the dict (arbitrary key)
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
237 * Search the given \a key. Throws not_found_error when not found.
239 void *xbt_dict_get_ext(xbt_dict_t dict,
244 unsigned int hash_code;
245 xbt_dictelm_t current;
249 hash_code = xbt_dict_hash_ext(key,key_len) % dict->table_size;
251 current = dict->table[hash_code];
252 while (current != NULL &&
253 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
254 current = current->next;
257 if (current == NULL) {
258 THROW2(not_found_error, 0, "key %.*s not found", key_len, key);
261 return current->content;
265 * \brief Retrieve data from the dict (null-terminated key)
267 * \param dict the dealer of data
268 * \param key the key to find data
269 * \return the data that we are looking for
271 * Search the given \a key. Throws not_found_error when not found.
272 * Check xbt_dict_get_or_null() for a version returning NULL without exception when
275 void *xbt_dict_get(xbt_dict_t dict,
279 unsigned int hash_code ;
280 xbt_dictelm_t current;
284 hash_code = xbt_dict_hash(key) % dict->table_size;
286 current = dict->table[hash_code];
287 while (current != NULL && (strcmp(key, current->key))) {
288 current = current->next;
291 if (current == NULL) {
292 THROW1(not_found_error, 0, "key %s not found", key);
295 return current->content;
299 * \brief like xbt_dict_get(), but returning NULL when not found
301 void *xbt_dict_get_or_null(xbt_dict_t dict,
306 result = xbt_dict_get(dict, key);
308 if (e.category != not_found_error)
318 * \brief Remove data from the dict (arbitrary key)
320 * \param dict the trash can
321 * \param key the key of the data to be removed
322 * \param key_len the size of the \a key
324 * Remove the entry associated with the given \a key (throws not_found)
326 void xbt_dict_remove_ext(xbt_dict_t dict,
331 unsigned int hash_code ;
332 xbt_dictelm_t current, previous = NULL;
336 hash_code = xbt_dict_hash_ext(key,key_len) % dict->table_size;
338 current = dict->table[hash_code];
339 while (current != NULL &&
340 (key_len != current->key_len || strncmp(key, current->key, key_len))) {
341 previous = current; /* save the previous node */
342 current = current->next;
345 if (current == NULL) {
346 THROW2(not_found_error, 0, "key %.*s not found", key_len, key);
349 if (previous != NULL) {
350 xbt_assert0(previous->next == current, "previous-next != current");
351 previous->next = current->next;
354 dict->table[hash_code] = current->next;
357 xbt_dictelm_free(current);
362 * \brief Remove data from the dict (null-terminated key)
364 * \param dict the dict
365 * \param key the key of the data to be removed
367 * Remove the entry associated with the given \a key
369 void xbt_dict_remove(xbt_dict_t dict,
373 xbt_dict_remove_ext(dict, key, strlen(key));
377 * \brief Remove all data from the dict
378 * \param dict the dict
380 void xbt_dict_reset(xbt_dict_t dict) {
384 xbt_dictelm_t current, previous = NULL;
388 if (dict->count == 0)
391 for (i = 0; i < dict->table_size; i++) {
392 current = dict->table[i];
393 while (current != NULL) {
395 current = current->next;
396 xbt_dictelm_free(previous);
398 dict->table[i] = NULL;
405 * \brief Return the number of elements in the dict.
406 * \param dict a dictionary
408 int xbt_dict_length(xbt_dict_t dict) {
415 * Add an already mallocated element to a dictionary.
417 void xbt_dict_add_element(xbt_dict_t dict, xbt_dictelm_t element) {
424 hashcode = xbt_dict_hash_ext(element->key,element->key_len) % dict->table_size;
425 element->next = dict->table[hashcode];
426 dict->table[hashcode] = element;
430 * \brief Outputs the content of the structure (debuging purpose)
432 * \param dict the exibitionist
433 * \param output a function to dump each data in the tree
435 * Ouputs the content of the structure. (for debuging purpose). \a ouput is a
436 * function to output the data. If NULL, data won't be displayed.
439 void xbt_dict_dump(xbt_dict_t dict,
440 void_f_pvoid_t *output) {
442 xbt_dictelm_t element;
443 printf("Dict %p:\n", dict);
445 for (i = 0; i < dict->table_size; i++) {
446 element = dict->table[i];
447 while (element != NULL) {
448 printf("%s -> ", element->key);
449 if (output != NULL) {
450 output(element->content);
453 element = element->next;
460 * Destroy the dict mallocators.
461 * This is an internal XBT function called by xbt_exit().
463 void xbt_dict_exit(void) {
464 if (dict_mallocator != NULL) {
465 xbt_mallocator_free(dict_mallocator);
466 xbt_mallocator_free(dict_elm_mallocator);
470 static void* dict_mallocator_new_f(void) {
471 return xbt_new(s_xbt_dict_t, 1);
474 static void dict_mallocator_free_f(void* dict) {
478 static void dict_mallocator_reset_f(void* dict) {
479 /* nothing to do because all fields are
480 * initialized in xbt_dict_new
487 #include "portable.h"
489 XBT_LOG_EXTERNAL_CATEGORY(xbt_dict);
490 XBT_LOG_DEFAULT_CATEGORY(xbt_dict);
492 XBT_TEST_SUITE("dict","Dict data container");
494 static void print_str(void *str) {
495 printf("%s",(char*)PRINTF_STR(str));
498 static void debuged_add_ext(xbt_dict_t head,const char*key,const char*data_to_fill) {
499 char *data=xbt_strdup(data_to_fill);
501 xbt_test_log2("Add %s under %s",PRINTF_STR(data_to_fill),PRINTF_STR(key));
503 xbt_dict_set(head,key,data,&free);
504 if (XBT_LOG_ISENABLED(xbt_dict,xbt_log_priority_debug)) {
505 xbt_dict_dump(head,(void (*)(void*))&printf);
509 static void debuged_add(xbt_dict_t head,const char*key) {
510 debuged_add_ext(head,key,key);
513 static void fill(xbt_dict_t *head) {
514 xbt_test_add0("Fill in the dictionnary");
516 *head = xbt_dict_new();
517 debuged_add(*head,"12");
518 debuged_add(*head,"12a");
519 debuged_add(*head,"12b");
520 debuged_add(*head,"123");
521 debuged_add(*head,"123456");
522 /* Child becomes child of what to add */
523 debuged_add(*head,"1234");
524 /* Need of common ancestor */
525 debuged_add(*head,"123457");
529 static void search_ext(xbt_dict_t head,const char*key, const char *data) {
532 xbt_test_add1("Search %s",key);
533 found=xbt_dict_get(head,key);
534 xbt_test_log1("Found %s",(char *)found);
536 xbt_test_assert1(found,"data do not match expectations: found NULL while searching for %s",data);
538 xbt_test_assert2(!strcmp((char*)data,found),"data do not match expectations: found %s while searching for %s", (char*)found, data);
541 static void search(xbt_dict_t head,const char*key) {
542 search_ext(head,key,key);
545 static void debuged_remove(xbt_dict_t head,const char*key) {
547 xbt_test_add1("Remove '%s'",PRINTF_STR(key));
548 xbt_dict_remove(head,key);
549 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
553 static void traverse(xbt_dict_t head) {
554 xbt_dict_cursor_t cursor=NULL;
558 xbt_dict_foreach(head,cursor,key,data) {
559 xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data));
560 xbt_test_assert2(!data || !strcmp(key,data),
561 "Key(%s) != value(%s). Abording\n",key,data);
565 static void search_not_found(xbt_dict_t head, const char *data) {
569 xbt_test_add1("Search %s (expected not to be found)",data);
572 data = xbt_dict_get(head, data);
573 THROW1(unknown_error,0,"Found something which shouldn't be there (%s)",data);
575 if (e.category != not_found_error)
576 xbt_test_exception(e);
580 xbt_test_assert0(ok,"Exception not raised");
583 static void count(xbt_dict_t dict, int length) {
584 xbt_test_add1("Count elements (expecting %d)", length);
585 xbt_test_assert2(xbt_dict_length(dict) == length, "Length(%d) != %d.", xbt_dict_length(dict), length);
589 xbt_dict_t head=NULL;
593 XBT_TEST_UNIT("basic",test_dict_basic,"Basic usage: change, retrieve, traverse"){
594 xbt_test_add0("Traversal the null dictionnary");
597 xbt_test_add0("Traversal and search the empty dictionnary");
598 head = xbt_dict_new();
601 debuged_remove(head,"12346");
603 if (e.category != not_found_error)
604 xbt_test_exception(e);
607 xbt_dict_free(&head);
609 xbt_test_add0("Traverse the full dictionnary");
613 debuged_add_ext(head,"toto","tutu");
614 search_ext(head,"toto","tutu");
615 debuged_remove(head,"toto");
620 xbt_test_add0("Free the dictionnary (twice)");
621 xbt_dict_free(&head);
622 xbt_dict_free(&head);
627 xbt_test_add0("Change 123 to 'Changed 123'");
628 xbt_dict_set(head,"123",strdup("Changed 123"),&free);
631 xbt_test_add0("Change 123 back to '123'");
632 xbt_dict_set(head,"123",strdup("123"),&free);
635 xbt_test_add0("Change 12a to 'Dummy 12a'");
636 xbt_dict_set(head,"12a",strdup("Dummy 12a"),&free);
639 xbt_test_add0("Change 12a to '12a'");
640 xbt_dict_set(head,"12a",strdup("12a"),&free);
643 xbt_test_add0("Traverse the resulting dictionnary");
647 xbt_test_add0("Search 123");
648 data = xbt_dict_get(head,"123");
649 xbt_test_assert(data);
650 xbt_test_assert(!strcmp("123",data));
652 search_not_found(head,"Can't be found");
653 search_not_found(head,"123 Can't be found");
654 search_not_found(head,"12345678 NOT");
659 search(head,"123456");
661 search(head,"123457");
663 xbt_test_add0("Traverse the resulting dictionnary");
666 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
668 xbt_test_add0("Free the dictionnary twice");
669 xbt_dict_free(&head);
670 xbt_dict_free(&head);
672 xbt_test_add0("Traverse the resulting dictionnary");
676 XBT_TEST_UNIT("remove",test_dict_remove,"Removing some values"){
679 xbt_test_add0("Remove non existing data");
681 debuged_remove(head,"Does not exist");
683 if (e.category != not_found_error)
684 xbt_test_exception(e);
689 xbt_dict_free(&head);
691 xbt_test_add0("Remove each data manually (traversing the resulting dictionnary each time)");
693 debuged_remove(head,"12a"); traverse(head);
695 debuged_remove(head,"12b"); traverse(head);
697 debuged_remove(head,"12"); traverse(head);
699 debuged_remove(head,"123456"); traverse(head);
702 debuged_remove(head,"12346");
704 if (e.category != not_found_error)
705 xbt_test_exception(e);
709 debuged_remove(head,"1234"); traverse(head);
710 debuged_remove(head,"123457"); traverse(head);
711 debuged_remove(head,"123"); traverse(head);
713 debuged_remove(head,"12346");
715 if (e.category != not_found_error)
716 xbt_test_exception(e);
720 xbt_test_add0("Remove all values");
721 xbt_dict_free(&head);
723 xbt_dict_reset(head);
727 xbt_test_add0("Free the dictionnary twice");
728 xbt_dict_free(&head);
729 xbt_dict_free(&head);
732 XBT_TEST_UNIT("nulldata",test_dict_nulldata,"NULL data management"){
735 xbt_test_add0("Store NULL under 'null'");
736 xbt_dict_set(head,"null",NULL,NULL);
737 search_ext(head,"null",NULL);
739 xbt_test_add0("Check whether I see it while traversing...");
741 xbt_dict_cursor_t cursor=NULL;
745 xbt_dict_foreach(head,cursor,key,data) {
746 xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data));
747 if (!strcmp(key,"null"))
750 xbt_test_assert0(found,"the key 'null', associated to NULL is not found");
752 xbt_dict_free(&head);
756 #define SIZEOFKEY 1024
757 static int countelems(xbt_dict_t head) {
758 xbt_dict_cursor_t cursor;
763 xbt_dict_foreach(head,cursor,key,data) {
769 XBT_TEST_UNIT("crash",test_dict_crash,"Crash test"){
770 xbt_dict_t head=NULL;
775 srand((unsigned int)time(NULL));
777 xbt_test_add0("CRASH test");
778 xbt_test_log0("Fill the struct, count its elems and frees the structure (x10)");
779 xbt_test_log1("using 1000 elements with %d chars long randomized keys.",SIZEOFKEY);
783 /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
785 for (j=0;j<1000;j++) {
786 key=xbt_malloc(SIZEOFKEY);
788 for (k=0;k<SIZEOFKEY-1;k++)
789 key[k]=rand() % ('z' - 'a') + 'a';
791 /* printf("[%d %s]\n",j,key); */
792 xbt_dict_set(head,key,key,&free);
794 /* xbt_dict_dump(head,(void (*)(void*))&printf); */
795 nb = countelems(head);
796 xbt_test_assert1(nb == 1000,"found %d elements instead of 1000",nb);
798 xbt_dict_free(&head);
799 xbt_dict_free(&head);
804 xbt_test_add1("Fill %d elements, with keys being the number of element",NB_ELM);
805 for (j=0;j<NB_ELM;j++) {
806 /* if (!(j%1000)) { printf("."); fflush(stdout); } */
808 key = xbt_malloc(10);
811 xbt_dict_set(head,key,key,&free);
814 xbt_test_add0("Count the elements (retrieving the key and data for each)");
815 i = countelems(head);
816 xbt_test_log1("There is %d elements",i);
818 xbt_test_add1("Search my %d elements 20 times",NB_ELM);
821 /* if (i%10) printf("."); else printf("%d",i/10); fflush(stdout); */
822 for (j=0;j<NB_ELM;j++) {
825 data = xbt_dict_get(head,key);
826 xbt_test_assert2(!strcmp(key,(char*)data),
827 "key=%s != data=%s\n",key,(char*)data);
832 xbt_test_add1("Remove my %d elements",NB_ELM);
834 for (j=0;j<NB_ELM;j++) {
835 /* if (!(j%10000)) printf("."); fflush(stdout); */
838 xbt_dict_remove(head,key);
843 xbt_test_add0("Free the structure (twice)");
844 xbt_dict_free(&head);
845 xbt_dict_free(&head);
848 static void str_free(void *s) {
853 XBT_TEST_UNIT("multicrash",test_dict_multicrash,"Multi-dict crash test"){
856 #define NB_ELM 100 /*00*/
859 #define NB_TEST 20 /*20*/
862 xbt_dict_t mdict = NULL;
864 xbt_dynar_t keys = xbt_dynar_new(sizeof(char*),str_free);
869 xbt_test_add0("Generic multicache CRASH test");
870 xbt_test_log4(" Fill the struct and frees it %d times, using %d elements, "
871 "depth of multicache=%d, key size=%d",
872 NB_TEST,NB_ELM,DEPTH,KEY_SIZE);
874 for (l=0 ; l<DEPTH ; l++) {
875 key=xbt_malloc(KEY_SIZE);
876 xbt_dynar_push(keys,&key);
879 for (i=0;i<NB_TEST;i++) {
880 mdict = xbt_dict_new();
881 VERB1("mdict=%p",mdict);
883 printf("Test %d\n",i);
884 /* else if (i%10) printf("."); else printf("%d",i/10);*/
886 for (j=0;j<NB_ELM;j++) {
887 if (verbose>0) printf (" Add {");
889 for (l=0 ; l<DEPTH ; l++) {
890 key=*(char**)xbt_dynar_get_ptr(keys,l);
892 for (k=0;k<KEY_SIZE-1;k++)
893 key[k]=rand() % ('z' - 'a') + 'a';
897 if (verbose>0) printf("%p=%s %s ",key, key,(l<DEPTH-1?";":"}"));
899 if (verbose>0) printf("in multitree %p.\n",mdict);
901 xbt_multidict_set(mdict,keys,xbt_strdup(key),free);
903 data = xbt_multidict_get(mdict,keys);
905 xbt_test_assert2(data && !strcmp((char*)data,key),
906 "Retrieved value (%s) does not match the entrered one (%s)\n",
909 xbt_dict_free(&mdict);
912 xbt_dynar_free(&keys);
915 xbt_dict_dump(mdict,&xbt_dict_print);*/
917 xbt_dict_free(&mdict);
918 xbt_dynar_free(&keys);
921 #endif /* SIMGRID_TEST */